Expressions
Every AST node in SQLGlot is represented by a subclass of Expression
.
This module contains the implementation of all supported Expression
types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select
.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot._typing import E 25from sqlglot.errors import ParseError 26from sqlglot.helper import ( 27 AutoName, 28 camel_to_snake_case, 29 ensure_collection, 30 ensure_list, 31 seq_get, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39 40class _Expression(type): 41 def __new__(cls, clsname, bases, attrs): 42 klass = super().__new__(cls, clsname, bases, attrs) 43 44 # When an Expression class is created, its key is automatically set to be 45 # the lowercase version of the class' name. 46 klass.key = clsname.lower() 47 48 # This is so that docstrings are not inherited in pdoc 49 klass.__doc__ = klass.__doc__ or "" 50 51 return klass 52 53 54class Expression(metaclass=_Expression): 55 """ 56 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 57 context, such as its child expressions, their names (arg keys), and whether a given child expression 58 is optional or not. 59 60 Attributes: 61 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 62 and representing expressions as strings. 63 arg_types: determines what arguments (child nodes) are supported by an expression. It 64 maps arg keys to booleans that indicate whether the corresponding args are optional. 65 parent: a reference to the parent expression (or None, in case of root expressions). 66 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 67 uses to refer to it. 68 comments: a list of comments that are associated with a given expression. This is used in 69 order to preserve comments when transpiling SQL code. 70 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 71 optimizer, in order to enable some transformations that require type information. 72 73 Example: 74 >>> class Foo(Expression): 75 ... arg_types = {"this": True, "expression": False} 76 77 The above definition informs us that Foo is an Expression that requires an argument called 78 "this" and may also optionally receive an argument called "expression". 79 80 Args: 81 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 82 """ 83 84 key = "expression" 85 arg_types = {"this": True} 86 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 87 88 def __init__(self, **args: t.Any): 89 self.args: t.Dict[str, t.Any] = args 90 self.parent: t.Optional[Expression] = None 91 self.arg_key: t.Optional[str] = None 92 self.comments: t.Optional[t.List[str]] = None 93 self._type: t.Optional[DataType] = None 94 self._meta: t.Optional[t.Dict[str, t.Any]] = None 95 self._hash: t.Optional[int] = None 96 97 for arg_key, value in self.args.items(): 98 self._set_parent(arg_key, value) 99 100 def __eq__(self, other) -> bool: 101 return type(self) is type(other) and hash(self) == hash(other) 102 103 @property 104 def hashable_args(self) -> t.Any: 105 args = (self.args.get(k) for k in self.arg_types) 106 107 return tuple( 108 (tuple(_norm_arg(a) for a in arg) if arg else None) 109 if type(arg) is list 110 else (_norm_arg(arg) if arg is not None and arg is not False else None) 111 for arg in args 112 ) 113 114 def __hash__(self) -> int: 115 if self._hash is not None: 116 return self._hash 117 118 return hash((self.__class__, self.hashable_args)) 119 120 @property 121 def this(self): 122 """ 123 Retrieves the argument with key "this". 124 """ 125 return self.args.get("this") 126 127 @property 128 def expression(self): 129 """ 130 Retrieves the argument with key "expression". 131 """ 132 return self.args.get("expression") 133 134 @property 135 def expressions(self): 136 """ 137 Retrieves the argument with key "expressions". 138 """ 139 return self.args.get("expressions") or [] 140 141 def text(self, key) -> str: 142 """ 143 Returns a textual representation of the argument corresponding to "key". This can only be used 144 for args that are strings or leaf Expression instances, such as identifiers and literals. 145 """ 146 field = self.args.get(key) 147 if isinstance(field, str): 148 return field 149 if isinstance(field, (Identifier, Literal, Var)): 150 return field.this 151 if isinstance(field, (Star, Null)): 152 return field.name 153 return "" 154 155 @property 156 def is_string(self) -> bool: 157 """ 158 Checks whether a Literal expression is a string. 159 """ 160 return isinstance(self, Literal) and self.args["is_string"] 161 162 @property 163 def is_number(self) -> bool: 164 """ 165 Checks whether a Literal expression is a number. 166 """ 167 return isinstance(self, Literal) and not self.args["is_string"] 168 169 @property 170 def is_int(self) -> bool: 171 """ 172 Checks whether a Literal expression is an integer. 173 """ 174 if self.is_number: 175 try: 176 int(self.name) 177 return True 178 except ValueError: 179 pass 180 return False 181 182 @property 183 def is_star(self) -> bool: 184 """Checks whether an expression is a star.""" 185 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 186 187 @property 188 def alias(self) -> str: 189 """ 190 Returns the alias of the expression, or an empty string if it's not aliased. 191 """ 192 if isinstance(self.args.get("alias"), TableAlias): 193 return self.args["alias"].name 194 return self.text("alias") 195 196 @property 197 def name(self) -> str: 198 return self.text("this") 199 200 @property 201 def alias_or_name(self) -> str: 202 return self.alias or self.name 203 204 @property 205 def output_name(self) -> str: 206 """ 207 Name of the output column if this expression is a selection. 208 209 If the Expression has no output name, an empty string is returned. 210 211 Example: 212 >>> from sqlglot import parse_one 213 >>> parse_one("SELECT a").expressions[0].output_name 214 'a' 215 >>> parse_one("SELECT b AS c").expressions[0].output_name 216 'c' 217 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 218 '' 219 """ 220 return "" 221 222 @property 223 def type(self) -> t.Optional[DataType]: 224 return self._type 225 226 @type.setter 227 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 228 if dtype and not isinstance(dtype, DataType): 229 dtype = DataType.build(dtype) 230 self._type = dtype # type: ignore 231 232 @property 233 def meta(self) -> t.Dict[str, t.Any]: 234 if self._meta is None: 235 self._meta = {} 236 return self._meta 237 238 def __deepcopy__(self, memo): 239 copy = self.__class__(**deepcopy(self.args)) 240 if self.comments is not None: 241 copy.comments = deepcopy(self.comments) 242 243 if self._type is not None: 244 copy._type = self._type.copy() 245 246 if self._meta is not None: 247 copy._meta = deepcopy(self._meta) 248 249 return copy 250 251 def copy(self): 252 """ 253 Returns a deep copy of the expression. 254 """ 255 new = deepcopy(self) 256 new.parent = self.parent 257 return new 258 259 def add_comments(self, comments: t.Optional[t.List[str]]) -> None: 260 if self.comments is None: 261 self.comments = [] 262 if comments: 263 self.comments.extend(comments) 264 265 def append(self, arg_key: str, value: t.Any) -> None: 266 """ 267 Appends value to arg_key if it's a list or sets it as a new list. 268 269 Args: 270 arg_key (str): name of the list expression arg 271 value (Any): value to append to the list 272 """ 273 if not isinstance(self.args.get(arg_key), list): 274 self.args[arg_key] = [] 275 self.args[arg_key].append(value) 276 self._set_parent(arg_key, value) 277 278 def set(self, arg_key: str, value: t.Any) -> None: 279 """ 280 Sets `arg_key` to `value`. 281 282 Args: 283 arg_key (str): name of the expression arg. 284 value: value to set the arg to. 285 """ 286 self.args[arg_key] = value 287 self._set_parent(arg_key, value) 288 289 def _set_parent(self, arg_key: str, value: t.Any) -> None: 290 if hasattr(value, "parent"): 291 value.parent = self 292 value.arg_key = arg_key 293 elif type(value) is list: 294 for v in value: 295 if hasattr(v, "parent"): 296 v.parent = self 297 v.arg_key = arg_key 298 299 @property 300 def depth(self) -> int: 301 """ 302 Returns the depth of this tree. 303 """ 304 if self.parent: 305 return self.parent.depth + 1 306 return 0 307 308 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 309 """Yields the key and expression for all arguments, exploding list args.""" 310 for k, vs in self.args.items(): 311 if type(vs) is list: 312 for v in vs: 313 if hasattr(v, "parent"): 314 yield k, v 315 else: 316 if hasattr(vs, "parent"): 317 yield k, vs 318 319 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 320 """ 321 Returns the first node in this tree which matches at least one of 322 the specified types. 323 324 Args: 325 expression_types: the expression type(s) to match. 326 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 327 328 Returns: 329 The node which matches the criteria or None if no such node was found. 330 """ 331 return next(self.find_all(*expression_types, bfs=bfs), None) 332 333 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 334 """ 335 Returns a generator object which visits all nodes in this tree and only 336 yields those that match at least one of the specified expression types. 337 338 Args: 339 expression_types: the expression type(s) to match. 340 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 341 342 Returns: 343 The generator object. 344 """ 345 for expression, *_ in self.walk(bfs=bfs): 346 if isinstance(expression, expression_types): 347 yield expression 348 349 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 350 """ 351 Returns a nearest parent matching expression_types. 352 353 Args: 354 expression_types: the expression type(s) to match. 355 356 Returns: 357 The parent node. 358 """ 359 ancestor = self.parent 360 while ancestor and not isinstance(ancestor, expression_types): 361 ancestor = ancestor.parent 362 return t.cast(E, ancestor) 363 364 @property 365 def parent_select(self) -> t.Optional[Select]: 366 """ 367 Returns the parent select statement. 368 """ 369 return self.find_ancestor(Select) 370 371 @property 372 def same_parent(self) -> bool: 373 """Returns if the parent is the same class as itself.""" 374 return type(self.parent) is self.__class__ 375 376 def root(self) -> Expression: 377 """ 378 Returns the root expression of this tree. 379 """ 380 expression = self 381 while expression.parent: 382 expression = expression.parent 383 return expression 384 385 def walk(self, bfs=True, prune=None): 386 """ 387 Returns a generator object which visits all nodes in this tree. 388 389 Args: 390 bfs (bool): if set to True the BFS traversal order will be applied, 391 otherwise the DFS traversal will be used instead. 392 prune ((node, parent, arg_key) -> bool): callable that returns True if 393 the generator should stop traversing this branch of the tree. 394 395 Returns: 396 the generator object. 397 """ 398 if bfs: 399 yield from self.bfs(prune=prune) 400 else: 401 yield from self.dfs(prune=prune) 402 403 def dfs(self, parent=None, key=None, prune=None): 404 """ 405 Returns a generator object which visits all nodes in this tree in 406 the DFS (Depth-first) order. 407 408 Returns: 409 The generator object. 410 """ 411 parent = parent or self.parent 412 yield self, parent, key 413 if prune and prune(self, parent, key): 414 return 415 416 for k, v in self.iter_expressions(): 417 yield from v.dfs(self, k, prune) 418 419 def bfs(self, prune=None): 420 """ 421 Returns a generator object which visits all nodes in this tree in 422 the BFS (Breadth-first) order. 423 424 Returns: 425 The generator object. 426 """ 427 queue = deque([(self, self.parent, None)]) 428 429 while queue: 430 item, parent, key = queue.popleft() 431 432 yield item, parent, key 433 if prune and prune(item, parent, key): 434 continue 435 436 for k, v in item.iter_expressions(): 437 queue.append((v, item, k)) 438 439 def unnest(self): 440 """ 441 Returns the first non parenthesis child or self. 442 """ 443 expression = self 444 while type(expression) is Paren: 445 expression = expression.this 446 return expression 447 448 def unalias(self): 449 """ 450 Returns the inner expression if this is an Alias. 451 """ 452 if isinstance(self, Alias): 453 return self.this 454 return self 455 456 def unnest_operands(self): 457 """ 458 Returns unnested operands as a tuple. 459 """ 460 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 461 462 def flatten(self, unnest=True): 463 """ 464 Returns a generator which yields child nodes who's parents are the same class. 465 466 A AND B AND C -> [A, B, C] 467 """ 468 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 469 if not type(node) is self.__class__: 470 yield node.unnest() if unnest else node 471 472 def __str__(self) -> str: 473 return self.sql() 474 475 def __repr__(self) -> str: 476 return self._to_s() 477 478 def sql(self, dialect: DialectType = None, **opts) -> str: 479 """ 480 Returns SQL string representation of this tree. 481 482 Args: 483 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 484 opts: other `sqlglot.generator.Generator` options. 485 486 Returns: 487 The SQL string. 488 """ 489 from sqlglot.dialects import Dialect 490 491 return Dialect.get_or_raise(dialect)().generate(self, **opts) 492 493 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 494 indent = "" if not level else "\n" 495 indent += "".join([" "] * level) 496 left = f"({self.key.upper()} " 497 498 args: t.Dict[str, t.Any] = { 499 k: ", ".join( 500 v._to_s(hide_missing=hide_missing, level=level + 1) 501 if hasattr(v, "_to_s") 502 else str(v) 503 for v in ensure_list(vs) 504 if v is not None 505 ) 506 for k, vs in self.args.items() 507 } 508 args["comments"] = self.comments 509 args["type"] = self.type 510 args = {k: v for k, v in args.items() if v or not hide_missing} 511 512 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 513 right += ")" 514 515 return indent + left + right 516 517 def transform(self, fun, *args, copy=True, **kwargs): 518 """ 519 Recursively visits all tree nodes (excluding already transformed ones) 520 and applies the given transformation function to each node. 521 522 Args: 523 fun (function): a function which takes a node as an argument and returns a 524 new transformed node or the same node without modifications. If the function 525 returns None, then the corresponding node will be removed from the syntax tree. 526 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 527 modified in place. 528 529 Returns: 530 The transformed tree. 531 """ 532 node = self.copy() if copy else self 533 new_node = fun(node, *args, **kwargs) 534 535 if new_node is None or not isinstance(new_node, Expression): 536 return new_node 537 if new_node is not node: 538 new_node.parent = node.parent 539 return new_node 540 541 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 542 return new_node 543 544 @t.overload 545 def replace(self, expression: E) -> E: 546 ... 547 548 @t.overload 549 def replace(self, expression: None) -> None: 550 ... 551 552 def replace(self, expression): 553 """ 554 Swap out this expression with a new expression. 555 556 For example:: 557 558 >>> tree = Select().select("x").from_("tbl") 559 >>> tree.find(Column).replace(Column(this="y")) 560 (COLUMN this: y) 561 >>> tree.sql() 562 'SELECT y FROM tbl' 563 564 Args: 565 expression: new node 566 567 Returns: 568 The new expression or expressions. 569 """ 570 if not self.parent: 571 return expression 572 573 parent = self.parent 574 self.parent = None 575 576 replace_children(parent, lambda child: expression if child is self else child) 577 return expression 578 579 def pop(self: E) -> E: 580 """ 581 Remove this expression from its AST. 582 583 Returns: 584 The popped expression. 585 """ 586 self.replace(None) 587 return self 588 589 def assert_is(self, type_: t.Type[E]) -> E: 590 """ 591 Assert that this `Expression` is an instance of `type_`. 592 593 If it is NOT an instance of `type_`, this raises an assertion error. 594 Otherwise, this returns this expression. 595 596 Examples: 597 This is useful for type security in chained expressions: 598 599 >>> import sqlglot 600 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 601 'SELECT x, z FROM y' 602 """ 603 assert isinstance(self, type_) 604 return self 605 606 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 607 """ 608 Checks if this expression is valid (e.g. all mandatory args are set). 609 610 Args: 611 args: a sequence of values that were used to instantiate a Func expression. This is used 612 to check that the provided arguments don't exceed the function argument limit. 613 614 Returns: 615 A list of error messages for all possible errors that were found. 616 """ 617 errors: t.List[str] = [] 618 619 for k in self.args: 620 if k not in self.arg_types: 621 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 622 for k, mandatory in self.arg_types.items(): 623 v = self.args.get(k) 624 if mandatory and (v is None or (isinstance(v, list) and not v)): 625 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 626 627 if ( 628 args 629 and isinstance(self, Func) 630 and len(args) > len(self.arg_types) 631 and not self.is_var_len_args 632 ): 633 errors.append( 634 f"The number of provided arguments ({len(args)}) is greater than " 635 f"the maximum number of supported arguments ({len(self.arg_types)})" 636 ) 637 638 return errors 639 640 def dump(self): 641 """ 642 Dump this Expression to a JSON-serializable dict. 643 """ 644 from sqlglot.serde import dump 645 646 return dump(self) 647 648 @classmethod 649 def load(cls, obj): 650 """ 651 Load a dict (as returned by `Expression.dump`) into an Expression instance. 652 """ 653 from sqlglot.serde import load 654 655 return load(obj) 656 657 658IntoType = t.Union[ 659 str, 660 t.Type[Expression], 661 t.Collection[t.Union[str, t.Type[Expression]]], 662] 663ExpOrStr = t.Union[str, Expression] 664 665 666class Condition(Expression): 667 def and_( 668 self, 669 *expressions: t.Optional[ExpOrStr], 670 dialect: DialectType = None, 671 copy: bool = True, 672 **opts, 673 ) -> Condition: 674 """ 675 AND this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").and_("y=1").sql() 679 'x = 1 AND y = 1' 680 681 Args: 682 *expressions: the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect: the dialect used to parse the input expression. 685 copy: whether or not to copy the involved expressions (only applies to Expressions). 686 opts: other options to use to parse the input expressions. 687 688 Returns: 689 The new And condition. 690 """ 691 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 692 693 def or_( 694 self, 695 *expressions: t.Optional[ExpOrStr], 696 dialect: DialectType = None, 697 copy: bool = True, 698 **opts, 699 ) -> Condition: 700 """ 701 OR this condition with one or multiple expressions. 702 703 Example: 704 >>> condition("x=1").or_("y=1").sql() 705 'x = 1 OR y = 1' 706 707 Args: 708 *expressions: the SQL code strings to parse. 709 If an `Expression` instance is passed, it will be used as-is. 710 dialect: the dialect used to parse the input expression. 711 copy: whether or not to copy the involved expressions (only applies to Expressions). 712 opts: other options to use to parse the input expressions. 713 714 Returns: 715 The new Or condition. 716 """ 717 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 718 719 def not_(self, copy: bool = True): 720 """ 721 Wrap this condition with NOT. 722 723 Example: 724 >>> condition("x=1").not_().sql() 725 'NOT x = 1' 726 727 Args: 728 copy: whether or not to copy this object. 729 730 Returns: 731 The new Not instance. 732 """ 733 return not_(self, copy=copy) 734 735 def as_( 736 self, 737 alias: str | Identifier, 738 quoted: t.Optional[bool] = None, 739 dialect: DialectType = None, 740 copy: bool = True, 741 **opts, 742 ) -> Alias: 743 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 744 745 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 746 this = self.copy() 747 other = convert(other, copy=True) 748 if not isinstance(this, klass) and not isinstance(other, klass): 749 this = _wrap(this, Binary) 750 other = _wrap(other, Binary) 751 if reverse: 752 return klass(this=other, expression=this) 753 return klass(this=this, expression=other) 754 755 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 756 return Bracket( 757 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 758 ) 759 760 def isin( 761 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 762 ) -> In: 763 return In( 764 this=_maybe_copy(self, copy), 765 expressions=[convert(e, copy=copy) for e in expressions], 766 query=maybe_parse(query, copy=copy, **opts) if query else None, 767 ) 768 769 def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between: 770 return Between( 771 this=_maybe_copy(self, copy), 772 low=convert(low, copy=copy, **opts), 773 high=convert(high, copy=copy, **opts), 774 ) 775 776 def is_(self, other: ExpOrStr) -> Is: 777 return self._binop(Is, other) 778 779 def like(self, other: ExpOrStr) -> Like: 780 return self._binop(Like, other) 781 782 def ilike(self, other: ExpOrStr) -> ILike: 783 return self._binop(ILike, other) 784 785 def eq(self, other: t.Any) -> EQ: 786 return self._binop(EQ, other) 787 788 def neq(self, other: t.Any) -> NEQ: 789 return self._binop(NEQ, other) 790 791 def rlike(self, other: ExpOrStr) -> RegexpLike: 792 return self._binop(RegexpLike, other) 793 794 def __lt__(self, other: t.Any) -> LT: 795 return self._binop(LT, other) 796 797 def __le__(self, other: t.Any) -> LTE: 798 return self._binop(LTE, other) 799 800 def __gt__(self, other: t.Any) -> GT: 801 return self._binop(GT, other) 802 803 def __ge__(self, other: t.Any) -> GTE: 804 return self._binop(GTE, other) 805 806 def __add__(self, other: t.Any) -> Add: 807 return self._binop(Add, other) 808 809 def __radd__(self, other: t.Any) -> Add: 810 return self._binop(Add, other, reverse=True) 811 812 def __sub__(self, other: t.Any) -> Sub: 813 return self._binop(Sub, other) 814 815 def __rsub__(self, other: t.Any) -> Sub: 816 return self._binop(Sub, other, reverse=True) 817 818 def __mul__(self, other: t.Any) -> Mul: 819 return self._binop(Mul, other) 820 821 def __rmul__(self, other: t.Any) -> Mul: 822 return self._binop(Mul, other, reverse=True) 823 824 def __truediv__(self, other: t.Any) -> Div: 825 return self._binop(Div, other) 826 827 def __rtruediv__(self, other: t.Any) -> Div: 828 return self._binop(Div, other, reverse=True) 829 830 def __floordiv__(self, other: t.Any) -> IntDiv: 831 return self._binop(IntDiv, other) 832 833 def __rfloordiv__(self, other: t.Any) -> IntDiv: 834 return self._binop(IntDiv, other, reverse=True) 835 836 def __mod__(self, other: t.Any) -> Mod: 837 return self._binop(Mod, other) 838 839 def __rmod__(self, other: t.Any) -> Mod: 840 return self._binop(Mod, other, reverse=True) 841 842 def __pow__(self, other: t.Any) -> Pow: 843 return self._binop(Pow, other) 844 845 def __rpow__(self, other: t.Any) -> Pow: 846 return self._binop(Pow, other, reverse=True) 847 848 def __and__(self, other: t.Any) -> And: 849 return self._binop(And, other) 850 851 def __rand__(self, other: t.Any) -> And: 852 return self._binop(And, other, reverse=True) 853 854 def __or__(self, other: t.Any) -> Or: 855 return self._binop(Or, other) 856 857 def __ror__(self, other: t.Any) -> Or: 858 return self._binop(Or, other, reverse=True) 859 860 def __neg__(self) -> Neg: 861 return Neg(this=_wrap(self.copy(), Binary)) 862 863 def __invert__(self) -> Not: 864 return not_(self.copy()) 865 866 867class Predicate(Condition): 868 """Relationships like x = y, x > 1, x >= y.""" 869 870 871class DerivedTable(Expression): 872 @property 873 def alias_column_names(self) -> t.List[str]: 874 table_alias = self.args.get("alias") 875 if not table_alias: 876 return [] 877 return [c.name for c in table_alias.args.get("columns") or []] 878 879 @property 880 def selects(self): 881 return self.this.selects if isinstance(self.this, Subqueryable) else [] 882 883 @property 884 def named_selects(self): 885 return [select.output_name for select in self.selects] 886 887 888class Unionable(Expression): 889 def union( 890 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 891 ) -> Unionable: 892 """ 893 Builds a UNION expression. 894 895 Example: 896 >>> import sqlglot 897 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 898 'SELECT * FROM foo UNION SELECT * FROM bla' 899 900 Args: 901 expression: the SQL code string. 902 If an `Expression` instance is passed, it will be used as-is. 903 distinct: set the DISTINCT flag if and only if this is true. 904 dialect: the dialect used to parse the input expression. 905 opts: other options to use to parse the input expressions. 906 907 Returns: 908 The new Union expression. 909 """ 910 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 911 912 def intersect( 913 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 914 ) -> Unionable: 915 """ 916 Builds an INTERSECT expression. 917 918 Example: 919 >>> import sqlglot 920 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 921 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 922 923 Args: 924 expression: the SQL code string. 925 If an `Expression` instance is passed, it will be used as-is. 926 distinct: set the DISTINCT flag if and only if this is true. 927 dialect: the dialect used to parse the input expression. 928 opts: other options to use to parse the input expressions. 929 930 Returns: 931 The new Intersect expression. 932 """ 933 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 934 935 def except_( 936 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 937 ) -> Unionable: 938 """ 939 Builds an EXCEPT expression. 940 941 Example: 942 >>> import sqlglot 943 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 944 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 945 946 Args: 947 expression: the SQL code string. 948 If an `Expression` instance is passed, it will be used as-is. 949 distinct: set the DISTINCT flag if and only if this is true. 950 dialect: the dialect used to parse the input expression. 951 opts: other options to use to parse the input expressions. 952 953 Returns: 954 The new Except expression. 955 """ 956 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 957 958 959class UDTF(DerivedTable, Unionable): 960 @property 961 def selects(self): 962 alias = self.args.get("alias") 963 return alias.columns if alias else [] 964 965 966class Cache(Expression): 967 arg_types = { 968 "with": False, 969 "this": True, 970 "lazy": False, 971 "options": False, 972 "expression": False, 973 } 974 975 976class Uncache(Expression): 977 arg_types = {"this": True, "exists": False} 978 979 980class Create(Expression): 981 arg_types = { 982 "with": False, 983 "this": True, 984 "kind": True, 985 "expression": False, 986 "exists": False, 987 "properties": False, 988 "replace": False, 989 "unique": False, 990 "indexes": False, 991 "no_schema_binding": False, 992 "begin": False, 993 "clone": False, 994 } 995 996 997# https://docs.snowflake.com/en/sql-reference/sql/create-clone 998class Clone(Expression): 999 arg_types = { 1000 "this": True, 1001 "when": False, 1002 "kind": False, 1003 "expression": False, 1004 } 1005 1006 1007class Describe(Expression): 1008 arg_types = {"this": True, "kind": False} 1009 1010 1011class Pragma(Expression): 1012 pass 1013 1014 1015class Set(Expression): 1016 arg_types = {"expressions": False} 1017 1018 1019class SetItem(Expression): 1020 arg_types = { 1021 "this": False, 1022 "expressions": False, 1023 "kind": False, 1024 "collate": False, # MySQL SET NAMES statement 1025 "global": False, 1026 } 1027 1028 1029class Show(Expression): 1030 arg_types = { 1031 "this": True, 1032 "target": False, 1033 "offset": False, 1034 "limit": False, 1035 "like": False, 1036 "where": False, 1037 "db": False, 1038 "full": False, 1039 "mutex": False, 1040 "query": False, 1041 "channel": False, 1042 "global": False, 1043 "log": False, 1044 "position": False, 1045 "types": False, 1046 } 1047 1048 1049class UserDefinedFunction(Expression): 1050 arg_types = {"this": True, "expressions": False, "wrapped": False} 1051 1052 1053class CharacterSet(Expression): 1054 arg_types = {"this": True, "default": False} 1055 1056 1057class With(Expression): 1058 arg_types = {"expressions": True, "recursive": False} 1059 1060 @property 1061 def recursive(self) -> bool: 1062 return bool(self.args.get("recursive")) 1063 1064 1065class WithinGroup(Expression): 1066 arg_types = {"this": True, "expression": False} 1067 1068 1069class CTE(DerivedTable): 1070 arg_types = {"this": True, "alias": True} 1071 1072 1073class TableAlias(Expression): 1074 arg_types = {"this": False, "columns": False} 1075 1076 @property 1077 def columns(self): 1078 return self.args.get("columns") or [] 1079 1080 1081class BitString(Condition): 1082 pass 1083 1084 1085class HexString(Condition): 1086 pass 1087 1088 1089class ByteString(Condition): 1090 pass 1091 1092 1093class RawString(Condition): 1094 pass 1095 1096 1097class Column(Condition): 1098 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1099 1100 @property 1101 def table(self) -> str: 1102 return self.text("table") 1103 1104 @property 1105 def db(self) -> str: 1106 return self.text("db") 1107 1108 @property 1109 def catalog(self) -> str: 1110 return self.text("catalog") 1111 1112 @property 1113 def output_name(self) -> str: 1114 return self.name 1115 1116 @property 1117 def parts(self) -> t.List[Identifier]: 1118 """Return the parts of a column in order catalog, db, table, name.""" 1119 return [ 1120 t.cast(Identifier, self.args[part]) 1121 for part in ("catalog", "db", "table", "this") 1122 if self.args.get(part) 1123 ] 1124 1125 def to_dot(self) -> Dot: 1126 """Converts the column into a dot expression.""" 1127 parts = self.parts 1128 parent = self.parent 1129 1130 while parent: 1131 if isinstance(parent, Dot): 1132 parts.append(parent.expression) 1133 parent = parent.parent 1134 1135 return Dot.build(parts) 1136 1137 1138class ColumnPosition(Expression): 1139 arg_types = {"this": False, "position": True} 1140 1141 1142class ColumnDef(Expression): 1143 arg_types = { 1144 "this": True, 1145 "kind": False, 1146 "constraints": False, 1147 "exists": False, 1148 "position": False, 1149 } 1150 1151 @property 1152 def constraints(self) -> t.List[ColumnConstraint]: 1153 return self.args.get("constraints") or [] 1154 1155 1156class AlterColumn(Expression): 1157 arg_types = { 1158 "this": True, 1159 "dtype": False, 1160 "collate": False, 1161 "using": False, 1162 "default": False, 1163 "drop": False, 1164 } 1165 1166 1167class RenameTable(Expression): 1168 pass 1169 1170 1171class SetTag(Expression): 1172 arg_types = {"expressions": True, "unset": False} 1173 1174 1175class Comment(Expression): 1176 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 1177 1178 1179# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1180class MergeTreeTTLAction(Expression): 1181 arg_types = { 1182 "this": True, 1183 "delete": False, 1184 "recompress": False, 1185 "to_disk": False, 1186 "to_volume": False, 1187 } 1188 1189 1190# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1191class MergeTreeTTL(Expression): 1192 arg_types = { 1193 "expressions": True, 1194 "where": False, 1195 "group": False, 1196 "aggregates": False, 1197 } 1198 1199 1200class ColumnConstraint(Expression): 1201 arg_types = {"this": False, "kind": True} 1202 1203 @property 1204 def kind(self) -> ColumnConstraintKind: 1205 return self.args["kind"] 1206 1207 1208class ColumnConstraintKind(Expression): 1209 pass 1210 1211 1212class AutoIncrementColumnConstraint(ColumnConstraintKind): 1213 pass 1214 1215 1216class CaseSpecificColumnConstraint(ColumnConstraintKind): 1217 arg_types = {"not_": True} 1218 1219 1220class CharacterSetColumnConstraint(ColumnConstraintKind): 1221 arg_types = {"this": True} 1222 1223 1224class CheckColumnConstraint(ColumnConstraintKind): 1225 pass 1226 1227 1228class CollateColumnConstraint(ColumnConstraintKind): 1229 pass 1230 1231 1232class CommentColumnConstraint(ColumnConstraintKind): 1233 pass 1234 1235 1236class CompressColumnConstraint(ColumnConstraintKind): 1237 pass 1238 1239 1240class DateFormatColumnConstraint(ColumnConstraintKind): 1241 arg_types = {"this": True} 1242 1243 1244class DefaultColumnConstraint(ColumnConstraintKind): 1245 pass 1246 1247 1248class EncodeColumnConstraint(ColumnConstraintKind): 1249 pass 1250 1251 1252class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1253 # this: True -> ALWAYS, this: False -> BY DEFAULT 1254 arg_types = { 1255 "this": False, 1256 "expression": False, 1257 "on_null": False, 1258 "start": False, 1259 "increment": False, 1260 "minvalue": False, 1261 "maxvalue": False, 1262 "cycle": False, 1263 } 1264 1265 1266class InlineLengthColumnConstraint(ColumnConstraintKind): 1267 pass 1268 1269 1270class NotNullColumnConstraint(ColumnConstraintKind): 1271 arg_types = {"allow_null": False} 1272 1273 1274# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 1275class OnUpdateColumnConstraint(ColumnConstraintKind): 1276 pass 1277 1278 1279class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1280 arg_types = {"desc": False} 1281 1282 1283class TitleColumnConstraint(ColumnConstraintKind): 1284 pass 1285 1286 1287class UniqueColumnConstraint(ColumnConstraintKind): 1288 arg_types = {"this": False} 1289 1290 1291class UppercaseColumnConstraint(ColumnConstraintKind): 1292 arg_types: t.Dict[str, t.Any] = {} 1293 1294 1295class PathColumnConstraint(ColumnConstraintKind): 1296 pass 1297 1298 1299class Constraint(Expression): 1300 arg_types = {"this": True, "expressions": True} 1301 1302 1303class Delete(Expression): 1304 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1305 1306 def delete( 1307 self, 1308 table: ExpOrStr, 1309 dialect: DialectType = None, 1310 copy: bool = True, 1311 **opts, 1312 ) -> Delete: 1313 """ 1314 Create a DELETE expression or replace the table on an existing DELETE expression. 1315 1316 Example: 1317 >>> delete("tbl").sql() 1318 'DELETE FROM tbl' 1319 1320 Args: 1321 table: the table from which to delete. 1322 dialect: the dialect used to parse the input expression. 1323 copy: if `False`, modify this expression instance in-place. 1324 opts: other options to use to parse the input expressions. 1325 1326 Returns: 1327 Delete: the modified expression. 1328 """ 1329 return _apply_builder( 1330 expression=table, 1331 instance=self, 1332 arg="this", 1333 dialect=dialect, 1334 into=Table, 1335 copy=copy, 1336 **opts, 1337 ) 1338 1339 def where( 1340 self, 1341 *expressions: t.Optional[ExpOrStr], 1342 append: bool = True, 1343 dialect: DialectType = None, 1344 copy: bool = True, 1345 **opts, 1346 ) -> Delete: 1347 """ 1348 Append to or set the WHERE expressions. 1349 1350 Example: 1351 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1352 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1353 1354 Args: 1355 *expressions: the SQL code strings to parse. 1356 If an `Expression` instance is passed, it will be used as-is. 1357 Multiple expressions are combined with an AND operator. 1358 append: if `True`, AND the new expressions to any existing expression. 1359 Otherwise, this resets the expression. 1360 dialect: the dialect used to parse the input expressions. 1361 copy: if `False`, modify this expression instance in-place. 1362 opts: other options to use to parse the input expressions. 1363 1364 Returns: 1365 Delete: the modified expression. 1366 """ 1367 return _apply_conjunction_builder( 1368 *expressions, 1369 instance=self, 1370 arg="where", 1371 append=append, 1372 into=Where, 1373 dialect=dialect, 1374 copy=copy, 1375 **opts, 1376 ) 1377 1378 def returning( 1379 self, 1380 expression: ExpOrStr, 1381 dialect: DialectType = None, 1382 copy: bool = True, 1383 **opts, 1384 ) -> Delete: 1385 """ 1386 Set the RETURNING expression. Not supported by all dialects. 1387 1388 Example: 1389 >>> delete("tbl").returning("*", dialect="postgres").sql() 1390 'DELETE FROM tbl RETURNING *' 1391 1392 Args: 1393 expression: the SQL code strings to parse. 1394 If an `Expression` instance is passed, it will be used as-is. 1395 dialect: the dialect used to parse the input expressions. 1396 copy: if `False`, modify this expression instance in-place. 1397 opts: other options to use to parse the input expressions. 1398 1399 Returns: 1400 Delete: the modified expression. 1401 """ 1402 return _apply_builder( 1403 expression=expression, 1404 instance=self, 1405 arg="returning", 1406 prefix="RETURNING", 1407 dialect=dialect, 1408 copy=copy, 1409 into=Returning, 1410 **opts, 1411 ) 1412 1413 1414class Drop(Expression): 1415 arg_types = { 1416 "this": False, 1417 "kind": False, 1418 "exists": False, 1419 "temporary": False, 1420 "materialized": False, 1421 "cascade": False, 1422 "constraints": False, 1423 "purge": False, 1424 } 1425 1426 1427class Filter(Expression): 1428 arg_types = {"this": True, "expression": True} 1429 1430 1431class Check(Expression): 1432 pass 1433 1434 1435class Directory(Expression): 1436 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1437 arg_types = {"this": True, "local": False, "row_format": False} 1438 1439 1440class ForeignKey(Expression): 1441 arg_types = { 1442 "expressions": True, 1443 "reference": False, 1444 "delete": False, 1445 "update": False, 1446 } 1447 1448 1449class PrimaryKey(Expression): 1450 arg_types = {"expressions": True, "options": False} 1451 1452 1453# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1454# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1455class Into(Expression): 1456 arg_types = {"this": True, "temporary": False, "unlogged": False} 1457 1458 1459class From(Expression): 1460 @property 1461 def name(self) -> str: 1462 return self.this.name 1463 1464 @property 1465 def alias_or_name(self) -> str: 1466 return self.this.alias_or_name 1467 1468 1469class Having(Expression): 1470 pass 1471 1472 1473class Hint(Expression): 1474 arg_types = {"expressions": True} 1475 1476 1477class JoinHint(Expression): 1478 arg_types = {"this": True, "expressions": True} 1479 1480 1481class Identifier(Expression): 1482 arg_types = {"this": True, "quoted": False} 1483 1484 @property 1485 def quoted(self) -> bool: 1486 return bool(self.args.get("quoted")) 1487 1488 @property 1489 def hashable_args(self) -> t.Any: 1490 if self.quoted and any(char.isupper() for char in self.this): 1491 return (self.this, self.quoted) 1492 return self.this.lower() 1493 1494 @property 1495 def output_name(self) -> str: 1496 return self.name 1497 1498 1499class Index(Expression): 1500 arg_types = { 1501 "this": False, 1502 "table": False, 1503 "where": False, 1504 "columns": False, 1505 "unique": False, 1506 "primary": False, 1507 "amp": False, # teradata 1508 "partition_by": False, # teradata 1509 } 1510 1511 1512class Insert(Expression): 1513 arg_types = { 1514 "with": False, 1515 "this": True, 1516 "expression": False, 1517 "conflict": False, 1518 "returning": False, 1519 "overwrite": False, 1520 "exists": False, 1521 "partition": False, 1522 "alternative": False, 1523 } 1524 1525 def with_( 1526 self, 1527 alias: ExpOrStr, 1528 as_: ExpOrStr, 1529 recursive: t.Optional[bool] = None, 1530 append: bool = True, 1531 dialect: DialectType = None, 1532 copy: bool = True, 1533 **opts, 1534 ) -> Insert: 1535 """ 1536 Append to or set the common table expressions. 1537 1538 Example: 1539 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1540 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1541 1542 Args: 1543 alias: the SQL code string to parse as the table name. 1544 If an `Expression` instance is passed, this is used as-is. 1545 as_: the SQL code string to parse as the table expression. 1546 If an `Expression` instance is passed, it will be used as-is. 1547 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1548 append: if `True`, add to any existing expressions. 1549 Otherwise, this resets the expressions. 1550 dialect: the dialect used to parse the input expression. 1551 copy: if `False`, modify this expression instance in-place. 1552 opts: other options to use to parse the input expressions. 1553 1554 Returns: 1555 The modified expression. 1556 """ 1557 return _apply_cte_builder( 1558 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1559 ) 1560 1561 1562class OnConflict(Expression): 1563 arg_types = { 1564 "duplicate": False, 1565 "expressions": False, 1566 "nothing": False, 1567 "key": False, 1568 "constraint": False, 1569 } 1570 1571 1572class Returning(Expression): 1573 arg_types = {"expressions": True} 1574 1575 1576# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1577class Introducer(Expression): 1578 arg_types = {"this": True, "expression": True} 1579 1580 1581# national char, like n'utf8' 1582class National(Expression): 1583 pass 1584 1585 1586class LoadData(Expression): 1587 arg_types = { 1588 "this": True, 1589 "local": False, 1590 "overwrite": False, 1591 "inpath": True, 1592 "partition": False, 1593 "input_format": False, 1594 "serde": False, 1595 } 1596 1597 1598class Partition(Expression): 1599 arg_types = {"expressions": True} 1600 1601 1602class Fetch(Expression): 1603 arg_types = { 1604 "direction": False, 1605 "count": False, 1606 "percent": False, 1607 "with_ties": False, 1608 } 1609 1610 1611class Group(Expression): 1612 arg_types = { 1613 "expressions": False, 1614 "grouping_sets": False, 1615 "cube": False, 1616 "rollup": False, 1617 "totals": False, 1618 } 1619 1620 1621class Lambda(Expression): 1622 arg_types = {"this": True, "expressions": True} 1623 1624 1625class Limit(Expression): 1626 arg_types = {"this": False, "expression": True} 1627 1628 1629class Literal(Condition): 1630 arg_types = {"this": True, "is_string": True} 1631 1632 @property 1633 def hashable_args(self) -> t.Any: 1634 return (self.this, self.args.get("is_string")) 1635 1636 @classmethod 1637 def number(cls, number) -> Literal: 1638 return cls(this=str(number), is_string=False) 1639 1640 @classmethod 1641 def string(cls, string) -> Literal: 1642 return cls(this=str(string), is_string=True) 1643 1644 @property 1645 def output_name(self) -> str: 1646 return self.name 1647 1648 1649class Join(Expression): 1650 arg_types = { 1651 "this": True, 1652 "on": False, 1653 "side": False, 1654 "kind": False, 1655 "using": False, 1656 "method": False, 1657 "global": False, 1658 "hint": False, 1659 } 1660 1661 @property 1662 def method(self) -> str: 1663 return self.text("method").upper() 1664 1665 @property 1666 def kind(self) -> str: 1667 return self.text("kind").upper() 1668 1669 @property 1670 def side(self) -> str: 1671 return self.text("side").upper() 1672 1673 @property 1674 def hint(self) -> str: 1675 return self.text("hint").upper() 1676 1677 @property 1678 def alias_or_name(self) -> str: 1679 return self.this.alias_or_name 1680 1681 def on( 1682 self, 1683 *expressions: t.Optional[ExpOrStr], 1684 append: bool = True, 1685 dialect: DialectType = None, 1686 copy: bool = True, 1687 **opts, 1688 ) -> Join: 1689 """ 1690 Append to or set the ON expressions. 1691 1692 Example: 1693 >>> import sqlglot 1694 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1695 'JOIN x ON y = 1' 1696 1697 Args: 1698 *expressions: the SQL code strings to parse. 1699 If an `Expression` instance is passed, it will be used as-is. 1700 Multiple expressions are combined with an AND operator. 1701 append: if `True`, AND the new expressions to any existing expression. 1702 Otherwise, this resets the expression. 1703 dialect: the dialect used to parse the input expressions. 1704 copy: if `False`, modify this expression instance in-place. 1705 opts: other options to use to parse the input expressions. 1706 1707 Returns: 1708 The modified Join expression. 1709 """ 1710 join = _apply_conjunction_builder( 1711 *expressions, 1712 instance=self, 1713 arg="on", 1714 append=append, 1715 dialect=dialect, 1716 copy=copy, 1717 **opts, 1718 ) 1719 1720 if join.kind == "CROSS": 1721 join.set("kind", None) 1722 1723 return join 1724 1725 def using( 1726 self, 1727 *expressions: t.Optional[ExpOrStr], 1728 append: bool = True, 1729 dialect: DialectType = None, 1730 copy: bool = True, 1731 **opts, 1732 ) -> Join: 1733 """ 1734 Append to or set the USING expressions. 1735 1736 Example: 1737 >>> import sqlglot 1738 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1739 'JOIN x USING (foo, bla)' 1740 1741 Args: 1742 *expressions: the SQL code strings to parse. 1743 If an `Expression` instance is passed, it will be used as-is. 1744 append: if `True`, concatenate the new expressions to the existing "using" list. 1745 Otherwise, this resets the expression. 1746 dialect: the dialect used to parse the input expressions. 1747 copy: if `False`, modify this expression instance in-place. 1748 opts: other options to use to parse the input expressions. 1749 1750 Returns: 1751 The modified Join expression. 1752 """ 1753 join = _apply_list_builder( 1754 *expressions, 1755 instance=self, 1756 arg="using", 1757 append=append, 1758 dialect=dialect, 1759 copy=copy, 1760 **opts, 1761 ) 1762 1763 if join.kind == "CROSS": 1764 join.set("kind", None) 1765 1766 return join 1767 1768 1769class Lateral(UDTF): 1770 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1771 1772 1773class MatchRecognize(Expression): 1774 arg_types = { 1775 "partition_by": False, 1776 "order": False, 1777 "measures": False, 1778 "rows": False, 1779 "after": False, 1780 "pattern": False, 1781 "define": False, 1782 "alias": False, 1783 } 1784 1785 1786# Clickhouse FROM FINAL modifier 1787# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1788class Final(Expression): 1789 pass 1790 1791 1792class Offset(Expression): 1793 arg_types = {"this": False, "expression": True} 1794 1795 1796class Order(Expression): 1797 arg_types = {"this": False, "expressions": True} 1798 1799 1800# hive specific sorts 1801# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1802class Cluster(Order): 1803 pass 1804 1805 1806class Distribute(Order): 1807 pass 1808 1809 1810class Sort(Order): 1811 pass 1812 1813 1814class Ordered(Expression): 1815 arg_types = {"this": True, "desc": True, "nulls_first": True} 1816 1817 1818class Property(Expression): 1819 arg_types = {"this": True, "value": True} 1820 1821 1822class AlgorithmProperty(Property): 1823 arg_types = {"this": True} 1824 1825 1826class AutoIncrementProperty(Property): 1827 arg_types = {"this": True} 1828 1829 1830class BlockCompressionProperty(Property): 1831 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1832 1833 1834class CharacterSetProperty(Property): 1835 arg_types = {"this": True, "default": True} 1836 1837 1838class ChecksumProperty(Property): 1839 arg_types = {"on": False, "default": False} 1840 1841 1842class CollateProperty(Property): 1843 arg_types = {"this": True} 1844 1845 1846class DataBlocksizeProperty(Property): 1847 arg_types = { 1848 "size": False, 1849 "units": False, 1850 "minimum": False, 1851 "maximum": False, 1852 "default": False, 1853 } 1854 1855 1856class DefinerProperty(Property): 1857 arg_types = {"this": True} 1858 1859 1860class DistKeyProperty(Property): 1861 arg_types = {"this": True} 1862 1863 1864class DistStyleProperty(Property): 1865 arg_types = {"this": True} 1866 1867 1868class EngineProperty(Property): 1869 arg_types = {"this": True} 1870 1871 1872class ExecuteAsProperty(Property): 1873 arg_types = {"this": True} 1874 1875 1876class ExternalProperty(Property): 1877 arg_types = {"this": False} 1878 1879 1880class FallbackProperty(Property): 1881 arg_types = {"no": True, "protection": False} 1882 1883 1884class FileFormatProperty(Property): 1885 arg_types = {"this": True} 1886 1887 1888class FreespaceProperty(Property): 1889 arg_types = {"this": True, "percent": False} 1890 1891 1892class InputOutputFormat(Expression): 1893 arg_types = {"input_format": False, "output_format": False} 1894 1895 1896class IsolatedLoadingProperty(Property): 1897 arg_types = { 1898 "no": True, 1899 "concurrent": True, 1900 "for_all": True, 1901 "for_insert": True, 1902 "for_none": True, 1903 } 1904 1905 1906class JournalProperty(Property): 1907 arg_types = { 1908 "no": False, 1909 "dual": False, 1910 "before": False, 1911 "local": False, 1912 "after": False, 1913 } 1914 1915 1916class LanguageProperty(Property): 1917 arg_types = {"this": True} 1918 1919 1920class DictProperty(Property): 1921 arg_types = {"this": True, "kind": True, "settings": False} 1922 1923 1924class DictSubProperty(Property): 1925 pass 1926 1927 1928class DictRange(Property): 1929 arg_types = {"this": True, "min": True, "max": True} 1930 1931 1932# Clickhouse CREATE ... ON CLUSTER modifier 1933# https://clickhouse.com/docs/en/sql-reference/distributed-ddl 1934class OnCluster(Property): 1935 arg_types = {"this": True} 1936 1937 1938class LikeProperty(Property): 1939 arg_types = {"this": True, "expressions": False} 1940 1941 1942class LocationProperty(Property): 1943 arg_types = {"this": True} 1944 1945 1946class LockingProperty(Property): 1947 arg_types = { 1948 "this": False, 1949 "kind": True, 1950 "for_or_in": True, 1951 "lock_type": True, 1952 "override": False, 1953 } 1954 1955 1956class LogProperty(Property): 1957 arg_types = {"no": True} 1958 1959 1960class MaterializedProperty(Property): 1961 arg_types = {"this": False} 1962 1963 1964class MergeBlockRatioProperty(Property): 1965 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1966 1967 1968class NoPrimaryIndexProperty(Property): 1969 arg_types = {} 1970 1971 1972class OnCommitProperty(Property): 1973 arg_type = {"delete": False} 1974 1975 1976class PartitionedByProperty(Property): 1977 arg_types = {"this": True} 1978 1979 1980class ReturnsProperty(Property): 1981 arg_types = {"this": True, "is_table": False, "table": False} 1982 1983 1984class RowFormatProperty(Property): 1985 arg_types = {"this": True} 1986 1987 1988class RowFormatDelimitedProperty(Property): 1989 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1990 arg_types = { 1991 "fields": False, 1992 "escaped": False, 1993 "collection_items": False, 1994 "map_keys": False, 1995 "lines": False, 1996 "null": False, 1997 "serde": False, 1998 } 1999 2000 2001class RowFormatSerdeProperty(Property): 2002 arg_types = {"this": True} 2003 2004 2005class SchemaCommentProperty(Property): 2006 arg_types = {"this": True} 2007 2008 2009class SerdeProperties(Property): 2010 arg_types = {"expressions": True} 2011 2012 2013class SetProperty(Property): 2014 arg_types = {"multi": True} 2015 2016 2017class SettingsProperty(Property): 2018 arg_types = {"expressions": True} 2019 2020 2021class SortKeyProperty(Property): 2022 arg_types = {"this": True, "compound": False} 2023 2024 2025class SqlSecurityProperty(Property): 2026 arg_types = {"definer": True} 2027 2028 2029class StabilityProperty(Property): 2030 arg_types = {"this": True} 2031 2032 2033class TemporaryProperty(Property): 2034 arg_types = {} 2035 2036 2037class TransientProperty(Property): 2038 arg_types = {"this": False} 2039 2040 2041class VolatileProperty(Property): 2042 arg_types = {"this": False} 2043 2044 2045class WithDataProperty(Property): 2046 arg_types = {"no": True, "statistics": False} 2047 2048 2049class WithJournalTableProperty(Property): 2050 arg_types = {"this": True} 2051 2052 2053class Properties(Expression): 2054 arg_types = {"expressions": True} 2055 2056 NAME_TO_PROPERTY = { 2057 "ALGORITHM": AlgorithmProperty, 2058 "AUTO_INCREMENT": AutoIncrementProperty, 2059 "CHARACTER SET": CharacterSetProperty, 2060 "COLLATE": CollateProperty, 2061 "COMMENT": SchemaCommentProperty, 2062 "DEFINER": DefinerProperty, 2063 "DISTKEY": DistKeyProperty, 2064 "DISTSTYLE": DistStyleProperty, 2065 "ENGINE": EngineProperty, 2066 "EXECUTE AS": ExecuteAsProperty, 2067 "FORMAT": FileFormatProperty, 2068 "LANGUAGE": LanguageProperty, 2069 "LOCATION": LocationProperty, 2070 "PARTITIONED_BY": PartitionedByProperty, 2071 "RETURNS": ReturnsProperty, 2072 "ROW_FORMAT": RowFormatProperty, 2073 "SORTKEY": SortKeyProperty, 2074 } 2075 2076 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2077 2078 # CREATE property locations 2079 # Form: schema specified 2080 # create [POST_CREATE] 2081 # table a [POST_NAME] 2082 # (b int) [POST_SCHEMA] 2083 # with ([POST_WITH]) 2084 # index (b) [POST_INDEX] 2085 # 2086 # Form: alias selection 2087 # create [POST_CREATE] 2088 # table a [POST_NAME] 2089 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2090 # index (c) [POST_INDEX] 2091 class Location(AutoName): 2092 POST_CREATE = auto() 2093 POST_NAME = auto() 2094 POST_SCHEMA = auto() 2095 POST_WITH = auto() 2096 POST_ALIAS = auto() 2097 POST_EXPRESSION = auto() 2098 POST_INDEX = auto() 2099 UNSUPPORTED = auto() 2100 2101 @classmethod 2102 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2103 expressions = [] 2104 for key, value in properties_dict.items(): 2105 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2106 if property_cls: 2107 expressions.append(property_cls(this=convert(value))) 2108 else: 2109 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2110 2111 return cls(expressions=expressions) 2112 2113 2114class Qualify(Expression): 2115 pass 2116 2117 2118# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 2119class Return(Expression): 2120 pass 2121 2122 2123class Reference(Expression): 2124 arg_types = {"this": True, "expressions": False, "options": False} 2125 2126 2127class Tuple(Expression): 2128 arg_types = {"expressions": False} 2129 2130 def isin( 2131 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2132 ) -> In: 2133 return In( 2134 this=_maybe_copy(self, copy), 2135 expressions=[convert(e, copy=copy) for e in expressions], 2136 query=maybe_parse(query, copy=copy, **opts) if query else None, 2137 ) 2138 2139 2140class Subqueryable(Unionable): 2141 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2142 """ 2143 Convert this expression to an aliased expression that can be used as a Subquery. 2144 2145 Example: 2146 >>> subquery = Select().select("x").from_("tbl").subquery() 2147 >>> Select().select("x").from_(subquery).sql() 2148 'SELECT x FROM (SELECT x FROM tbl)' 2149 2150 Args: 2151 alias (str | Identifier): an optional alias for the subquery 2152 copy (bool): if `False`, modify this expression instance in-place. 2153 2154 Returns: 2155 Alias: the subquery 2156 """ 2157 instance = _maybe_copy(self, copy) 2158 if not isinstance(alias, Expression): 2159 alias = TableAlias(this=to_identifier(alias)) if alias else None 2160 2161 return Subquery(this=instance, alias=alias) 2162 2163 def limit( 2164 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2165 ) -> Select: 2166 raise NotImplementedError 2167 2168 @property 2169 def ctes(self): 2170 with_ = self.args.get("with") 2171 if not with_: 2172 return [] 2173 return with_.expressions 2174 2175 @property 2176 def selects(self): 2177 raise NotImplementedError("Subqueryable objects must implement `selects`") 2178 2179 @property 2180 def named_selects(self): 2181 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2182 2183 def with_( 2184 self, 2185 alias: ExpOrStr, 2186 as_: ExpOrStr, 2187 recursive: t.Optional[bool] = None, 2188 append: bool = True, 2189 dialect: DialectType = None, 2190 copy: bool = True, 2191 **opts, 2192 ) -> Subqueryable: 2193 """ 2194 Append to or set the common table expressions. 2195 2196 Example: 2197 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2198 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2199 2200 Args: 2201 alias: the SQL code string to parse as the table name. 2202 If an `Expression` instance is passed, this is used as-is. 2203 as_: the SQL code string to parse as the table expression. 2204 If an `Expression` instance is passed, it will be used as-is. 2205 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2206 append: if `True`, add to any existing expressions. 2207 Otherwise, this resets the expressions. 2208 dialect: the dialect used to parse the input expression. 2209 copy: if `False`, modify this expression instance in-place. 2210 opts: other options to use to parse the input expressions. 2211 2212 Returns: 2213 The modified expression. 2214 """ 2215 return _apply_cte_builder( 2216 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2217 ) 2218 2219 2220QUERY_MODIFIERS = { 2221 "match": False, 2222 "laterals": False, 2223 "joins": False, 2224 "pivots": False, 2225 "where": False, 2226 "group": False, 2227 "having": False, 2228 "qualify": False, 2229 "windows": False, 2230 "distribute": False, 2231 "sort": False, 2232 "cluster": False, 2233 "order": False, 2234 "limit": False, 2235 "offset": False, 2236 "locks": False, 2237 "sample": False, 2238 "settings": False, 2239 "format": False, 2240} 2241 2242 2243class Table(Expression): 2244 arg_types = { 2245 "this": True, 2246 "alias": False, 2247 "db": False, 2248 "catalog": False, 2249 "laterals": False, 2250 "joins": False, 2251 "pivots": False, 2252 "hints": False, 2253 "system_time": False, 2254 } 2255 2256 @property 2257 def db(self) -> str: 2258 return self.text("db") 2259 2260 @property 2261 def catalog(self) -> str: 2262 return self.text("catalog") 2263 2264 @property 2265 def parts(self) -> t.List[Identifier]: 2266 """Return the parts of a table in order catalog, db, table.""" 2267 return [ 2268 t.cast(Identifier, self.args[part]) 2269 for part in ("catalog", "db", "this") 2270 if self.args.get(part) 2271 ] 2272 2273 2274# See the TSQL "Querying data in a system-versioned temporal table" page 2275class SystemTime(Expression): 2276 arg_types = { 2277 "this": False, 2278 "expression": False, 2279 "kind": True, 2280 } 2281 2282 2283class Union(Subqueryable): 2284 arg_types = { 2285 "with": False, 2286 "this": True, 2287 "expression": True, 2288 "distinct": False, 2289 **QUERY_MODIFIERS, 2290 } 2291 2292 def limit( 2293 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2294 ) -> Select: 2295 """ 2296 Set the LIMIT expression. 2297 2298 Example: 2299 >>> select("1").union(select("1")).limit(1).sql() 2300 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2301 2302 Args: 2303 expression: the SQL code string to parse. 2304 This can also be an integer. 2305 If a `Limit` instance is passed, this is used as-is. 2306 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2307 dialect: the dialect used to parse the input expression. 2308 copy: if `False`, modify this expression instance in-place. 2309 opts: other options to use to parse the input expressions. 2310 2311 Returns: 2312 The limited subqueryable. 2313 """ 2314 return ( 2315 select("*") 2316 .from_(self.subquery(alias="_l_0", copy=copy)) 2317 .limit(expression, dialect=dialect, copy=False, **opts) 2318 ) 2319 2320 def select( 2321 self, 2322 *expressions: t.Optional[ExpOrStr], 2323 append: bool = True, 2324 dialect: DialectType = None, 2325 copy: bool = True, 2326 **opts, 2327 ) -> Union: 2328 """Append to or set the SELECT of the union recursively. 2329 2330 Example: 2331 >>> from sqlglot import parse_one 2332 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2333 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2334 2335 Args: 2336 *expressions: the SQL code strings to parse. 2337 If an `Expression` instance is passed, it will be used as-is. 2338 append: if `True`, add to any existing expressions. 2339 Otherwise, this resets the expressions. 2340 dialect: the dialect used to parse the input expressions. 2341 copy: if `False`, modify this expression instance in-place. 2342 opts: other options to use to parse the input expressions. 2343 2344 Returns: 2345 Union: the modified expression. 2346 """ 2347 this = self.copy() if copy else self 2348 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2349 this.expression.unnest().select( 2350 *expressions, append=append, dialect=dialect, copy=False, **opts 2351 ) 2352 return this 2353 2354 @property 2355 def named_selects(self): 2356 return self.this.unnest().named_selects 2357 2358 @property 2359 def is_star(self) -> bool: 2360 return self.this.is_star or self.expression.is_star 2361 2362 @property 2363 def selects(self): 2364 return self.this.unnest().selects 2365 2366 @property 2367 def left(self): 2368 return self.this 2369 2370 @property 2371 def right(self): 2372 return self.expression 2373 2374 2375class Except(Union): 2376 pass 2377 2378 2379class Intersect(Union): 2380 pass 2381 2382 2383class Unnest(UDTF): 2384 arg_types = { 2385 "expressions": True, 2386 "ordinality": False, 2387 "alias": False, 2388 "offset": False, 2389 } 2390 2391 2392class Update(Expression): 2393 arg_types = { 2394 "with": False, 2395 "this": False, 2396 "expressions": True, 2397 "from": False, 2398 "where": False, 2399 "returning": False, 2400 } 2401 2402 2403class Values(UDTF): 2404 arg_types = { 2405 "expressions": True, 2406 "ordinality": False, 2407 "alias": False, 2408 } 2409 2410 2411class Var(Expression): 2412 pass 2413 2414 2415class Schema(Expression): 2416 arg_types = {"this": False, "expressions": False} 2417 2418 2419# https://dev.mysql.com/doc/refman/8.0/en/select.html 2420# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html 2421class Lock(Expression): 2422 arg_types = {"update": True, "expressions": False, "wait": False} 2423 2424 2425class Select(Subqueryable): 2426 arg_types = { 2427 "with": False, 2428 "kind": False, 2429 "expressions": False, 2430 "hint": False, 2431 "distinct": False, 2432 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2433 "value": False, 2434 "into": False, 2435 "from": False, 2436 **QUERY_MODIFIERS, 2437 } 2438 2439 def from_( 2440 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2441 ) -> Select: 2442 """ 2443 Set the FROM expression. 2444 2445 Example: 2446 >>> Select().from_("tbl").select("x").sql() 2447 'SELECT x FROM tbl' 2448 2449 Args: 2450 expression : the SQL code strings to parse. 2451 If a `From` instance is passed, this is used as-is. 2452 If another `Expression` instance is passed, it will be wrapped in a `From`. 2453 dialect: the dialect used to parse the input expression. 2454 copy: if `False`, modify this expression instance in-place. 2455 opts: other options to use to parse the input expressions. 2456 2457 Returns: 2458 The modified Select expression. 2459 """ 2460 return _apply_builder( 2461 expression=expression, 2462 instance=self, 2463 arg="from", 2464 into=From, 2465 prefix="FROM", 2466 dialect=dialect, 2467 copy=copy, 2468 **opts, 2469 ) 2470 2471 def group_by( 2472 self, 2473 *expressions: t.Optional[ExpOrStr], 2474 append: bool = True, 2475 dialect: DialectType = None, 2476 copy: bool = True, 2477 **opts, 2478 ) -> Select: 2479 """ 2480 Set the GROUP BY expression. 2481 2482 Example: 2483 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2484 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2485 2486 Args: 2487 *expressions: the SQL code strings to parse. 2488 If a `Group` instance is passed, this is used as-is. 2489 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2490 If nothing is passed in then a group by is not applied to the expression 2491 append: if `True`, add to any existing expressions. 2492 Otherwise, this flattens all the `Group` expression into a single expression. 2493 dialect: the dialect used to parse the input expression. 2494 copy: if `False`, modify this expression instance in-place. 2495 opts: other options to use to parse the input expressions. 2496 2497 Returns: 2498 The modified Select expression. 2499 """ 2500 if not expressions: 2501 return self if not copy else self.copy() 2502 2503 return _apply_child_list_builder( 2504 *expressions, 2505 instance=self, 2506 arg="group", 2507 append=append, 2508 copy=copy, 2509 prefix="GROUP BY", 2510 into=Group, 2511 dialect=dialect, 2512 **opts, 2513 ) 2514 2515 def order_by( 2516 self, 2517 *expressions: t.Optional[ExpOrStr], 2518 append: bool = True, 2519 dialect: DialectType = None, 2520 copy: bool = True, 2521 **opts, 2522 ) -> Select: 2523 """ 2524 Set the ORDER BY expression. 2525 2526 Example: 2527 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2528 'SELECT x FROM tbl ORDER BY x DESC' 2529 2530 Args: 2531 *expressions: the SQL code strings to parse. 2532 If a `Group` instance is passed, this is used as-is. 2533 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2534 append: if `True`, add to any existing expressions. 2535 Otherwise, this flattens all the `Order` expression into a single expression. 2536 dialect: the dialect used to parse the input expression. 2537 copy: if `False`, modify this expression instance in-place. 2538 opts: other options to use to parse the input expressions. 2539 2540 Returns: 2541 The modified Select expression. 2542 """ 2543 return _apply_child_list_builder( 2544 *expressions, 2545 instance=self, 2546 arg="order", 2547 append=append, 2548 copy=copy, 2549 prefix="ORDER BY", 2550 into=Order, 2551 dialect=dialect, 2552 **opts, 2553 ) 2554 2555 def sort_by( 2556 self, 2557 *expressions: t.Optional[ExpOrStr], 2558 append: bool = True, 2559 dialect: DialectType = None, 2560 copy: bool = True, 2561 **opts, 2562 ) -> Select: 2563 """ 2564 Set the SORT BY expression. 2565 2566 Example: 2567 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2568 'SELECT x FROM tbl SORT BY x DESC' 2569 2570 Args: 2571 *expressions: the SQL code strings to parse. 2572 If a `Group` instance is passed, this is used as-is. 2573 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2574 append: if `True`, add to any existing expressions. 2575 Otherwise, this flattens all the `Order` expression into a single expression. 2576 dialect: the dialect used to parse the input expression. 2577 copy: if `False`, modify this expression instance in-place. 2578 opts: other options to use to parse the input expressions. 2579 2580 Returns: 2581 The modified Select expression. 2582 """ 2583 return _apply_child_list_builder( 2584 *expressions, 2585 instance=self, 2586 arg="sort", 2587 append=append, 2588 copy=copy, 2589 prefix="SORT BY", 2590 into=Sort, 2591 dialect=dialect, 2592 **opts, 2593 ) 2594 2595 def cluster_by( 2596 self, 2597 *expressions: t.Optional[ExpOrStr], 2598 append: bool = True, 2599 dialect: DialectType = None, 2600 copy: bool = True, 2601 **opts, 2602 ) -> Select: 2603 """ 2604 Set the CLUSTER BY expression. 2605 2606 Example: 2607 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2608 'SELECT x FROM tbl CLUSTER BY x DESC' 2609 2610 Args: 2611 *expressions: the SQL code strings to parse. 2612 If a `Group` instance is passed, this is used as-is. 2613 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2614 append: if `True`, add to any existing expressions. 2615 Otherwise, this flattens all the `Order` expression into a single expression. 2616 dialect: the dialect used to parse the input expression. 2617 copy: if `False`, modify this expression instance in-place. 2618 opts: other options to use to parse the input expressions. 2619 2620 Returns: 2621 The modified Select expression. 2622 """ 2623 return _apply_child_list_builder( 2624 *expressions, 2625 instance=self, 2626 arg="cluster", 2627 append=append, 2628 copy=copy, 2629 prefix="CLUSTER BY", 2630 into=Cluster, 2631 dialect=dialect, 2632 **opts, 2633 ) 2634 2635 def limit( 2636 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2637 ) -> Select: 2638 """ 2639 Set the LIMIT expression. 2640 2641 Example: 2642 >>> Select().from_("tbl").select("x").limit(10).sql() 2643 'SELECT x FROM tbl LIMIT 10' 2644 2645 Args: 2646 expression: the SQL code string to parse. 2647 This can also be an integer. 2648 If a `Limit` instance is passed, this is used as-is. 2649 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2650 dialect: the dialect used to parse the input expression. 2651 copy: if `False`, modify this expression instance in-place. 2652 opts: other options to use to parse the input expressions. 2653 2654 Returns: 2655 Select: the modified expression. 2656 """ 2657 return _apply_builder( 2658 expression=expression, 2659 instance=self, 2660 arg="limit", 2661 into=Limit, 2662 prefix="LIMIT", 2663 dialect=dialect, 2664 copy=copy, 2665 **opts, 2666 ) 2667 2668 def offset( 2669 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2670 ) -> Select: 2671 """ 2672 Set the OFFSET expression. 2673 2674 Example: 2675 >>> Select().from_("tbl").select("x").offset(10).sql() 2676 'SELECT x FROM tbl OFFSET 10' 2677 2678 Args: 2679 expression: the SQL code string to parse. 2680 This can also be an integer. 2681 If a `Offset` instance is passed, this is used as-is. 2682 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2683 dialect: the dialect used to parse the input expression. 2684 copy: if `False`, modify this expression instance in-place. 2685 opts: other options to use to parse the input expressions. 2686 2687 Returns: 2688 The modified Select expression. 2689 """ 2690 return _apply_builder( 2691 expression=expression, 2692 instance=self, 2693 arg="offset", 2694 into=Offset, 2695 prefix="OFFSET", 2696 dialect=dialect, 2697 copy=copy, 2698 **opts, 2699 ) 2700 2701 def select( 2702 self, 2703 *expressions: t.Optional[ExpOrStr], 2704 append: bool = True, 2705 dialect: DialectType = None, 2706 copy: bool = True, 2707 **opts, 2708 ) -> Select: 2709 """ 2710 Append to or set the SELECT expressions. 2711 2712 Example: 2713 >>> Select().select("x", "y").sql() 2714 'SELECT x, y' 2715 2716 Args: 2717 *expressions: the SQL code strings to parse. 2718 If an `Expression` instance is passed, it will be used as-is. 2719 append: if `True`, add to any existing expressions. 2720 Otherwise, this resets the expressions. 2721 dialect: the dialect used to parse the input expressions. 2722 copy: if `False`, modify this expression instance in-place. 2723 opts: other options to use to parse the input expressions. 2724 2725 Returns: 2726 The modified Select expression. 2727 """ 2728 return _apply_list_builder( 2729 *expressions, 2730 instance=self, 2731 arg="expressions", 2732 append=append, 2733 dialect=dialect, 2734 copy=copy, 2735 **opts, 2736 ) 2737 2738 def lateral( 2739 self, 2740 *expressions: t.Optional[ExpOrStr], 2741 append: bool = True, 2742 dialect: DialectType = None, 2743 copy: bool = True, 2744 **opts, 2745 ) -> Select: 2746 """ 2747 Append to or set the LATERAL expressions. 2748 2749 Example: 2750 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2751 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2752 2753 Args: 2754 *expressions: the SQL code strings to parse. 2755 If an `Expression` instance is passed, it will be used as-is. 2756 append: if `True`, add to any existing expressions. 2757 Otherwise, this resets the expressions. 2758 dialect: the dialect used to parse the input expressions. 2759 copy: if `False`, modify this expression instance in-place. 2760 opts: other options to use to parse the input expressions. 2761 2762 Returns: 2763 The modified Select expression. 2764 """ 2765 return _apply_list_builder( 2766 *expressions, 2767 instance=self, 2768 arg="laterals", 2769 append=append, 2770 into=Lateral, 2771 prefix="LATERAL VIEW", 2772 dialect=dialect, 2773 copy=copy, 2774 **opts, 2775 ) 2776 2777 def join( 2778 self, 2779 expression: ExpOrStr, 2780 on: t.Optional[ExpOrStr] = None, 2781 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2782 append: bool = True, 2783 join_type: t.Optional[str] = None, 2784 join_alias: t.Optional[Identifier | str] = None, 2785 dialect: DialectType = None, 2786 copy: bool = True, 2787 **opts, 2788 ) -> Select: 2789 """ 2790 Append to or set the JOIN expressions. 2791 2792 Example: 2793 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2794 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2795 2796 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2797 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2798 2799 Use `join_type` to change the type of join: 2800 2801 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2802 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2803 2804 Args: 2805 expression: the SQL code string to parse. 2806 If an `Expression` instance is passed, it will be used as-is. 2807 on: optionally specify the join "on" criteria as a SQL string. 2808 If an `Expression` instance is passed, it will be used as-is. 2809 using: optionally specify the join "using" criteria as a SQL string. 2810 If an `Expression` instance is passed, it will be used as-is. 2811 append: if `True`, add to any existing expressions. 2812 Otherwise, this resets the expressions. 2813 join_type: if set, alter the parsed join type. 2814 join_alias: an optional alias for the joined source. 2815 dialect: the dialect used to parse the input expressions. 2816 copy: if `False`, modify this expression instance in-place. 2817 opts: other options to use to parse the input expressions. 2818 2819 Returns: 2820 Select: the modified expression. 2821 """ 2822 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2823 2824 try: 2825 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2826 except ParseError: 2827 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2828 2829 join = expression if isinstance(expression, Join) else Join(this=expression) 2830 2831 if isinstance(join.this, Select): 2832 join.this.replace(join.this.subquery()) 2833 2834 if join_type: 2835 method: t.Optional[Token] 2836 side: t.Optional[Token] 2837 kind: t.Optional[Token] 2838 2839 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2840 2841 if method: 2842 join.set("method", method.text) 2843 if side: 2844 join.set("side", side.text) 2845 if kind: 2846 join.set("kind", kind.text) 2847 2848 if on: 2849 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2850 join.set("on", on) 2851 2852 if using: 2853 join = _apply_list_builder( 2854 *ensure_list(using), 2855 instance=join, 2856 arg="using", 2857 append=append, 2858 copy=copy, 2859 **opts, 2860 ) 2861 2862 if join_alias: 2863 join.set("this", alias_(join.this, join_alias, table=True)) 2864 2865 return _apply_list_builder( 2866 join, 2867 instance=self, 2868 arg="joins", 2869 append=append, 2870 copy=copy, 2871 **opts, 2872 ) 2873 2874 def where( 2875 self, 2876 *expressions: t.Optional[ExpOrStr], 2877 append: bool = True, 2878 dialect: DialectType = None, 2879 copy: bool = True, 2880 **opts, 2881 ) -> Select: 2882 """ 2883 Append to or set the WHERE expressions. 2884 2885 Example: 2886 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2887 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2888 2889 Args: 2890 *expressions: the SQL code strings to parse. 2891 If an `Expression` instance is passed, it will be used as-is. 2892 Multiple expressions are combined with an AND operator. 2893 append: if `True`, AND the new expressions to any existing expression. 2894 Otherwise, this resets the expression. 2895 dialect: the dialect used to parse the input expressions. 2896 copy: if `False`, modify this expression instance in-place. 2897 opts: other options to use to parse the input expressions. 2898 2899 Returns: 2900 Select: the modified expression. 2901 """ 2902 return _apply_conjunction_builder( 2903 *expressions, 2904 instance=self, 2905 arg="where", 2906 append=append, 2907 into=Where, 2908 dialect=dialect, 2909 copy=copy, 2910 **opts, 2911 ) 2912 2913 def having( 2914 self, 2915 *expressions: t.Optional[ExpOrStr], 2916 append: bool = True, 2917 dialect: DialectType = None, 2918 copy: bool = True, 2919 **opts, 2920 ) -> Select: 2921 """ 2922 Append to or set the HAVING expressions. 2923 2924 Example: 2925 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2926 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2927 2928 Args: 2929 *expressions: the SQL code strings to parse. 2930 If an `Expression` instance is passed, it will be used as-is. 2931 Multiple expressions are combined with an AND operator. 2932 append: if `True`, AND the new expressions to any existing expression. 2933 Otherwise, this resets the expression. 2934 dialect: the dialect used to parse the input expressions. 2935 copy: if `False`, modify this expression instance in-place. 2936 opts: other options to use to parse the input expressions. 2937 2938 Returns: 2939 The modified Select expression. 2940 """ 2941 return _apply_conjunction_builder( 2942 *expressions, 2943 instance=self, 2944 arg="having", 2945 append=append, 2946 into=Having, 2947 dialect=dialect, 2948 copy=copy, 2949 **opts, 2950 ) 2951 2952 def window( 2953 self, 2954 *expressions: t.Optional[ExpOrStr], 2955 append: bool = True, 2956 dialect: DialectType = None, 2957 copy: bool = True, 2958 **opts, 2959 ) -> Select: 2960 return _apply_list_builder( 2961 *expressions, 2962 instance=self, 2963 arg="windows", 2964 append=append, 2965 into=Window, 2966 dialect=dialect, 2967 copy=copy, 2968 **opts, 2969 ) 2970 2971 def qualify( 2972 self, 2973 *expressions: t.Optional[ExpOrStr], 2974 append: bool = True, 2975 dialect: DialectType = None, 2976 copy: bool = True, 2977 **opts, 2978 ) -> Select: 2979 return _apply_conjunction_builder( 2980 *expressions, 2981 instance=self, 2982 arg="qualify", 2983 append=append, 2984 into=Qualify, 2985 dialect=dialect, 2986 copy=copy, 2987 **opts, 2988 ) 2989 2990 def distinct( 2991 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2992 ) -> Select: 2993 """ 2994 Set the OFFSET expression. 2995 2996 Example: 2997 >>> Select().from_("tbl").select("x").distinct().sql() 2998 'SELECT DISTINCT x FROM tbl' 2999 3000 Args: 3001 ons: the expressions to distinct on 3002 distinct: whether the Select should be distinct 3003 copy: if `False`, modify this expression instance in-place. 3004 3005 Returns: 3006 Select: the modified expression. 3007 """ 3008 instance = _maybe_copy(self, copy) 3009 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3010 instance.set("distinct", Distinct(on=on) if distinct else None) 3011 return instance 3012 3013 def ctas( 3014 self, 3015 table: ExpOrStr, 3016 properties: t.Optional[t.Dict] = None, 3017 dialect: DialectType = None, 3018 copy: bool = True, 3019 **opts, 3020 ) -> Create: 3021 """ 3022 Convert this expression to a CREATE TABLE AS statement. 3023 3024 Example: 3025 >>> Select().select("*").from_("tbl").ctas("x").sql() 3026 'CREATE TABLE x AS SELECT * FROM tbl' 3027 3028 Args: 3029 table: the SQL code string to parse as the table name. 3030 If another `Expression` instance is passed, it will be used as-is. 3031 properties: an optional mapping of table properties 3032 dialect: the dialect used to parse the input table. 3033 copy: if `False`, modify this expression instance in-place. 3034 opts: other options to use to parse the input table. 3035 3036 Returns: 3037 The new Create expression. 3038 """ 3039 instance = _maybe_copy(self, copy) 3040 table_expression = maybe_parse( 3041 table, 3042 into=Table, 3043 dialect=dialect, 3044 **opts, 3045 ) 3046 properties_expression = None 3047 if properties: 3048 properties_expression = Properties.from_dict(properties) 3049 3050 return Create( 3051 this=table_expression, 3052 kind="table", 3053 expression=instance, 3054 properties=properties_expression, 3055 ) 3056 3057 def lock(self, update: bool = True, copy: bool = True) -> Select: 3058 """ 3059 Set the locking read mode for this expression. 3060 3061 Examples: 3062 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3063 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3064 3065 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3066 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3067 3068 Args: 3069 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3070 copy: if `False`, modify this expression instance in-place. 3071 3072 Returns: 3073 The modified expression. 3074 """ 3075 3076 inst = _maybe_copy(self, copy) 3077 inst.set("locks", [Lock(update=update)]) 3078 3079 return inst 3080 3081 @property 3082 def named_selects(self) -> t.List[str]: 3083 return [e.output_name for e in self.expressions if e.alias_or_name] 3084 3085 @property 3086 def is_star(self) -> bool: 3087 return any(expression.is_star for expression in self.expressions) 3088 3089 @property 3090 def selects(self) -> t.List[Expression]: 3091 return self.expressions 3092 3093 3094class Subquery(DerivedTable, Unionable): 3095 arg_types = { 3096 "this": True, 3097 "alias": False, 3098 "with": False, 3099 **QUERY_MODIFIERS, 3100 } 3101 3102 def unnest(self): 3103 """ 3104 Returns the first non subquery. 3105 """ 3106 expression = self 3107 while isinstance(expression, Subquery): 3108 expression = expression.this 3109 return expression 3110 3111 @property 3112 def is_star(self) -> bool: 3113 return self.this.is_star 3114 3115 @property 3116 def output_name(self) -> str: 3117 return self.alias 3118 3119 3120class TableSample(Expression): 3121 arg_types = { 3122 "this": False, 3123 "method": False, 3124 "bucket_numerator": False, 3125 "bucket_denominator": False, 3126 "bucket_field": False, 3127 "percent": False, 3128 "rows": False, 3129 "size": False, 3130 "seed": False, 3131 "kind": False, 3132 } 3133 3134 3135class Tag(Expression): 3136 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3137 3138 arg_types = { 3139 "this": False, 3140 "prefix": False, 3141 "postfix": False, 3142 } 3143 3144 3145# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax 3146# https://duckdb.org/docs/sql/statements/pivot 3147class Pivot(Expression): 3148 arg_types = { 3149 "this": False, 3150 "alias": False, 3151 "expressions": True, 3152 "field": False, 3153 "unpivot": False, 3154 "using": False, 3155 "group": False, 3156 "columns": False, 3157 } 3158 3159 3160class Window(Expression): 3161 arg_types = { 3162 "this": True, 3163 "partition_by": False, 3164 "order": False, 3165 "spec": False, 3166 "alias": False, 3167 "over": False, 3168 "first": False, 3169 } 3170 3171 3172class WindowSpec(Expression): 3173 arg_types = { 3174 "kind": False, 3175 "start": False, 3176 "start_side": False, 3177 "end": False, 3178 "end_side": False, 3179 } 3180 3181 3182class Where(Expression): 3183 pass 3184 3185 3186class Star(Expression): 3187 arg_types = {"except": False, "replace": False} 3188 3189 @property 3190 def name(self) -> str: 3191 return "*" 3192 3193 @property 3194 def output_name(self) -> str: 3195 return self.name 3196 3197 3198class Parameter(Expression): 3199 arg_types = {"this": True, "wrapped": False} 3200 3201 3202class SessionParameter(Expression): 3203 arg_types = {"this": True, "kind": False} 3204 3205 3206class Placeholder(Expression): 3207 arg_types = {"this": False, "kind": False} 3208 3209 3210class Null(Condition): 3211 arg_types: t.Dict[str, t.Any] = {} 3212 3213 @property 3214 def name(self) -> str: 3215 return "NULL" 3216 3217 3218class Boolean(Condition): 3219 pass 3220 3221 3222class DataTypeSize(Expression): 3223 arg_types = {"this": True, "expression": False} 3224 3225 3226class DataType(Expression): 3227 arg_types = { 3228 "this": True, 3229 "expressions": False, 3230 "nested": False, 3231 "values": False, 3232 "prefix": False, 3233 } 3234 3235 class Type(AutoName): 3236 ARRAY = auto() 3237 BIGDECIMAL = auto() 3238 BIGINT = auto() 3239 BIGSERIAL = auto() 3240 BINARY = auto() 3241 BIT = auto() 3242 BOOLEAN = auto() 3243 CHAR = auto() 3244 DATE = auto() 3245 DATETIME = auto() 3246 DATETIME64 = auto() 3247 INT4RANGE = auto() 3248 INT4MULTIRANGE = auto() 3249 INT8RANGE = auto() 3250 INT8MULTIRANGE = auto() 3251 NUMRANGE = auto() 3252 NUMMULTIRANGE = auto() 3253 TSRANGE = auto() 3254 TSMULTIRANGE = auto() 3255 TSTZRANGE = auto() 3256 TSTZMULTIRANGE = auto() 3257 DATERANGE = auto() 3258 DATEMULTIRANGE = auto() 3259 DECIMAL = auto() 3260 DOUBLE = auto() 3261 FLOAT = auto() 3262 GEOGRAPHY = auto() 3263 GEOMETRY = auto() 3264 HLLSKETCH = auto() 3265 HSTORE = auto() 3266 IMAGE = auto() 3267 INET = auto() 3268 INT = auto() 3269 INT128 = auto() 3270 INT256 = auto() 3271 INTERVAL = auto() 3272 JSON = auto() 3273 JSONB = auto() 3274 LONGBLOB = auto() 3275 LONGTEXT = auto() 3276 MAP = auto() 3277 MEDIUMBLOB = auto() 3278 MEDIUMTEXT = auto() 3279 MONEY = auto() 3280 NCHAR = auto() 3281 NULL = auto() 3282 NULLABLE = auto() 3283 NVARCHAR = auto() 3284 OBJECT = auto() 3285 ROWVERSION = auto() 3286 SERIAL = auto() 3287 SMALLINT = auto() 3288 SMALLMONEY = auto() 3289 SMALLSERIAL = auto() 3290 STRUCT = auto() 3291 SUPER = auto() 3292 TEXT = auto() 3293 TIME = auto() 3294 TIMESTAMP = auto() 3295 TIMESTAMPTZ = auto() 3296 TIMESTAMPLTZ = auto() 3297 TINYINT = auto() 3298 UBIGINT = auto() 3299 UINT = auto() 3300 USMALLINT = auto() 3301 UTINYINT = auto() 3302 UNKNOWN = auto() # Sentinel value, useful for type annotation 3303 UINT128 = auto() 3304 UINT256 = auto() 3305 UNIQUEIDENTIFIER = auto() 3306 UUID = auto() 3307 VARBINARY = auto() 3308 VARCHAR = auto() 3309 VARIANT = auto() 3310 XML = auto() 3311 3312 TEXT_TYPES = { 3313 Type.CHAR, 3314 Type.NCHAR, 3315 Type.VARCHAR, 3316 Type.NVARCHAR, 3317 Type.TEXT, 3318 } 3319 3320 INTEGER_TYPES = { 3321 Type.INT, 3322 Type.TINYINT, 3323 Type.SMALLINT, 3324 Type.BIGINT, 3325 Type.INT128, 3326 Type.INT256, 3327 } 3328 3329 FLOAT_TYPES = { 3330 Type.FLOAT, 3331 Type.DOUBLE, 3332 } 3333 3334 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3335 3336 TEMPORAL_TYPES = { 3337 Type.TIMESTAMP, 3338 Type.TIMESTAMPTZ, 3339 Type.TIMESTAMPLTZ, 3340 Type.DATE, 3341 Type.DATETIME, 3342 Type.DATETIME64, 3343 } 3344 3345 @classmethod 3346 def build( 3347 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3348 ) -> DataType: 3349 from sqlglot import parse_one 3350 3351 if isinstance(dtype, str): 3352 if dtype.upper() in cls.Type.__members__: 3353 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3354 else: 3355 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3356 3357 if data_type_exp is None: 3358 raise ValueError(f"Unparsable data type value: {dtype}") 3359 elif isinstance(dtype, DataType.Type): 3360 data_type_exp = DataType(this=dtype) 3361 elif isinstance(dtype, DataType): 3362 return dtype 3363 else: 3364 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3365 3366 return DataType(**{**data_type_exp.args, **kwargs}) 3367 3368 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3369 return any(self.this == DataType.build(dtype).this for dtype in dtypes) 3370 3371 3372# https://www.postgresql.org/docs/15/datatype-pseudo.html 3373class PseudoType(Expression): 3374 pass 3375 3376 3377# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 3378class SubqueryPredicate(Predicate): 3379 pass 3380 3381 3382class All(SubqueryPredicate): 3383 pass 3384 3385 3386class Any(SubqueryPredicate): 3387 pass 3388 3389 3390class Exists(SubqueryPredicate): 3391 pass 3392 3393 3394# Commands to interact with the databases or engines. For most of the command 3395# expressions we parse whatever comes after the command's name as a string. 3396class Command(Expression): 3397 arg_types = {"this": True, "expression": False} 3398 3399 3400class Transaction(Expression): 3401 arg_types = {"this": False, "modes": False} 3402 3403 3404class Commit(Expression): 3405 arg_types = {"chain": False} 3406 3407 3408class Rollback(Expression): 3409 arg_types = {"savepoint": False} 3410 3411 3412class AlterTable(Expression): 3413 arg_types = {"this": True, "actions": True, "exists": False} 3414 3415 3416class AddConstraint(Expression): 3417 arg_types = {"this": False, "expression": False, "enforced": False} 3418 3419 3420class DropPartition(Expression): 3421 arg_types = {"expressions": True, "exists": False} 3422 3423 3424# Binary expressions like (ADD a b) 3425class Binary(Condition): 3426 arg_types = {"this": True, "expression": True} 3427 3428 @property 3429 def left(self): 3430 return self.this 3431 3432 @property 3433 def right(self): 3434 return self.expression 3435 3436 3437class Add(Binary): 3438 pass 3439 3440 3441class Connector(Binary): 3442 pass 3443 3444 3445class And(Connector): 3446 pass 3447 3448 3449class Or(Connector): 3450 pass 3451 3452 3453class BitwiseAnd(Binary): 3454 pass 3455 3456 3457class BitwiseLeftShift(Binary): 3458 pass 3459 3460 3461class BitwiseOr(Binary): 3462 pass 3463 3464 3465class BitwiseRightShift(Binary): 3466 pass 3467 3468 3469class BitwiseXor(Binary): 3470 pass 3471 3472 3473class Div(Binary): 3474 pass 3475 3476 3477class Overlaps(Binary): 3478 pass 3479 3480 3481class Dot(Binary): 3482 @property 3483 def name(self) -> str: 3484 return self.expression.name 3485 3486 @classmethod 3487 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3488 """Build a Dot object with a sequence of expressions.""" 3489 if len(expressions) < 2: 3490 raise ValueError(f"Dot requires >= 2 expressions.") 3491 3492 a, b, *expressions = expressions 3493 dot = Dot(this=a, expression=b) 3494 3495 for expression in expressions: 3496 dot = Dot(this=dot, expression=expression) 3497 3498 return dot 3499 3500 3501class DPipe(Binary): 3502 pass 3503 3504 3505class EQ(Binary, Predicate): 3506 pass 3507 3508 3509class NullSafeEQ(Binary, Predicate): 3510 pass 3511 3512 3513class NullSafeNEQ(Binary, Predicate): 3514 pass 3515 3516 3517class Distance(Binary): 3518 pass 3519 3520 3521class Escape(Binary): 3522 pass 3523 3524 3525class Glob(Binary, Predicate): 3526 pass 3527 3528 3529class GT(Binary, Predicate): 3530 pass 3531 3532 3533class GTE(Binary, Predicate): 3534 pass 3535 3536 3537class ILike(Binary, Predicate): 3538 pass 3539 3540 3541class ILikeAny(Binary, Predicate): 3542 pass 3543 3544 3545class IntDiv(Binary): 3546 pass 3547 3548 3549class Is(Binary, Predicate): 3550 pass 3551 3552 3553class Kwarg(Binary): 3554 """Kwarg in special functions like func(kwarg => y).""" 3555 3556 3557class Like(Binary, Predicate): 3558 pass 3559 3560 3561class LikeAny(Binary, Predicate): 3562 pass 3563 3564 3565class LT(Binary, Predicate): 3566 pass 3567 3568 3569class LTE(Binary, Predicate): 3570 pass 3571 3572 3573class Mod(Binary): 3574 pass 3575 3576 3577class Mul(Binary): 3578 pass 3579 3580 3581class NEQ(Binary, Predicate): 3582 pass 3583 3584 3585class SimilarTo(Binary, Predicate): 3586 pass 3587 3588 3589class Slice(Binary): 3590 arg_types = {"this": False, "expression": False} 3591 3592 3593class Sub(Binary): 3594 pass 3595 3596 3597class ArrayOverlaps(Binary): 3598 pass 3599 3600 3601# Unary Expressions 3602# (NOT a) 3603class Unary(Condition): 3604 pass 3605 3606 3607class BitwiseNot(Unary): 3608 pass 3609 3610 3611class Not(Unary): 3612 pass 3613 3614 3615class Paren(Unary): 3616 arg_types = {"this": True, "with": False} 3617 3618 3619class Neg(Unary): 3620 pass 3621 3622 3623class Alias(Expression): 3624 arg_types = {"this": True, "alias": False} 3625 3626 @property 3627 def output_name(self) -> str: 3628 return self.alias 3629 3630 3631class Aliases(Expression): 3632 arg_types = {"this": True, "expressions": True} 3633 3634 @property 3635 def aliases(self): 3636 return self.expressions 3637 3638 3639class AtTimeZone(Expression): 3640 arg_types = {"this": True, "zone": True} 3641 3642 3643class Between(Predicate): 3644 arg_types = {"this": True, "low": True, "high": True} 3645 3646 3647class Bracket(Condition): 3648 arg_types = {"this": True, "expressions": True} 3649 3650 3651class Distinct(Expression): 3652 arg_types = {"expressions": False, "on": False} 3653 3654 3655class In(Predicate): 3656 arg_types = { 3657 "this": True, 3658 "expressions": False, 3659 "query": False, 3660 "unnest": False, 3661 "field": False, 3662 "is_global": False, 3663 } 3664 3665 3666class TimeUnit(Expression): 3667 """Automatically converts unit arg into a var.""" 3668 3669 arg_types = {"unit": False} 3670 3671 def __init__(self, **args): 3672 unit = args.get("unit") 3673 if isinstance(unit, (Column, Literal)): 3674 args["unit"] = Var(this=unit.name) 3675 elif isinstance(unit, Week): 3676 unit.set("this", Var(this=unit.this.name)) 3677 3678 super().__init__(**args) 3679 3680 3681class Interval(TimeUnit): 3682 arg_types = {"this": False, "unit": False} 3683 3684 @property 3685 def unit(self) -> t.Optional[Var]: 3686 return self.args.get("unit") 3687 3688 3689class IgnoreNulls(Expression): 3690 pass 3691 3692 3693class RespectNulls(Expression): 3694 pass 3695 3696 3697# Functions 3698class Func(Condition): 3699 """ 3700 The base class for all function expressions. 3701 3702 Attributes: 3703 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3704 treated as a variable length argument and the argument's value will be stored as a list. 3705 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3706 for this function expression. These values are used to map this node to a name during parsing 3707 as well as to provide the function's name during SQL string generation. By default the SQL 3708 name is set to the expression's class name transformed to snake case. 3709 """ 3710 3711 is_var_len_args = False 3712 3713 @classmethod 3714 def from_arg_list(cls, args): 3715 if cls.is_var_len_args: 3716 all_arg_keys = list(cls.arg_types) 3717 # If this function supports variable length argument treat the last argument as such. 3718 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3719 num_non_var = len(non_var_len_arg_keys) 3720 3721 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3722 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3723 else: 3724 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3725 3726 return cls(**args_dict) 3727 3728 @classmethod 3729 def sql_names(cls): 3730 if cls is Func: 3731 raise NotImplementedError( 3732 "SQL name is only supported by concrete function implementations" 3733 ) 3734 if "_sql_names" not in cls.__dict__: 3735 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3736 return cls._sql_names 3737 3738 @classmethod 3739 def sql_name(cls): 3740 return cls.sql_names()[0] 3741 3742 @classmethod 3743 def default_parser_mappings(cls): 3744 return {name: cls.from_arg_list for name in cls.sql_names()} 3745 3746 3747class AggFunc(Func): 3748 pass 3749 3750 3751class ParameterizedAgg(AggFunc): 3752 arg_types = {"this": True, "expressions": True, "params": True} 3753 3754 3755class Abs(Func): 3756 pass 3757 3758 3759class Anonymous(Func): 3760 arg_types = {"this": True, "expressions": False} 3761 is_var_len_args = True 3762 3763 3764# https://docs.snowflake.com/en/sql-reference/functions/hll 3765# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3766class Hll(AggFunc): 3767 arg_types = {"this": True, "expressions": False} 3768 is_var_len_args = True 3769 3770 3771class ApproxDistinct(AggFunc): 3772 arg_types = {"this": True, "accuracy": False} 3773 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"] 3774 3775 3776class Array(Func): 3777 arg_types = {"expressions": False} 3778 is_var_len_args = True 3779 3780 3781# https://docs.snowflake.com/en/sql-reference/functions/to_char 3782class ToChar(Func): 3783 arg_types = {"this": True, "format": False} 3784 3785 3786class GenerateSeries(Func): 3787 arg_types = {"start": True, "end": True, "step": False} 3788 3789 3790class ArrayAgg(AggFunc): 3791 pass 3792 3793 3794class ArrayAll(Func): 3795 arg_types = {"this": True, "expression": True} 3796 3797 3798class ArrayAny(Func): 3799 arg_types = {"this": True, "expression": True} 3800 3801 3802class ArrayConcat(Func): 3803 arg_types = {"this": True, "expressions": False} 3804 is_var_len_args = True 3805 3806 3807class ArrayContains(Binary, Func): 3808 pass 3809 3810 3811class ArrayContained(Binary): 3812 pass 3813 3814 3815class ArrayFilter(Func): 3816 arg_types = {"this": True, "expression": True} 3817 _sql_names = ["FILTER", "ARRAY_FILTER"] 3818 3819 3820class ArrayJoin(Func): 3821 arg_types = {"this": True, "expression": True, "null": False} 3822 3823 3824class ArraySize(Func): 3825 arg_types = {"this": True, "expression": False} 3826 3827 3828class ArraySort(Func): 3829 arg_types = {"this": True, "expression": False} 3830 3831 3832class ArraySum(Func): 3833 pass 3834 3835 3836class ArrayUnionAgg(AggFunc): 3837 pass 3838 3839 3840class Avg(AggFunc): 3841 pass 3842 3843 3844class AnyValue(AggFunc): 3845 pass 3846 3847 3848class Case(Func): 3849 arg_types = {"this": False, "ifs": True, "default": False} 3850 3851 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3852 instance = _maybe_copy(self, copy) 3853 instance.append( 3854 "ifs", 3855 If( 3856 this=maybe_parse(condition, copy=copy, **opts), 3857 true=maybe_parse(then, copy=copy, **opts), 3858 ), 3859 ) 3860 return instance 3861 3862 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3863 instance = _maybe_copy(self, copy) 3864 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3865 return instance 3866 3867 3868class Cast(Func): 3869 arg_types = {"this": True, "to": True} 3870 3871 @property 3872 def name(self) -> str: 3873 return self.this.name 3874 3875 @property 3876 def to(self) -> DataType: 3877 return self.args["to"] 3878 3879 @property 3880 def output_name(self) -> str: 3881 return self.name 3882 3883 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3884 return self.to.is_type(*dtypes) 3885 3886 3887class CastToStrType(Func): 3888 arg_types = {"this": True, "expression": True} 3889 3890 3891class Collate(Binary): 3892 pass 3893 3894 3895class TryCast(Cast): 3896 pass 3897 3898 3899class Ceil(Func): 3900 arg_types = {"this": True, "decimals": False} 3901 _sql_names = ["CEIL", "CEILING"] 3902 3903 3904class Coalesce(Func): 3905 arg_types = {"this": True, "expressions": False} 3906 is_var_len_args = True 3907 3908 3909class Concat(Func): 3910 arg_types = {"expressions": True} 3911 is_var_len_args = True 3912 3913 3914class ConcatWs(Concat): 3915 _sql_names = ["CONCAT_WS"] 3916 3917 3918class Count(AggFunc): 3919 arg_types = {"this": False} 3920 3921 3922class CountIf(AggFunc): 3923 pass 3924 3925 3926class CurrentDate(Func): 3927 arg_types = {"this": False} 3928 3929 3930class CurrentDatetime(Func): 3931 arg_types = {"this": False} 3932 3933 3934class CurrentTime(Func): 3935 arg_types = {"this": False} 3936 3937 3938class CurrentTimestamp(Func): 3939 arg_types = {"this": False} 3940 3941 3942class CurrentUser(Func): 3943 arg_types = {"this": False} 3944 3945 3946class DateAdd(Func, TimeUnit): 3947 arg_types = {"this": True, "expression": True, "unit": False} 3948 3949 3950class DateSub(Func, TimeUnit): 3951 arg_types = {"this": True, "expression": True, "unit": False} 3952 3953 3954class DateDiff(Func, TimeUnit): 3955 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3956 arg_types = {"this": True, "expression": True, "unit": False} 3957 3958 3959class DateTrunc(Func): 3960 arg_types = {"unit": True, "this": True, "zone": False} 3961 3962 3963class DatetimeAdd(Func, TimeUnit): 3964 arg_types = {"this": True, "expression": True, "unit": False} 3965 3966 3967class DatetimeSub(Func, TimeUnit): 3968 arg_types = {"this": True, "expression": True, "unit": False} 3969 3970 3971class DatetimeDiff(Func, TimeUnit): 3972 arg_types = {"this": True, "expression": True, "unit": False} 3973 3974 3975class DatetimeTrunc(Func, TimeUnit): 3976 arg_types = {"this": True, "unit": True, "zone": False} 3977 3978 3979class DayOfWeek(Func): 3980 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3981 3982 3983class DayOfMonth(Func): 3984 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3985 3986 3987class DayOfYear(Func): 3988 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3989 3990 3991class WeekOfYear(Func): 3992 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3993 3994 3995class LastDateOfMonth(Func): 3996 pass 3997 3998 3999class Extract(Func): 4000 arg_types = {"this": True, "expression": True} 4001 4002 4003class TimestampAdd(Func, TimeUnit): 4004 arg_types = {"this": True, "expression": True, "unit": False} 4005 4006 4007class TimestampSub(Func, TimeUnit): 4008 arg_types = {"this": True, "expression": True, "unit": False} 4009 4010 4011class TimestampDiff(Func, TimeUnit): 4012 arg_types = {"this": True, "expression": True, "unit": False} 4013 4014 4015class TimestampTrunc(Func, TimeUnit): 4016 arg_types = {"this": True, "unit": True, "zone": False} 4017 4018 4019class TimeAdd(Func, TimeUnit): 4020 arg_types = {"this": True, "expression": True, "unit": False} 4021 4022 4023class TimeSub(Func, TimeUnit): 4024 arg_types = {"this": True, "expression": True, "unit": False} 4025 4026 4027class TimeDiff(Func, TimeUnit): 4028 arg_types = {"this": True, "expression": True, "unit": False} 4029 4030 4031class TimeTrunc(Func, TimeUnit): 4032 arg_types = {"this": True, "unit": True, "zone": False} 4033 4034 4035class DateFromParts(Func): 4036 _sql_names = ["DATEFROMPARTS"] 4037 arg_types = {"year": True, "month": True, "day": True} 4038 4039 4040class DateStrToDate(Func): 4041 pass 4042 4043 4044class DateToDateStr(Func): 4045 pass 4046 4047 4048class DateToDi(Func): 4049 pass 4050 4051 4052class Day(Func): 4053 pass 4054 4055 4056class Decode(Func): 4057 arg_types = {"this": True, "charset": True, "replace": False} 4058 4059 4060class DiToDate(Func): 4061 pass 4062 4063 4064class Encode(Func): 4065 arg_types = {"this": True, "charset": True} 4066 4067 4068class Exp(Func): 4069 pass 4070 4071 4072class Explode(Func): 4073 pass 4074 4075 4076class Floor(Func): 4077 arg_types = {"this": True, "decimals": False} 4078 4079 4080class FromBase64(Func): 4081 pass 4082 4083 4084class ToBase64(Func): 4085 pass 4086 4087 4088class Greatest(Func): 4089 arg_types = {"this": True, "expressions": False} 4090 is_var_len_args = True 4091 4092 4093class GroupConcat(Func): 4094 arg_types = {"this": True, "separator": False} 4095 4096 4097class Hex(Func): 4098 pass 4099 4100 4101class If(Func): 4102 arg_types = {"this": True, "true": True, "false": False} 4103 4104 4105class IfNull(Func): 4106 arg_types = {"this": True, "expression": False} 4107 _sql_names = ["IFNULL", "NVL"] 4108 4109 4110class Initcap(Func): 4111 arg_types = {"this": True, "expression": False} 4112 4113 4114class JSONKeyValue(Expression): 4115 arg_types = {"this": True, "expression": True} 4116 4117 4118class JSONObject(Func): 4119 arg_types = { 4120 "expressions": False, 4121 "null_handling": False, 4122 "unique_keys": False, 4123 "return_type": False, 4124 "format_json": False, 4125 "encoding": False, 4126 } 4127 4128 4129class OpenJSONColumnDef(Expression): 4130 arg_types = {"this": True, "kind": True, "path": False, "as_json": False} 4131 4132 4133class OpenJSON(Func): 4134 arg_types = {"this": True, "path": False, "expressions": False} 4135 4136 4137class JSONBContains(Binary): 4138 _sql_names = ["JSONB_CONTAINS"] 4139 4140 4141class JSONExtract(Binary, Func): 4142 _sql_names = ["JSON_EXTRACT"] 4143 4144 4145class JSONExtractScalar(JSONExtract): 4146 _sql_names = ["JSON_EXTRACT_SCALAR"] 4147 4148 4149class JSONBExtract(JSONExtract): 4150 _sql_names = ["JSONB_EXTRACT"] 4151 4152 4153class JSONBExtractScalar(JSONExtract): 4154 _sql_names = ["JSONB_EXTRACT_SCALAR"] 4155 4156 4157class JSONFormat(Func): 4158 arg_types = {"this": False, "options": False} 4159 _sql_names = ["JSON_FORMAT"] 4160 4161 4162class Least(Func): 4163 arg_types = {"expressions": False} 4164 is_var_len_args = True 4165 4166 4167class Left(Func): 4168 arg_types = {"this": True, "expression": True} 4169 4170 4171class Right(Func): 4172 arg_types = {"this": True, "expression": True} 4173 4174 4175class Length(Func): 4176 _sql_names = ["LENGTH", "LEN"] 4177 4178 4179class Levenshtein(Func): 4180 arg_types = { 4181 "this": True, 4182 "expression": False, 4183 "ins_cost": False, 4184 "del_cost": False, 4185 "sub_cost": False, 4186 } 4187 4188 4189class Ln(Func): 4190 pass 4191 4192 4193class Log(Func): 4194 arg_types = {"this": True, "expression": False} 4195 4196 4197class Log2(Func): 4198 pass 4199 4200 4201class Log10(Func): 4202 pass 4203 4204 4205class LogicalOr(AggFunc): 4206 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 4207 4208 4209class LogicalAnd(AggFunc): 4210 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 4211 4212 4213class Lower(Func): 4214 _sql_names = ["LOWER", "LCASE"] 4215 4216 4217class Map(Func): 4218 arg_types = {"keys": False, "values": False} 4219 4220 4221class StarMap(Func): 4222 pass 4223 4224 4225class VarMap(Func): 4226 arg_types = {"keys": True, "values": True} 4227 is_var_len_args = True 4228 4229 @property 4230 def keys(self) -> t.List[Expression]: 4231 return self.args["keys"].expressions 4232 4233 @property 4234 def values(self) -> t.List[Expression]: 4235 return self.args["values"].expressions 4236 4237 4238# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 4239class MatchAgainst(Func): 4240 arg_types = {"this": True, "expressions": True, "modifier": False} 4241 4242 4243class Max(AggFunc): 4244 arg_types = {"this": True, "expressions": False} 4245 is_var_len_args = True 4246 4247 4248class MD5(Func): 4249 _sql_names = ["MD5"] 4250 4251 4252class Min(AggFunc): 4253 arg_types = {"this": True, "expressions": False} 4254 is_var_len_args = True 4255 4256 4257class Month(Func): 4258 pass 4259 4260 4261class Nvl2(Func): 4262 arg_types = {"this": True, "true": True, "false": False} 4263 4264 4265class Posexplode(Func): 4266 pass 4267 4268 4269class Pow(Binary, Func): 4270 _sql_names = ["POWER", "POW"] 4271 4272 4273class PercentileCont(AggFunc): 4274 arg_types = {"this": True, "expression": False} 4275 4276 4277class PercentileDisc(AggFunc): 4278 arg_types = {"this": True, "expression": False} 4279 4280 4281class Quantile(AggFunc): 4282 arg_types = {"this": True, "quantile": True} 4283 4284 4285class ApproxQuantile(Quantile): 4286 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 4287 4288 4289class RangeN(Func): 4290 arg_types = {"this": True, "expressions": True, "each": False} 4291 4292 4293class ReadCSV(Func): 4294 _sql_names = ["READ_CSV"] 4295 is_var_len_args = True 4296 arg_types = {"this": True, "expressions": False} 4297 4298 4299class Reduce(Func): 4300 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 4301 4302 4303class RegexpExtract(Func): 4304 arg_types = { 4305 "this": True, 4306 "expression": True, 4307 "position": False, 4308 "occurrence": False, 4309 "group": False, 4310 } 4311 4312 4313class RegexpLike(Func): 4314 arg_types = {"this": True, "expression": True, "flag": False} 4315 4316 4317class RegexpILike(Func): 4318 arg_types = {"this": True, "expression": True, "flag": False} 4319 4320 4321# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 4322# limit is the number of times a pattern is applied 4323class RegexpSplit(Func): 4324 arg_types = {"this": True, "expression": True, "limit": False} 4325 4326 4327class Repeat(Func): 4328 arg_types = {"this": True, "times": True} 4329 4330 4331class Round(Func): 4332 arg_types = {"this": True, "decimals": False} 4333 4334 4335class RowNumber(Func): 4336 arg_types: t.Dict[str, t.Any] = {} 4337 4338 4339class SafeDivide(Func): 4340 arg_types = {"this": True, "expression": True} 4341 4342 4343class SetAgg(AggFunc): 4344 pass 4345 4346 4347class SHA(Func): 4348 _sql_names = ["SHA", "SHA1"] 4349 4350 4351class SHA2(Func): 4352 _sql_names = ["SHA2"] 4353 arg_types = {"this": True, "length": False} 4354 4355 4356class SortArray(Func): 4357 arg_types = {"this": True, "asc": False} 4358 4359 4360class Split(Func): 4361 arg_types = {"this": True, "expression": True, "limit": False} 4362 4363 4364# Start may be omitted in the case of postgres 4365# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 4366class Substring(Func): 4367 arg_types = {"this": True, "start": False, "length": False} 4368 4369 4370class StandardHash(Func): 4371 arg_types = {"this": True, "expression": False} 4372 4373 4374class StrPosition(Func): 4375 arg_types = { 4376 "this": True, 4377 "substr": True, 4378 "position": False, 4379 "instance": False, 4380 } 4381 4382 4383class StrToDate(Func): 4384 arg_types = {"this": True, "format": True} 4385 4386 4387class StrToTime(Func): 4388 arg_types = {"this": True, "format": True} 4389 4390 4391# Spark allows unix_timestamp() 4392# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 4393class StrToUnix(Func): 4394 arg_types = {"this": False, "format": False} 4395 4396 4397class NumberToStr(Func): 4398 arg_types = {"this": True, "format": True} 4399 4400 4401class FromBase(Func): 4402 arg_types = {"this": True, "expression": True} 4403 4404 4405class Struct(Func): 4406 arg_types = {"expressions": True} 4407 is_var_len_args = True 4408 4409 4410class StructExtract(Func): 4411 arg_types = {"this": True, "expression": True} 4412 4413 4414class Sum(AggFunc): 4415 pass 4416 4417 4418class Sqrt(Func): 4419 pass 4420 4421 4422class Stddev(AggFunc): 4423 pass 4424 4425 4426class StddevPop(AggFunc): 4427 pass 4428 4429 4430class StddevSamp(AggFunc): 4431 pass 4432 4433 4434class TimeToStr(Func): 4435 arg_types = {"this": True, "format": True} 4436 4437 4438class TimeToTimeStr(Func): 4439 pass 4440 4441 4442class TimeToUnix(Func): 4443 pass 4444 4445 4446class TimeStrToDate(Func): 4447 pass 4448 4449 4450class TimeStrToTime(Func): 4451 pass 4452 4453 4454class TimeStrToUnix(Func): 4455 pass 4456 4457 4458class Trim(Func): 4459 arg_types = { 4460 "this": True, 4461 "expression": False, 4462 "position": False, 4463 "collation": False, 4464 } 4465 4466 4467class TsOrDsAdd(Func, TimeUnit): 4468 arg_types = {"this": True, "expression": True, "unit": False} 4469 4470 4471class TsOrDsToDateStr(Func): 4472 pass 4473 4474 4475class TsOrDsToDate(Func): 4476 arg_types = {"this": True, "format": False} 4477 4478 4479class TsOrDiToDi(Func): 4480 pass 4481 4482 4483class Unhex(Func): 4484 pass 4485 4486 4487class UnixToStr(Func): 4488 arg_types = {"this": True, "format": False} 4489 4490 4491# https://prestodb.io/docs/current/functions/datetime.html 4492# presto has weird zone/hours/minutes 4493class UnixToTime(Func): 4494 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4495 4496 SECONDS = Literal.string("seconds") 4497 MILLIS = Literal.string("millis") 4498 MICROS = Literal.string("micros") 4499 4500 4501class UnixToTimeStr(Func): 4502 pass 4503 4504 4505class Upper(Func): 4506 _sql_names = ["UPPER", "UCASE"] 4507 4508 4509class Variance(AggFunc): 4510 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4511 4512 4513class VariancePop(AggFunc): 4514 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4515 4516 4517class Week(Func): 4518 arg_types = {"this": True, "mode": False} 4519 4520 4521class XMLTable(Func): 4522 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4523 4524 4525class Year(Func): 4526 pass 4527 4528 4529class Use(Expression): 4530 arg_types = {"this": True, "kind": False} 4531 4532 4533class Merge(Expression): 4534 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4535 4536 4537class When(Func): 4538 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4539 4540 4541# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html 4542# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16 4543class NextValueFor(Func): 4544 arg_types = {"this": True, "order": False} 4545 4546 4547def _norm_arg(arg): 4548 return arg.lower() if type(arg) is str else arg 4549 4550 4551ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4552 4553 4554# Helpers 4555@t.overload 4556def maybe_parse( 4557 sql_or_expression: ExpOrStr, 4558 *, 4559 into: t.Type[E], 4560 dialect: DialectType = None, 4561 prefix: t.Optional[str] = None, 4562 copy: bool = False, 4563 **opts, 4564) -> E: 4565 ... 4566 4567 4568@t.overload 4569def maybe_parse( 4570 sql_or_expression: str | E, 4571 *, 4572 into: t.Optional[IntoType] = None, 4573 dialect: DialectType = None, 4574 prefix: t.Optional[str] = None, 4575 copy: bool = False, 4576 **opts, 4577) -> E: 4578 ... 4579 4580 4581def maybe_parse( 4582 sql_or_expression: ExpOrStr, 4583 *, 4584 into: t.Optional[IntoType] = None, 4585 dialect: DialectType = None, 4586 prefix: t.Optional[str] = None, 4587 copy: bool = False, 4588 **opts, 4589) -> Expression: 4590 """Gracefully handle a possible string or expression. 4591 4592 Example: 4593 >>> maybe_parse("1") 4594 (LITERAL this: 1, is_string: False) 4595 >>> maybe_parse(to_identifier("x")) 4596 (IDENTIFIER this: x, quoted: False) 4597 4598 Args: 4599 sql_or_expression: the SQL code string or an expression 4600 into: the SQLGlot Expression to parse into 4601 dialect: the dialect used to parse the input expressions (in the case that an 4602 input expression is a SQL string). 4603 prefix: a string to prefix the sql with before it gets parsed 4604 (automatically includes a space) 4605 copy: whether or not to copy the expression. 4606 **opts: other options to use to parse the input expressions (again, in the case 4607 that an input expression is a SQL string). 4608 4609 Returns: 4610 Expression: the parsed or given expression. 4611 """ 4612 if isinstance(sql_or_expression, Expression): 4613 if copy: 4614 return sql_or_expression.copy() 4615 return sql_or_expression 4616 4617 if sql_or_expression is None: 4618 raise ParseError(f"SQL cannot be None") 4619 4620 import sqlglot 4621 4622 sql = str(sql_or_expression) 4623 if prefix: 4624 sql = f"{prefix} {sql}" 4625 4626 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4627 4628 4629def _maybe_copy(instance: E, copy: bool = True) -> E: 4630 return instance.copy() if copy else instance 4631 4632 4633def _is_wrong_expression(expression, into): 4634 return isinstance(expression, Expression) and not isinstance(expression, into) 4635 4636 4637def _apply_builder( 4638 expression, 4639 instance, 4640 arg, 4641 copy=True, 4642 prefix=None, 4643 into=None, 4644 dialect=None, 4645 **opts, 4646): 4647 if _is_wrong_expression(expression, into): 4648 expression = into(this=expression) 4649 instance = _maybe_copy(instance, copy) 4650 expression = maybe_parse( 4651 sql_or_expression=expression, 4652 prefix=prefix, 4653 into=into, 4654 dialect=dialect, 4655 **opts, 4656 ) 4657 instance.set(arg, expression) 4658 return instance 4659 4660 4661def _apply_child_list_builder( 4662 *expressions, 4663 instance, 4664 arg, 4665 append=True, 4666 copy=True, 4667 prefix=None, 4668 into=None, 4669 dialect=None, 4670 properties=None, 4671 **opts, 4672): 4673 instance = _maybe_copy(instance, copy) 4674 parsed = [] 4675 for expression in expressions: 4676 if expression is not None: 4677 if _is_wrong_expression(expression, into): 4678 expression = into(expressions=[expression]) 4679 4680 expression = maybe_parse( 4681 expression, 4682 into=into, 4683 dialect=dialect, 4684 prefix=prefix, 4685 **opts, 4686 ) 4687 parsed.extend(expression.expressions) 4688 4689 existing = instance.args.get(arg) 4690 if append and existing: 4691 parsed = existing.expressions + parsed 4692 4693 child = into(expressions=parsed) 4694 for k, v in (properties or {}).items(): 4695 child.set(k, v) 4696 instance.set(arg, child) 4697 4698 return instance 4699 4700 4701def _apply_list_builder( 4702 *expressions, 4703 instance, 4704 arg, 4705 append=True, 4706 copy=True, 4707 prefix=None, 4708 into=None, 4709 dialect=None, 4710 **opts, 4711): 4712 inst = _maybe_copy(instance, copy) 4713 4714 expressions = [ 4715 maybe_parse( 4716 sql_or_expression=expression, 4717 into=into, 4718 prefix=prefix, 4719 dialect=dialect, 4720 **opts, 4721 ) 4722 for expression in expressions 4723 if expression is not None 4724 ] 4725 4726 existing_expressions = inst.args.get(arg) 4727 if append and existing_expressions: 4728 expressions = existing_expressions + expressions 4729 4730 inst.set(arg, expressions) 4731 return inst 4732 4733 4734def _apply_conjunction_builder( 4735 *expressions, 4736 instance, 4737 arg, 4738 into=None, 4739 append=True, 4740 copy=True, 4741 dialect=None, 4742 **opts, 4743): 4744 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4745 if not expressions: 4746 return instance 4747 4748 inst = _maybe_copy(instance, copy) 4749 4750 existing = inst.args.get(arg) 4751 if append and existing is not None: 4752 expressions = [existing.this if into else existing] + list(expressions) 4753 4754 node = and_(*expressions, dialect=dialect, copy=copy, **opts) 4755 4756 inst.set(arg, into(this=node) if into else node) 4757 return inst 4758 4759 4760def _apply_cte_builder( 4761 instance: E, 4762 alias: ExpOrStr, 4763 as_: ExpOrStr, 4764 recursive: t.Optional[bool] = None, 4765 append: bool = True, 4766 dialect: DialectType = None, 4767 copy: bool = True, 4768 **opts, 4769) -> E: 4770 alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts) 4771 as_expression = maybe_parse(as_, dialect=dialect, **opts) 4772 cte = CTE(this=as_expression, alias=alias_expression) 4773 return _apply_child_list_builder( 4774 cte, 4775 instance=instance, 4776 arg="with", 4777 append=append, 4778 copy=copy, 4779 into=With, 4780 properties={"recursive": recursive or False}, 4781 ) 4782 4783 4784def _combine( 4785 expressions: t.Sequence[t.Optional[ExpOrStr]], 4786 operator: t.Type[Connector], 4787 dialect: DialectType = None, 4788 copy: bool = True, 4789 **opts, 4790) -> Expression: 4791 conditions = [ 4792 condition(expression, dialect=dialect, copy=copy, **opts) 4793 for expression in expressions 4794 if expression is not None 4795 ] 4796 4797 this, *rest = conditions 4798 if rest: 4799 this = _wrap(this, Connector) 4800 for expression in rest: 4801 this = operator(this=this, expression=_wrap(expression, Connector)) 4802 4803 return this 4804 4805 4806def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: 4807 return Paren(this=expression) if isinstance(expression, kind) else expression 4808 4809 4810def union( 4811 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4812) -> Union: 4813 """ 4814 Initializes a syntax tree from one UNION expression. 4815 4816 Example: 4817 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4818 'SELECT * FROM foo UNION SELECT * FROM bla' 4819 4820 Args: 4821 left: the SQL code string corresponding to the left-hand side. 4822 If an `Expression` instance is passed, it will be used as-is. 4823 right: the SQL code string corresponding to the right-hand side. 4824 If an `Expression` instance is passed, it will be used as-is. 4825 distinct: set the DISTINCT flag if and only if this is true. 4826 dialect: the dialect used to parse the input expression. 4827 opts: other options to use to parse the input expressions. 4828 4829 Returns: 4830 The new Union instance. 4831 """ 4832 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4833 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4834 4835 return Union(this=left, expression=right, distinct=distinct) 4836 4837 4838def intersect( 4839 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4840) -> Intersect: 4841 """ 4842 Initializes a syntax tree from one INTERSECT expression. 4843 4844 Example: 4845 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4846 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4847 4848 Args: 4849 left: the SQL code string corresponding to the left-hand side. 4850 If an `Expression` instance is passed, it will be used as-is. 4851 right: the SQL code string corresponding to the right-hand side. 4852 If an `Expression` instance is passed, it will be used as-is. 4853 distinct: set the DISTINCT flag if and only if this is true. 4854 dialect: the dialect used to parse the input expression. 4855 opts: other options to use to parse the input expressions. 4856 4857 Returns: 4858 The new Intersect instance. 4859 """ 4860 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4861 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4862 4863 return Intersect(this=left, expression=right, distinct=distinct) 4864 4865 4866def except_( 4867 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4868) -> Except: 4869 """ 4870 Initializes a syntax tree from one EXCEPT expression. 4871 4872 Example: 4873 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4874 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4875 4876 Args: 4877 left: the SQL code string corresponding to the left-hand side. 4878 If an `Expression` instance is passed, it will be used as-is. 4879 right: the SQL code string corresponding to the right-hand side. 4880 If an `Expression` instance is passed, it will be used as-is. 4881 distinct: set the DISTINCT flag if and only if this is true. 4882 dialect: the dialect used to parse the input expression. 4883 opts: other options to use to parse the input expressions. 4884 4885 Returns: 4886 The new Except instance. 4887 """ 4888 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4889 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4890 4891 return Except(this=left, expression=right, distinct=distinct) 4892 4893 4894def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4895 """ 4896 Initializes a syntax tree from one or multiple SELECT expressions. 4897 4898 Example: 4899 >>> select("col1", "col2").from_("tbl").sql() 4900 'SELECT col1, col2 FROM tbl' 4901 4902 Args: 4903 *expressions: the SQL code string to parse as the expressions of a 4904 SELECT statement. If an Expression instance is passed, this is used as-is. 4905 dialect: the dialect used to parse the input expressions (in the case that an 4906 input expression is a SQL string). 4907 **opts: other options to use to parse the input expressions (again, in the case 4908 that an input expression is a SQL string). 4909 4910 Returns: 4911 Select: the syntax tree for the SELECT statement. 4912 """ 4913 return Select().select(*expressions, dialect=dialect, **opts) 4914 4915 4916def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4917 """ 4918 Initializes a syntax tree from a FROM expression. 4919 4920 Example: 4921 >>> from_("tbl").select("col1", "col2").sql() 4922 'SELECT col1, col2 FROM tbl' 4923 4924 Args: 4925 *expression: the SQL code string to parse as the FROM expressions of a 4926 SELECT statement. If an Expression instance is passed, this is used as-is. 4927 dialect: the dialect used to parse the input expression (in the case that the 4928 input expression is a SQL string). 4929 **opts: other options to use to parse the input expressions (again, in the case 4930 that the input expression is a SQL string). 4931 4932 Returns: 4933 Select: the syntax tree for the SELECT statement. 4934 """ 4935 return Select().from_(expression, dialect=dialect, **opts) 4936 4937 4938def update( 4939 table: str | Table, 4940 properties: dict, 4941 where: t.Optional[ExpOrStr] = None, 4942 from_: t.Optional[ExpOrStr] = None, 4943 dialect: DialectType = None, 4944 **opts, 4945) -> Update: 4946 """ 4947 Creates an update statement. 4948 4949 Example: 4950 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4951 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4952 4953 Args: 4954 *properties: dictionary of properties to set which are 4955 auto converted to sql objects eg None -> NULL 4956 where: sql conditional parsed into a WHERE statement 4957 from_: sql statement parsed into a FROM statement 4958 dialect: the dialect used to parse the input expressions. 4959 **opts: other options to use to parse the input expressions. 4960 4961 Returns: 4962 Update: the syntax tree for the UPDATE statement. 4963 """ 4964 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4965 update_expr.set( 4966 "expressions", 4967 [ 4968 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4969 for k, v in properties.items() 4970 ], 4971 ) 4972 if from_: 4973 update_expr.set( 4974 "from", 4975 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4976 ) 4977 if isinstance(where, Condition): 4978 where = Where(this=where) 4979 if where: 4980 update_expr.set( 4981 "where", 4982 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4983 ) 4984 return update_expr 4985 4986 4987def delete( 4988 table: ExpOrStr, 4989 where: t.Optional[ExpOrStr] = None, 4990 returning: t.Optional[ExpOrStr] = None, 4991 dialect: DialectType = None, 4992 **opts, 4993) -> Delete: 4994 """ 4995 Builds a delete statement. 4996 4997 Example: 4998 >>> delete("my_table", where="id > 1").sql() 4999 'DELETE FROM my_table WHERE id > 1' 5000 5001 Args: 5002 where: sql conditional parsed into a WHERE statement 5003 returning: sql conditional parsed into a RETURNING statement 5004 dialect: the dialect used to parse the input expressions. 5005 **opts: other options to use to parse the input expressions. 5006 5007 Returns: 5008 Delete: the syntax tree for the DELETE statement. 5009 """ 5010 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5011 if where: 5012 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5013 if returning: 5014 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5015 return delete_expr 5016 5017 5018def insert( 5019 expression: ExpOrStr, 5020 into: ExpOrStr, 5021 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5022 overwrite: t.Optional[bool] = None, 5023 dialect: DialectType = None, 5024 copy: bool = True, 5025 **opts, 5026) -> Insert: 5027 """ 5028 Builds an INSERT statement. 5029 5030 Example: 5031 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5032 'INSERT INTO tbl VALUES (1, 2, 3)' 5033 5034 Args: 5035 expression: the sql string or expression of the INSERT statement 5036 into: the tbl to insert data to. 5037 columns: optionally the table's column names. 5038 overwrite: whether to INSERT OVERWRITE or not. 5039 dialect: the dialect used to parse the input expressions. 5040 copy: whether or not to copy the expression. 5041 **opts: other options to use to parse the input expressions. 5042 5043 Returns: 5044 Insert: the syntax tree for the INSERT statement. 5045 """ 5046 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5047 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5048 5049 if columns: 5050 this = _apply_list_builder( 5051 *columns, 5052 instance=Schema(this=this), 5053 arg="expressions", 5054 into=Identifier, 5055 copy=False, 5056 dialect=dialect, 5057 **opts, 5058 ) 5059 5060 return Insert(this=this, expression=expr, overwrite=overwrite) 5061 5062 5063def condition( 5064 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5065) -> Condition: 5066 """ 5067 Initialize a logical condition expression. 5068 5069 Example: 5070 >>> condition("x=1").sql() 5071 'x = 1' 5072 5073 This is helpful for composing larger logical syntax trees: 5074 >>> where = condition("x=1") 5075 >>> where = where.and_("y=1") 5076 >>> Select().from_("tbl").select("*").where(where).sql() 5077 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5078 5079 Args: 5080 *expression: the SQL code string to parse. 5081 If an Expression instance is passed, this is used as-is. 5082 dialect: the dialect used to parse the input expression (in the case that the 5083 input expression is a SQL string). 5084 copy: Whether or not to copy `expression` (only applies to expressions). 5085 **opts: other options to use to parse the input expressions (again, in the case 5086 that the input expression is a SQL string). 5087 5088 Returns: 5089 The new Condition instance 5090 """ 5091 return maybe_parse( 5092 expression, 5093 into=Condition, 5094 dialect=dialect, 5095 copy=copy, 5096 **opts, 5097 ) 5098 5099 5100def and_( 5101 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5102) -> Condition: 5103 """ 5104 Combine multiple conditions with an AND logical operator. 5105 5106 Example: 5107 >>> and_("x=1", and_("y=1", "z=1")).sql() 5108 'x = 1 AND (y = 1 AND z = 1)' 5109 5110 Args: 5111 *expressions: the SQL code strings to parse. 5112 If an Expression instance is passed, this is used as-is. 5113 dialect: the dialect used to parse the input expression. 5114 copy: whether or not to copy `expressions` (only applies to Expressions). 5115 **opts: other options to use to parse the input expressions. 5116 5117 Returns: 5118 And: the new condition 5119 """ 5120 return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts)) 5121 5122 5123def or_( 5124 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5125) -> Condition: 5126 """ 5127 Combine multiple conditions with an OR logical operator. 5128 5129 Example: 5130 >>> or_("x=1", or_("y=1", "z=1")).sql() 5131 'x = 1 OR (y = 1 OR z = 1)' 5132 5133 Args: 5134 *expressions: the SQL code strings to parse. 5135 If an Expression instance is passed, this is used as-is. 5136 dialect: the dialect used to parse the input expression. 5137 copy: whether or not to copy `expressions` (only applies to Expressions). 5138 **opts: other options to use to parse the input expressions. 5139 5140 Returns: 5141 Or: the new condition 5142 """ 5143 return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts)) 5144 5145 5146def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5147 """ 5148 Wrap a condition with a NOT operator. 5149 5150 Example: 5151 >>> not_("this_suit='black'").sql() 5152 "NOT this_suit = 'black'" 5153 5154 Args: 5155 expression: the SQL code string to parse. 5156 If an Expression instance is passed, this is used as-is. 5157 dialect: the dialect used to parse the input expression. 5158 copy: whether to copy the expression or not. 5159 **opts: other options to use to parse the input expressions. 5160 5161 Returns: 5162 The new condition. 5163 """ 5164 this = condition( 5165 expression, 5166 dialect=dialect, 5167 copy=copy, 5168 **opts, 5169 ) 5170 return Not(this=_wrap(this, Connector)) 5171 5172 5173def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5174 """ 5175 Wrap an expression in parentheses. 5176 5177 Example: 5178 >>> paren("5 + 3").sql() 5179 '(5 + 3)' 5180 5181 Args: 5182 expression: the SQL code string to parse. 5183 If an Expression instance is passed, this is used as-is. 5184 copy: whether to copy the expression or not. 5185 5186 Returns: 5187 The wrapped expression. 5188 """ 5189 return Paren(this=maybe_parse(expression, copy=copy)) 5190 5191 5192SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 5193 5194 5195@t.overload 5196def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None: 5197 ... 5198 5199 5200@t.overload 5201def to_identifier( 5202 name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True 5203) -> Identifier: 5204 ... 5205 5206 5207def to_identifier(name, quoted=None, copy=True): 5208 """Builds an identifier. 5209 5210 Args: 5211 name: The name to turn into an identifier. 5212 quoted: Whether or not force quote the identifier. 5213 copy: Whether or not to copy a passed in Identefier node. 5214 5215 Returns: 5216 The identifier ast node. 5217 """ 5218 5219 if name is None: 5220 return None 5221 5222 if isinstance(name, Identifier): 5223 identifier = _maybe_copy(name, copy) 5224 elif isinstance(name, str): 5225 identifier = Identifier( 5226 this=name, 5227 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5228 ) 5229 else: 5230 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5231 return identifier 5232 5233 5234INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 5235 5236 5237def to_interval(interval: str | Literal) -> Interval: 5238 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5239 if isinstance(interval, Literal): 5240 if not interval.is_string: 5241 raise ValueError("Invalid interval string.") 5242 5243 interval = interval.this 5244 5245 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5246 5247 if not interval_parts: 5248 raise ValueError("Invalid interval string.") 5249 5250 return Interval( 5251 this=Literal.string(interval_parts.group(1)), 5252 unit=Var(this=interval_parts.group(2)), 5253 ) 5254 5255 5256@t.overload 5257def to_table(sql_path: str | Table, **kwargs) -> Table: 5258 ... 5259 5260 5261@t.overload 5262def to_table(sql_path: None, **kwargs) -> None: 5263 ... 5264 5265 5266def to_table( 5267 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5268) -> t.Optional[Table]: 5269 """ 5270 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5271 If a table is passed in then that table is returned. 5272 5273 Args: 5274 sql_path: a `[catalog].[schema].[table]` string. 5275 dialect: the source dialect according to which the table name will be parsed. 5276 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5277 5278 Returns: 5279 A table expression. 5280 """ 5281 if sql_path is None or isinstance(sql_path, Table): 5282 return sql_path 5283 if not isinstance(sql_path, str): 5284 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5285 5286 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5287 if table: 5288 for k, v in kwargs.items(): 5289 table.set(k, v) 5290 5291 return table 5292 5293 5294def to_column(sql_path: str | Column, **kwargs) -> Column: 5295 """ 5296 Create a column from a `[table].[column]` sql path. Schema is optional. 5297 5298 If a column is passed in then that column is returned. 5299 5300 Args: 5301 sql_path: `[table].[column]` string 5302 Returns: 5303 Table: A column expression 5304 """ 5305 if sql_path is None or isinstance(sql_path, Column): 5306 return sql_path 5307 if not isinstance(sql_path, str): 5308 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5309 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 5310 5311 5312def alias_( 5313 expression: ExpOrStr, 5314 alias: str | Identifier, 5315 table: bool | t.Sequence[str | Identifier] = False, 5316 quoted: t.Optional[bool] = None, 5317 dialect: DialectType = None, 5318 copy: bool = True, 5319 **opts, 5320): 5321 """Create an Alias expression. 5322 5323 Example: 5324 >>> alias_('foo', 'bar').sql() 5325 'foo AS bar' 5326 5327 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5328 '(SELECT 1, 2) AS bar(a, b)' 5329 5330 Args: 5331 expression: the SQL code strings to parse. 5332 If an Expression instance is passed, this is used as-is. 5333 alias: the alias name to use. If the name has 5334 special characters it is quoted. 5335 table: Whether or not to create a table alias, can also be a list of columns. 5336 quoted: whether or not to quote the alias 5337 dialect: the dialect used to parse the input expression. 5338 copy: Whether or not to copy the expression. 5339 **opts: other options to use to parse the input expressions. 5340 5341 Returns: 5342 Alias: the aliased expression 5343 """ 5344 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5345 alias = to_identifier(alias, quoted=quoted) 5346 5347 if table: 5348 table_alias = TableAlias(this=alias) 5349 exp.set("alias", table_alias) 5350 5351 if not isinstance(table, bool): 5352 for column in table: 5353 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5354 5355 return exp 5356 5357 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5358 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5359 # for the complete Window expression. 5360 # 5361 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5362 5363 if "alias" in exp.arg_types and not isinstance(exp, Window): 5364 exp.set("alias", alias) 5365 return exp 5366 return Alias(this=exp, alias=alias) 5367 5368 5369def subquery( 5370 expression: ExpOrStr, 5371 alias: t.Optional[Identifier | str] = None, 5372 dialect: DialectType = None, 5373 **opts, 5374) -> Select: 5375 """ 5376 Build a subquery expression. 5377 5378 Example: 5379 >>> subquery('select x from tbl', 'bar').select('x').sql() 5380 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5381 5382 Args: 5383 expression: the SQL code strings to parse. 5384 If an Expression instance is passed, this is used as-is. 5385 alias: the alias name to use. 5386 dialect: the dialect used to parse the input expression. 5387 **opts: other options to use to parse the input expressions. 5388 5389 Returns: 5390 A new Select instance with the subquery expression included. 5391 """ 5392 5393 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5394 return Select().from_(expression, dialect=dialect, **opts) 5395 5396 5397def column( 5398 col: str | Identifier, 5399 table: t.Optional[str | Identifier] = None, 5400 db: t.Optional[str | Identifier] = None, 5401 catalog: t.Optional[str | Identifier] = None, 5402 quoted: t.Optional[bool] = None, 5403) -> Column: 5404 """ 5405 Build a Column. 5406 5407 Args: 5408 col: Column name. 5409 table: Table name. 5410 db: Database name. 5411 catalog: Catalog name. 5412 quoted: Whether to force quotes on the column's identifiers. 5413 5414 Returns: 5415 The new Column instance. 5416 """ 5417 return Column( 5418 this=to_identifier(col, quoted=quoted), 5419 table=to_identifier(table, quoted=quoted), 5420 db=to_identifier(db, quoted=quoted), 5421 catalog=to_identifier(catalog, quoted=quoted), 5422 ) 5423 5424 5425def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5426 """Cast an expression to a data type. 5427 5428 Example: 5429 >>> cast('x + 1', 'int').sql() 5430 'CAST(x + 1 AS INT)' 5431 5432 Args: 5433 expression: The expression to cast. 5434 to: The datatype to cast to. 5435 5436 Returns: 5437 The new Cast instance. 5438 """ 5439 expression = maybe_parse(expression, **opts) 5440 return Cast(this=expression, to=DataType.build(to, **opts)) 5441 5442 5443def table_( 5444 table: Identifier | str, 5445 db: t.Optional[Identifier | str] = None, 5446 catalog: t.Optional[Identifier | str] = None, 5447 quoted: t.Optional[bool] = None, 5448 alias: t.Optional[Identifier | str] = None, 5449) -> Table: 5450 """Build a Table. 5451 5452 Args: 5453 table: Table name. 5454 db: Database name. 5455 catalog: Catalog name. 5456 quote: Whether to force quotes on the table's identifiers. 5457 alias: Table's alias. 5458 5459 Returns: 5460 The new Table instance. 5461 """ 5462 return Table( 5463 this=to_identifier(table, quoted=quoted), 5464 db=to_identifier(db, quoted=quoted), 5465 catalog=to_identifier(catalog, quoted=quoted), 5466 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5467 ) 5468 5469 5470def values( 5471 values: t.Iterable[t.Tuple[t.Any, ...]], 5472 alias: t.Optional[str] = None, 5473 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5474) -> Values: 5475 """Build VALUES statement. 5476 5477 Example: 5478 >>> values([(1, '2')]).sql() 5479 "VALUES (1, '2')" 5480 5481 Args: 5482 values: values statements that will be converted to SQL 5483 alias: optional alias 5484 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5485 If either are provided then an alias is also required. 5486 5487 Returns: 5488 Values: the Values expression object 5489 """ 5490 if columns and not alias: 5491 raise ValueError("Alias is required when providing columns") 5492 5493 return Values( 5494 expressions=[convert(tup) for tup in values], 5495 alias=( 5496 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5497 if columns 5498 else (TableAlias(this=to_identifier(alias)) if alias else None) 5499 ), 5500 ) 5501 5502 5503def var(name: t.Optional[ExpOrStr]) -> Var: 5504 """Build a SQL variable. 5505 5506 Example: 5507 >>> repr(var('x')) 5508 '(VAR this: x)' 5509 5510 >>> repr(var(column('x', table='y'))) 5511 '(VAR this: x)' 5512 5513 Args: 5514 name: The name of the var or an expression who's name will become the var. 5515 5516 Returns: 5517 The new variable node. 5518 """ 5519 if not name: 5520 raise ValueError("Cannot convert empty name into var.") 5521 5522 if isinstance(name, Expression): 5523 name = name.name 5524 return Var(this=name) 5525 5526 5527def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5528 """Build ALTER TABLE... RENAME... expression 5529 5530 Args: 5531 old_name: The old name of the table 5532 new_name: The new name of the table 5533 5534 Returns: 5535 Alter table expression 5536 """ 5537 old_table = to_table(old_name) 5538 new_table = to_table(new_name) 5539 return AlterTable( 5540 this=old_table, 5541 actions=[ 5542 RenameTable(this=new_table), 5543 ], 5544 ) 5545 5546 5547def convert(value: t.Any, copy: bool = False) -> Expression: 5548 """Convert a python value into an expression object. 5549 5550 Raises an error if a conversion is not possible. 5551 5552 Args: 5553 value: A python object. 5554 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5555 5556 Returns: 5557 Expression: the equivalent expression object. 5558 """ 5559 if isinstance(value, Expression): 5560 return _maybe_copy(value, copy) 5561 if isinstance(value, str): 5562 return Literal.string(value) 5563 if isinstance(value, bool): 5564 return Boolean(this=value) 5565 if value is None or (isinstance(value, float) and math.isnan(value)): 5566 return NULL 5567 if isinstance(value, numbers.Number): 5568 return Literal.number(value) 5569 if isinstance(value, datetime.datetime): 5570 datetime_literal = Literal.string( 5571 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5572 ) 5573 return TimeStrToTime(this=datetime_literal) 5574 if isinstance(value, datetime.date): 5575 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5576 return DateStrToDate(this=date_literal) 5577 if isinstance(value, tuple): 5578 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5579 if isinstance(value, list): 5580 return Array(expressions=[convert(v, copy=copy) for v in value]) 5581 if isinstance(value, dict): 5582 return Map( 5583 keys=[convert(k, copy=copy) for k in value], 5584 values=[convert(v, copy=copy) for v in value.values()], 5585 ) 5586 raise ValueError(f"Cannot convert {value}") 5587 5588 5589def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5590 """ 5591 Replace children of an expression with the result of a lambda fun(child) -> exp. 5592 """ 5593 for k, v in expression.args.items(): 5594 is_list_arg = type(v) is list 5595 5596 child_nodes = v if is_list_arg else [v] 5597 new_child_nodes = [] 5598 5599 for cn in child_nodes: 5600 if isinstance(cn, Expression): 5601 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5602 new_child_nodes.append(child_node) 5603 child_node.parent = expression 5604 child_node.arg_key = k 5605 else: 5606 new_child_nodes.append(cn) 5607 5608 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 5609 5610 5611def column_table_names(expression: Expression) -> t.List[str]: 5612 """ 5613 Return all table names referenced through columns in an expression. 5614 5615 Example: 5616 >>> import sqlglot 5617 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5618 ['c', 'a'] 5619 5620 Args: 5621 expression: expression to find table names. 5622 5623 Returns: 5624 A list of unique names. 5625 """ 5626 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 5627 5628 5629def table_name(table: Table | str) -> str: 5630 """Get the full name of a table as a string. 5631 5632 Args: 5633 table: table expression node or string. 5634 5635 Examples: 5636 >>> from sqlglot import exp, parse_one 5637 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5638 'a.b.c' 5639 5640 Returns: 5641 The table name. 5642 """ 5643 5644 table = maybe_parse(table, into=Table) 5645 5646 if not table: 5647 raise ValueError(f"Cannot parse {table}") 5648 5649 return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part) 5650 5651 5652def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E: 5653 """Replace all tables in expression according to the mapping. 5654 5655 Args: 5656 expression: expression node to be transformed and replaced. 5657 mapping: mapping of table names. 5658 5659 Examples: 5660 >>> from sqlglot import exp, parse_one 5661 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5662 'SELECT * FROM c' 5663 5664 Returns: 5665 The mapped expression. 5666 """ 5667 5668 def _replace_tables(node: Expression) -> Expression: 5669 if isinstance(node, Table): 5670 new_name = mapping.get(table_name(node)) 5671 if new_name: 5672 return to_table( 5673 new_name, 5674 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5675 ) 5676 return node 5677 5678 return expression.transform(_replace_tables) 5679 5680 5681def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5682 """Replace placeholders in an expression. 5683 5684 Args: 5685 expression: expression node to be transformed and replaced. 5686 args: positional names that will substitute unnamed placeholders in the given order. 5687 kwargs: keyword arguments that will substitute named placeholders. 5688 5689 Examples: 5690 >>> from sqlglot import exp, parse_one 5691 >>> replace_placeholders( 5692 ... parse_one("select * from :tbl where ? = ?"), 5693 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5694 ... ).sql() 5695 "SELECT * FROM foo WHERE str_col = 'b'" 5696 5697 Returns: 5698 The mapped expression. 5699 """ 5700 5701 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5702 if isinstance(node, Placeholder): 5703 if node.name: 5704 new_name = kwargs.get(node.name) 5705 if new_name: 5706 return convert(new_name) 5707 else: 5708 try: 5709 return convert(next(args)) 5710 except StopIteration: 5711 pass 5712 return node 5713 5714 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5715 5716 5717def expand( 5718 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5719) -> Expression: 5720 """Transforms an expression by expanding all referenced sources into subqueries. 5721 5722 Examples: 5723 >>> from sqlglot import parse_one 5724 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5725 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5726 5727 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5728 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5729 5730 Args: 5731 expression: The expression to expand. 5732 sources: A dictionary of name to Subqueryables. 5733 copy: Whether or not to copy the expression during transformation. Defaults to True. 5734 5735 Returns: 5736 The transformed expression. 5737 """ 5738 5739 def _expand(node: Expression): 5740 if isinstance(node, Table): 5741 name = table_name(node) 5742 source = sources.get(name) 5743 if source: 5744 subquery = source.subquery(node.alias or name) 5745 subquery.comments = [f"source: {name}"] 5746 return subquery.transform(_expand, copy=False) 5747 return node 5748 5749 return expression.transform(_expand, copy=copy) 5750 5751 5752def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5753 """ 5754 Returns a Func expression. 5755 5756 Examples: 5757 >>> func("abs", 5).sql() 5758 'ABS(5)' 5759 5760 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5761 'CAST(5 AS DOUBLE)' 5762 5763 Args: 5764 name: the name of the function to build. 5765 args: the args used to instantiate the function of interest. 5766 dialect: the source dialect. 5767 kwargs: the kwargs used to instantiate the function of interest. 5768 5769 Note: 5770 The arguments `args` and `kwargs` are mutually exclusive. 5771 5772 Returns: 5773 An instance of the function of interest, or an anonymous function, if `name` doesn't 5774 correspond to an existing `sqlglot.expressions.Func` class. 5775 """ 5776 if args and kwargs: 5777 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5778 5779 from sqlglot.dialects.dialect import Dialect 5780 5781 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5782 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5783 5784 parser = Dialect.get_or_raise(dialect)().parser() 5785 from_args_list = parser.FUNCTIONS.get(name.upper()) 5786 5787 if from_args_list: 5788 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5789 else: 5790 kwargs = kwargs or {"expressions": converted} 5791 function = Anonymous(this=name, **kwargs) 5792 5793 for error_message in function.error_messages(converted): 5794 raise ValueError(error_message) 5795 5796 return function 5797 5798 5799def true() -> Boolean: 5800 """ 5801 Returns a true Boolean expression. 5802 """ 5803 return Boolean(this=True) 5804 5805 5806def false() -> Boolean: 5807 """ 5808 Returns a false Boolean expression. 5809 """ 5810 return Boolean(this=False) 5811 5812 5813def null() -> Null: 5814 """ 5815 Returns a Null expression. 5816 """ 5817 return Null() 5818 5819 5820# TODO: deprecate this 5821TRUE = Boolean(this=True) 5822FALSE = Boolean(this=False) 5823NULL = Null()
55class Expression(metaclass=_Expression): 56 """ 57 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 58 context, such as its child expressions, their names (arg keys), and whether a given child expression 59 is optional or not. 60 61 Attributes: 62 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 63 and representing expressions as strings. 64 arg_types: determines what arguments (child nodes) are supported by an expression. It 65 maps arg keys to booleans that indicate whether the corresponding args are optional. 66 parent: a reference to the parent expression (or None, in case of root expressions). 67 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 68 uses to refer to it. 69 comments: a list of comments that are associated with a given expression. This is used in 70 order to preserve comments when transpiling SQL code. 71 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 72 optimizer, in order to enable some transformations that require type information. 73 74 Example: 75 >>> class Foo(Expression): 76 ... arg_types = {"this": True, "expression": False} 77 78 The above definition informs us that Foo is an Expression that requires an argument called 79 "this" and may also optionally receive an argument called "expression". 80 81 Args: 82 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 83 """ 84 85 key = "expression" 86 arg_types = {"this": True} 87 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 88 89 def __init__(self, **args: t.Any): 90 self.args: t.Dict[str, t.Any] = args 91 self.parent: t.Optional[Expression] = None 92 self.arg_key: t.Optional[str] = None 93 self.comments: t.Optional[t.List[str]] = None 94 self._type: t.Optional[DataType] = None 95 self._meta: t.Optional[t.Dict[str, t.Any]] = None 96 self._hash: t.Optional[int] = None 97 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value) 100 101 def __eq__(self, other) -> bool: 102 return type(self) is type(other) and hash(self) == hash(other) 103 104 @property 105 def hashable_args(self) -> t.Any: 106 args = (self.args.get(k) for k in self.arg_types) 107 108 return tuple( 109 (tuple(_norm_arg(a) for a in arg) if arg else None) 110 if type(arg) is list 111 else (_norm_arg(arg) if arg is not None and arg is not False else None) 112 for arg in args 113 ) 114 115 def __hash__(self) -> int: 116 if self._hash is not None: 117 return self._hash 118 119 return hash((self.__class__, self.hashable_args)) 120 121 @property 122 def this(self): 123 """ 124 Retrieves the argument with key "this". 125 """ 126 return self.args.get("this") 127 128 @property 129 def expression(self): 130 """ 131 Retrieves the argument with key "expression". 132 """ 133 return self.args.get("expression") 134 135 @property 136 def expressions(self): 137 """ 138 Retrieves the argument with key "expressions". 139 """ 140 return self.args.get("expressions") or [] 141 142 def text(self, key) -> str: 143 """ 144 Returns a textual representation of the argument corresponding to "key". This can only be used 145 for args that are strings or leaf Expression instances, such as identifiers and literals. 146 """ 147 field = self.args.get(key) 148 if isinstance(field, str): 149 return field 150 if isinstance(field, (Identifier, Literal, Var)): 151 return field.this 152 if isinstance(field, (Star, Null)): 153 return field.name 154 return "" 155 156 @property 157 def is_string(self) -> bool: 158 """ 159 Checks whether a Literal expression is a string. 160 """ 161 return isinstance(self, Literal) and self.args["is_string"] 162 163 @property 164 def is_number(self) -> bool: 165 """ 166 Checks whether a Literal expression is a number. 167 """ 168 return isinstance(self, Literal) and not self.args["is_string"] 169 170 @property 171 def is_int(self) -> bool: 172 """ 173 Checks whether a Literal expression is an integer. 174 """ 175 if self.is_number: 176 try: 177 int(self.name) 178 return True 179 except ValueError: 180 pass 181 return False 182 183 @property 184 def is_star(self) -> bool: 185 """Checks whether an expression is a star.""" 186 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 187 188 @property 189 def alias(self) -> str: 190 """ 191 Returns the alias of the expression, or an empty string if it's not aliased. 192 """ 193 if isinstance(self.args.get("alias"), TableAlias): 194 return self.args["alias"].name 195 return self.text("alias") 196 197 @property 198 def name(self) -> str: 199 return self.text("this") 200 201 @property 202 def alias_or_name(self) -> str: 203 return self.alias or self.name 204 205 @property 206 def output_name(self) -> str: 207 """ 208 Name of the output column if this expression is a selection. 209 210 If the Expression has no output name, an empty string is returned. 211 212 Example: 213 >>> from sqlglot import parse_one 214 >>> parse_one("SELECT a").expressions[0].output_name 215 'a' 216 >>> parse_one("SELECT b AS c").expressions[0].output_name 217 'c' 218 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 219 '' 220 """ 221 return "" 222 223 @property 224 def type(self) -> t.Optional[DataType]: 225 return self._type 226 227 @type.setter 228 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 229 if dtype and not isinstance(dtype, DataType): 230 dtype = DataType.build(dtype) 231 self._type = dtype # type: ignore 232 233 @property 234 def meta(self) -> t.Dict[str, t.Any]: 235 if self._meta is None: 236 self._meta = {} 237 return self._meta 238 239 def __deepcopy__(self, memo): 240 copy = self.__class__(**deepcopy(self.args)) 241 if self.comments is not None: 242 copy.comments = deepcopy(self.comments) 243 244 if self._type is not None: 245 copy._type = self._type.copy() 246 247 if self._meta is not None: 248 copy._meta = deepcopy(self._meta) 249 250 return copy 251 252 def copy(self): 253 """ 254 Returns a deep copy of the expression. 255 """ 256 new = deepcopy(self) 257 new.parent = self.parent 258 return new 259 260 def add_comments(self, comments: t.Optional[t.List[str]]) -> None: 261 if self.comments is None: 262 self.comments = [] 263 if comments: 264 self.comments.extend(comments) 265 266 def append(self, arg_key: str, value: t.Any) -> None: 267 """ 268 Appends value to arg_key if it's a list or sets it as a new list. 269 270 Args: 271 arg_key (str): name of the list expression arg 272 value (Any): value to append to the list 273 """ 274 if not isinstance(self.args.get(arg_key), list): 275 self.args[arg_key] = [] 276 self.args[arg_key].append(value) 277 self._set_parent(arg_key, value) 278 279 def set(self, arg_key: str, value: t.Any) -> None: 280 """ 281 Sets `arg_key` to `value`. 282 283 Args: 284 arg_key (str): name of the expression arg. 285 value: value to set the arg to. 286 """ 287 self.args[arg_key] = value 288 self._set_parent(arg_key, value) 289 290 def _set_parent(self, arg_key: str, value: t.Any) -> None: 291 if hasattr(value, "parent"): 292 value.parent = self 293 value.arg_key = arg_key 294 elif type(value) is list: 295 for v in value: 296 if hasattr(v, "parent"): 297 v.parent = self 298 v.arg_key = arg_key 299 300 @property 301 def depth(self) -> int: 302 """ 303 Returns the depth of this tree. 304 """ 305 if self.parent: 306 return self.parent.depth + 1 307 return 0 308 309 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 310 """Yields the key and expression for all arguments, exploding list args.""" 311 for k, vs in self.args.items(): 312 if type(vs) is list: 313 for v in vs: 314 if hasattr(v, "parent"): 315 yield k, v 316 else: 317 if hasattr(vs, "parent"): 318 yield k, vs 319 320 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 321 """ 322 Returns the first node in this tree which matches at least one of 323 the specified types. 324 325 Args: 326 expression_types: the expression type(s) to match. 327 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 328 329 Returns: 330 The node which matches the criteria or None if no such node was found. 331 """ 332 return next(self.find_all(*expression_types, bfs=bfs), None) 333 334 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 335 """ 336 Returns a generator object which visits all nodes in this tree and only 337 yields those that match at least one of the specified expression types. 338 339 Args: 340 expression_types: the expression type(s) to match. 341 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression 349 350 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor) 364 365 @property 366 def parent_select(self) -> t.Optional[Select]: 367 """ 368 Returns the parent select statement. 369 """ 370 return self.find_ancestor(Select) 371 372 @property 373 def same_parent(self) -> bool: 374 """Returns if the parent is the same class as itself.""" 375 return type(self.parent) is self.__class__ 376 377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression 385 386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune) 403 404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune) 419 420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k)) 439 440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression 448 449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self 456 457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 462 463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node 472 473 def __str__(self) -> str: 474 return self.sql() 475 476 def __repr__(self) -> str: 477 return self._to_s() 478 479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts) 493 494 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 495 indent = "" if not level else "\n" 496 indent += "".join([" "] * level) 497 left = f"({self.key.upper()} " 498 499 args: t.Dict[str, t.Any] = { 500 k: ", ".join( 501 v._to_s(hide_missing=hide_missing, level=level + 1) 502 if hasattr(v, "_to_s") 503 else str(v) 504 for v in ensure_list(vs) 505 if v is not None 506 ) 507 for k, vs in self.args.items() 508 } 509 args["comments"] = self.comments 510 args["type"] = self.type 511 args = {k: v for k, v in args.items() if v or not hide_missing} 512 513 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 514 right += ")" 515 516 return indent + left + right 517 518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node 544 545 @t.overload 546 def replace(self, expression: E) -> E: 547 ... 548 549 @t.overload 550 def replace(self, expression: None) -> None: 551 ... 552 553 def replace(self, expression): 554 """ 555 Swap out this expression with a new expression. 556 557 For example:: 558 559 >>> tree = Select().select("x").from_("tbl") 560 >>> tree.find(Column).replace(Column(this="y")) 561 (COLUMN this: y) 562 >>> tree.sql() 563 'SELECT y FROM tbl' 564 565 Args: 566 expression: new node 567 568 Returns: 569 The new expression or expressions. 570 """ 571 if not self.parent: 572 return expression 573 574 parent = self.parent 575 self.parent = None 576 577 replace_children(parent, lambda child: expression if child is self else child) 578 return expression 579 580 def pop(self: E) -> E: 581 """ 582 Remove this expression from its AST. 583 584 Returns: 585 The popped expression. 586 """ 587 self.replace(None) 588 return self 589 590 def assert_is(self, type_: t.Type[E]) -> E: 591 """ 592 Assert that this `Expression` is an instance of `type_`. 593 594 If it is NOT an instance of `type_`, this raises an assertion error. 595 Otherwise, this returns this expression. 596 597 Examples: 598 This is useful for type security in chained expressions: 599 600 >>> import sqlglot 601 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 602 'SELECT x, z FROM y' 603 """ 604 assert isinstance(self, type_) 605 return self 606 607 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 608 """ 609 Checks if this expression is valid (e.g. all mandatory args are set). 610 611 Args: 612 args: a sequence of values that were used to instantiate a Func expression. This is used 613 to check that the provided arguments don't exceed the function argument limit. 614 615 Returns: 616 A list of error messages for all possible errors that were found. 617 """ 618 errors: t.List[str] = [] 619 620 for k in self.args: 621 if k not in self.arg_types: 622 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 623 for k, mandatory in self.arg_types.items(): 624 v = self.args.get(k) 625 if mandatory and (v is None or (isinstance(v, list) and not v)): 626 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 627 628 if ( 629 args 630 and isinstance(self, Func) 631 and len(args) > len(self.arg_types) 632 and not self.is_var_len_args 633 ): 634 errors.append( 635 f"The number of provided arguments ({len(args)}) is greater than " 636 f"the maximum number of supported arguments ({len(self.arg_types)})" 637 ) 638 639 return errors 640 641 def dump(self): 642 """ 643 Dump this Expression to a JSON-serializable dict. 644 """ 645 from sqlglot.serde import dump 646 647 return dump(self) 648 649 @classmethod 650 def load(cls, obj): 651 """ 652 Load a dict (as returned by `Expression.dump`) into an Expression instance. 653 """ 654 from sqlglot.serde import load 655 656 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataType
type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
89 def __init__(self, **args: t.Any): 90 self.args: t.Dict[str, t.Any] = args 91 self.parent: t.Optional[Expression] = None 92 self.arg_key: t.Optional[str] = None 93 self.comments: t.Optional[t.List[str]] = None 94 self._type: t.Optional[DataType] = None 95 self._meta: t.Optional[t.Dict[str, t.Any]] = None 96 self._hash: t.Optional[int] = None 97 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value)
142 def text(self, key) -> str: 143 """ 144 Returns a textual representation of the argument corresponding to "key". This can only be used 145 for args that are strings or leaf Expression instances, such as identifiers and literals. 146 """ 147 field = self.args.get(key) 148 if isinstance(field, str): 149 return field 150 if isinstance(field, (Identifier, Literal, Var)): 151 return field.this 152 if isinstance(field, (Star, Null)): 153 return field.name 154 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
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 ''
252 def copy(self): 253 """ 254 Returns a deep copy of the expression. 255 """ 256 new = deepcopy(self) 257 new.parent = self.parent 258 return new
Returns a deep copy of the expression.
266 def append(self, arg_key: str, value: t.Any) -> None: 267 """ 268 Appends value to arg_key if it's a list or sets it as a new list. 269 270 Args: 271 arg_key (str): name of the list expression arg 272 value (Any): value to append to the list 273 """ 274 if not isinstance(self.args.get(arg_key), list): 275 self.args[arg_key] = [] 276 self.args[arg_key].append(value) 277 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
279 def set(self, arg_key: str, value: t.Any) -> None: 280 """ 281 Sets `arg_key` to `value`. 282 283 Args: 284 arg_key (str): name of the expression arg. 285 value: value to set the arg to. 286 """ 287 self.args[arg_key] = value 288 self._set_parent(arg_key, value)
Sets arg_key
to value
.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
309 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 310 """Yields the key and expression for all arguments, exploding list args.""" 311 for k, vs in self.args.items(): 312 if type(vs) is list: 313 for v in vs: 314 if hasattr(v, "parent"): 315 yield k, v 316 else: 317 if hasattr(vs, "parent"): 318 yield k, vs
Yields the key and expression for all arguments, exploding list args.
320 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 321 """ 322 Returns the first node in this tree which matches at least one of 323 the specified types. 324 325 Args: 326 expression_types: the expression type(s) to match. 327 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 328 329 Returns: 330 The node which matches the criteria or None if no such node was found. 331 """ 332 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
- bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:
The node which matches the criteria or None if no such node was found.
334 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 335 """ 336 Returns a generator object which visits all nodes in this tree and only 337 yields those that match at least one of the specified expression types. 338 339 Args: 340 expression_types: the expression type(s) to match. 341 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
- bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:
The generator object.
350 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression
Returns the root expression of this tree.
386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression
Returns the first non parenthesis child or self.
449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self
Returns the inner expression if this is an Alias.
457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generator
options.
Returns:
The SQL string.
518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
553 def replace(self, expression): 554 """ 555 Swap out this expression with a new expression. 556 557 For example:: 558 559 >>> tree = Select().select("x").from_("tbl") 560 >>> tree.find(Column).replace(Column(this="y")) 561 (COLUMN this: y) 562 >>> tree.sql() 563 'SELECT y FROM tbl' 564 565 Args: 566 expression: new node 567 568 Returns: 569 The new expression or expressions. 570 """ 571 if not self.parent: 572 return expression 573 574 parent = self.parent 575 self.parent = None 576 577 replace_children(parent, lambda child: expression if child is self else child) 578 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression: new node
Returns:
The new expression or expressions.
580 def pop(self: E) -> E: 581 """ 582 Remove this expression from its AST. 583 584 Returns: 585 The popped expression. 586 """ 587 self.replace(None) 588 return self
Remove this expression from its AST.
Returns:
The popped expression.
590 def assert_is(self, type_: t.Type[E]) -> E: 591 """ 592 Assert that this `Expression` is an instance of `type_`. 593 594 If it is NOT an instance of `type_`, this raises an assertion error. 595 Otherwise, this returns this expression. 596 597 Examples: 598 This is useful for type security in chained expressions: 599 600 >>> import sqlglot 601 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 602 'SELECT x, z FROM y' 603 """ 604 assert isinstance(self, type_) 605 return self
Assert that this Expression
is an instance of type_
.
If it is NOT an instance of type_
, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
607 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 608 """ 609 Checks if this expression is valid (e.g. all mandatory args are set). 610 611 Args: 612 args: a sequence of values that were used to instantiate a Func expression. This is used 613 to check that the provided arguments don't exceed the function argument limit. 614 615 Returns: 616 A list of error messages for all possible errors that were found. 617 """ 618 errors: t.List[str] = [] 619 620 for k in self.args: 621 if k not in self.arg_types: 622 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 623 for k, mandatory in self.arg_types.items(): 624 v = self.args.get(k) 625 if mandatory and (v is None or (isinstance(v, list) and not v)): 626 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 627 628 if ( 629 args 630 and isinstance(self, Func) 631 and len(args) > len(self.arg_types) 632 and not self.is_var_len_args 633 ): 634 errors.append( 635 f"The number of provided arguments ({len(args)}) is greater than " 636 f"the maximum number of supported arguments ({len(self.arg_types)})" 637 ) 638 639 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
641 def dump(self): 642 """ 643 Dump this Expression to a JSON-serializable dict. 644 """ 645 from sqlglot.serde import dump 646 647 return dump(self)
Dump this Expression to a JSON-serializable dict.
649 @classmethod 650 def load(cls, obj): 651 """ 652 Load a dict (as returned by `Expression.dump`) into an Expression instance. 653 """ 654 from sqlglot.serde import load 655 656 return load(obj)
Load a dict (as returned by Expression.dump
) into an Expression instance.
667class Condition(Expression): 668 def and_( 669 self, 670 *expressions: t.Optional[ExpOrStr], 671 dialect: DialectType = None, 672 copy: bool = True, 673 **opts, 674 ) -> Condition: 675 """ 676 AND this condition with one or multiple expressions. 677 678 Example: 679 >>> condition("x=1").and_("y=1").sql() 680 'x = 1 AND y = 1' 681 682 Args: 683 *expressions: the SQL code strings to parse. 684 If an `Expression` instance is passed, it will be used as-is. 685 dialect: the dialect used to parse the input expression. 686 copy: whether or not to copy the involved expressions (only applies to Expressions). 687 opts: other options to use to parse the input expressions. 688 689 Returns: 690 The new And condition. 691 """ 692 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 693 694 def or_( 695 self, 696 *expressions: t.Optional[ExpOrStr], 697 dialect: DialectType = None, 698 copy: bool = True, 699 **opts, 700 ) -> Condition: 701 """ 702 OR this condition with one or multiple expressions. 703 704 Example: 705 >>> condition("x=1").or_("y=1").sql() 706 'x = 1 OR y = 1' 707 708 Args: 709 *expressions: the SQL code strings to parse. 710 If an `Expression` instance is passed, it will be used as-is. 711 dialect: the dialect used to parse the input expression. 712 copy: whether or not to copy the involved expressions (only applies to Expressions). 713 opts: other options to use to parse the input expressions. 714 715 Returns: 716 The new Or condition. 717 """ 718 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 719 720 def not_(self, copy: bool = True): 721 """ 722 Wrap this condition with NOT. 723 724 Example: 725 >>> condition("x=1").not_().sql() 726 'NOT x = 1' 727 728 Args: 729 copy: whether or not to copy this object. 730 731 Returns: 732 The new Not instance. 733 """ 734 return not_(self, copy=copy) 735 736 def as_( 737 self, 738 alias: str | Identifier, 739 quoted: t.Optional[bool] = None, 740 dialect: DialectType = None, 741 copy: bool = True, 742 **opts, 743 ) -> Alias: 744 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 745 746 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 747 this = self.copy() 748 other = convert(other, copy=True) 749 if not isinstance(this, klass) and not isinstance(other, klass): 750 this = _wrap(this, Binary) 751 other = _wrap(other, Binary) 752 if reverse: 753 return klass(this=other, expression=this) 754 return klass(this=this, expression=other) 755 756 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 757 return Bracket( 758 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 759 ) 760 761 def isin( 762 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 763 ) -> In: 764 return In( 765 this=_maybe_copy(self, copy), 766 expressions=[convert(e, copy=copy) for e in expressions], 767 query=maybe_parse(query, copy=copy, **opts) if query else None, 768 ) 769 770 def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between: 771 return Between( 772 this=_maybe_copy(self, copy), 773 low=convert(low, copy=copy, **opts), 774 high=convert(high, copy=copy, **opts), 775 ) 776 777 def is_(self, other: ExpOrStr) -> Is: 778 return self._binop(Is, other) 779 780 def like(self, other: ExpOrStr) -> Like: 781 return self._binop(Like, other) 782 783 def ilike(self, other: ExpOrStr) -> ILike: 784 return self._binop(ILike, other) 785 786 def eq(self, other: t.Any) -> EQ: 787 return self._binop(EQ, other) 788 789 def neq(self, other: t.Any) -> NEQ: 790 return self._binop(NEQ, other) 791 792 def rlike(self, other: ExpOrStr) -> RegexpLike: 793 return self._binop(RegexpLike, other) 794 795 def __lt__(self, other: t.Any) -> LT: 796 return self._binop(LT, other) 797 798 def __le__(self, other: t.Any) -> LTE: 799 return self._binop(LTE, other) 800 801 def __gt__(self, other: t.Any) -> GT: 802 return self._binop(GT, other) 803 804 def __ge__(self, other: t.Any) -> GTE: 805 return self._binop(GTE, other) 806 807 def __add__(self, other: t.Any) -> Add: 808 return self._binop(Add, other) 809 810 def __radd__(self, other: t.Any) -> Add: 811 return self._binop(Add, other, reverse=True) 812 813 def __sub__(self, other: t.Any) -> Sub: 814 return self._binop(Sub, other) 815 816 def __rsub__(self, other: t.Any) -> Sub: 817 return self._binop(Sub, other, reverse=True) 818 819 def __mul__(self, other: t.Any) -> Mul: 820 return self._binop(Mul, other) 821 822 def __rmul__(self, other: t.Any) -> Mul: 823 return self._binop(Mul, other, reverse=True) 824 825 def __truediv__(self, other: t.Any) -> Div: 826 return self._binop(Div, other) 827 828 def __rtruediv__(self, other: t.Any) -> Div: 829 return self._binop(Div, other, reverse=True) 830 831 def __floordiv__(self, other: t.Any) -> IntDiv: 832 return self._binop(IntDiv, other) 833 834 def __rfloordiv__(self, other: t.Any) -> IntDiv: 835 return self._binop(IntDiv, other, reverse=True) 836 837 def __mod__(self, other: t.Any) -> Mod: 838 return self._binop(Mod, other) 839 840 def __rmod__(self, other: t.Any) -> Mod: 841 return self._binop(Mod, other, reverse=True) 842 843 def __pow__(self, other: t.Any) -> Pow: 844 return self._binop(Pow, other) 845 846 def __rpow__(self, other: t.Any) -> Pow: 847 return self._binop(Pow, other, reverse=True) 848 849 def __and__(self, other: t.Any) -> And: 850 return self._binop(And, other) 851 852 def __rand__(self, other: t.Any) -> And: 853 return self._binop(And, other, reverse=True) 854 855 def __or__(self, other: t.Any) -> Or: 856 return self._binop(Or, other) 857 858 def __ror__(self, other: t.Any) -> Or: 859 return self._binop(Or, other, reverse=True) 860 861 def __neg__(self) -> Neg: 862 return Neg(this=_wrap(self.copy(), Binary)) 863 864 def __invert__(self) -> Not: 865 return not_(self.copy())
668 def and_( 669 self, 670 *expressions: t.Optional[ExpOrStr], 671 dialect: DialectType = None, 672 copy: bool = True, 673 **opts, 674 ) -> Condition: 675 """ 676 AND this condition with one or multiple expressions. 677 678 Example: 679 >>> condition("x=1").and_("y=1").sql() 680 'x = 1 AND y = 1' 681 682 Args: 683 *expressions: the SQL code strings to parse. 684 If an `Expression` instance is passed, it will be used as-is. 685 dialect: the dialect used to parse the input expression. 686 copy: whether or not to copy the involved expressions (only applies to Expressions). 687 opts: other options to use to parse the input expressions. 688 689 Returns: 690 The new And condition. 691 """ 692 return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expression.
- copy: whether or not to copy the involved expressions (only applies to Expressions).
- opts: other options to use to parse the input expressions.
Returns:
The new And condition.
694 def or_( 695 self, 696 *expressions: t.Optional[ExpOrStr], 697 dialect: DialectType = None, 698 copy: bool = True, 699 **opts, 700 ) -> Condition: 701 """ 702 OR this condition with one or multiple expressions. 703 704 Example: 705 >>> condition("x=1").or_("y=1").sql() 706 'x = 1 OR y = 1' 707 708 Args: 709 *expressions: the SQL code strings to parse. 710 If an `Expression` instance is passed, it will be used as-is. 711 dialect: the dialect used to parse the input expression. 712 copy: whether or not to copy the involved expressions (only applies to Expressions). 713 opts: other options to use to parse the input expressions. 714 715 Returns: 716 The new Or condition. 717 """ 718 return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expression.
- copy: whether or not to copy the involved expressions (only applies to Expressions).
- opts: other options to use to parse the input expressions.
Returns:
The new Or condition.
720 def not_(self, copy: bool = True): 721 """ 722 Wrap this condition with NOT. 723 724 Example: 725 >>> condition("x=1").not_().sql() 726 'NOT x = 1' 727 728 Args: 729 copy: whether or not to copy this object. 730 731 Returns: 732 The new Not instance. 733 """ 734 return not_(self, copy=copy)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Arguments:
- copy: whether or not to copy this object.
Returns:
The new Not instance.
761 def isin( 762 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 763 ) -> In: 764 return In( 765 this=_maybe_copy(self, copy), 766 expressions=[convert(e, copy=copy) for e in expressions], 767 query=maybe_parse(query, copy=copy, **opts) if query else None, 768 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
872class DerivedTable(Expression): 873 @property 874 def alias_column_names(self) -> t.List[str]: 875 table_alias = self.args.get("alias") 876 if not table_alias: 877 return [] 878 return [c.name for c in table_alias.args.get("columns") or []] 879 880 @property 881 def selects(self): 882 return self.this.selects if isinstance(self.this, Subqueryable) else [] 883 884 @property 885 def named_selects(self): 886 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
889class Unionable(Expression): 890 def union( 891 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 892 ) -> Unionable: 893 """ 894 Builds a UNION expression. 895 896 Example: 897 >>> import sqlglot 898 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 899 'SELECT * FROM foo UNION SELECT * FROM bla' 900 901 Args: 902 expression: the SQL code string. 903 If an `Expression` instance is passed, it will be used as-is. 904 distinct: set the DISTINCT flag if and only if this is true. 905 dialect: the dialect used to parse the input expression. 906 opts: other options to use to parse the input expressions. 907 908 Returns: 909 The new Union expression. 910 """ 911 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 912 913 def intersect( 914 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 915 ) -> Unionable: 916 """ 917 Builds an INTERSECT expression. 918 919 Example: 920 >>> import sqlglot 921 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 922 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 923 924 Args: 925 expression: the SQL code string. 926 If an `Expression` instance is passed, it will be used as-is. 927 distinct: set the DISTINCT flag if and only if this is true. 928 dialect: the dialect used to parse the input expression. 929 opts: other options to use to parse the input expressions. 930 931 Returns: 932 The new Intersect expression. 933 """ 934 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 935 936 def except_( 937 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 938 ) -> Unionable: 939 """ 940 Builds an EXCEPT expression. 941 942 Example: 943 >>> import sqlglot 944 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 945 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 946 947 Args: 948 expression: the SQL code string. 949 If an `Expression` instance is passed, it will be used as-is. 950 distinct: set the DISTINCT flag if and only if this is true. 951 dialect: the dialect used to parse the input expression. 952 opts: other options to use to parse the input expressions. 953 954 Returns: 955 The new Except expression. 956 """ 957 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
890 def union( 891 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 892 ) -> Unionable: 893 """ 894 Builds a UNION expression. 895 896 Example: 897 >>> import sqlglot 898 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 899 'SELECT * FROM foo UNION SELECT * FROM bla' 900 901 Args: 902 expression: the SQL code string. 903 If an `Expression` instance is passed, it will be used as-is. 904 distinct: set the DISTINCT flag if and only if this is true. 905 dialect: the dialect used to parse the input expression. 906 opts: other options to use to parse the input expressions. 907 908 Returns: 909 The new Union expression. 910 """ 911 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Union expression.
913 def intersect( 914 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 915 ) -> Unionable: 916 """ 917 Builds an INTERSECT expression. 918 919 Example: 920 >>> import sqlglot 921 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 922 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 923 924 Args: 925 expression: the SQL code string. 926 If an `Expression` instance is passed, it will be used as-is. 927 distinct: set the DISTINCT flag if and only if this is true. 928 dialect: the dialect used to parse the input expression. 929 opts: other options to use to parse the input expressions. 930 931 Returns: 932 The new Intersect expression. 933 """ 934 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Intersect expression.
936 def except_( 937 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 938 ) -> Unionable: 939 """ 940 Builds an EXCEPT expression. 941 942 Example: 943 >>> import sqlglot 944 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 945 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 946 947 Args: 948 expression: the SQL code string. 949 If an `Expression` instance is passed, it will be used as-is. 950 distinct: set the DISTINCT flag if and only if this is true. 951 dialect: the dialect used to parse the input expression. 952 opts: other options to use to parse the input expressions. 953 954 Returns: 955 The new Except expression. 956 """ 957 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Except expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
960class UDTF(DerivedTable, Unionable): 961 @property 962 def selects(self): 963 alias = self.args.get("alias") 964 return alias.columns if alias else []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
967class Cache(Expression): 968 arg_types = { 969 "with": False, 970 "this": True, 971 "lazy": False, 972 "options": False, 973 "expression": False, 974 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
981class Create(Expression): 982 arg_types = { 983 "with": False, 984 "this": True, 985 "kind": True, 986 "expression": False, 987 "exists": False, 988 "properties": False, 989 "replace": False, 990 "unique": False, 991 "indexes": False, 992 "no_schema_binding": False, 993 "begin": False, 994 "clone": False, 995 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
999class Clone(Expression): 1000 arg_types = { 1001 "this": True, 1002 "when": False, 1003 "kind": False, 1004 "expression": False, 1005 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1020class SetItem(Expression): 1021 arg_types = { 1022 "this": False, 1023 "expressions": False, 1024 "kind": False, 1025 "collate": False, # MySQL SET NAMES statement 1026 "global": False, 1027 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1030class Show(Expression): 1031 arg_types = { 1032 "this": True, 1033 "target": False, 1034 "offset": False, 1035 "limit": False, 1036 "like": False, 1037 "where": False, 1038 "db": False, 1039 "full": False, 1040 "mutex": False, 1041 "query": False, 1042 "channel": False, 1043 "global": False, 1044 "log": False, 1045 "position": False, 1046 "types": False, 1047 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1050class UserDefinedFunction(Expression): 1051 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1058class With(Expression): 1059 arg_types = {"expressions": True, "recursive": False} 1060 1061 @property 1062 def recursive(self) -> bool: 1063 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1074class TableAlias(Expression): 1075 arg_types = {"this": False, "columns": False} 1076 1077 @property 1078 def columns(self): 1079 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1098class Column(Condition): 1099 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1100 1101 @property 1102 def table(self) -> str: 1103 return self.text("table") 1104 1105 @property 1106 def db(self) -> str: 1107 return self.text("db") 1108 1109 @property 1110 def catalog(self) -> str: 1111 return self.text("catalog") 1112 1113 @property 1114 def output_name(self) -> str: 1115 return self.name 1116 1117 @property 1118 def parts(self) -> t.List[Identifier]: 1119 """Return the parts of a column in order catalog, db, table, name.""" 1120 return [ 1121 t.cast(Identifier, self.args[part]) 1122 for part in ("catalog", "db", "table", "this") 1123 if self.args.get(part) 1124 ] 1125 1126 def to_dot(self) -> Dot: 1127 """Converts the column into a dot expression.""" 1128 parts = self.parts 1129 parent = self.parent 1130 1131 while parent: 1132 if isinstance(parent, Dot): 1133 parts.append(parent.expression) 1134 parent = parent.parent 1135 1136 return Dot.build(parts)
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.
1126 def to_dot(self) -> Dot: 1127 """Converts the column into a dot expression.""" 1128 parts = self.parts 1129 parent = self.parent 1130 1131 while parent: 1132 if isinstance(parent, Dot): 1133 parts.append(parent.expression) 1134 parent = parent.parent 1135 1136 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1143class ColumnDef(Expression): 1144 arg_types = { 1145 "this": True, 1146 "kind": False, 1147 "constraints": False, 1148 "exists": False, 1149 "position": False, 1150 } 1151 1152 @property 1153 def constraints(self) -> t.List[ColumnConstraint]: 1154 return self.args.get("constraints") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1157class AlterColumn(Expression): 1158 arg_types = { 1159 "this": True, 1160 "dtype": False, 1161 "collate": False, 1162 "using": False, 1163 "default": False, 1164 "drop": False, 1165 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1176class Comment(Expression): 1177 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1181class MergeTreeTTLAction(Expression): 1182 arg_types = { 1183 "this": True, 1184 "delete": False, 1185 "recompress": False, 1186 "to_disk": False, 1187 "to_volume": False, 1188 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1192class MergeTreeTTL(Expression): 1193 arg_types = { 1194 "expressions": True, 1195 "where": False, 1196 "group": False, 1197 "aggregates": False, 1198 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1201class ColumnConstraint(Expression): 1202 arg_types = {"this": False, "kind": True} 1203 1204 @property 1205 def kind(self) -> ColumnConstraintKind: 1206 return self.args["kind"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1253class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1254 # this: True -> ALWAYS, this: False -> BY DEFAULT 1255 arg_types = { 1256 "this": False, 1257 "expression": False, 1258 "on_null": False, 1259 "start": False, 1260 "increment": False, 1261 "minvalue": False, 1262 "maxvalue": False, 1263 "cycle": False, 1264 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1304class Delete(Expression): 1305 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1306 1307 def delete( 1308 self, 1309 table: ExpOrStr, 1310 dialect: DialectType = None, 1311 copy: bool = True, 1312 **opts, 1313 ) -> Delete: 1314 """ 1315 Create a DELETE expression or replace the table on an existing DELETE expression. 1316 1317 Example: 1318 >>> delete("tbl").sql() 1319 'DELETE FROM tbl' 1320 1321 Args: 1322 table: the table from which to delete. 1323 dialect: the dialect used to parse the input expression. 1324 copy: if `False`, modify this expression instance in-place. 1325 opts: other options to use to parse the input expressions. 1326 1327 Returns: 1328 Delete: the modified expression. 1329 """ 1330 return _apply_builder( 1331 expression=table, 1332 instance=self, 1333 arg="this", 1334 dialect=dialect, 1335 into=Table, 1336 copy=copy, 1337 **opts, 1338 ) 1339 1340 def where( 1341 self, 1342 *expressions: t.Optional[ExpOrStr], 1343 append: bool = True, 1344 dialect: DialectType = None, 1345 copy: bool = True, 1346 **opts, 1347 ) -> Delete: 1348 """ 1349 Append to or set the WHERE expressions. 1350 1351 Example: 1352 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1353 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1354 1355 Args: 1356 *expressions: the SQL code strings to parse. 1357 If an `Expression` instance is passed, it will be used as-is. 1358 Multiple expressions are combined with an AND operator. 1359 append: if `True`, AND the new expressions to any existing expression. 1360 Otherwise, this resets the expression. 1361 dialect: the dialect used to parse the input expressions. 1362 copy: if `False`, modify this expression instance in-place. 1363 opts: other options to use to parse the input expressions. 1364 1365 Returns: 1366 Delete: the modified expression. 1367 """ 1368 return _apply_conjunction_builder( 1369 *expressions, 1370 instance=self, 1371 arg="where", 1372 append=append, 1373 into=Where, 1374 dialect=dialect, 1375 copy=copy, 1376 **opts, 1377 ) 1378 1379 def returning( 1380 self, 1381 expression: ExpOrStr, 1382 dialect: DialectType = None, 1383 copy: bool = True, 1384 **opts, 1385 ) -> Delete: 1386 """ 1387 Set the RETURNING expression. Not supported by all dialects. 1388 1389 Example: 1390 >>> delete("tbl").returning("*", dialect="postgres").sql() 1391 'DELETE FROM tbl RETURNING *' 1392 1393 Args: 1394 expression: the SQL code strings to parse. 1395 If an `Expression` instance is passed, it will be used as-is. 1396 dialect: the dialect used to parse the input expressions. 1397 copy: if `False`, modify this expression instance in-place. 1398 opts: other options to use to parse the input expressions. 1399 1400 Returns: 1401 Delete: the modified expression. 1402 """ 1403 return _apply_builder( 1404 expression=expression, 1405 instance=self, 1406 arg="returning", 1407 prefix="RETURNING", 1408 dialect=dialect, 1409 copy=copy, 1410 into=Returning, 1411 **opts, 1412 )
1307 def delete( 1308 self, 1309 table: ExpOrStr, 1310 dialect: DialectType = None, 1311 copy: bool = True, 1312 **opts, 1313 ) -> Delete: 1314 """ 1315 Create a DELETE expression or replace the table on an existing DELETE expression. 1316 1317 Example: 1318 >>> delete("tbl").sql() 1319 'DELETE FROM tbl' 1320 1321 Args: 1322 table: the table from which to delete. 1323 dialect: the dialect used to parse the input expression. 1324 copy: if `False`, modify this expression instance in-place. 1325 opts: other options to use to parse the input expressions. 1326 1327 Returns: 1328 Delete: the modified expression. 1329 """ 1330 return _apply_builder( 1331 expression=table, 1332 instance=self, 1333 arg="this", 1334 dialect=dialect, 1335 into=Table, 1336 copy=copy, 1337 **opts, 1338 )
Create a DELETE expression or replace the table on an existing DELETE expression.
Example:
>>> delete("tbl").sql() 'DELETE FROM tbl'
Arguments:
- table: the table from which to delete.
- dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1340 def where( 1341 self, 1342 *expressions: t.Optional[ExpOrStr], 1343 append: bool = True, 1344 dialect: DialectType = None, 1345 copy: bool = True, 1346 **opts, 1347 ) -> Delete: 1348 """ 1349 Append to or set the WHERE expressions. 1350 1351 Example: 1352 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1353 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1354 1355 Args: 1356 *expressions: the SQL code strings to parse. 1357 If an `Expression` instance is passed, it will be used as-is. 1358 Multiple expressions are combined with an AND operator. 1359 append: if `True`, AND the new expressions to any existing expression. 1360 Otherwise, this resets the expression. 1361 dialect: the dialect used to parse the input expressions. 1362 copy: if `False`, modify this expression instance in-place. 1363 opts: other options to use to parse the input expressions. 1364 1365 Returns: 1366 Delete: the modified expression. 1367 """ 1368 return _apply_conjunction_builder( 1369 *expressions, 1370 instance=self, 1371 arg="where", 1372 append=append, 1373 into=Where, 1374 dialect=dialect, 1375 copy=copy, 1376 **opts, 1377 )
Append to or set the WHERE expressions.
Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1379 def returning( 1380 self, 1381 expression: ExpOrStr, 1382 dialect: DialectType = None, 1383 copy: bool = True, 1384 **opts, 1385 ) -> Delete: 1386 """ 1387 Set the RETURNING expression. Not supported by all dialects. 1388 1389 Example: 1390 >>> delete("tbl").returning("*", dialect="postgres").sql() 1391 'DELETE FROM tbl RETURNING *' 1392 1393 Args: 1394 expression: the SQL code strings to parse. 1395 If an `Expression` instance is passed, it will be used as-is. 1396 dialect: the dialect used to parse the input expressions. 1397 copy: if `False`, modify this expression instance in-place. 1398 opts: other options to use to parse the input expressions. 1399 1400 Returns: 1401 Delete: the modified expression. 1402 """ 1403 return _apply_builder( 1404 expression=expression, 1405 instance=self, 1406 arg="returning", 1407 prefix="RETURNING", 1408 dialect=dialect, 1409 copy=copy, 1410 into=Returning, 1411 **opts, 1412 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1415class Drop(Expression): 1416 arg_types = { 1417 "this": False, 1418 "kind": False, 1419 "exists": False, 1420 "temporary": False, 1421 "materialized": False, 1422 "cascade": False, 1423 "constraints": False, 1424 "purge": False, 1425 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1436class Directory(Expression): 1437 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1438 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1441class ForeignKey(Expression): 1442 arg_types = { 1443 "expressions": True, 1444 "reference": False, 1445 "delete": False, 1446 "update": False, 1447 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1460class From(Expression): 1461 @property 1462 def name(self) -> str: 1463 return self.this.name 1464 1465 @property 1466 def alias_or_name(self) -> str: 1467 return self.this.alias_or_name
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1482class Identifier(Expression): 1483 arg_types = {"this": True, "quoted": False} 1484 1485 @property 1486 def quoted(self) -> bool: 1487 return bool(self.args.get("quoted")) 1488 1489 @property 1490 def hashable_args(self) -> t.Any: 1491 if self.quoted and any(char.isupper() for char in self.this): 1492 return (self.this, self.quoted) 1493 return self.this.lower() 1494 1495 @property 1496 def output_name(self) -> str: 1497 return self.name
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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1500class Index(Expression): 1501 arg_types = { 1502 "this": False, 1503 "table": False, 1504 "where": False, 1505 "columns": False, 1506 "unique": False, 1507 "primary": False, 1508 "amp": False, # teradata 1509 "partition_by": False, # teradata 1510 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1513class Insert(Expression): 1514 arg_types = { 1515 "with": False, 1516 "this": True, 1517 "expression": False, 1518 "conflict": False, 1519 "returning": False, 1520 "overwrite": False, 1521 "exists": False, 1522 "partition": False, 1523 "alternative": False, 1524 } 1525 1526 def with_( 1527 self, 1528 alias: ExpOrStr, 1529 as_: ExpOrStr, 1530 recursive: t.Optional[bool] = None, 1531 append: bool = True, 1532 dialect: DialectType = None, 1533 copy: bool = True, 1534 **opts, 1535 ) -> Insert: 1536 """ 1537 Append to or set the common table expressions. 1538 1539 Example: 1540 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1541 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1542 1543 Args: 1544 alias: the SQL code string to parse as the table name. 1545 If an `Expression` instance is passed, this is used as-is. 1546 as_: the SQL code string to parse as the table expression. 1547 If an `Expression` instance is passed, it will be used as-is. 1548 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1549 append: if `True`, add to any existing expressions. 1550 Otherwise, this resets the expressions. 1551 dialect: the dialect used to parse the input expression. 1552 copy: if `False`, modify this expression instance in-place. 1553 opts: other options to use to parse the input expressions. 1554 1555 Returns: 1556 The modified expression. 1557 """ 1558 return _apply_cte_builder( 1559 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1560 )
1526 def with_( 1527 self, 1528 alias: ExpOrStr, 1529 as_: ExpOrStr, 1530 recursive: t.Optional[bool] = None, 1531 append: bool = True, 1532 dialect: DialectType = None, 1533 copy: bool = True, 1534 **opts, 1535 ) -> Insert: 1536 """ 1537 Append to or set the common table expressions. 1538 1539 Example: 1540 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1541 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1542 1543 Args: 1544 alias: the SQL code string to parse as the table name. 1545 If an `Expression` instance is passed, this is used as-is. 1546 as_: the SQL code string to parse as the table expression. 1547 If an `Expression` instance is passed, it will be used as-is. 1548 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1549 append: if `True`, add to any existing expressions. 1550 Otherwise, this resets the expressions. 1551 dialect: the dialect used to parse the input expression. 1552 copy: if `False`, modify this expression instance in-place. 1553 opts: other options to use to parse the input expressions. 1554 1555 Returns: 1556 The modified expression. 1557 """ 1558 return _apply_cte_builder( 1559 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1560 )
Append to or set the common table expressions.
Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
- alias: the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_: the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive: set the RECURSIVE part of the expression. Defaults to
False
. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1563class OnConflict(Expression): 1564 arg_types = { 1565 "duplicate": False, 1566 "expressions": False, 1567 "nothing": False, 1568 "key": False, 1569 "constraint": False, 1570 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1587class LoadData(Expression): 1588 arg_types = { 1589 "this": True, 1590 "local": False, 1591 "overwrite": False, 1592 "inpath": True, 1593 "partition": False, 1594 "input_format": False, 1595 "serde": False, 1596 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1603class Fetch(Expression): 1604 arg_types = { 1605 "direction": False, 1606 "count": False, 1607 "percent": False, 1608 "with_ties": False, 1609 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1612class Group(Expression): 1613 arg_types = { 1614 "expressions": False, 1615 "grouping_sets": False, 1616 "cube": False, 1617 "rollup": False, 1618 "totals": False, 1619 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1630class Literal(Condition): 1631 arg_types = {"this": True, "is_string": True} 1632 1633 @property 1634 def hashable_args(self) -> t.Any: 1635 return (self.this, self.args.get("is_string")) 1636 1637 @classmethod 1638 def number(cls, number) -> Literal: 1639 return cls(this=str(number), is_string=False) 1640 1641 @classmethod 1642 def string(cls, string) -> Literal: 1643 return cls(this=str(string), is_string=True) 1644 1645 @property 1646 def output_name(self) -> str: 1647 return self.name
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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1650class Join(Expression): 1651 arg_types = { 1652 "this": True, 1653 "on": False, 1654 "side": False, 1655 "kind": False, 1656 "using": False, 1657 "method": False, 1658 "global": False, 1659 "hint": False, 1660 } 1661 1662 @property 1663 def method(self) -> str: 1664 return self.text("method").upper() 1665 1666 @property 1667 def kind(self) -> str: 1668 return self.text("kind").upper() 1669 1670 @property 1671 def side(self) -> str: 1672 return self.text("side").upper() 1673 1674 @property 1675 def hint(self) -> str: 1676 return self.text("hint").upper() 1677 1678 @property 1679 def alias_or_name(self) -> str: 1680 return self.this.alias_or_name 1681 1682 def on( 1683 self, 1684 *expressions: t.Optional[ExpOrStr], 1685 append: bool = True, 1686 dialect: DialectType = None, 1687 copy: bool = True, 1688 **opts, 1689 ) -> Join: 1690 """ 1691 Append to or set the ON expressions. 1692 1693 Example: 1694 >>> import sqlglot 1695 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1696 'JOIN x ON y = 1' 1697 1698 Args: 1699 *expressions: the SQL code strings to parse. 1700 If an `Expression` instance is passed, it will be used as-is. 1701 Multiple expressions are combined with an AND operator. 1702 append: if `True`, AND the new expressions to any existing expression. 1703 Otherwise, this resets the expression. 1704 dialect: the dialect used to parse the input expressions. 1705 copy: if `False`, modify this expression instance in-place. 1706 opts: other options to use to parse the input expressions. 1707 1708 Returns: 1709 The modified Join expression. 1710 """ 1711 join = _apply_conjunction_builder( 1712 *expressions, 1713 instance=self, 1714 arg="on", 1715 append=append, 1716 dialect=dialect, 1717 copy=copy, 1718 **opts, 1719 ) 1720 1721 if join.kind == "CROSS": 1722 join.set("kind", None) 1723 1724 return join 1725 1726 def using( 1727 self, 1728 *expressions: t.Optional[ExpOrStr], 1729 append: bool = True, 1730 dialect: DialectType = None, 1731 copy: bool = True, 1732 **opts, 1733 ) -> Join: 1734 """ 1735 Append to or set the USING expressions. 1736 1737 Example: 1738 >>> import sqlglot 1739 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1740 'JOIN x USING (foo, bla)' 1741 1742 Args: 1743 *expressions: the SQL code strings to parse. 1744 If an `Expression` instance is passed, it will be used as-is. 1745 append: if `True`, concatenate the new expressions to the existing "using" list. 1746 Otherwise, this resets the expression. 1747 dialect: the dialect used to parse the input expressions. 1748 copy: if `False`, modify this expression instance in-place. 1749 opts: other options to use to parse the input expressions. 1750 1751 Returns: 1752 The modified Join expression. 1753 """ 1754 join = _apply_list_builder( 1755 *expressions, 1756 instance=self, 1757 arg="using", 1758 append=append, 1759 dialect=dialect, 1760 copy=copy, 1761 **opts, 1762 ) 1763 1764 if join.kind == "CROSS": 1765 join.set("kind", None) 1766 1767 return join
1682 def on( 1683 self, 1684 *expressions: t.Optional[ExpOrStr], 1685 append: bool = True, 1686 dialect: DialectType = None, 1687 copy: bool = True, 1688 **opts, 1689 ) -> Join: 1690 """ 1691 Append to or set the ON expressions. 1692 1693 Example: 1694 >>> import sqlglot 1695 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1696 'JOIN x ON y = 1' 1697 1698 Args: 1699 *expressions: the SQL code strings to parse. 1700 If an `Expression` instance is passed, it will be used as-is. 1701 Multiple expressions are combined with an AND operator. 1702 append: if `True`, AND the new expressions to any existing expression. 1703 Otherwise, this resets the expression. 1704 dialect: the dialect used to parse the input expressions. 1705 copy: if `False`, modify this expression instance in-place. 1706 opts: other options to use to parse the input expressions. 1707 1708 Returns: 1709 The modified Join expression. 1710 """ 1711 join = _apply_conjunction_builder( 1712 *expressions, 1713 instance=self, 1714 arg="on", 1715 append=append, 1716 dialect=dialect, 1717 copy=copy, 1718 **opts, 1719 ) 1720 1721 if join.kind == "CROSS": 1722 join.set("kind", None) 1723 1724 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Join expression.
1726 def using( 1727 self, 1728 *expressions: t.Optional[ExpOrStr], 1729 append: bool = True, 1730 dialect: DialectType = None, 1731 copy: bool = True, 1732 **opts, 1733 ) -> Join: 1734 """ 1735 Append to or set the USING expressions. 1736 1737 Example: 1738 >>> import sqlglot 1739 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1740 'JOIN x USING (foo, bla)' 1741 1742 Args: 1743 *expressions: the SQL code strings to parse. 1744 If an `Expression` instance is passed, it will be used as-is. 1745 append: if `True`, concatenate the new expressions to the existing "using" list. 1746 Otherwise, this resets the expression. 1747 dialect: the dialect used to parse the input expressions. 1748 copy: if `False`, modify this expression instance in-place. 1749 opts: other options to use to parse the input expressions. 1750 1751 Returns: 1752 The modified Join expression. 1753 """ 1754 join = _apply_list_builder( 1755 *expressions, 1756 instance=self, 1757 arg="using", 1758 append=append, 1759 dialect=dialect, 1760 copy=copy, 1761 **opts, 1762 ) 1763 1764 if join.kind == "CROSS": 1765 join.set("kind", None) 1766 1767 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1770class Lateral(UDTF): 1771 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1774class MatchRecognize(Expression): 1775 arg_types = { 1776 "partition_by": False, 1777 "order": False, 1778 "measures": False, 1779 "rows": False, 1780 "after": False, 1781 "pattern": False, 1782 "define": False, 1783 "alias": False, 1784 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1831class BlockCompressionProperty(Property): 1832 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1847class DataBlocksizeProperty(Property): 1848 arg_types = { 1849 "size": False, 1850 "units": False, 1851 "minimum": False, 1852 "maximum": False, 1853 "default": False, 1854 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1893class InputOutputFormat(Expression): 1894 arg_types = {"input_format": False, "output_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1897class IsolatedLoadingProperty(Property): 1898 arg_types = { 1899 "no": True, 1900 "concurrent": True, 1901 "for_all": True, 1902 "for_insert": True, 1903 "for_none": True, 1904 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1907class JournalProperty(Property): 1908 arg_types = { 1909 "no": False, 1910 "dual": False, 1911 "before": False, 1912 "local": False, 1913 "after": False, 1914 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1947class LockingProperty(Property): 1948 arg_types = { 1949 "this": False, 1950 "kind": True, 1951 "for_or_in": True, 1952 "lock_type": True, 1953 "override": False, 1954 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1965class MergeBlockRatioProperty(Property): 1966 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1981class ReturnsProperty(Property): 1982 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1989class RowFormatDelimitedProperty(Property): 1990 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1991 arg_types = { 1992 "fields": False, 1993 "escaped": False, 1994 "collection_items": False, 1995 "map_keys": False, 1996 "lines": False, 1997 "null": False, 1998 "serde": False, 1999 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2054class Properties(Expression): 2055 arg_types = {"expressions": True} 2056 2057 NAME_TO_PROPERTY = { 2058 "ALGORITHM": AlgorithmProperty, 2059 "AUTO_INCREMENT": AutoIncrementProperty, 2060 "CHARACTER SET": CharacterSetProperty, 2061 "COLLATE": CollateProperty, 2062 "COMMENT": SchemaCommentProperty, 2063 "DEFINER": DefinerProperty, 2064 "DISTKEY": DistKeyProperty, 2065 "DISTSTYLE": DistStyleProperty, 2066 "ENGINE": EngineProperty, 2067 "EXECUTE AS": ExecuteAsProperty, 2068 "FORMAT": FileFormatProperty, 2069 "LANGUAGE": LanguageProperty, 2070 "LOCATION": LocationProperty, 2071 "PARTITIONED_BY": PartitionedByProperty, 2072 "RETURNS": ReturnsProperty, 2073 "ROW_FORMAT": RowFormatProperty, 2074 "SORTKEY": SortKeyProperty, 2075 } 2076 2077 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2078 2079 # CREATE property locations 2080 # Form: schema specified 2081 # create [POST_CREATE] 2082 # table a [POST_NAME] 2083 # (b int) [POST_SCHEMA] 2084 # with ([POST_WITH]) 2085 # index (b) [POST_INDEX] 2086 # 2087 # Form: alias selection 2088 # create [POST_CREATE] 2089 # table a [POST_NAME] 2090 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2091 # index (c) [POST_INDEX] 2092 class Location(AutoName): 2093 POST_CREATE = auto() 2094 POST_NAME = auto() 2095 POST_SCHEMA = auto() 2096 POST_WITH = auto() 2097 POST_ALIAS = auto() 2098 POST_EXPRESSION = auto() 2099 POST_INDEX = auto() 2100 UNSUPPORTED = auto() 2101 2102 @classmethod 2103 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2104 expressions = [] 2105 for key, value in properties_dict.items(): 2106 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2107 if property_cls: 2108 expressions.append(property_cls(this=convert(value))) 2109 else: 2110 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2111 2112 return cls(expressions=expressions)
2102 @classmethod 2103 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2104 expressions = [] 2105 for key, value in properties_dict.items(): 2106 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2107 if property_cls: 2108 expressions.append(property_cls(this=convert(value))) 2109 else: 2110 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2111 2112 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2092 class Location(AutoName): 2093 POST_CREATE = auto() 2094 POST_NAME = auto() 2095 POST_SCHEMA = auto() 2096 POST_WITH = auto() 2097 POST_ALIAS = auto() 2098 POST_EXPRESSION = auto() 2099 POST_INDEX = auto() 2100 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2124class Reference(Expression): 2125 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2128class Tuple(Expression): 2129 arg_types = {"expressions": False} 2130 2131 def isin( 2132 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2133 ) -> In: 2134 return In( 2135 this=_maybe_copy(self, copy), 2136 expressions=[convert(e, copy=copy) for e in expressions], 2137 query=maybe_parse(query, copy=copy, **opts) if query else None, 2138 )
2131 def isin( 2132 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2133 ) -> In: 2134 return In( 2135 this=_maybe_copy(self, copy), 2136 expressions=[convert(e, copy=copy) for e in expressions], 2137 query=maybe_parse(query, copy=copy, **opts) if query else None, 2138 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2141class Subqueryable(Unionable): 2142 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2143 """ 2144 Convert this expression to an aliased expression that can be used as a Subquery. 2145 2146 Example: 2147 >>> subquery = Select().select("x").from_("tbl").subquery() 2148 >>> Select().select("x").from_(subquery).sql() 2149 'SELECT x FROM (SELECT x FROM tbl)' 2150 2151 Args: 2152 alias (str | Identifier): an optional alias for the subquery 2153 copy (bool): if `False`, modify this expression instance in-place. 2154 2155 Returns: 2156 Alias: the subquery 2157 """ 2158 instance = _maybe_copy(self, copy) 2159 if not isinstance(alias, Expression): 2160 alias = TableAlias(this=to_identifier(alias)) if alias else None 2161 2162 return Subquery(this=instance, alias=alias) 2163 2164 def limit( 2165 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2166 ) -> Select: 2167 raise NotImplementedError 2168 2169 @property 2170 def ctes(self): 2171 with_ = self.args.get("with") 2172 if not with_: 2173 return [] 2174 return with_.expressions 2175 2176 @property 2177 def selects(self): 2178 raise NotImplementedError("Subqueryable objects must implement `selects`") 2179 2180 @property 2181 def named_selects(self): 2182 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2183 2184 def with_( 2185 self, 2186 alias: ExpOrStr, 2187 as_: ExpOrStr, 2188 recursive: t.Optional[bool] = None, 2189 append: bool = True, 2190 dialect: DialectType = None, 2191 copy: bool = True, 2192 **opts, 2193 ) -> Subqueryable: 2194 """ 2195 Append to or set the common table expressions. 2196 2197 Example: 2198 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2199 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2200 2201 Args: 2202 alias: the SQL code string to parse as the table name. 2203 If an `Expression` instance is passed, this is used as-is. 2204 as_: the SQL code string to parse as the table expression. 2205 If an `Expression` instance is passed, it will be used as-is. 2206 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2207 append: if `True`, add to any existing expressions. 2208 Otherwise, this resets the expressions. 2209 dialect: the dialect used to parse the input expression. 2210 copy: if `False`, modify this expression instance in-place. 2211 opts: other options to use to parse the input expressions. 2212 2213 Returns: 2214 The modified expression. 2215 """ 2216 return _apply_cte_builder( 2217 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2218 )
2142 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2143 """ 2144 Convert this expression to an aliased expression that can be used as a Subquery. 2145 2146 Example: 2147 >>> subquery = Select().select("x").from_("tbl").subquery() 2148 >>> Select().select("x").from_(subquery).sql() 2149 'SELECT x FROM (SELECT x FROM tbl)' 2150 2151 Args: 2152 alias (str | Identifier): an optional alias for the subquery 2153 copy (bool): if `False`, modify this expression instance in-place. 2154 2155 Returns: 2156 Alias: the subquery 2157 """ 2158 instance = _maybe_copy(self, copy) 2159 if not isinstance(alias, Expression): 2160 alias = TableAlias(this=to_identifier(alias)) if alias else None 2161 2162 return Subquery(this=instance, alias=alias)
Convert this expression to an aliased expression that can be used as a Subquery.
Example:
>>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
- alias (str | Identifier): an optional alias for the subquery
- copy (bool): if
False
, modify this expression instance in-place.
Returns:
Alias: the subquery
2184 def with_( 2185 self, 2186 alias: ExpOrStr, 2187 as_: ExpOrStr, 2188 recursive: t.Optional[bool] = None, 2189 append: bool = True, 2190 dialect: DialectType = None, 2191 copy: bool = True, 2192 **opts, 2193 ) -> Subqueryable: 2194 """ 2195 Append to or set the common table expressions. 2196 2197 Example: 2198 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2199 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2200 2201 Args: 2202 alias: the SQL code string to parse as the table name. 2203 If an `Expression` instance is passed, this is used as-is. 2204 as_: the SQL code string to parse as the table expression. 2205 If an `Expression` instance is passed, it will be used as-is. 2206 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2207 append: if `True`, add to any existing expressions. 2208 Otherwise, this resets the expressions. 2209 dialect: the dialect used to parse the input expression. 2210 copy: if `False`, modify this expression instance in-place. 2211 opts: other options to use to parse the input expressions. 2212 2213 Returns: 2214 The modified expression. 2215 """ 2216 return _apply_cte_builder( 2217 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2218 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias: the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_: the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive: set the RECURSIVE part of the expression. Defaults to
False
. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2244class Table(Expression): 2245 arg_types = { 2246 "this": True, 2247 "alias": False, 2248 "db": False, 2249 "catalog": False, 2250 "laterals": False, 2251 "joins": False, 2252 "pivots": False, 2253 "hints": False, 2254 "system_time": False, 2255 } 2256 2257 @property 2258 def db(self) -> str: 2259 return self.text("db") 2260 2261 @property 2262 def catalog(self) -> str: 2263 return self.text("catalog") 2264 2265 @property 2266 def parts(self) -> t.List[Identifier]: 2267 """Return the parts of a table in order catalog, db, table.""" 2268 return [ 2269 t.cast(Identifier, self.args[part]) 2270 for part in ("catalog", "db", "this") 2271 if self.args.get(part) 2272 ]
Return the parts of a table in order catalog, db, table.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2276class SystemTime(Expression): 2277 arg_types = { 2278 "this": False, 2279 "expression": False, 2280 "kind": True, 2281 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2284class Union(Subqueryable): 2285 arg_types = { 2286 "with": False, 2287 "this": True, 2288 "expression": True, 2289 "distinct": False, 2290 **QUERY_MODIFIERS, 2291 } 2292 2293 def limit( 2294 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2295 ) -> Select: 2296 """ 2297 Set the LIMIT expression. 2298 2299 Example: 2300 >>> select("1").union(select("1")).limit(1).sql() 2301 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2302 2303 Args: 2304 expression: the SQL code string to parse. 2305 This can also be an integer. 2306 If a `Limit` instance is passed, this is used as-is. 2307 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2308 dialect: the dialect used to parse the input expression. 2309 copy: if `False`, modify this expression instance in-place. 2310 opts: other options to use to parse the input expressions. 2311 2312 Returns: 2313 The limited subqueryable. 2314 """ 2315 return ( 2316 select("*") 2317 .from_(self.subquery(alias="_l_0", copy=copy)) 2318 .limit(expression, dialect=dialect, copy=False, **opts) 2319 ) 2320 2321 def select( 2322 self, 2323 *expressions: t.Optional[ExpOrStr], 2324 append: bool = True, 2325 dialect: DialectType = None, 2326 copy: bool = True, 2327 **opts, 2328 ) -> Union: 2329 """Append to or set the SELECT of the union recursively. 2330 2331 Example: 2332 >>> from sqlglot import parse_one 2333 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2334 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 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 Union: the modified expression. 2347 """ 2348 this = self.copy() if copy else self 2349 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2350 this.expression.unnest().select( 2351 *expressions, append=append, dialect=dialect, copy=False, **opts 2352 ) 2353 return this 2354 2355 @property 2356 def named_selects(self): 2357 return self.this.unnest().named_selects 2358 2359 @property 2360 def is_star(self) -> bool: 2361 return self.this.is_star or self.expression.is_star 2362 2363 @property 2364 def selects(self): 2365 return self.this.unnest().selects 2366 2367 @property 2368 def left(self): 2369 return self.this 2370 2371 @property 2372 def right(self): 2373 return self.expression
2293 def limit( 2294 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2295 ) -> Select: 2296 """ 2297 Set the LIMIT expression. 2298 2299 Example: 2300 >>> select("1").union(select("1")).limit(1).sql() 2301 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2302 2303 Args: 2304 expression: the SQL code string to parse. 2305 This can also be an integer. 2306 If a `Limit` instance is passed, this is used as-is. 2307 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2308 dialect: the dialect used to parse the input expression. 2309 copy: if `False`, modify this expression instance in-place. 2310 opts: other options to use to parse the input expressions. 2311 2312 Returns: 2313 The limited subqueryable. 2314 """ 2315 return ( 2316 select("*") 2317 .from_(self.subquery(alias="_l_0", copy=copy)) 2318 .limit(expression, dialect=dialect, copy=False, **opts) 2319 )
Set the LIMIT expression.
Example:
>>> select("1").union(select("1")).limit(1).sql() 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
- expression: the SQL code string to parse.
This can also be an integer.
If a
Limit
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aLimit
. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The limited subqueryable.
2321 def select( 2322 self, 2323 *expressions: t.Optional[ExpOrStr], 2324 append: bool = True, 2325 dialect: DialectType = None, 2326 copy: bool = True, 2327 **opts, 2328 ) -> Union: 2329 """Append to or set the SELECT of the union recursively. 2330 2331 Example: 2332 >>> from sqlglot import parse_one 2333 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2334 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 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 Union: the modified expression. 2347 """ 2348 this = self.copy() if copy else self 2349 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2350 this.expression.unnest().select( 2351 *expressions, append=append, dialect=dialect, copy=False, **opts 2352 ) 2353 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.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2384class Unnest(UDTF): 2385 arg_types = { 2386 "expressions": True, 2387 "ordinality": False, 2388 "alias": False, 2389 "offset": False, 2390 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2393class Update(Expression): 2394 arg_types = { 2395 "with": False, 2396 "this": False, 2397 "expressions": True, 2398 "from": False, 2399 "where": False, 2400 "returning": False, 2401 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2404class Values(UDTF): 2405 arg_types = { 2406 "expressions": True, 2407 "ordinality": False, 2408 "alias": False, 2409 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2426class Select(Subqueryable): 2427 arg_types = { 2428 "with": False, 2429 "kind": False, 2430 "expressions": False, 2431 "hint": False, 2432 "distinct": False, 2433 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2434 "value": False, 2435 "into": False, 2436 "from": False, 2437 **QUERY_MODIFIERS, 2438 } 2439 2440 def from_( 2441 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2442 ) -> Select: 2443 """ 2444 Set the FROM expression. 2445 2446 Example: 2447 >>> Select().from_("tbl").select("x").sql() 2448 'SELECT x FROM tbl' 2449 2450 Args: 2451 expression : the SQL code strings to parse. 2452 If a `From` instance is passed, this is used as-is. 2453 If another `Expression` instance is passed, it will be wrapped in a `From`. 2454 dialect: the dialect used to parse the input expression. 2455 copy: if `False`, modify this expression instance in-place. 2456 opts: other options to use to parse the input expressions. 2457 2458 Returns: 2459 The modified Select expression. 2460 """ 2461 return _apply_builder( 2462 expression=expression, 2463 instance=self, 2464 arg="from", 2465 into=From, 2466 prefix="FROM", 2467 dialect=dialect, 2468 copy=copy, 2469 **opts, 2470 ) 2471 2472 def group_by( 2473 self, 2474 *expressions: t.Optional[ExpOrStr], 2475 append: bool = True, 2476 dialect: DialectType = None, 2477 copy: bool = True, 2478 **opts, 2479 ) -> Select: 2480 """ 2481 Set the GROUP BY expression. 2482 2483 Example: 2484 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2485 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2486 2487 Args: 2488 *expressions: the SQL code strings to parse. 2489 If a `Group` instance is passed, this is used as-is. 2490 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2491 If nothing is passed in then a group by is not applied to the expression 2492 append: if `True`, add to any existing expressions. 2493 Otherwise, this flattens all the `Group` expression into a single expression. 2494 dialect: the dialect used to parse the input expression. 2495 copy: if `False`, modify this expression instance in-place. 2496 opts: other options to use to parse the input expressions. 2497 2498 Returns: 2499 The modified Select expression. 2500 """ 2501 if not expressions: 2502 return self if not copy else self.copy() 2503 2504 return _apply_child_list_builder( 2505 *expressions, 2506 instance=self, 2507 arg="group", 2508 append=append, 2509 copy=copy, 2510 prefix="GROUP BY", 2511 into=Group, 2512 dialect=dialect, 2513 **opts, 2514 ) 2515 2516 def order_by( 2517 self, 2518 *expressions: t.Optional[ExpOrStr], 2519 append: bool = True, 2520 dialect: DialectType = None, 2521 copy: bool = True, 2522 **opts, 2523 ) -> Select: 2524 """ 2525 Set the ORDER BY expression. 2526 2527 Example: 2528 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2529 'SELECT x FROM tbl ORDER BY x DESC' 2530 2531 Args: 2532 *expressions: the SQL code strings to parse. 2533 If a `Group` instance is passed, this is used as-is. 2534 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2535 append: if `True`, add to any existing expressions. 2536 Otherwise, this flattens all the `Order` expression into a single expression. 2537 dialect: the dialect used to parse the input expression. 2538 copy: if `False`, modify this expression instance in-place. 2539 opts: other options to use to parse the input expressions. 2540 2541 Returns: 2542 The modified Select expression. 2543 """ 2544 return _apply_child_list_builder( 2545 *expressions, 2546 instance=self, 2547 arg="order", 2548 append=append, 2549 copy=copy, 2550 prefix="ORDER BY", 2551 into=Order, 2552 dialect=dialect, 2553 **opts, 2554 ) 2555 2556 def sort_by( 2557 self, 2558 *expressions: t.Optional[ExpOrStr], 2559 append: bool = True, 2560 dialect: DialectType = None, 2561 copy: bool = True, 2562 **opts, 2563 ) -> Select: 2564 """ 2565 Set the SORT BY expression. 2566 2567 Example: 2568 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2569 'SELECT x FROM tbl SORT BY x DESC' 2570 2571 Args: 2572 *expressions: the SQL code strings to parse. 2573 If a `Group` instance is passed, this is used as-is. 2574 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2575 append: if `True`, add to any existing expressions. 2576 Otherwise, this flattens all the `Order` expression into a single expression. 2577 dialect: the dialect used to parse the input expression. 2578 copy: if `False`, modify this expression instance in-place. 2579 opts: other options to use to parse the input expressions. 2580 2581 Returns: 2582 The modified Select expression. 2583 """ 2584 return _apply_child_list_builder( 2585 *expressions, 2586 instance=self, 2587 arg="sort", 2588 append=append, 2589 copy=copy, 2590 prefix="SORT BY", 2591 into=Sort, 2592 dialect=dialect, 2593 **opts, 2594 ) 2595 2596 def cluster_by( 2597 self, 2598 *expressions: t.Optional[ExpOrStr], 2599 append: bool = True, 2600 dialect: DialectType = None, 2601 copy: bool = True, 2602 **opts, 2603 ) -> Select: 2604 """ 2605 Set the CLUSTER BY expression. 2606 2607 Example: 2608 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2609 'SELECT x FROM tbl CLUSTER BY x DESC' 2610 2611 Args: 2612 *expressions: the SQL code strings to parse. 2613 If a `Group` instance is passed, this is used as-is. 2614 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2615 append: if `True`, add to any existing expressions. 2616 Otherwise, this flattens all the `Order` expression into a single expression. 2617 dialect: the dialect used to parse the input expression. 2618 copy: if `False`, modify this expression instance in-place. 2619 opts: other options to use to parse the input expressions. 2620 2621 Returns: 2622 The modified Select expression. 2623 """ 2624 return _apply_child_list_builder( 2625 *expressions, 2626 instance=self, 2627 arg="cluster", 2628 append=append, 2629 copy=copy, 2630 prefix="CLUSTER BY", 2631 into=Cluster, 2632 dialect=dialect, 2633 **opts, 2634 ) 2635 2636 def limit( 2637 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2638 ) -> Select: 2639 """ 2640 Set the LIMIT expression. 2641 2642 Example: 2643 >>> Select().from_("tbl").select("x").limit(10).sql() 2644 'SELECT x FROM tbl LIMIT 10' 2645 2646 Args: 2647 expression: the SQL code string to parse. 2648 This can also be an integer. 2649 If a `Limit` instance is passed, this is used as-is. 2650 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2651 dialect: the dialect used to parse the input expression. 2652 copy: if `False`, modify this expression instance in-place. 2653 opts: other options to use to parse the input expressions. 2654 2655 Returns: 2656 Select: the modified expression. 2657 """ 2658 return _apply_builder( 2659 expression=expression, 2660 instance=self, 2661 arg="limit", 2662 into=Limit, 2663 prefix="LIMIT", 2664 dialect=dialect, 2665 copy=copy, 2666 **opts, 2667 ) 2668 2669 def offset( 2670 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2671 ) -> Select: 2672 """ 2673 Set the OFFSET expression. 2674 2675 Example: 2676 >>> Select().from_("tbl").select("x").offset(10).sql() 2677 'SELECT x FROM tbl OFFSET 10' 2678 2679 Args: 2680 expression: the SQL code string to parse. 2681 This can also be an integer. 2682 If a `Offset` instance is passed, this is used as-is. 2683 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2684 dialect: the dialect used to parse the input expression. 2685 copy: if `False`, modify this expression instance in-place. 2686 opts: other options to use to parse the input expressions. 2687 2688 Returns: 2689 The modified Select expression. 2690 """ 2691 return _apply_builder( 2692 expression=expression, 2693 instance=self, 2694 arg="offset", 2695 into=Offset, 2696 prefix="OFFSET", 2697 dialect=dialect, 2698 copy=copy, 2699 **opts, 2700 ) 2701 2702 def select( 2703 self, 2704 *expressions: t.Optional[ExpOrStr], 2705 append: bool = True, 2706 dialect: DialectType = None, 2707 copy: bool = True, 2708 **opts, 2709 ) -> Select: 2710 """ 2711 Append to or set the SELECT expressions. 2712 2713 Example: 2714 >>> Select().select("x", "y").sql() 2715 'SELECT x, y' 2716 2717 Args: 2718 *expressions: the SQL code strings to parse. 2719 If an `Expression` instance is passed, it will be used as-is. 2720 append: if `True`, add to any existing expressions. 2721 Otherwise, this resets the expressions. 2722 dialect: the dialect used to parse the input expressions. 2723 copy: if `False`, modify this expression instance in-place. 2724 opts: other options to use to parse the input expressions. 2725 2726 Returns: 2727 The modified Select expression. 2728 """ 2729 return _apply_list_builder( 2730 *expressions, 2731 instance=self, 2732 arg="expressions", 2733 append=append, 2734 dialect=dialect, 2735 copy=copy, 2736 **opts, 2737 ) 2738 2739 def lateral( 2740 self, 2741 *expressions: t.Optional[ExpOrStr], 2742 append: bool = True, 2743 dialect: DialectType = None, 2744 copy: bool = True, 2745 **opts, 2746 ) -> Select: 2747 """ 2748 Append to or set the LATERAL expressions. 2749 2750 Example: 2751 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2752 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2753 2754 Args: 2755 *expressions: the SQL code strings to parse. 2756 If an `Expression` instance is passed, it will be used as-is. 2757 append: if `True`, add to any existing expressions. 2758 Otherwise, this resets the expressions. 2759 dialect: the dialect used to parse the input expressions. 2760 copy: if `False`, modify this expression instance in-place. 2761 opts: other options to use to parse the input expressions. 2762 2763 Returns: 2764 The modified Select expression. 2765 """ 2766 return _apply_list_builder( 2767 *expressions, 2768 instance=self, 2769 arg="laterals", 2770 append=append, 2771 into=Lateral, 2772 prefix="LATERAL VIEW", 2773 dialect=dialect, 2774 copy=copy, 2775 **opts, 2776 ) 2777 2778 def join( 2779 self, 2780 expression: ExpOrStr, 2781 on: t.Optional[ExpOrStr] = None, 2782 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2783 append: bool = True, 2784 join_type: t.Optional[str] = None, 2785 join_alias: t.Optional[Identifier | str] = None, 2786 dialect: DialectType = None, 2787 copy: bool = True, 2788 **opts, 2789 ) -> Select: 2790 """ 2791 Append to or set the JOIN expressions. 2792 2793 Example: 2794 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2795 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2796 2797 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2798 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2799 2800 Use `join_type` to change the type of join: 2801 2802 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2803 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2804 2805 Args: 2806 expression: the SQL code string to parse. 2807 If an `Expression` instance is passed, it will be used as-is. 2808 on: optionally specify the join "on" criteria as a SQL string. 2809 If an `Expression` instance is passed, it will be used as-is. 2810 using: optionally specify the join "using" criteria as a SQL string. 2811 If an `Expression` instance is passed, it will be used as-is. 2812 append: if `True`, add to any existing expressions. 2813 Otherwise, this resets the expressions. 2814 join_type: if set, alter the parsed join type. 2815 join_alias: an optional alias for the joined source. 2816 dialect: the dialect used to parse the input expressions. 2817 copy: if `False`, modify this expression instance in-place. 2818 opts: other options to use to parse the input expressions. 2819 2820 Returns: 2821 Select: the modified expression. 2822 """ 2823 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2824 2825 try: 2826 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2827 except ParseError: 2828 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2829 2830 join = expression if isinstance(expression, Join) else Join(this=expression) 2831 2832 if isinstance(join.this, Select): 2833 join.this.replace(join.this.subquery()) 2834 2835 if join_type: 2836 method: t.Optional[Token] 2837 side: t.Optional[Token] 2838 kind: t.Optional[Token] 2839 2840 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2841 2842 if method: 2843 join.set("method", method.text) 2844 if side: 2845 join.set("side", side.text) 2846 if kind: 2847 join.set("kind", kind.text) 2848 2849 if on: 2850 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2851 join.set("on", on) 2852 2853 if using: 2854 join = _apply_list_builder( 2855 *ensure_list(using), 2856 instance=join, 2857 arg="using", 2858 append=append, 2859 copy=copy, 2860 **opts, 2861 ) 2862 2863 if join_alias: 2864 join.set("this", alias_(join.this, join_alias, table=True)) 2865 2866 return _apply_list_builder( 2867 join, 2868 instance=self, 2869 arg="joins", 2870 append=append, 2871 copy=copy, 2872 **opts, 2873 ) 2874 2875 def where( 2876 self, 2877 *expressions: t.Optional[ExpOrStr], 2878 append: bool = True, 2879 dialect: DialectType = None, 2880 copy: bool = True, 2881 **opts, 2882 ) -> Select: 2883 """ 2884 Append to or set the WHERE expressions. 2885 2886 Example: 2887 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2888 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2889 2890 Args: 2891 *expressions: the SQL code strings to parse. 2892 If an `Expression` instance is passed, it will be used as-is. 2893 Multiple expressions are combined with an AND operator. 2894 append: if `True`, AND the new expressions to any existing expression. 2895 Otherwise, this resets the expression. 2896 dialect: the dialect used to parse the input expressions. 2897 copy: if `False`, modify this expression instance in-place. 2898 opts: other options to use to parse the input expressions. 2899 2900 Returns: 2901 Select: the modified expression. 2902 """ 2903 return _apply_conjunction_builder( 2904 *expressions, 2905 instance=self, 2906 arg="where", 2907 append=append, 2908 into=Where, 2909 dialect=dialect, 2910 copy=copy, 2911 **opts, 2912 ) 2913 2914 def having( 2915 self, 2916 *expressions: t.Optional[ExpOrStr], 2917 append: bool = True, 2918 dialect: DialectType = None, 2919 copy: bool = True, 2920 **opts, 2921 ) -> Select: 2922 """ 2923 Append to or set the HAVING expressions. 2924 2925 Example: 2926 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2927 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2928 2929 Args: 2930 *expressions: the SQL code strings to parse. 2931 If an `Expression` instance is passed, it will be used as-is. 2932 Multiple expressions are combined with an AND operator. 2933 append: if `True`, AND the new expressions to any existing expression. 2934 Otherwise, this resets the expression. 2935 dialect: the dialect used to parse the input expressions. 2936 copy: if `False`, modify this expression instance in-place. 2937 opts: other options to use to parse the input expressions. 2938 2939 Returns: 2940 The modified Select expression. 2941 """ 2942 return _apply_conjunction_builder( 2943 *expressions, 2944 instance=self, 2945 arg="having", 2946 append=append, 2947 into=Having, 2948 dialect=dialect, 2949 copy=copy, 2950 **opts, 2951 ) 2952 2953 def window( 2954 self, 2955 *expressions: t.Optional[ExpOrStr], 2956 append: bool = True, 2957 dialect: DialectType = None, 2958 copy: bool = True, 2959 **opts, 2960 ) -> Select: 2961 return _apply_list_builder( 2962 *expressions, 2963 instance=self, 2964 arg="windows", 2965 append=append, 2966 into=Window, 2967 dialect=dialect, 2968 copy=copy, 2969 **opts, 2970 ) 2971 2972 def qualify( 2973 self, 2974 *expressions: t.Optional[ExpOrStr], 2975 append: bool = True, 2976 dialect: DialectType = None, 2977 copy: bool = True, 2978 **opts, 2979 ) -> Select: 2980 return _apply_conjunction_builder( 2981 *expressions, 2982 instance=self, 2983 arg="qualify", 2984 append=append, 2985 into=Qualify, 2986 dialect=dialect, 2987 copy=copy, 2988 **opts, 2989 ) 2990 2991 def distinct( 2992 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2993 ) -> Select: 2994 """ 2995 Set the OFFSET expression. 2996 2997 Example: 2998 >>> Select().from_("tbl").select("x").distinct().sql() 2999 'SELECT DISTINCT x FROM tbl' 3000 3001 Args: 3002 ons: the expressions to distinct on 3003 distinct: whether the Select should be distinct 3004 copy: if `False`, modify this expression instance in-place. 3005 3006 Returns: 3007 Select: the modified expression. 3008 """ 3009 instance = _maybe_copy(self, copy) 3010 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3011 instance.set("distinct", Distinct(on=on) if distinct else None) 3012 return instance 3013 3014 def ctas( 3015 self, 3016 table: ExpOrStr, 3017 properties: t.Optional[t.Dict] = None, 3018 dialect: DialectType = None, 3019 copy: bool = True, 3020 **opts, 3021 ) -> Create: 3022 """ 3023 Convert this expression to a CREATE TABLE AS statement. 3024 3025 Example: 3026 >>> Select().select("*").from_("tbl").ctas("x").sql() 3027 'CREATE TABLE x AS SELECT * FROM tbl' 3028 3029 Args: 3030 table: the SQL code string to parse as the table name. 3031 If another `Expression` instance is passed, it will be used as-is. 3032 properties: an optional mapping of table properties 3033 dialect: the dialect used to parse the input table. 3034 copy: if `False`, modify this expression instance in-place. 3035 opts: other options to use to parse the input table. 3036 3037 Returns: 3038 The new Create expression. 3039 """ 3040 instance = _maybe_copy(self, copy) 3041 table_expression = maybe_parse( 3042 table, 3043 into=Table, 3044 dialect=dialect, 3045 **opts, 3046 ) 3047 properties_expression = None 3048 if properties: 3049 properties_expression = Properties.from_dict(properties) 3050 3051 return Create( 3052 this=table_expression, 3053 kind="table", 3054 expression=instance, 3055 properties=properties_expression, 3056 ) 3057 3058 def lock(self, update: bool = True, copy: bool = True) -> Select: 3059 """ 3060 Set the locking read mode for this expression. 3061 3062 Examples: 3063 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3064 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3065 3066 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3067 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3068 3069 Args: 3070 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3071 copy: if `False`, modify this expression instance in-place. 3072 3073 Returns: 3074 The modified expression. 3075 """ 3076 3077 inst = _maybe_copy(self, copy) 3078 inst.set("locks", [Lock(update=update)]) 3079 3080 return inst 3081 3082 @property 3083 def named_selects(self) -> t.List[str]: 3084 return [e.output_name for e in self.expressions if e.alias_or_name] 3085 3086 @property 3087 def is_star(self) -> bool: 3088 return any(expression.is_star for expression in self.expressions) 3089 3090 @property 3091 def selects(self) -> t.List[Expression]: 3092 return self.expressions
2440 def from_( 2441 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2442 ) -> Select: 2443 """ 2444 Set the FROM expression. 2445 2446 Example: 2447 >>> Select().from_("tbl").select("x").sql() 2448 'SELECT x FROM tbl' 2449 2450 Args: 2451 expression : the SQL code strings to parse. 2452 If a `From` instance is passed, this is used as-is. 2453 If another `Expression` instance is passed, it will be wrapped in a `From`. 2454 dialect: the dialect used to parse the input expression. 2455 copy: if `False`, modify this expression instance in-place. 2456 opts: other options to use to parse the input expressions. 2457 2458 Returns: 2459 The modified Select expression. 2460 """ 2461 return _apply_builder( 2462 expression=expression, 2463 instance=self, 2464 arg="from", 2465 into=From, 2466 prefix="FROM", 2467 dialect=dialect, 2468 copy=copy, 2469 **opts, 2470 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- expression : the SQL code strings to parse.
If a
From
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aFrom
. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2472 def group_by( 2473 self, 2474 *expressions: t.Optional[ExpOrStr], 2475 append: bool = True, 2476 dialect: DialectType = None, 2477 copy: bool = True, 2478 **opts, 2479 ) -> Select: 2480 """ 2481 Set the GROUP BY expression. 2482 2483 Example: 2484 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2485 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2486 2487 Args: 2488 *expressions: the SQL code strings to parse. 2489 If a `Group` instance is passed, this is used as-is. 2490 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2491 If nothing is passed in then a group by is not applied to the expression 2492 append: if `True`, add to any existing expressions. 2493 Otherwise, this flattens all the `Group` expression into a single expression. 2494 dialect: the dialect used to parse the input expression. 2495 copy: if `False`, modify this expression instance in-place. 2496 opts: other options to use to parse the input expressions. 2497 2498 Returns: 2499 The modified Select expression. 2500 """ 2501 if not expressions: 2502 return self if not copy else self.copy() 2503 2504 return _apply_child_list_builder( 2505 *expressions, 2506 instance=self, 2507 arg="group", 2508 append=append, 2509 copy=copy, 2510 prefix="GROUP BY", 2511 into=Group, 2512 dialect=dialect, 2513 **opts, 2514 )
Set the GROUP BY expression.
Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
- *expressions: the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aGroup
. If nothing is passed in then a group by is not applied to the expression - append: if
True
, add to any existing expressions. Otherwise, this flattens all theGroup
expression into a single expression. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2516 def order_by( 2517 self, 2518 *expressions: t.Optional[ExpOrStr], 2519 append: bool = True, 2520 dialect: DialectType = None, 2521 copy: bool = True, 2522 **opts, 2523 ) -> Select: 2524 """ 2525 Set the ORDER BY expression. 2526 2527 Example: 2528 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2529 'SELECT x FROM tbl ORDER BY x DESC' 2530 2531 Args: 2532 *expressions: the SQL code strings to parse. 2533 If a `Group` instance is passed, this is used as-is. 2534 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2535 append: if `True`, add to any existing expressions. 2536 Otherwise, this flattens all the `Order` expression into a single expression. 2537 dialect: the dialect used to parse the input expression. 2538 copy: if `False`, modify this expression instance in-place. 2539 opts: other options to use to parse the input expressions. 2540 2541 Returns: 2542 The modified Select expression. 2543 """ 2544 return _apply_child_list_builder( 2545 *expressions, 2546 instance=self, 2547 arg="order", 2548 append=append, 2549 copy=copy, 2550 prefix="ORDER BY", 2551 into=Order, 2552 dialect=dialect, 2553 **opts, 2554 )
Set the ORDER BY expression.
Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
- *expressions: the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aOrder
. - append: if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2556 def sort_by( 2557 self, 2558 *expressions: t.Optional[ExpOrStr], 2559 append: bool = True, 2560 dialect: DialectType = None, 2561 copy: bool = True, 2562 **opts, 2563 ) -> Select: 2564 """ 2565 Set the SORT BY expression. 2566 2567 Example: 2568 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2569 'SELECT x FROM tbl SORT BY x DESC' 2570 2571 Args: 2572 *expressions: the SQL code strings to parse. 2573 If a `Group` instance is passed, this is used as-is. 2574 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2575 append: if `True`, add to any existing expressions. 2576 Otherwise, this flattens all the `Order` expression into a single expression. 2577 dialect: the dialect used to parse the input expression. 2578 copy: if `False`, modify this expression instance in-place. 2579 opts: other options to use to parse the input expressions. 2580 2581 Returns: 2582 The modified Select expression. 2583 """ 2584 return _apply_child_list_builder( 2585 *expressions, 2586 instance=self, 2587 arg="sort", 2588 append=append, 2589 copy=copy, 2590 prefix="SORT BY", 2591 into=Sort, 2592 dialect=dialect, 2593 **opts, 2594 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions: the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aSORT
. - append: if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2596 def cluster_by( 2597 self, 2598 *expressions: t.Optional[ExpOrStr], 2599 append: bool = True, 2600 dialect: DialectType = None, 2601 copy: bool = True, 2602 **opts, 2603 ) -> Select: 2604 """ 2605 Set the CLUSTER BY expression. 2606 2607 Example: 2608 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2609 'SELECT x FROM tbl CLUSTER BY x DESC' 2610 2611 Args: 2612 *expressions: the SQL code strings to parse. 2613 If a `Group` instance is passed, this is used as-is. 2614 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2615 append: if `True`, add to any existing expressions. 2616 Otherwise, this flattens all the `Order` expression into a single expression. 2617 dialect: the dialect used to parse the input expression. 2618 copy: if `False`, modify this expression instance in-place. 2619 opts: other options to use to parse the input expressions. 2620 2621 Returns: 2622 The modified Select expression. 2623 """ 2624 return _apply_child_list_builder( 2625 *expressions, 2626 instance=self, 2627 arg="cluster", 2628 append=append, 2629 copy=copy, 2630 prefix="CLUSTER BY", 2631 into=Cluster, 2632 dialect=dialect, 2633 **opts, 2634 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions: the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aCluster
. - append: if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2636 def limit( 2637 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2638 ) -> Select: 2639 """ 2640 Set the LIMIT expression. 2641 2642 Example: 2643 >>> Select().from_("tbl").select("x").limit(10).sql() 2644 'SELECT x FROM tbl LIMIT 10' 2645 2646 Args: 2647 expression: the SQL code string to parse. 2648 This can also be an integer. 2649 If a `Limit` instance is passed, this is used as-is. 2650 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2651 dialect: the dialect used to parse the input expression. 2652 copy: if `False`, modify this expression instance in-place. 2653 opts: other options to use to parse the input expressions. 2654 2655 Returns: 2656 Select: the modified expression. 2657 """ 2658 return _apply_builder( 2659 expression=expression, 2660 instance=self, 2661 arg="limit", 2662 into=Limit, 2663 prefix="LIMIT", 2664 dialect=dialect, 2665 copy=copy, 2666 **opts, 2667 )
Set the LIMIT expression.
Example:
>>> Select().from_("tbl").select("x").limit(10).sql() 'SELECT x FROM tbl LIMIT 10'
Arguments:
- expression: the SQL code string to parse.
This can also be an integer.
If a
Limit
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aLimit
. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2669 def offset( 2670 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2671 ) -> Select: 2672 """ 2673 Set the OFFSET expression. 2674 2675 Example: 2676 >>> Select().from_("tbl").select("x").offset(10).sql() 2677 'SELECT x FROM tbl OFFSET 10' 2678 2679 Args: 2680 expression: the SQL code string to parse. 2681 This can also be an integer. 2682 If a `Offset` instance is passed, this is used as-is. 2683 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2684 dialect: the dialect used to parse the input expression. 2685 copy: if `False`, modify this expression instance in-place. 2686 opts: other options to use to parse the input expressions. 2687 2688 Returns: 2689 The modified Select expression. 2690 """ 2691 return _apply_builder( 2692 expression=expression, 2693 instance=self, 2694 arg="offset", 2695 into=Offset, 2696 prefix="OFFSET", 2697 dialect=dialect, 2698 copy=copy, 2699 **opts, 2700 )
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Arguments:
- expression: the SQL code string to parse.
This can also be an integer.
If a
Offset
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aOffset
. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2702 def select( 2703 self, 2704 *expressions: t.Optional[ExpOrStr], 2705 append: bool = True, 2706 dialect: DialectType = None, 2707 copy: bool = True, 2708 **opts, 2709 ) -> Select: 2710 """ 2711 Append to or set the SELECT expressions. 2712 2713 Example: 2714 >>> Select().select("x", "y").sql() 2715 'SELECT x, y' 2716 2717 Args: 2718 *expressions: the SQL code strings to parse. 2719 If an `Expression` instance is passed, it will be used as-is. 2720 append: if `True`, add to any existing expressions. 2721 Otherwise, this resets the expressions. 2722 dialect: the dialect used to parse the input expressions. 2723 copy: if `False`, modify this expression instance in-place. 2724 opts: other options to use to parse the input expressions. 2725 2726 Returns: 2727 The modified Select expression. 2728 """ 2729 return _apply_list_builder( 2730 *expressions, 2731 instance=self, 2732 arg="expressions", 2733 append=append, 2734 dialect=dialect, 2735 copy=copy, 2736 **opts, 2737 )
Append to or set the SELECT expressions.
Example:
>>> Select().select("x", "y").sql() 'SELECT x, y'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2739 def lateral( 2740 self, 2741 *expressions: t.Optional[ExpOrStr], 2742 append: bool = True, 2743 dialect: DialectType = None, 2744 copy: bool = True, 2745 **opts, 2746 ) -> Select: 2747 """ 2748 Append to or set the LATERAL expressions. 2749 2750 Example: 2751 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2752 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2753 2754 Args: 2755 *expressions: the SQL code strings to parse. 2756 If an `Expression` instance is passed, it will be used as-is. 2757 append: if `True`, add to any existing expressions. 2758 Otherwise, this resets the expressions. 2759 dialect: the dialect used to parse the input expressions. 2760 copy: if `False`, modify this expression instance in-place. 2761 opts: other options to use to parse the input expressions. 2762 2763 Returns: 2764 The modified Select expression. 2765 """ 2766 return _apply_list_builder( 2767 *expressions, 2768 instance=self, 2769 arg="laterals", 2770 append=append, 2771 into=Lateral, 2772 prefix="LATERAL VIEW", 2773 dialect=dialect, 2774 copy=copy, 2775 **opts, 2776 )
Append to or set the LATERAL expressions.
Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2778 def join( 2779 self, 2780 expression: ExpOrStr, 2781 on: t.Optional[ExpOrStr] = None, 2782 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2783 append: bool = True, 2784 join_type: t.Optional[str] = None, 2785 join_alias: t.Optional[Identifier | str] = None, 2786 dialect: DialectType = None, 2787 copy: bool = True, 2788 **opts, 2789 ) -> Select: 2790 """ 2791 Append to or set the JOIN expressions. 2792 2793 Example: 2794 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2795 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2796 2797 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2798 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2799 2800 Use `join_type` to change the type of join: 2801 2802 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2803 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2804 2805 Args: 2806 expression: the SQL code string to parse. 2807 If an `Expression` instance is passed, it will be used as-is. 2808 on: optionally specify the join "on" criteria as a SQL string. 2809 If an `Expression` instance is passed, it will be used as-is. 2810 using: optionally specify the join "using" criteria as a SQL string. 2811 If an `Expression` instance is passed, it will be used as-is. 2812 append: if `True`, add to any existing expressions. 2813 Otherwise, this resets the expressions. 2814 join_type: if set, alter the parsed join type. 2815 join_alias: an optional alias for the joined source. 2816 dialect: the dialect used to parse the input expressions. 2817 copy: if `False`, modify this expression instance in-place. 2818 opts: other options to use to parse the input expressions. 2819 2820 Returns: 2821 Select: the modified expression. 2822 """ 2823 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2824 2825 try: 2826 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2827 except ParseError: 2828 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2829 2830 join = expression if isinstance(expression, Join) else Join(this=expression) 2831 2832 if isinstance(join.this, Select): 2833 join.this.replace(join.this.subquery()) 2834 2835 if join_type: 2836 method: t.Optional[Token] 2837 side: t.Optional[Token] 2838 kind: t.Optional[Token] 2839 2840 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2841 2842 if method: 2843 join.set("method", method.text) 2844 if side: 2845 join.set("side", side.text) 2846 if kind: 2847 join.set("kind", kind.text) 2848 2849 if on: 2850 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2851 join.set("on", on) 2852 2853 if using: 2854 join = _apply_list_builder( 2855 *ensure_list(using), 2856 instance=join, 2857 arg="using", 2858 append=append, 2859 copy=copy, 2860 **opts, 2861 ) 2862 2863 if join_alias: 2864 join.set("this", alias_(join.this, join_alias, table=True)) 2865 2866 return _apply_list_builder( 2867 join, 2868 instance=self, 2869 arg="joins", 2870 append=append, 2871 copy=copy, 2872 **opts, 2873 )
Append to or set the JOIN expressions.
Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'
Use
join_type
to change the type of join:>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
- expression: the SQL code string to parse.
If an
Expression
instance is passed, it will be used as-is. - on: optionally specify the join "on" criteria as a SQL string.
If an
Expression
instance is passed, it will be used as-is. - using: optionally specify the join "using" criteria as a SQL string.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - join_type: if set, alter the parsed join type.
- join_alias: an optional alias for the joined source.
- dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2875 def where( 2876 self, 2877 *expressions: t.Optional[ExpOrStr], 2878 append: bool = True, 2879 dialect: DialectType = None, 2880 copy: bool = True, 2881 **opts, 2882 ) -> Select: 2883 """ 2884 Append to or set the WHERE expressions. 2885 2886 Example: 2887 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2888 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2889 2890 Args: 2891 *expressions: the SQL code strings to parse. 2892 If an `Expression` instance is passed, it will be used as-is. 2893 Multiple expressions are combined with an AND operator. 2894 append: if `True`, AND the new expressions to any existing expression. 2895 Otherwise, this resets the expression. 2896 dialect: the dialect used to parse the input expressions. 2897 copy: if `False`, modify this expression instance in-place. 2898 opts: other options to use to parse the input expressions. 2899 2900 Returns: 2901 Select: the modified expression. 2902 """ 2903 return _apply_conjunction_builder( 2904 *expressions, 2905 instance=self, 2906 arg="where", 2907 append=append, 2908 into=Where, 2909 dialect=dialect, 2910 copy=copy, 2911 **opts, 2912 )
Append to or set the WHERE expressions.
Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2914 def having( 2915 self, 2916 *expressions: t.Optional[ExpOrStr], 2917 append: bool = True, 2918 dialect: DialectType = None, 2919 copy: bool = True, 2920 **opts, 2921 ) -> Select: 2922 """ 2923 Append to or set the HAVING expressions. 2924 2925 Example: 2926 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2927 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2928 2929 Args: 2930 *expressions: the SQL code strings to parse. 2931 If an `Expression` instance is passed, it will be used as-is. 2932 Multiple expressions are combined with an AND operator. 2933 append: if `True`, AND the new expressions to any existing expression. 2934 Otherwise, this resets the expression. 2935 dialect: the dialect used to parse the input expressions. 2936 copy: if `False`, modify this expression instance in-place. 2937 opts: other options to use to parse the input expressions. 2938 2939 Returns: 2940 The modified Select expression. 2941 """ 2942 return _apply_conjunction_builder( 2943 *expressions, 2944 instance=self, 2945 arg="having", 2946 append=append, 2947 into=Having, 2948 dialect=dialect, 2949 copy=copy, 2950 **opts, 2951 )
Append to or set the HAVING expressions.
Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Select expression.
2953 def window( 2954 self, 2955 *expressions: t.Optional[ExpOrStr], 2956 append: bool = True, 2957 dialect: DialectType = None, 2958 copy: bool = True, 2959 **opts, 2960 ) -> Select: 2961 return _apply_list_builder( 2962 *expressions, 2963 instance=self, 2964 arg="windows", 2965 append=append, 2966 into=Window, 2967 dialect=dialect, 2968 copy=copy, 2969 **opts, 2970 )
2972 def qualify( 2973 self, 2974 *expressions: t.Optional[ExpOrStr], 2975 append: bool = True, 2976 dialect: DialectType = None, 2977 copy: bool = True, 2978 **opts, 2979 ) -> Select: 2980 return _apply_conjunction_builder( 2981 *expressions, 2982 instance=self, 2983 arg="qualify", 2984 append=append, 2985 into=Qualify, 2986 dialect=dialect, 2987 copy=copy, 2988 **opts, 2989 )
2991 def distinct( 2992 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2993 ) -> Select: 2994 """ 2995 Set the OFFSET expression. 2996 2997 Example: 2998 >>> Select().from_("tbl").select("x").distinct().sql() 2999 'SELECT DISTINCT x FROM tbl' 3000 3001 Args: 3002 ons: the expressions to distinct on 3003 distinct: whether the Select should be distinct 3004 copy: if `False`, modify this expression instance in-place. 3005 3006 Returns: 3007 Select: the modified expression. 3008 """ 3009 instance = _maybe_copy(self, copy) 3010 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3011 instance.set("distinct", Distinct(on=on) if distinct else None) 3012 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- ons: the expressions to distinct on
- distinct: whether the Select should be distinct
- copy: if
False
, modify this expression instance in-place.
Returns:
Select: the modified expression.
3014 def ctas( 3015 self, 3016 table: ExpOrStr, 3017 properties: t.Optional[t.Dict] = None, 3018 dialect: DialectType = None, 3019 copy: bool = True, 3020 **opts, 3021 ) -> Create: 3022 """ 3023 Convert this expression to a CREATE TABLE AS statement. 3024 3025 Example: 3026 >>> Select().select("*").from_("tbl").ctas("x").sql() 3027 'CREATE TABLE x AS SELECT * FROM tbl' 3028 3029 Args: 3030 table: the SQL code string to parse as the table name. 3031 If another `Expression` instance is passed, it will be used as-is. 3032 properties: an optional mapping of table properties 3033 dialect: the dialect used to parse the input table. 3034 copy: if `False`, modify this expression instance in-place. 3035 opts: other options to use to parse the input table. 3036 3037 Returns: 3038 The new Create expression. 3039 """ 3040 instance = _maybe_copy(self, copy) 3041 table_expression = maybe_parse( 3042 table, 3043 into=Table, 3044 dialect=dialect, 3045 **opts, 3046 ) 3047 properties_expression = None 3048 if properties: 3049 properties_expression = Properties.from_dict(properties) 3050 3051 return Create( 3052 this=table_expression, 3053 kind="table", 3054 expression=instance, 3055 properties=properties_expression, 3056 )
Convert this expression to a CREATE TABLE AS statement.
Example:
>>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
- table: the SQL code string to parse as the table name.
If another
Expression
instance is passed, it will be used as-is. - properties: an optional mapping of table properties
- dialect: the dialect used to parse the input table.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input table.
Returns:
The new Create expression.
3058 def lock(self, update: bool = True, copy: bool = True) -> Select: 3059 """ 3060 Set the locking read mode for this expression. 3061 3062 Examples: 3063 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3064 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3065 3066 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3067 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3068 3069 Args: 3070 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3071 copy: if `False`, modify this expression instance in-place. 3072 3073 Returns: 3074 The modified expression. 3075 """ 3076 3077 inst = _maybe_copy(self, copy) 3078 inst.set("locks", [Lock(update=update)]) 3079 3080 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 beFOR UPDATE
, else it will beFOR SHARE
. - copy: if
False
, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3095class Subquery(DerivedTable, Unionable): 3096 arg_types = { 3097 "this": True, 3098 "alias": False, 3099 "with": False, 3100 **QUERY_MODIFIERS, 3101 } 3102 3103 def unnest(self): 3104 """ 3105 Returns the first non subquery. 3106 """ 3107 expression = self 3108 while isinstance(expression, Subquery): 3109 expression = expression.this 3110 return expression 3111 3112 @property 3113 def is_star(self) -> bool: 3114 return self.this.is_star 3115 3116 @property 3117 def output_name(self) -> str: 3118 return self.alias
3103 def unnest(self): 3104 """ 3105 Returns the first non subquery. 3106 """ 3107 expression = self 3108 while isinstance(expression, Subquery): 3109 expression = expression.this 3110 return expression
Returns the first non subquery.
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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3121class TableSample(Expression): 3122 arg_types = { 3123 "this": False, 3124 "method": False, 3125 "bucket_numerator": False, 3126 "bucket_denominator": False, 3127 "bucket_field": False, 3128 "percent": False, 3129 "rows": False, 3130 "size": False, 3131 "seed": False, 3132 "kind": False, 3133 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3136class Tag(Expression): 3137 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3138 3139 arg_types = { 3140 "this": False, 3141 "prefix": False, 3142 "postfix": False, 3143 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3148class Pivot(Expression): 3149 arg_types = { 3150 "this": False, 3151 "alias": False, 3152 "expressions": True, 3153 "field": False, 3154 "unpivot": False, 3155 "using": False, 3156 "group": False, 3157 "columns": False, 3158 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3161class Window(Expression): 3162 arg_types = { 3163 "this": True, 3164 "partition_by": False, 3165 "order": False, 3166 "spec": False, 3167 "alias": False, 3168 "over": False, 3169 "first": False, 3170 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3173class WindowSpec(Expression): 3174 arg_types = { 3175 "kind": False, 3176 "start": False, 3177 "start_side": False, 3178 "end": False, 3179 "end_side": False, 3180 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3187class Star(Expression): 3188 arg_types = {"except": False, "replace": False} 3189 3190 @property 3191 def name(self) -> str: 3192 return "*" 3193 3194 @property 3195 def output_name(self) -> str: 3196 return self.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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3211class Null(Condition): 3212 arg_types: t.Dict[str, t.Any] = {} 3213 3214 @property 3215 def name(self) -> str: 3216 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3227class DataType(Expression): 3228 arg_types = { 3229 "this": True, 3230 "expressions": False, 3231 "nested": False, 3232 "values": False, 3233 "prefix": False, 3234 } 3235 3236 class Type(AutoName): 3237 ARRAY = auto() 3238 BIGDECIMAL = auto() 3239 BIGINT = auto() 3240 BIGSERIAL = auto() 3241 BINARY = auto() 3242 BIT = auto() 3243 BOOLEAN = auto() 3244 CHAR = auto() 3245 DATE = auto() 3246 DATETIME = auto() 3247 DATETIME64 = auto() 3248 INT4RANGE = auto() 3249 INT4MULTIRANGE = auto() 3250 INT8RANGE = auto() 3251 INT8MULTIRANGE = auto() 3252 NUMRANGE = auto() 3253 NUMMULTIRANGE = auto() 3254 TSRANGE = auto() 3255 TSMULTIRANGE = auto() 3256 TSTZRANGE = auto() 3257 TSTZMULTIRANGE = auto() 3258 DATERANGE = auto() 3259 DATEMULTIRANGE = auto() 3260 DECIMAL = auto() 3261 DOUBLE = auto() 3262 FLOAT = auto() 3263 GEOGRAPHY = auto() 3264 GEOMETRY = auto() 3265 HLLSKETCH = auto() 3266 HSTORE = auto() 3267 IMAGE = auto() 3268 INET = auto() 3269 INT = auto() 3270 INT128 = auto() 3271 INT256 = auto() 3272 INTERVAL = auto() 3273 JSON = auto() 3274 JSONB = auto() 3275 LONGBLOB = auto() 3276 LONGTEXT = auto() 3277 MAP = auto() 3278 MEDIUMBLOB = auto() 3279 MEDIUMTEXT = auto() 3280 MONEY = auto() 3281 NCHAR = auto() 3282 NULL = auto() 3283 NULLABLE = auto() 3284 NVARCHAR = auto() 3285 OBJECT = auto() 3286 ROWVERSION = auto() 3287 SERIAL = auto() 3288 SMALLINT = auto() 3289 SMALLMONEY = auto() 3290 SMALLSERIAL = auto() 3291 STRUCT = auto() 3292 SUPER = auto() 3293 TEXT = auto() 3294 TIME = auto() 3295 TIMESTAMP = auto() 3296 TIMESTAMPTZ = auto() 3297 TIMESTAMPLTZ = auto() 3298 TINYINT = auto() 3299 UBIGINT = auto() 3300 UINT = auto() 3301 USMALLINT = auto() 3302 UTINYINT = auto() 3303 UNKNOWN = auto() # Sentinel value, useful for type annotation 3304 UINT128 = auto() 3305 UINT256 = auto() 3306 UNIQUEIDENTIFIER = auto() 3307 UUID = auto() 3308 VARBINARY = auto() 3309 VARCHAR = auto() 3310 VARIANT = auto() 3311 XML = auto() 3312 3313 TEXT_TYPES = { 3314 Type.CHAR, 3315 Type.NCHAR, 3316 Type.VARCHAR, 3317 Type.NVARCHAR, 3318 Type.TEXT, 3319 } 3320 3321 INTEGER_TYPES = { 3322 Type.INT, 3323 Type.TINYINT, 3324 Type.SMALLINT, 3325 Type.BIGINT, 3326 Type.INT128, 3327 Type.INT256, 3328 } 3329 3330 FLOAT_TYPES = { 3331 Type.FLOAT, 3332 Type.DOUBLE, 3333 } 3334 3335 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3336 3337 TEMPORAL_TYPES = { 3338 Type.TIMESTAMP, 3339 Type.TIMESTAMPTZ, 3340 Type.TIMESTAMPLTZ, 3341 Type.DATE, 3342 Type.DATETIME, 3343 Type.DATETIME64, 3344 } 3345 3346 @classmethod 3347 def build( 3348 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3349 ) -> DataType: 3350 from sqlglot import parse_one 3351 3352 if isinstance(dtype, str): 3353 if dtype.upper() in cls.Type.__members__: 3354 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3355 else: 3356 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3357 3358 if data_type_exp is None: 3359 raise ValueError(f"Unparsable data type value: {dtype}") 3360 elif isinstance(dtype, DataType.Type): 3361 data_type_exp = DataType(this=dtype) 3362 elif isinstance(dtype, DataType): 3363 return dtype 3364 else: 3365 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3366 3367 return DataType(**{**data_type_exp.args, **kwargs}) 3368 3369 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3370 return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3346 @classmethod 3347 def build( 3348 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3349 ) -> DataType: 3350 from sqlglot import parse_one 3351 3352 if isinstance(dtype, str): 3353 if dtype.upper() in cls.Type.__members__: 3354 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3355 else: 3356 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3357 3358 if data_type_exp is None: 3359 raise ValueError(f"Unparsable data type value: {dtype}") 3360 elif isinstance(dtype, DataType.Type): 3361 data_type_exp = DataType(this=dtype) 3362 elif isinstance(dtype, DataType): 3363 return dtype 3364 else: 3365 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3366 3367 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3236 class Type(AutoName): 3237 ARRAY = auto() 3238 BIGDECIMAL = auto() 3239 BIGINT = auto() 3240 BIGSERIAL = auto() 3241 BINARY = auto() 3242 BIT = auto() 3243 BOOLEAN = auto() 3244 CHAR = auto() 3245 DATE = auto() 3246 DATETIME = auto() 3247 DATETIME64 = auto() 3248 INT4RANGE = auto() 3249 INT4MULTIRANGE = auto() 3250 INT8RANGE = auto() 3251 INT8MULTIRANGE = auto() 3252 NUMRANGE = auto() 3253 NUMMULTIRANGE = auto() 3254 TSRANGE = auto() 3255 TSMULTIRANGE = auto() 3256 TSTZRANGE = auto() 3257 TSTZMULTIRANGE = auto() 3258 DATERANGE = auto() 3259 DATEMULTIRANGE = auto() 3260 DECIMAL = auto() 3261 DOUBLE = auto() 3262 FLOAT = auto() 3263 GEOGRAPHY = auto() 3264 GEOMETRY = auto() 3265 HLLSKETCH = auto() 3266 HSTORE = auto() 3267 IMAGE = auto() 3268 INET = auto() 3269 INT = auto() 3270 INT128 = auto() 3271 INT256 = auto() 3272 INTERVAL = auto() 3273 JSON = auto() 3274 JSONB = auto() 3275 LONGBLOB = auto() 3276 LONGTEXT = auto() 3277 MAP = auto() 3278 MEDIUMBLOB = auto() 3279 MEDIUMTEXT = auto() 3280 MONEY = auto() 3281 NCHAR = auto() 3282 NULL = auto() 3283 NULLABLE = auto() 3284 NVARCHAR = auto() 3285 OBJECT = auto() 3286 ROWVERSION = auto() 3287 SERIAL = auto() 3288 SMALLINT = auto() 3289 SMALLMONEY = auto() 3290 SMALLSERIAL = auto() 3291 STRUCT = auto() 3292 SUPER = auto() 3293 TEXT = auto() 3294 TIME = auto() 3295 TIMESTAMP = auto() 3296 TIMESTAMPTZ = auto() 3297 TIMESTAMPLTZ = auto() 3298 TINYINT = auto() 3299 UBIGINT = auto() 3300 UINT = auto() 3301 USMALLINT = auto() 3302 UTINYINT = auto() 3303 UNKNOWN = auto() # Sentinel value, useful for type annotation 3304 UINT128 = auto() 3305 UINT256 = auto() 3306 UNIQUEIDENTIFIER = auto() 3307 UUID = auto() 3308 VARBINARY = auto() 3309 VARCHAR = auto() 3310 VARIANT = auto() 3311 XML = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3417class AddConstraint(Expression): 3418 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3426class Binary(Condition): 3427 arg_types = {"this": True, "expression": True} 3428 3429 @property 3430 def left(self): 3431 return self.this 3432 3433 @property 3434 def right(self): 3435 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3482class Dot(Binary): 3483 @property 3484 def name(self) -> str: 3485 return self.expression.name 3486 3487 @classmethod 3488 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3489 """Build a Dot object with a sequence of expressions.""" 3490 if len(expressions) < 2: 3491 raise ValueError(f"Dot requires >= 2 expressions.") 3492 3493 a, b, *expressions = expressions 3494 dot = Dot(this=a, expression=b) 3495 3496 for expression in expressions: 3497 dot = Dot(this=dot, expression=expression) 3498 3499 return dot
3487 @classmethod 3488 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3489 """Build a Dot object with a sequence of expressions.""" 3490 if len(expressions) < 2: 3491 raise ValueError(f"Dot requires >= 2 expressions.") 3492 3493 a, b, *expressions = expressions 3494 dot = Dot(this=a, expression=b) 3495 3496 for expression in expressions: 3497 dot = Dot(this=dot, expression=expression) 3498 3499 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3624class Alias(Expression): 3625 arg_types = {"this": True, "alias": False} 3626 3627 @property 3628 def output_name(self) -> str: 3629 return self.alias
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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3632class Aliases(Expression): 3633 arg_types = {"this": True, "expressions": True} 3634 3635 @property 3636 def aliases(self): 3637 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3656class In(Predicate): 3657 arg_types = { 3658 "this": True, 3659 "expressions": False, 3660 "query": False, 3661 "unnest": False, 3662 "field": False, 3663 "is_global": False, 3664 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3667class TimeUnit(Expression): 3668 """Automatically converts unit arg into a var.""" 3669 3670 arg_types = {"unit": False} 3671 3672 def __init__(self, **args): 3673 unit = args.get("unit") 3674 if isinstance(unit, (Column, Literal)): 3675 args["unit"] = Var(this=unit.name) 3676 elif isinstance(unit, Week): 3677 unit.set("this", Var(this=unit.this.name)) 3678 3679 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3682class Interval(TimeUnit): 3683 arg_types = {"this": False, "unit": False} 3684 3685 @property 3686 def unit(self) -> t.Optional[Var]: 3687 return self.args.get("unit")
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3699class Func(Condition): 3700 """ 3701 The base class for all function expressions. 3702 3703 Attributes: 3704 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3705 treated as a variable length argument and the argument's value will be stored as a list. 3706 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3707 for this function expression. These values are used to map this node to a name during parsing 3708 as well as to provide the function's name during SQL string generation. By default the SQL 3709 name is set to the expression's class name transformed to snake case. 3710 """ 3711 3712 is_var_len_args = False 3713 3714 @classmethod 3715 def from_arg_list(cls, args): 3716 if cls.is_var_len_args: 3717 all_arg_keys = list(cls.arg_types) 3718 # If this function supports variable length argument treat the last argument as such. 3719 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3720 num_non_var = len(non_var_len_arg_keys) 3721 3722 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3723 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3724 else: 3725 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3726 3727 return cls(**args_dict) 3728 3729 @classmethod 3730 def sql_names(cls): 3731 if cls is Func: 3732 raise NotImplementedError( 3733 "SQL name is only supported by concrete function implementations" 3734 ) 3735 if "_sql_names" not in cls.__dict__: 3736 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3737 return cls._sql_names 3738 3739 @classmethod 3740 def sql_name(cls): 3741 return cls.sql_names()[0] 3742 3743 @classmethod 3744 def default_parser_mappings(cls): 3745 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.
3714 @classmethod 3715 def from_arg_list(cls, args): 3716 if cls.is_var_len_args: 3717 all_arg_keys = list(cls.arg_types) 3718 # If this function supports variable length argument treat the last argument as such. 3719 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3720 num_non_var = len(non_var_len_arg_keys) 3721 3722 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3723 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3724 else: 3725 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3726 3727 return cls(**args_dict)
3729 @classmethod 3730 def sql_names(cls): 3731 if cls is Func: 3732 raise NotImplementedError( 3733 "SQL name is only supported by concrete function implementations" 3734 ) 3735 if "_sql_names" not in cls.__dict__: 3736 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3737 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3752class ParameterizedAgg(AggFunc): 3753 arg_types = {"this": True, "expressions": True, "params": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3760class Anonymous(Func): 3761 arg_types = {"this": True, "expressions": False} 3762 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3767class Hll(AggFunc): 3768 arg_types = {"this": True, "expressions": False} 3769 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3772class ApproxDistinct(AggFunc): 3773 arg_types = {"this": True, "accuracy": False} 3774 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3803class ArrayConcat(Func): 3804 arg_types = {"this": True, "expressions": False} 3805 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3816class ArrayFilter(Func): 3817 arg_types = {"this": True, "expression": True} 3818 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3849class Case(Func): 3850 arg_types = {"this": False, "ifs": True, "default": False} 3851 3852 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3853 instance = _maybe_copy(self, copy) 3854 instance.append( 3855 "ifs", 3856 If( 3857 this=maybe_parse(condition, copy=copy, **opts), 3858 true=maybe_parse(then, copy=copy, **opts), 3859 ), 3860 ) 3861 return instance 3862 3863 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3864 instance = _maybe_copy(self, copy) 3865 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3866 return instance
3852 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3853 instance = _maybe_copy(self, copy) 3854 instance.append( 3855 "ifs", 3856 If( 3857 this=maybe_parse(condition, copy=copy, **opts), 3858 true=maybe_parse(then, copy=copy, **opts), 3859 ), 3860 ) 3861 return instance
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3869class Cast(Func): 3870 arg_types = {"this": True, "to": True} 3871 3872 @property 3873 def name(self) -> str: 3874 return self.this.name 3875 3876 @property 3877 def to(self) -> DataType: 3878 return self.args["to"] 3879 3880 @property 3881 def output_name(self) -> str: 3882 return self.name 3883 3884 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3885 return self.to.is_type(*dtypes)
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 ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3900class Ceil(Func): 3901 arg_types = {"this": True, "decimals": False} 3902 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3905class Coalesce(Func): 3906 arg_types = {"this": True, "expressions": False} 3907 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3947class DateAdd(Func, TimeUnit): 3948 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3951class DateSub(Func, TimeUnit): 3952 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3955class DateDiff(Func, TimeUnit): 3956 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3957 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3964class DatetimeAdd(Func, TimeUnit): 3965 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3968class DatetimeSub(Func, TimeUnit): 3969 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3972class DatetimeDiff(Func, TimeUnit): 3973 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3976class DatetimeTrunc(Func, TimeUnit): 3977 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4004class TimestampAdd(Func, TimeUnit): 4005 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4008class TimestampSub(Func, TimeUnit): 4009 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4012class TimestampDiff(Func, TimeUnit): 4013 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4016class TimestampTrunc(Func, TimeUnit): 4017 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4020class TimeAdd(Func, TimeUnit): 4021 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4024class TimeSub(Func, TimeUnit): 4025 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4028class TimeDiff(Func, TimeUnit): 4029 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4036class DateFromParts(Func): 4037 _sql_names = ["DATEFROMPARTS"] 4038 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4089class Greatest(Func): 4090 arg_types = {"this": True, "expressions": False} 4091 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4106class IfNull(Func): 4107 arg_types = {"this": True, "expression": False} 4108 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4119class JSONObject(Func): 4120 arg_types = { 4121 "expressions": False, 4122 "null_handling": False, 4123 "unique_keys": False, 4124 "return_type": False, 4125 "format_json": False, 4126 "encoding": False, 4127 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4130class OpenJSONColumnDef(Expression): 4131 arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4158class JSONFormat(Func): 4159 arg_types = {"this": False, "options": False} 4160 _sql_names = ["JSON_FORMAT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4180class Levenshtein(Func): 4181 arg_types = { 4182 "this": True, 4183 "expression": False, 4184 "ins_cost": False, 4185 "del_cost": False, 4186 "sub_cost": False, 4187 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4226class VarMap(Func): 4227 arg_types = {"keys": True, "values": True} 4228 is_var_len_args = True 4229 4230 @property 4231 def keys(self) -> t.List[Expression]: 4232 return self.args["keys"].expressions 4233 4234 @property 4235 def values(self) -> t.List[Expression]: 4236 return self.args["values"].expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4240class MatchAgainst(Func): 4241 arg_types = {"this": True, "expressions": True, "modifier": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4244class Max(AggFunc): 4245 arg_types = {"this": True, "expressions": False} 4246 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4253class Min(AggFunc): 4254 arg_types = {"this": True, "expressions": False} 4255 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4286class ApproxQuantile(Quantile): 4287 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4294class ReadCSV(Func): 4295 _sql_names = ["READ_CSV"] 4296 is_var_len_args = True 4297 arg_types = {"this": True, "expressions": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4300class Reduce(Func): 4301 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4304class RegexpExtract(Func): 4305 arg_types = { 4306 "this": True, 4307 "expression": True, 4308 "position": False, 4309 "occurrence": False, 4310 "group": False, 4311 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4375class StrPosition(Func): 4376 arg_types = { 4377 "this": True, 4378 "substr": True, 4379 "position": False, 4380 "instance": False, 4381 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4459class Trim(Func): 4460 arg_types = { 4461 "this": True, 4462 "expression": False, 4463 "position": False, 4464 "collation": False, 4465 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4468class TsOrDsAdd(Func, TimeUnit): 4469 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4494class UnixToTime(Func): 4495 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4496 4497 SECONDS = Literal.string("seconds") 4498 MILLIS = Literal.string("millis") 4499 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4522class XMLTable(Func): 4523 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4534class Merge(Expression): 4535 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4538class When(Func): 4539 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4582def maybe_parse( 4583 sql_or_expression: ExpOrStr, 4584 *, 4585 into: t.Optional[IntoType] = None, 4586 dialect: DialectType = None, 4587 prefix: t.Optional[str] = None, 4588 copy: bool = False, 4589 **opts, 4590) -> Expression: 4591 """Gracefully handle a possible string or expression. 4592 4593 Example: 4594 >>> maybe_parse("1") 4595 (LITERAL this: 1, is_string: False) 4596 >>> maybe_parse(to_identifier("x")) 4597 (IDENTIFIER this: x, quoted: False) 4598 4599 Args: 4600 sql_or_expression: the SQL code string or an expression 4601 into: the SQLGlot Expression to parse into 4602 dialect: the dialect used to parse the input expressions (in the case that an 4603 input expression is a SQL string). 4604 prefix: a string to prefix the sql with before it gets parsed 4605 (automatically includes a space) 4606 copy: whether or not to copy the expression. 4607 **opts: other options to use to parse the input expressions (again, in the case 4608 that an input expression is a SQL string). 4609 4610 Returns: 4611 Expression: the parsed or given expression. 4612 """ 4613 if isinstance(sql_or_expression, Expression): 4614 if copy: 4615 return sql_or_expression.copy() 4616 return sql_or_expression 4617 4618 if sql_or_expression is None: 4619 raise ParseError(f"SQL cannot be None") 4620 4621 import sqlglot 4622 4623 sql = str(sql_or_expression) 4624 if prefix: 4625 sql = f"{prefix} {sql}" 4626 4627 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.
4811def union( 4812 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4813) -> Union: 4814 """ 4815 Initializes a syntax tree from one UNION expression. 4816 4817 Example: 4818 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4819 'SELECT * FROM foo UNION SELECT * FROM bla' 4820 4821 Args: 4822 left: the SQL code string corresponding to the left-hand side. 4823 If an `Expression` instance is passed, it will be used as-is. 4824 right: the SQL code string corresponding to the right-hand side. 4825 If an `Expression` instance is passed, it will be used as-is. 4826 distinct: set the DISTINCT flag if and only if this is true. 4827 dialect: the dialect used to parse the input expression. 4828 opts: other options to use to parse the input expressions. 4829 4830 Returns: 4831 The new Union instance. 4832 """ 4833 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4834 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4835 4836 return Union(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one UNION expression.
Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- left: the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right: the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Union instance.
4839def intersect( 4840 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4841) -> Intersect: 4842 """ 4843 Initializes a syntax tree from one INTERSECT expression. 4844 4845 Example: 4846 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4847 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4848 4849 Args: 4850 left: the SQL code string corresponding to the left-hand side. 4851 If an `Expression` instance is passed, it will be used as-is. 4852 right: the SQL code string corresponding to the right-hand side. 4853 If an `Expression` instance is passed, it will be used as-is. 4854 distinct: set the DISTINCT flag if and only if this is true. 4855 dialect: the dialect used to parse the input expression. 4856 opts: other options to use to parse the input expressions. 4857 4858 Returns: 4859 The new Intersect instance. 4860 """ 4861 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4862 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4863 4864 return Intersect(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one INTERSECT expression.
Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- left: the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right: the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Intersect instance.
4867def except_( 4868 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4869) -> Except: 4870 """ 4871 Initializes a syntax tree from one EXCEPT expression. 4872 4873 Example: 4874 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4875 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4876 4877 Args: 4878 left: the SQL code string corresponding to the left-hand side. 4879 If an `Expression` instance is passed, it will be used as-is. 4880 right: the SQL code string corresponding to the right-hand side. 4881 If an `Expression` instance is passed, it will be used as-is. 4882 distinct: set the DISTINCT flag if and only if this is true. 4883 dialect: the dialect used to parse the input expression. 4884 opts: other options to use to parse the input expressions. 4885 4886 Returns: 4887 The new Except instance. 4888 """ 4889 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4890 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4891 4892 return Except(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one EXCEPT expression.
Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- left: the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right: the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Except instance.
4895def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4896 """ 4897 Initializes a syntax tree from one or multiple SELECT expressions. 4898 4899 Example: 4900 >>> select("col1", "col2").from_("tbl").sql() 4901 'SELECT col1, col2 FROM tbl' 4902 4903 Args: 4904 *expressions: the SQL code string to parse as the expressions of a 4905 SELECT statement. If an Expression instance is passed, this is used as-is. 4906 dialect: the dialect used to parse the input expressions (in the case that an 4907 input expression is a SQL string). 4908 **opts: other options to use to parse the input expressions (again, in the case 4909 that an input expression is a SQL string). 4910 4911 Returns: 4912 Select: the syntax tree for the SELECT statement. 4913 """ 4914 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.
4917def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4918 """ 4919 Initializes a syntax tree from a FROM expression. 4920 4921 Example: 4922 >>> from_("tbl").select("col1", "col2").sql() 4923 'SELECT col1, col2 FROM tbl' 4924 4925 Args: 4926 *expression: the SQL code string to parse as the FROM expressions of a 4927 SELECT statement. If an Expression instance is passed, this is used as-is. 4928 dialect: the dialect used to parse the input expression (in the case that the 4929 input expression is a SQL string). 4930 **opts: other options to use to parse the input expressions (again, in the case 4931 that the input expression is a SQL string). 4932 4933 Returns: 4934 Select: the syntax tree for the SELECT statement. 4935 """ 4936 return Select().from_(expression, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4939def update( 4940 table: str | Table, 4941 properties: dict, 4942 where: t.Optional[ExpOrStr] = None, 4943 from_: t.Optional[ExpOrStr] = None, 4944 dialect: DialectType = None, 4945 **opts, 4946) -> Update: 4947 """ 4948 Creates an update statement. 4949 4950 Example: 4951 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4952 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4953 4954 Args: 4955 *properties: dictionary of properties to set which are 4956 auto converted to sql objects eg None -> NULL 4957 where: sql conditional parsed into a WHERE statement 4958 from_: sql statement parsed into a FROM statement 4959 dialect: the dialect used to parse the input expressions. 4960 **opts: other options to use to parse the input expressions. 4961 4962 Returns: 4963 Update: the syntax tree for the UPDATE statement. 4964 """ 4965 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4966 update_expr.set( 4967 "expressions", 4968 [ 4969 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4970 for k, v in properties.items() 4971 ], 4972 ) 4973 if from_: 4974 update_expr.set( 4975 "from", 4976 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4977 ) 4978 if isinstance(where, Condition): 4979 where = Where(this=where) 4980 if where: 4981 update_expr.set( 4982 "where", 4983 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4984 ) 4985 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.
4988def delete( 4989 table: ExpOrStr, 4990 where: t.Optional[ExpOrStr] = None, 4991 returning: t.Optional[ExpOrStr] = None, 4992 dialect: DialectType = None, 4993 **opts, 4994) -> Delete: 4995 """ 4996 Builds a delete statement. 4997 4998 Example: 4999 >>> delete("my_table", where="id > 1").sql() 5000 'DELETE FROM my_table WHERE id > 1' 5001 5002 Args: 5003 where: sql conditional parsed into a WHERE statement 5004 returning: sql conditional parsed into a RETURNING statement 5005 dialect: the dialect used to parse the input expressions. 5006 **opts: other options to use to parse the input expressions. 5007 5008 Returns: 5009 Delete: the syntax tree for the DELETE statement. 5010 """ 5011 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5012 if where: 5013 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5014 if returning: 5015 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5016 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.
5019def insert( 5020 expression: ExpOrStr, 5021 into: ExpOrStr, 5022 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5023 overwrite: t.Optional[bool] = None, 5024 dialect: DialectType = None, 5025 copy: bool = True, 5026 **opts, 5027) -> Insert: 5028 """ 5029 Builds an INSERT statement. 5030 5031 Example: 5032 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5033 'INSERT INTO tbl VALUES (1, 2, 3)' 5034 5035 Args: 5036 expression: the sql string or expression of the INSERT statement 5037 into: the tbl to insert data to. 5038 columns: optionally the table's column names. 5039 overwrite: whether to INSERT OVERWRITE or not. 5040 dialect: the dialect used to parse the input expressions. 5041 copy: whether or not to copy the expression. 5042 **opts: other options to use to parse the input expressions. 5043 5044 Returns: 5045 Insert: the syntax tree for the INSERT statement. 5046 """ 5047 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5048 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5049 5050 if columns: 5051 this = _apply_list_builder( 5052 *columns, 5053 instance=Schema(this=this), 5054 arg="expressions", 5055 into=Identifier, 5056 copy=False, 5057 dialect=dialect, 5058 **opts, 5059 ) 5060 5061 return Insert(this=this, expression=expr, overwrite=overwrite)
Builds an INSERT statement.
Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql() 'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
- expression: the sql string or expression of the INSERT statement
- into: the tbl to insert data to.
- columns: optionally the table's column names.
- overwrite: whether to INSERT OVERWRITE or not.
- dialect: the dialect used to parse the input expressions.
- copy: whether or not to copy the expression.
- **opts: other options to use to parse the input expressions.
Returns:
Insert: the syntax tree for the INSERT statement.
5064def condition( 5065 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5066) -> Condition: 5067 """ 5068 Initialize a logical condition expression. 5069 5070 Example: 5071 >>> condition("x=1").sql() 5072 'x = 1' 5073 5074 This is helpful for composing larger logical syntax trees: 5075 >>> where = condition("x=1") 5076 >>> where = where.and_("y=1") 5077 >>> Select().from_("tbl").select("*").where(where).sql() 5078 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5079 5080 Args: 5081 *expression: the SQL code string to parse. 5082 If an Expression instance is passed, this is used as-is. 5083 dialect: the dialect used to parse the input expression (in the case that the 5084 input expression is a SQL string). 5085 copy: Whether or not to copy `expression` (only applies to expressions). 5086 **opts: other options to use to parse the input expressions (again, in the case 5087 that the input expression is a SQL string). 5088 5089 Returns: 5090 The new Condition instance 5091 """ 5092 return maybe_parse( 5093 expression, 5094 into=Condition, 5095 dialect=dialect, 5096 copy=copy, 5097 **opts, 5098 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'
This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- copy: Whether or not to copy
expression
(only applies to expressions). - **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
The new Condition instance
5101def and_( 5102 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5103) -> Condition: 5104 """ 5105 Combine multiple conditions with an AND logical operator. 5106 5107 Example: 5108 >>> and_("x=1", and_("y=1", "z=1")).sql() 5109 'x = 1 AND (y = 1 AND z = 1)' 5110 5111 Args: 5112 *expressions: the SQL code strings to parse. 5113 If an Expression instance is passed, this is used as-is. 5114 dialect: the dialect used to parse the input expression. 5115 copy: whether or not to copy `expressions` (only applies to Expressions). 5116 **opts: other options to use to parse the input expressions. 5117 5118 Returns: 5119 And: the new condition 5120 """ 5121 return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression.
- copy: whether or not to copy
expressions
(only applies to Expressions). - **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
5124def or_( 5125 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5126) -> Condition: 5127 """ 5128 Combine multiple conditions with an OR logical operator. 5129 5130 Example: 5131 >>> or_("x=1", or_("y=1", "z=1")).sql() 5132 'x = 1 OR (y = 1 OR z = 1)' 5133 5134 Args: 5135 *expressions: the SQL code strings to parse. 5136 If an Expression instance is passed, this is used as-is. 5137 dialect: the dialect used to parse the input expression. 5138 copy: whether or not to copy `expressions` (only applies to Expressions). 5139 **opts: other options to use to parse the input expressions. 5140 5141 Returns: 5142 Or: the new condition 5143 """ 5144 return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression.
- copy: whether or not to copy
expressions
(only applies to Expressions). - **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
5147def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5148 """ 5149 Wrap a condition with a NOT operator. 5150 5151 Example: 5152 >>> not_("this_suit='black'").sql() 5153 "NOT this_suit = 'black'" 5154 5155 Args: 5156 expression: the SQL code string to parse. 5157 If an Expression instance is passed, this is used as-is. 5158 dialect: the dialect used to parse the input expression. 5159 copy: whether to copy the expression or not. 5160 **opts: other options to use to parse the input expressions. 5161 5162 Returns: 5163 The new condition. 5164 """ 5165 this = condition( 5166 expression, 5167 dialect=dialect, 5168 copy=copy, 5169 **opts, 5170 ) 5171 return Not(this=_wrap(this, Connector))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression.
- copy: whether to copy the expression or not.
- **opts: other options to use to parse the input expressions.
Returns:
The new condition.
5174def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5175 """ 5176 Wrap an expression in parentheses. 5177 5178 Example: 5179 >>> paren("5 + 3").sql() 5180 '(5 + 3)' 5181 5182 Args: 5183 expression: the SQL code string to parse. 5184 If an Expression instance is passed, this is used as-is. 5185 copy: whether to copy the expression or not. 5186 5187 Returns: 5188 The wrapped expression. 5189 """ 5190 return Paren(this=maybe_parse(expression, copy=copy))
Wrap an expression in parentheses.
Example:
>>> paren("5 + 3").sql() '(5 + 3)'
Arguments:
- expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- copy: whether to copy the expression or not.
Returns:
The wrapped expression.
5208def to_identifier(name, quoted=None, copy=True): 5209 """Builds an identifier. 5210 5211 Args: 5212 name: The name to turn into an identifier. 5213 quoted: Whether or not force quote the identifier. 5214 copy: Whether or not to copy a passed in Identefier node. 5215 5216 Returns: 5217 The identifier ast node. 5218 """ 5219 5220 if name is None: 5221 return None 5222 5223 if isinstance(name, Identifier): 5224 identifier = _maybe_copy(name, copy) 5225 elif isinstance(name, str): 5226 identifier = Identifier( 5227 this=name, 5228 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5229 ) 5230 else: 5231 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5232 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
- copy: Whether or not to copy a passed in Identefier node.
Returns:
The identifier ast node.
5238def to_interval(interval: str | Literal) -> Interval: 5239 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5240 if isinstance(interval, Literal): 5241 if not interval.is_string: 5242 raise ValueError("Invalid interval string.") 5243 5244 interval = interval.this 5245 5246 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5247 5248 if not interval_parts: 5249 raise ValueError("Invalid interval string.") 5250 5251 return Interval( 5252 this=Literal.string(interval_parts.group(1)), 5253 unit=Var(this=interval_parts.group(2)), 5254 )
Builds an interval expression from a string like '1 day' or '5 months'.
5267def to_table( 5268 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5269) -> t.Optional[Table]: 5270 """ 5271 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5272 If a table is passed in then that table is returned. 5273 5274 Args: 5275 sql_path: a `[catalog].[schema].[table]` string. 5276 dialect: the source dialect according to which the table name will be parsed. 5277 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5278 5279 Returns: 5280 A table expression. 5281 """ 5282 if sql_path is None or isinstance(sql_path, Table): 5283 return sql_path 5284 if not isinstance(sql_path, str): 5285 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5286 5287 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5288 if table: 5289 for k, v in kwargs.items(): 5290 table.set(k, v) 5291 5292 return table
Create a table expression from a [catalog].[schema].[table]
sql path. Catalog and schema are optional.
If a table is passed in then that table is returned.
Arguments:
- sql_path: a
[catalog].[schema].[table]
string. - dialect: the source dialect according to which the table name will be parsed.
- kwargs: the kwargs to instantiate the resulting
Table
expression with.
Returns:
A table expression.
5295def to_column(sql_path: str | Column, **kwargs) -> Column: 5296 """ 5297 Create a column from a `[table].[column]` sql path. Schema is optional. 5298 5299 If a column is passed in then that column is returned. 5300 5301 Args: 5302 sql_path: `[table].[column]` string 5303 Returns: 5304 Table: A column expression 5305 """ 5306 if sql_path is None or isinstance(sql_path, Column): 5307 return sql_path 5308 if not isinstance(sql_path, str): 5309 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5310 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
5313def alias_( 5314 expression: ExpOrStr, 5315 alias: str | Identifier, 5316 table: bool | t.Sequence[str | Identifier] = False, 5317 quoted: t.Optional[bool] = None, 5318 dialect: DialectType = None, 5319 copy: bool = True, 5320 **opts, 5321): 5322 """Create an Alias expression. 5323 5324 Example: 5325 >>> alias_('foo', 'bar').sql() 5326 'foo AS bar' 5327 5328 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5329 '(SELECT 1, 2) AS bar(a, b)' 5330 5331 Args: 5332 expression: the SQL code strings to parse. 5333 If an Expression instance is passed, this is used as-is. 5334 alias: the alias name to use. If the name has 5335 special characters it is quoted. 5336 table: Whether or not to create a table alias, can also be a list of columns. 5337 quoted: whether or not to quote the alias 5338 dialect: the dialect used to parse the input expression. 5339 copy: Whether or not to copy the expression. 5340 **opts: other options to use to parse the input expressions. 5341 5342 Returns: 5343 Alias: the aliased expression 5344 """ 5345 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5346 alias = to_identifier(alias, quoted=quoted) 5347 5348 if table: 5349 table_alias = TableAlias(this=alias) 5350 exp.set("alias", table_alias) 5351 5352 if not isinstance(table, bool): 5353 for column in table: 5354 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5355 5356 return exp 5357 5358 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5359 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5360 # for the complete Window expression. 5361 # 5362 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5363 5364 if "alias" in exp.arg_types and not isinstance(exp, Window): 5365 exp.set("alias", alias) 5366 return exp 5367 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- copy: Whether or not to copy the expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
5370def subquery( 5371 expression: ExpOrStr, 5372 alias: t.Optional[Identifier | str] = None, 5373 dialect: DialectType = None, 5374 **opts, 5375) -> Select: 5376 """ 5377 Build a subquery expression. 5378 5379 Example: 5380 >>> subquery('select x from tbl', 'bar').select('x').sql() 5381 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5382 5383 Args: 5384 expression: the SQL code strings to parse. 5385 If an Expression instance is passed, this is used as-is. 5386 alias: the alias name to use. 5387 dialect: the dialect used to parse the input expression. 5388 **opts: other options to use to parse the input expressions. 5389 5390 Returns: 5391 A new Select instance with the subquery expression included. 5392 """ 5393 5394 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5395 return Select().from_(expression, dialect=dialect, **opts)
Build a subquery expression.
Example:
>>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use.
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
A new Select instance with the subquery expression included.
5398def column( 5399 col: str | Identifier, 5400 table: t.Optional[str | Identifier] = None, 5401 db: t.Optional[str | Identifier] = None, 5402 catalog: t.Optional[str | Identifier] = None, 5403 quoted: t.Optional[bool] = None, 5404) -> Column: 5405 """ 5406 Build a Column. 5407 5408 Args: 5409 col: Column name. 5410 table: Table name. 5411 db: Database name. 5412 catalog: Catalog name. 5413 quoted: Whether to force quotes on the column's identifiers. 5414 5415 Returns: 5416 The new Column instance. 5417 """ 5418 return Column( 5419 this=to_identifier(col, quoted=quoted), 5420 table=to_identifier(table, quoted=quoted), 5421 db=to_identifier(db, quoted=quoted), 5422 catalog=to_identifier(catalog, quoted=quoted), 5423 )
Build a Column.
Arguments:
- col: Column name.
- table: Table name.
- db: Database name.
- catalog: Catalog name.
- quoted: Whether to force quotes on the column's identifiers.
Returns:
The new Column instance.
5426def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5427 """Cast an expression to a data type. 5428 5429 Example: 5430 >>> cast('x + 1', 'int').sql() 5431 'CAST(x + 1 AS INT)' 5432 5433 Args: 5434 expression: The expression to cast. 5435 to: The datatype to cast to. 5436 5437 Returns: 5438 The new Cast instance. 5439 """ 5440 expression = maybe_parse(expression, **opts) 5441 return Cast(this=expression, to=DataType.build(to, **opts))
Cast an expression to a data type.
Example:
>>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Arguments:
- expression: The expression to cast.
- to: The datatype to cast to.
Returns:
The new Cast instance.
5444def table_( 5445 table: Identifier | str, 5446 db: t.Optional[Identifier | str] = None, 5447 catalog: t.Optional[Identifier | str] = None, 5448 quoted: t.Optional[bool] = None, 5449 alias: t.Optional[Identifier | str] = None, 5450) -> Table: 5451 """Build a Table. 5452 5453 Args: 5454 table: Table name. 5455 db: Database name. 5456 catalog: Catalog name. 5457 quote: Whether to force quotes on the table's identifiers. 5458 alias: Table's alias. 5459 5460 Returns: 5461 The new Table instance. 5462 """ 5463 return Table( 5464 this=to_identifier(table, quoted=quoted), 5465 db=to_identifier(db, quoted=quoted), 5466 catalog=to_identifier(catalog, quoted=quoted), 5467 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5468 )
Build a Table.
Arguments:
- table: Table name.
- db: Database name.
- catalog: Catalog name.
- quote: Whether to force quotes on the table's identifiers.
- alias: Table's alias.
Returns:
The new Table instance.
5471def values( 5472 values: t.Iterable[t.Tuple[t.Any, ...]], 5473 alias: t.Optional[str] = None, 5474 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5475) -> Values: 5476 """Build VALUES statement. 5477 5478 Example: 5479 >>> values([(1, '2')]).sql() 5480 "VALUES (1, '2')" 5481 5482 Args: 5483 values: values statements that will be converted to SQL 5484 alias: optional alias 5485 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5486 If either are provided then an alias is also required. 5487 5488 Returns: 5489 Values: the Values expression object 5490 """ 5491 if columns and not alias: 5492 raise ValueError("Alias is required when providing columns") 5493 5494 return Values( 5495 expressions=[convert(tup) for tup in values], 5496 alias=( 5497 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5498 if columns 5499 else (TableAlias(this=to_identifier(alias)) if alias else None) 5500 ), 5501 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:
Values: the Values expression object
5504def var(name: t.Optional[ExpOrStr]) -> Var: 5505 """Build a SQL variable. 5506 5507 Example: 5508 >>> repr(var('x')) 5509 '(VAR this: x)' 5510 5511 >>> repr(var(column('x', table='y'))) 5512 '(VAR this: x)' 5513 5514 Args: 5515 name: The name of the var or an expression who's name will become the var. 5516 5517 Returns: 5518 The new variable node. 5519 """ 5520 if not name: 5521 raise ValueError("Cannot convert empty name into var.") 5522 5523 if isinstance(name, Expression): 5524 name = name.name 5525 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.
5528def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5529 """Build ALTER TABLE... RENAME... expression 5530 5531 Args: 5532 old_name: The old name of the table 5533 new_name: The new name of the table 5534 5535 Returns: 5536 Alter table expression 5537 """ 5538 old_table = to_table(old_name) 5539 new_table = to_table(new_name) 5540 return AlterTable( 5541 this=old_table, 5542 actions=[ 5543 RenameTable(this=new_table), 5544 ], 5545 )
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
5548def convert(value: t.Any, copy: bool = False) -> Expression: 5549 """Convert a python value into an expression object. 5550 5551 Raises an error if a conversion is not possible. 5552 5553 Args: 5554 value: A python object. 5555 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5556 5557 Returns: 5558 Expression: the equivalent expression object. 5559 """ 5560 if isinstance(value, Expression): 5561 return _maybe_copy(value, copy) 5562 if isinstance(value, str): 5563 return Literal.string(value) 5564 if isinstance(value, bool): 5565 return Boolean(this=value) 5566 if value is None or (isinstance(value, float) and math.isnan(value)): 5567 return NULL 5568 if isinstance(value, numbers.Number): 5569 return Literal.number(value) 5570 if isinstance(value, datetime.datetime): 5571 datetime_literal = Literal.string( 5572 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5573 ) 5574 return TimeStrToTime(this=datetime_literal) 5575 if isinstance(value, datetime.date): 5576 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5577 return DateStrToDate(this=date_literal) 5578 if isinstance(value, tuple): 5579 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5580 if isinstance(value, list): 5581 return Array(expressions=[convert(v, copy=copy) for v in value]) 5582 if isinstance(value, dict): 5583 return Map( 5584 keys=[convert(k, copy=copy) for k in value], 5585 values=[convert(v, copy=copy) for v in value.values()], 5586 ) 5587 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value: A python object.
- copy: Whether or not to copy
value
(only applies to Expressions and collections).
Returns:
Expression: the equivalent expression object.
5590def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5591 """ 5592 Replace children of an expression with the result of a lambda fun(child) -> exp. 5593 """ 5594 for k, v in expression.args.items(): 5595 is_list_arg = type(v) is list 5596 5597 child_nodes = v if is_list_arg else [v] 5598 new_child_nodes = [] 5599 5600 for cn in child_nodes: 5601 if isinstance(cn, Expression): 5602 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5603 new_child_nodes.append(child_node) 5604 child_node.parent = expression 5605 child_node.arg_key = k 5606 else: 5607 new_child_nodes.append(cn) 5608 5609 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.
5612def column_table_names(expression: Expression) -> t.List[str]: 5613 """ 5614 Return all table names referenced through columns in an expression. 5615 5616 Example: 5617 >>> import sqlglot 5618 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5619 ['c', 'a'] 5620 5621 Args: 5622 expression: expression to find table names. 5623 5624 Returns: 5625 A list of unique names. 5626 """ 5627 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: expression to find table names.
Returns:
A list of unique names.
5630def table_name(table: Table | str) -> str: 5631 """Get the full name of a table as a string. 5632 5633 Args: 5634 table: table expression node or string. 5635 5636 Examples: 5637 >>> from sqlglot import exp, parse_one 5638 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5639 'a.b.c' 5640 5641 Returns: 5642 The table name. 5643 """ 5644 5645 table = maybe_parse(table, into=Table) 5646 5647 if not table: 5648 raise ValueError(f"Cannot parse {table}") 5649 5650 return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)
Get the full name of a table as a string.
Arguments:
- table: table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns:
The table name.
5653def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E: 5654 """Replace all tables in expression according to the mapping. 5655 5656 Args: 5657 expression: expression node to be transformed and replaced. 5658 mapping: mapping of table names. 5659 5660 Examples: 5661 >>> from sqlglot import exp, parse_one 5662 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5663 'SELECT * FROM c' 5664 5665 Returns: 5666 The mapped expression. 5667 """ 5668 5669 def _replace_tables(node: Expression) -> Expression: 5670 if isinstance(node, Table): 5671 new_name = mapping.get(table_name(node)) 5672 if new_name: 5673 return to_table( 5674 new_name, 5675 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5676 ) 5677 return node 5678 5679 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression: expression node to be transformed and replaced.
- mapping: 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.
5682def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5683 """Replace placeholders in an expression. 5684 5685 Args: 5686 expression: expression node to be transformed and replaced. 5687 args: positional names that will substitute unnamed placeholders in the given order. 5688 kwargs: keyword arguments that will substitute named placeholders. 5689 5690 Examples: 5691 >>> from sqlglot import exp, parse_one 5692 >>> replace_placeholders( 5693 ... parse_one("select * from :tbl where ? = ?"), 5694 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5695 ... ).sql() 5696 "SELECT * FROM foo WHERE str_col = 'b'" 5697 5698 Returns: 5699 The mapped expression. 5700 """ 5701 5702 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5703 if isinstance(node, Placeholder): 5704 if node.name: 5705 new_name = kwargs.get(node.name) 5706 if new_name: 5707 return convert(new_name) 5708 else: 5709 try: 5710 return convert(next(args)) 5711 except StopIteration: 5712 pass 5713 return node 5714 5715 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression: expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") ... ).sql() "SELECT * FROM foo WHERE str_col = 'b'"
Returns:
The mapped expression.
5718def expand( 5719 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5720) -> Expression: 5721 """Transforms an expression by expanding all referenced sources into subqueries. 5722 5723 Examples: 5724 >>> from sqlglot import parse_one 5725 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5726 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5727 5728 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5729 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5730 5731 Args: 5732 expression: The expression to expand. 5733 sources: A dictionary of name to Subqueryables. 5734 copy: Whether or not to copy the expression during transformation. Defaults to True. 5735 5736 Returns: 5737 The transformed expression. 5738 """ 5739 5740 def _expand(node: Expression): 5741 if isinstance(node, Table): 5742 name = table_name(node) 5743 source = sources.get(name) 5744 if source: 5745 subquery = source.subquery(node.alias or name) 5746 subquery.comments = [f"source: {name}"] 5747 return subquery.transform(_expand, copy=False) 5748 return node 5749 5750 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5753def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5754 """ 5755 Returns a Func expression. 5756 5757 Examples: 5758 >>> func("abs", 5).sql() 5759 'ABS(5)' 5760 5761 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5762 'CAST(5 AS DOUBLE)' 5763 5764 Args: 5765 name: the name of the function to build. 5766 args: the args used to instantiate the function of interest. 5767 dialect: the source dialect. 5768 kwargs: the kwargs used to instantiate the function of interest. 5769 5770 Note: 5771 The arguments `args` and `kwargs` are mutually exclusive. 5772 5773 Returns: 5774 An instance of the function of interest, or an anonymous function, if `name` doesn't 5775 correspond to an existing `sqlglot.expressions.Func` class. 5776 """ 5777 if args and kwargs: 5778 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5779 5780 from sqlglot.dialects.dialect import Dialect 5781 5782 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5783 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5784 5785 parser = Dialect.get_or_raise(dialect)().parser() 5786 from_args_list = parser.FUNCTIONS.get(name.upper()) 5787 5788 if from_args_list: 5789 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5790 else: 5791 kwargs = kwargs or {"expressions": converted} 5792 function = Anonymous(this=name, **kwargs) 5793 5794 for error_message in function.error_messages(converted): 5795 raise ValueError(error_message) 5796 5797 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
andkwargs
are mutually exclusive.
Returns:
An instance of the function of interest, or an anonymous function, if
name
doesn't correspond to an existingsqlglot.expressions.Func
class.
5800def true() -> Boolean: 5801 """ 5802 Returns a true Boolean expression. 5803 """ 5804 return Boolean(this=True)
Returns a true Boolean expression.
5807def false() -> Boolean: 5808 """ 5809 Returns a false Boolean expression. 5810 """ 5811 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.