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 "using": False, 1504 "where": False, 1505 "columns": False, 1506 "unique": False, 1507 "primary": False, 1508 "amp": False, # teradata 1509 "partition_by": False, # teradata 1510 } 1511 1512 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 ) 1561 1562 1563class OnConflict(Expression): 1564 arg_types = { 1565 "duplicate": False, 1566 "expressions": False, 1567 "nothing": False, 1568 "key": False, 1569 "constraint": False, 1570 } 1571 1572 1573class Returning(Expression): 1574 arg_types = {"expressions": True} 1575 1576 1577# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1578class Introducer(Expression): 1579 arg_types = {"this": True, "expression": True} 1580 1581 1582# national char, like n'utf8' 1583class National(Expression): 1584 pass 1585 1586 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 } 1597 1598 1599class Partition(Expression): 1600 arg_types = {"expressions": True} 1601 1602 1603class Fetch(Expression): 1604 arg_types = { 1605 "direction": False, 1606 "count": False, 1607 "percent": False, 1608 "with_ties": False, 1609 } 1610 1611 1612class Group(Expression): 1613 arg_types = { 1614 "expressions": False, 1615 "grouping_sets": False, 1616 "cube": False, 1617 "rollup": False, 1618 "totals": False, 1619 } 1620 1621 1622class Lambda(Expression): 1623 arg_types = {"this": True, "expressions": True} 1624 1625 1626class Limit(Expression): 1627 arg_types = {"this": False, "expression": True, "offset": False} 1628 1629 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 1648 1649 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 1768 1769 1770class Lateral(UDTF): 1771 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1772 1773 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 } 1785 1786 1787# Clickhouse FROM FINAL modifier 1788# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1789class Final(Expression): 1790 pass 1791 1792 1793class Offset(Expression): 1794 arg_types = {"this": False, "expression": True} 1795 1796 1797class Order(Expression): 1798 arg_types = {"this": False, "expressions": True} 1799 1800 1801# hive specific sorts 1802# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1803class Cluster(Order): 1804 pass 1805 1806 1807class Distribute(Order): 1808 pass 1809 1810 1811class Sort(Order): 1812 pass 1813 1814 1815class Ordered(Expression): 1816 arg_types = {"this": True, "desc": True, "nulls_first": True} 1817 1818 1819class Property(Expression): 1820 arg_types = {"this": True, "value": True} 1821 1822 1823class AlgorithmProperty(Property): 1824 arg_types = {"this": True} 1825 1826 1827class AutoIncrementProperty(Property): 1828 arg_types = {"this": True} 1829 1830 1831class BlockCompressionProperty(Property): 1832 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1833 1834 1835class CharacterSetProperty(Property): 1836 arg_types = {"this": True, "default": True} 1837 1838 1839class ChecksumProperty(Property): 1840 arg_types = {"on": False, "default": False} 1841 1842 1843class CollateProperty(Property): 1844 arg_types = {"this": True} 1845 1846 1847class DataBlocksizeProperty(Property): 1848 arg_types = { 1849 "size": False, 1850 "units": False, 1851 "minimum": False, 1852 "maximum": False, 1853 "default": False, 1854 } 1855 1856 1857class DefinerProperty(Property): 1858 arg_types = {"this": True} 1859 1860 1861class DistKeyProperty(Property): 1862 arg_types = {"this": True} 1863 1864 1865class DistStyleProperty(Property): 1866 arg_types = {"this": True} 1867 1868 1869class EngineProperty(Property): 1870 arg_types = {"this": True} 1871 1872 1873class ToTableProperty(Property): 1874 arg_types = {"this": True} 1875 1876 1877class ExecuteAsProperty(Property): 1878 arg_types = {"this": True} 1879 1880 1881class ExternalProperty(Property): 1882 arg_types = {"this": False} 1883 1884 1885class FallbackProperty(Property): 1886 arg_types = {"no": True, "protection": False} 1887 1888 1889class FileFormatProperty(Property): 1890 arg_types = {"this": True} 1891 1892 1893class FreespaceProperty(Property): 1894 arg_types = {"this": True, "percent": False} 1895 1896 1897class InputOutputFormat(Expression): 1898 arg_types = {"input_format": False, "output_format": False} 1899 1900 1901class IsolatedLoadingProperty(Property): 1902 arg_types = { 1903 "no": True, 1904 "concurrent": True, 1905 "for_all": True, 1906 "for_insert": True, 1907 "for_none": True, 1908 } 1909 1910 1911class JournalProperty(Property): 1912 arg_types = { 1913 "no": False, 1914 "dual": False, 1915 "before": False, 1916 "local": False, 1917 "after": False, 1918 } 1919 1920 1921class LanguageProperty(Property): 1922 arg_types = {"this": True} 1923 1924 1925class DictProperty(Property): 1926 arg_types = {"this": True, "kind": True, "settings": False} 1927 1928 1929class DictSubProperty(Property): 1930 pass 1931 1932 1933class DictRange(Property): 1934 arg_types = {"this": True, "min": True, "max": True} 1935 1936 1937# Clickhouse CREATE ... ON CLUSTER modifier 1938# https://clickhouse.com/docs/en/sql-reference/distributed-ddl 1939class OnCluster(Property): 1940 arg_types = {"this": True} 1941 1942 1943class LikeProperty(Property): 1944 arg_types = {"this": True, "expressions": False} 1945 1946 1947class LocationProperty(Property): 1948 arg_types = {"this": True} 1949 1950 1951class LockingProperty(Property): 1952 arg_types = { 1953 "this": False, 1954 "kind": True, 1955 "for_or_in": True, 1956 "lock_type": True, 1957 "override": False, 1958 } 1959 1960 1961class LogProperty(Property): 1962 arg_types = {"no": True} 1963 1964 1965class MaterializedProperty(Property): 1966 arg_types = {"this": False} 1967 1968 1969class MergeBlockRatioProperty(Property): 1970 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1971 1972 1973class NoPrimaryIndexProperty(Property): 1974 arg_types = {} 1975 1976 1977class OnCommitProperty(Property): 1978 arg_type = {"delete": False} 1979 1980 1981class PartitionedByProperty(Property): 1982 arg_types = {"this": True} 1983 1984 1985class ReturnsProperty(Property): 1986 arg_types = {"this": True, "is_table": False, "table": False} 1987 1988 1989class RowFormatProperty(Property): 1990 arg_types = {"this": True} 1991 1992 1993class RowFormatDelimitedProperty(Property): 1994 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1995 arg_types = { 1996 "fields": False, 1997 "escaped": False, 1998 "collection_items": False, 1999 "map_keys": False, 2000 "lines": False, 2001 "null": False, 2002 "serde": False, 2003 } 2004 2005 2006class RowFormatSerdeProperty(Property): 2007 arg_types = {"this": True} 2008 2009 2010class SchemaCommentProperty(Property): 2011 arg_types = {"this": True} 2012 2013 2014class SerdeProperties(Property): 2015 arg_types = {"expressions": True} 2016 2017 2018class SetProperty(Property): 2019 arg_types = {"multi": True} 2020 2021 2022class SettingsProperty(Property): 2023 arg_types = {"expressions": True} 2024 2025 2026class SortKeyProperty(Property): 2027 arg_types = {"this": True, "compound": False} 2028 2029 2030class SqlSecurityProperty(Property): 2031 arg_types = {"definer": True} 2032 2033 2034class StabilityProperty(Property): 2035 arg_types = {"this": True} 2036 2037 2038class TemporaryProperty(Property): 2039 arg_types = {} 2040 2041 2042class TransientProperty(Property): 2043 arg_types = {"this": False} 2044 2045 2046class VolatileProperty(Property): 2047 arg_types = {"this": False} 2048 2049 2050class WithDataProperty(Property): 2051 arg_types = {"no": True, "statistics": False} 2052 2053 2054class WithJournalTableProperty(Property): 2055 arg_types = {"this": True} 2056 2057 2058class Properties(Expression): 2059 arg_types = {"expressions": True} 2060 2061 NAME_TO_PROPERTY = { 2062 "ALGORITHM": AlgorithmProperty, 2063 "AUTO_INCREMENT": AutoIncrementProperty, 2064 "CHARACTER SET": CharacterSetProperty, 2065 "COLLATE": CollateProperty, 2066 "COMMENT": SchemaCommentProperty, 2067 "DEFINER": DefinerProperty, 2068 "DISTKEY": DistKeyProperty, 2069 "DISTSTYLE": DistStyleProperty, 2070 "ENGINE": EngineProperty, 2071 "EXECUTE AS": ExecuteAsProperty, 2072 "FORMAT": FileFormatProperty, 2073 "LANGUAGE": LanguageProperty, 2074 "LOCATION": LocationProperty, 2075 "PARTITIONED_BY": PartitionedByProperty, 2076 "RETURNS": ReturnsProperty, 2077 "ROW_FORMAT": RowFormatProperty, 2078 "SORTKEY": SortKeyProperty, 2079 } 2080 2081 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2082 2083 # CREATE property locations 2084 # Form: schema specified 2085 # create [POST_CREATE] 2086 # table a [POST_NAME] 2087 # (b int) [POST_SCHEMA] 2088 # with ([POST_WITH]) 2089 # index (b) [POST_INDEX] 2090 # 2091 # Form: alias selection 2092 # create [POST_CREATE] 2093 # table a [POST_NAME] 2094 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2095 # index (c) [POST_INDEX] 2096 class Location(AutoName): 2097 POST_CREATE = auto() 2098 POST_NAME = auto() 2099 POST_SCHEMA = auto() 2100 POST_WITH = auto() 2101 POST_ALIAS = auto() 2102 POST_EXPRESSION = auto() 2103 POST_INDEX = auto() 2104 UNSUPPORTED = auto() 2105 2106 @classmethod 2107 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2108 expressions = [] 2109 for key, value in properties_dict.items(): 2110 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2111 if property_cls: 2112 expressions.append(property_cls(this=convert(value))) 2113 else: 2114 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2115 2116 return cls(expressions=expressions) 2117 2118 2119class Qualify(Expression): 2120 pass 2121 2122 2123# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 2124class Return(Expression): 2125 pass 2126 2127 2128class Reference(Expression): 2129 arg_types = {"this": True, "expressions": False, "options": False} 2130 2131 2132class Tuple(Expression): 2133 arg_types = {"expressions": False} 2134 2135 def isin( 2136 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2137 ) -> In: 2138 return In( 2139 this=_maybe_copy(self, copy), 2140 expressions=[convert(e, copy=copy) for e in expressions], 2141 query=maybe_parse(query, copy=copy, **opts) if query else None, 2142 ) 2143 2144 2145class Subqueryable(Unionable): 2146 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2147 """ 2148 Convert this expression to an aliased expression that can be used as a Subquery. 2149 2150 Example: 2151 >>> subquery = Select().select("x").from_("tbl").subquery() 2152 >>> Select().select("x").from_(subquery).sql() 2153 'SELECT x FROM (SELECT x FROM tbl)' 2154 2155 Args: 2156 alias (str | Identifier): an optional alias for the subquery 2157 copy (bool): if `False`, modify this expression instance in-place. 2158 2159 Returns: 2160 Alias: the subquery 2161 """ 2162 instance = _maybe_copy(self, copy) 2163 if not isinstance(alias, Expression): 2164 alias = TableAlias(this=to_identifier(alias)) if alias else None 2165 2166 return Subquery(this=instance, alias=alias) 2167 2168 def limit( 2169 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2170 ) -> Select: 2171 raise NotImplementedError 2172 2173 @property 2174 def ctes(self): 2175 with_ = self.args.get("with") 2176 if not with_: 2177 return [] 2178 return with_.expressions 2179 2180 @property 2181 def selects(self): 2182 raise NotImplementedError("Subqueryable objects must implement `selects`") 2183 2184 @property 2185 def named_selects(self): 2186 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2187 2188 def with_( 2189 self, 2190 alias: ExpOrStr, 2191 as_: ExpOrStr, 2192 recursive: t.Optional[bool] = None, 2193 append: bool = True, 2194 dialect: DialectType = None, 2195 copy: bool = True, 2196 **opts, 2197 ) -> Subqueryable: 2198 """ 2199 Append to or set the common table expressions. 2200 2201 Example: 2202 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2203 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2204 2205 Args: 2206 alias: the SQL code string to parse as the table name. 2207 If an `Expression` instance is passed, this is used as-is. 2208 as_: the SQL code string to parse as the table expression. 2209 If an `Expression` instance is passed, it will be used as-is. 2210 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2211 append: if `True`, add to any existing expressions. 2212 Otherwise, this resets the expressions. 2213 dialect: the dialect used to parse the input expression. 2214 copy: if `False`, modify this expression instance in-place. 2215 opts: other options to use to parse the input expressions. 2216 2217 Returns: 2218 The modified expression. 2219 """ 2220 return _apply_cte_builder( 2221 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2222 ) 2223 2224 2225QUERY_MODIFIERS = { 2226 "match": False, 2227 "laterals": False, 2228 "joins": False, 2229 "pivots": False, 2230 "where": False, 2231 "group": False, 2232 "having": False, 2233 "qualify": False, 2234 "windows": False, 2235 "distribute": False, 2236 "sort": False, 2237 "cluster": False, 2238 "order": False, 2239 "limit": False, 2240 "offset": False, 2241 "locks": False, 2242 "sample": False, 2243 "settings": False, 2244 "format": False, 2245} 2246 2247 2248class Table(Expression): 2249 arg_types = { 2250 "this": True, 2251 "alias": False, 2252 "db": False, 2253 "catalog": False, 2254 "laterals": False, 2255 "joins": False, 2256 "pivots": False, 2257 "hints": False, 2258 "system_time": False, 2259 } 2260 2261 @property 2262 def db(self) -> str: 2263 return self.text("db") 2264 2265 @property 2266 def catalog(self) -> str: 2267 return self.text("catalog") 2268 2269 @property 2270 def parts(self) -> t.List[Identifier]: 2271 """Return the parts of a table in order catalog, db, table.""" 2272 return [ 2273 t.cast(Identifier, self.args[part]) 2274 for part in ("catalog", "db", "this") 2275 if self.args.get(part) 2276 ] 2277 2278 2279# See the TSQL "Querying data in a system-versioned temporal table" page 2280class SystemTime(Expression): 2281 arg_types = { 2282 "this": False, 2283 "expression": False, 2284 "kind": True, 2285 } 2286 2287 2288class Union(Subqueryable): 2289 arg_types = { 2290 "with": False, 2291 "this": True, 2292 "expression": True, 2293 "distinct": False, 2294 **QUERY_MODIFIERS, 2295 } 2296 2297 def limit( 2298 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2299 ) -> Select: 2300 """ 2301 Set the LIMIT expression. 2302 2303 Example: 2304 >>> select("1").union(select("1")).limit(1).sql() 2305 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2306 2307 Args: 2308 expression: the SQL code string to parse. 2309 This can also be an integer. 2310 If a `Limit` instance is passed, this is used as-is. 2311 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2312 dialect: the dialect used to parse the input expression. 2313 copy: if `False`, modify this expression instance in-place. 2314 opts: other options to use to parse the input expressions. 2315 2316 Returns: 2317 The limited subqueryable. 2318 """ 2319 return ( 2320 select("*") 2321 .from_(self.subquery(alias="_l_0", copy=copy)) 2322 .limit(expression, dialect=dialect, copy=False, **opts) 2323 ) 2324 2325 def select( 2326 self, 2327 *expressions: t.Optional[ExpOrStr], 2328 append: bool = True, 2329 dialect: DialectType = None, 2330 copy: bool = True, 2331 **opts, 2332 ) -> Union: 2333 """Append to or set the SELECT of the union recursively. 2334 2335 Example: 2336 >>> from sqlglot import parse_one 2337 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2338 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2339 2340 Args: 2341 *expressions: the SQL code strings to parse. 2342 If an `Expression` instance is passed, it will be used as-is. 2343 append: if `True`, add to any existing expressions. 2344 Otherwise, this resets the expressions. 2345 dialect: the dialect used to parse the input expressions. 2346 copy: if `False`, modify this expression instance in-place. 2347 opts: other options to use to parse the input expressions. 2348 2349 Returns: 2350 Union: the modified expression. 2351 """ 2352 this = self.copy() if copy else self 2353 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2354 this.expression.unnest().select( 2355 *expressions, append=append, dialect=dialect, copy=False, **opts 2356 ) 2357 return this 2358 2359 @property 2360 def named_selects(self): 2361 return self.this.unnest().named_selects 2362 2363 @property 2364 def is_star(self) -> bool: 2365 return self.this.is_star or self.expression.is_star 2366 2367 @property 2368 def selects(self): 2369 return self.this.unnest().selects 2370 2371 @property 2372 def left(self): 2373 return self.this 2374 2375 @property 2376 def right(self): 2377 return self.expression 2378 2379 2380class Except(Union): 2381 pass 2382 2383 2384class Intersect(Union): 2385 pass 2386 2387 2388class Unnest(UDTF): 2389 arg_types = { 2390 "expressions": True, 2391 "ordinality": False, 2392 "alias": False, 2393 "offset": False, 2394 } 2395 2396 2397class Update(Expression): 2398 arg_types = { 2399 "with": False, 2400 "this": False, 2401 "expressions": True, 2402 "from": False, 2403 "where": False, 2404 "returning": False, 2405 } 2406 2407 2408class Values(UDTF): 2409 arg_types = { 2410 "expressions": True, 2411 "ordinality": False, 2412 "alias": False, 2413 } 2414 2415 2416class Var(Expression): 2417 pass 2418 2419 2420class Schema(Expression): 2421 arg_types = {"this": False, "expressions": False} 2422 2423 2424# https://dev.mysql.com/doc/refman/8.0/en/select.html 2425# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html 2426class Lock(Expression): 2427 arg_types = {"update": True, "expressions": False, "wait": False} 2428 2429 2430class Select(Subqueryable): 2431 arg_types = { 2432 "with": False, 2433 "kind": False, 2434 "expressions": False, 2435 "hint": False, 2436 "distinct": False, 2437 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2438 "value": False, 2439 "into": False, 2440 "from": False, 2441 **QUERY_MODIFIERS, 2442 } 2443 2444 def from_( 2445 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2446 ) -> Select: 2447 """ 2448 Set the FROM expression. 2449 2450 Example: 2451 >>> Select().from_("tbl").select("x").sql() 2452 'SELECT x FROM tbl' 2453 2454 Args: 2455 expression : the SQL code strings to parse. 2456 If a `From` instance is passed, this is used as-is. 2457 If another `Expression` instance is passed, it will be wrapped in a `From`. 2458 dialect: the dialect used to parse the input expression. 2459 copy: if `False`, modify this expression instance in-place. 2460 opts: other options to use to parse the input expressions. 2461 2462 Returns: 2463 The modified Select expression. 2464 """ 2465 return _apply_builder( 2466 expression=expression, 2467 instance=self, 2468 arg="from", 2469 into=From, 2470 prefix="FROM", 2471 dialect=dialect, 2472 copy=copy, 2473 **opts, 2474 ) 2475 2476 def group_by( 2477 self, 2478 *expressions: t.Optional[ExpOrStr], 2479 append: bool = True, 2480 dialect: DialectType = None, 2481 copy: bool = True, 2482 **opts, 2483 ) -> Select: 2484 """ 2485 Set the GROUP BY expression. 2486 2487 Example: 2488 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2489 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2490 2491 Args: 2492 *expressions: the SQL code strings to parse. 2493 If a `Group` instance is passed, this is used as-is. 2494 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2495 If nothing is passed in then a group by is not applied to the expression 2496 append: if `True`, add to any existing expressions. 2497 Otherwise, this flattens all the `Group` expression into a single expression. 2498 dialect: the dialect used to parse the input expression. 2499 copy: if `False`, modify this expression instance in-place. 2500 opts: other options to use to parse the input expressions. 2501 2502 Returns: 2503 The modified Select expression. 2504 """ 2505 if not expressions: 2506 return self if not copy else self.copy() 2507 2508 return _apply_child_list_builder( 2509 *expressions, 2510 instance=self, 2511 arg="group", 2512 append=append, 2513 copy=copy, 2514 prefix="GROUP BY", 2515 into=Group, 2516 dialect=dialect, 2517 **opts, 2518 ) 2519 2520 def order_by( 2521 self, 2522 *expressions: t.Optional[ExpOrStr], 2523 append: bool = True, 2524 dialect: DialectType = None, 2525 copy: bool = True, 2526 **opts, 2527 ) -> Select: 2528 """ 2529 Set the ORDER BY expression. 2530 2531 Example: 2532 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2533 'SELECT x FROM tbl ORDER BY x DESC' 2534 2535 Args: 2536 *expressions: the SQL code strings to parse. 2537 If a `Group` instance is passed, this is used as-is. 2538 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2539 append: if `True`, add to any existing expressions. 2540 Otherwise, this flattens all the `Order` expression into a single expression. 2541 dialect: the dialect used to parse the input expression. 2542 copy: if `False`, modify this expression instance in-place. 2543 opts: other options to use to parse the input expressions. 2544 2545 Returns: 2546 The modified Select expression. 2547 """ 2548 return _apply_child_list_builder( 2549 *expressions, 2550 instance=self, 2551 arg="order", 2552 append=append, 2553 copy=copy, 2554 prefix="ORDER BY", 2555 into=Order, 2556 dialect=dialect, 2557 **opts, 2558 ) 2559 2560 def sort_by( 2561 self, 2562 *expressions: t.Optional[ExpOrStr], 2563 append: bool = True, 2564 dialect: DialectType = None, 2565 copy: bool = True, 2566 **opts, 2567 ) -> Select: 2568 """ 2569 Set the SORT BY expression. 2570 2571 Example: 2572 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2573 'SELECT x FROM tbl SORT BY x DESC' 2574 2575 Args: 2576 *expressions: the SQL code strings to parse. 2577 If a `Group` instance is passed, this is used as-is. 2578 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2579 append: if `True`, add to any existing expressions. 2580 Otherwise, this flattens all the `Order` expression into a single expression. 2581 dialect: the dialect used to parse the input expression. 2582 copy: if `False`, modify this expression instance in-place. 2583 opts: other options to use to parse the input expressions. 2584 2585 Returns: 2586 The modified Select expression. 2587 """ 2588 return _apply_child_list_builder( 2589 *expressions, 2590 instance=self, 2591 arg="sort", 2592 append=append, 2593 copy=copy, 2594 prefix="SORT BY", 2595 into=Sort, 2596 dialect=dialect, 2597 **opts, 2598 ) 2599 2600 def cluster_by( 2601 self, 2602 *expressions: t.Optional[ExpOrStr], 2603 append: bool = True, 2604 dialect: DialectType = None, 2605 copy: bool = True, 2606 **opts, 2607 ) -> Select: 2608 """ 2609 Set the CLUSTER BY expression. 2610 2611 Example: 2612 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2613 'SELECT x FROM tbl CLUSTER BY x DESC' 2614 2615 Args: 2616 *expressions: the SQL code strings to parse. 2617 If a `Group` instance is passed, this is used as-is. 2618 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2619 append: if `True`, add to any existing expressions. 2620 Otherwise, this flattens all the `Order` expression into a single expression. 2621 dialect: the dialect used to parse the input expression. 2622 copy: if `False`, modify this expression instance in-place. 2623 opts: other options to use to parse the input expressions. 2624 2625 Returns: 2626 The modified Select expression. 2627 """ 2628 return _apply_child_list_builder( 2629 *expressions, 2630 instance=self, 2631 arg="cluster", 2632 append=append, 2633 copy=copy, 2634 prefix="CLUSTER BY", 2635 into=Cluster, 2636 dialect=dialect, 2637 **opts, 2638 ) 2639 2640 def limit( 2641 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2642 ) -> Select: 2643 """ 2644 Set the LIMIT expression. 2645 2646 Example: 2647 >>> Select().from_("tbl").select("x").limit(10).sql() 2648 'SELECT x FROM tbl LIMIT 10' 2649 2650 Args: 2651 expression: the SQL code string to parse. 2652 This can also be an integer. 2653 If a `Limit` instance is passed, this is used as-is. 2654 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2655 dialect: the dialect used to parse the input expression. 2656 copy: if `False`, modify this expression instance in-place. 2657 opts: other options to use to parse the input expressions. 2658 2659 Returns: 2660 Select: the modified expression. 2661 """ 2662 return _apply_builder( 2663 expression=expression, 2664 instance=self, 2665 arg="limit", 2666 into=Limit, 2667 prefix="LIMIT", 2668 dialect=dialect, 2669 copy=copy, 2670 **opts, 2671 ) 2672 2673 def offset( 2674 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2675 ) -> Select: 2676 """ 2677 Set the OFFSET expression. 2678 2679 Example: 2680 >>> Select().from_("tbl").select("x").offset(10).sql() 2681 'SELECT x FROM tbl OFFSET 10' 2682 2683 Args: 2684 expression: the SQL code string to parse. 2685 This can also be an integer. 2686 If a `Offset` instance is passed, this is used as-is. 2687 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2688 dialect: the dialect used to parse the input expression. 2689 copy: if `False`, modify this expression instance in-place. 2690 opts: other options to use to parse the input expressions. 2691 2692 Returns: 2693 The modified Select expression. 2694 """ 2695 return _apply_builder( 2696 expression=expression, 2697 instance=self, 2698 arg="offset", 2699 into=Offset, 2700 prefix="OFFSET", 2701 dialect=dialect, 2702 copy=copy, 2703 **opts, 2704 ) 2705 2706 def select( 2707 self, 2708 *expressions: t.Optional[ExpOrStr], 2709 append: bool = True, 2710 dialect: DialectType = None, 2711 copy: bool = True, 2712 **opts, 2713 ) -> Select: 2714 """ 2715 Append to or set the SELECT expressions. 2716 2717 Example: 2718 >>> Select().select("x", "y").sql() 2719 'SELECT x, y' 2720 2721 Args: 2722 *expressions: the SQL code strings to parse. 2723 If an `Expression` instance is passed, it will be used as-is. 2724 append: if `True`, add to any existing expressions. 2725 Otherwise, this resets the expressions. 2726 dialect: the dialect used to parse the input expressions. 2727 copy: if `False`, modify this expression instance in-place. 2728 opts: other options to use to parse the input expressions. 2729 2730 Returns: 2731 The modified Select expression. 2732 """ 2733 return _apply_list_builder( 2734 *expressions, 2735 instance=self, 2736 arg="expressions", 2737 append=append, 2738 dialect=dialect, 2739 copy=copy, 2740 **opts, 2741 ) 2742 2743 def lateral( 2744 self, 2745 *expressions: t.Optional[ExpOrStr], 2746 append: bool = True, 2747 dialect: DialectType = None, 2748 copy: bool = True, 2749 **opts, 2750 ) -> Select: 2751 """ 2752 Append to or set the LATERAL expressions. 2753 2754 Example: 2755 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2756 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2757 2758 Args: 2759 *expressions: the SQL code strings to parse. 2760 If an `Expression` instance is passed, it will be used as-is. 2761 append: if `True`, add to any existing expressions. 2762 Otherwise, this resets the expressions. 2763 dialect: the dialect used to parse the input expressions. 2764 copy: if `False`, modify this expression instance in-place. 2765 opts: other options to use to parse the input expressions. 2766 2767 Returns: 2768 The modified Select expression. 2769 """ 2770 return _apply_list_builder( 2771 *expressions, 2772 instance=self, 2773 arg="laterals", 2774 append=append, 2775 into=Lateral, 2776 prefix="LATERAL VIEW", 2777 dialect=dialect, 2778 copy=copy, 2779 **opts, 2780 ) 2781 2782 def join( 2783 self, 2784 expression: ExpOrStr, 2785 on: t.Optional[ExpOrStr] = None, 2786 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2787 append: bool = True, 2788 join_type: t.Optional[str] = None, 2789 join_alias: t.Optional[Identifier | str] = None, 2790 dialect: DialectType = None, 2791 copy: bool = True, 2792 **opts, 2793 ) -> Select: 2794 """ 2795 Append to or set the JOIN expressions. 2796 2797 Example: 2798 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2799 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2800 2801 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2802 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2803 2804 Use `join_type` to change the type of join: 2805 2806 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2807 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2808 2809 Args: 2810 expression: the SQL code string to parse. 2811 If an `Expression` instance is passed, it will be used as-is. 2812 on: optionally specify the join "on" criteria as a SQL string. 2813 If an `Expression` instance is passed, it will be used as-is. 2814 using: optionally specify the join "using" criteria as a SQL string. 2815 If an `Expression` instance is passed, it will be used as-is. 2816 append: if `True`, add to any existing expressions. 2817 Otherwise, this resets the expressions. 2818 join_type: if set, alter the parsed join type. 2819 join_alias: an optional alias for the joined source. 2820 dialect: the dialect used to parse the input expressions. 2821 copy: if `False`, modify this expression instance in-place. 2822 opts: other options to use to parse the input expressions. 2823 2824 Returns: 2825 Select: the modified expression. 2826 """ 2827 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2828 2829 try: 2830 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2831 except ParseError: 2832 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2833 2834 join = expression if isinstance(expression, Join) else Join(this=expression) 2835 2836 if isinstance(join.this, Select): 2837 join.this.replace(join.this.subquery()) 2838 2839 if join_type: 2840 method: t.Optional[Token] 2841 side: t.Optional[Token] 2842 kind: t.Optional[Token] 2843 2844 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2845 2846 if method: 2847 join.set("method", method.text) 2848 if side: 2849 join.set("side", side.text) 2850 if kind: 2851 join.set("kind", kind.text) 2852 2853 if on: 2854 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2855 join.set("on", on) 2856 2857 if using: 2858 join = _apply_list_builder( 2859 *ensure_list(using), 2860 instance=join, 2861 arg="using", 2862 append=append, 2863 copy=copy, 2864 **opts, 2865 ) 2866 2867 if join_alias: 2868 join.set("this", alias_(join.this, join_alias, table=True)) 2869 2870 return _apply_list_builder( 2871 join, 2872 instance=self, 2873 arg="joins", 2874 append=append, 2875 copy=copy, 2876 **opts, 2877 ) 2878 2879 def where( 2880 self, 2881 *expressions: t.Optional[ExpOrStr], 2882 append: bool = True, 2883 dialect: DialectType = None, 2884 copy: bool = True, 2885 **opts, 2886 ) -> Select: 2887 """ 2888 Append to or set the WHERE expressions. 2889 2890 Example: 2891 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2892 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2893 2894 Args: 2895 *expressions: the SQL code strings to parse. 2896 If an `Expression` instance is passed, it will be used as-is. 2897 Multiple expressions are combined with an AND operator. 2898 append: if `True`, AND the new expressions to any existing expression. 2899 Otherwise, this resets the expression. 2900 dialect: the dialect used to parse the input expressions. 2901 copy: if `False`, modify this expression instance in-place. 2902 opts: other options to use to parse the input expressions. 2903 2904 Returns: 2905 Select: the modified expression. 2906 """ 2907 return _apply_conjunction_builder( 2908 *expressions, 2909 instance=self, 2910 arg="where", 2911 append=append, 2912 into=Where, 2913 dialect=dialect, 2914 copy=copy, 2915 **opts, 2916 ) 2917 2918 def having( 2919 self, 2920 *expressions: t.Optional[ExpOrStr], 2921 append: bool = True, 2922 dialect: DialectType = None, 2923 copy: bool = True, 2924 **opts, 2925 ) -> Select: 2926 """ 2927 Append to or set the HAVING expressions. 2928 2929 Example: 2930 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2931 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2932 2933 Args: 2934 *expressions: the SQL code strings to parse. 2935 If an `Expression` instance is passed, it will be used as-is. 2936 Multiple expressions are combined with an AND operator. 2937 append: if `True`, AND the new expressions to any existing expression. 2938 Otherwise, this resets the expression. 2939 dialect: the dialect used to parse the input expressions. 2940 copy: if `False`, modify this expression instance in-place. 2941 opts: other options to use to parse the input expressions. 2942 2943 Returns: 2944 The modified Select expression. 2945 """ 2946 return _apply_conjunction_builder( 2947 *expressions, 2948 instance=self, 2949 arg="having", 2950 append=append, 2951 into=Having, 2952 dialect=dialect, 2953 copy=copy, 2954 **opts, 2955 ) 2956 2957 def window( 2958 self, 2959 *expressions: t.Optional[ExpOrStr], 2960 append: bool = True, 2961 dialect: DialectType = None, 2962 copy: bool = True, 2963 **opts, 2964 ) -> Select: 2965 return _apply_list_builder( 2966 *expressions, 2967 instance=self, 2968 arg="windows", 2969 append=append, 2970 into=Window, 2971 dialect=dialect, 2972 copy=copy, 2973 **opts, 2974 ) 2975 2976 def qualify( 2977 self, 2978 *expressions: t.Optional[ExpOrStr], 2979 append: bool = True, 2980 dialect: DialectType = None, 2981 copy: bool = True, 2982 **opts, 2983 ) -> Select: 2984 return _apply_conjunction_builder( 2985 *expressions, 2986 instance=self, 2987 arg="qualify", 2988 append=append, 2989 into=Qualify, 2990 dialect=dialect, 2991 copy=copy, 2992 **opts, 2993 ) 2994 2995 def distinct( 2996 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2997 ) -> Select: 2998 """ 2999 Set the OFFSET expression. 3000 3001 Example: 3002 >>> Select().from_("tbl").select("x").distinct().sql() 3003 'SELECT DISTINCT x FROM tbl' 3004 3005 Args: 3006 ons: the expressions to distinct on 3007 distinct: whether the Select should be distinct 3008 copy: if `False`, modify this expression instance in-place. 3009 3010 Returns: 3011 Select: the modified expression. 3012 """ 3013 instance = _maybe_copy(self, copy) 3014 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3015 instance.set("distinct", Distinct(on=on) if distinct else None) 3016 return instance 3017 3018 def ctas( 3019 self, 3020 table: ExpOrStr, 3021 properties: t.Optional[t.Dict] = None, 3022 dialect: DialectType = None, 3023 copy: bool = True, 3024 **opts, 3025 ) -> Create: 3026 """ 3027 Convert this expression to a CREATE TABLE AS statement. 3028 3029 Example: 3030 >>> Select().select("*").from_("tbl").ctas("x").sql() 3031 'CREATE TABLE x AS SELECT * FROM tbl' 3032 3033 Args: 3034 table: the SQL code string to parse as the table name. 3035 If another `Expression` instance is passed, it will be used as-is. 3036 properties: an optional mapping of table properties 3037 dialect: the dialect used to parse the input table. 3038 copy: if `False`, modify this expression instance in-place. 3039 opts: other options to use to parse the input table. 3040 3041 Returns: 3042 The new Create expression. 3043 """ 3044 instance = _maybe_copy(self, copy) 3045 table_expression = maybe_parse( 3046 table, 3047 into=Table, 3048 dialect=dialect, 3049 **opts, 3050 ) 3051 properties_expression = None 3052 if properties: 3053 properties_expression = Properties.from_dict(properties) 3054 3055 return Create( 3056 this=table_expression, 3057 kind="table", 3058 expression=instance, 3059 properties=properties_expression, 3060 ) 3061 3062 def lock(self, update: bool = True, copy: bool = True) -> Select: 3063 """ 3064 Set the locking read mode for this expression. 3065 3066 Examples: 3067 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3068 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3069 3070 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3071 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3072 3073 Args: 3074 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3075 copy: if `False`, modify this expression instance in-place. 3076 3077 Returns: 3078 The modified expression. 3079 """ 3080 inst = _maybe_copy(self, copy) 3081 inst.set("locks", [Lock(update=update)]) 3082 3083 return inst 3084 3085 def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select: 3086 """ 3087 Set hints for this expression. 3088 3089 Examples: 3090 >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark") 3091 'SELECT /*+ BROADCAST(y) */ x FROM tbl' 3092 3093 Args: 3094 hints: The SQL code strings to parse as the hints. 3095 If an `Expression` instance is passed, it will be used as-is. 3096 dialect: The dialect used to parse the hints. 3097 copy: If `False`, modify this expression instance in-place. 3098 3099 Returns: 3100 The modified expression. 3101 """ 3102 inst = _maybe_copy(self, copy) 3103 inst.set( 3104 "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints]) 3105 ) 3106 3107 return inst 3108 3109 @property 3110 def named_selects(self) -> t.List[str]: 3111 return [e.output_name for e in self.expressions if e.alias_or_name] 3112 3113 @property 3114 def is_star(self) -> bool: 3115 return any(expression.is_star for expression in self.expressions) 3116 3117 @property 3118 def selects(self) -> t.List[Expression]: 3119 return self.expressions 3120 3121 3122class Subquery(DerivedTable, Unionable): 3123 arg_types = { 3124 "this": True, 3125 "alias": False, 3126 "with": False, 3127 **QUERY_MODIFIERS, 3128 } 3129 3130 def unnest(self): 3131 """ 3132 Returns the first non subquery. 3133 """ 3134 expression = self 3135 while isinstance(expression, Subquery): 3136 expression = expression.this 3137 return expression 3138 3139 @property 3140 def is_star(self) -> bool: 3141 return self.this.is_star 3142 3143 @property 3144 def output_name(self) -> str: 3145 return self.alias 3146 3147 3148class TableSample(Expression): 3149 arg_types = { 3150 "this": False, 3151 "method": False, 3152 "bucket_numerator": False, 3153 "bucket_denominator": False, 3154 "bucket_field": False, 3155 "percent": False, 3156 "rows": False, 3157 "size": False, 3158 "seed": False, 3159 "kind": False, 3160 } 3161 3162 3163class Tag(Expression): 3164 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3165 3166 arg_types = { 3167 "this": False, 3168 "prefix": False, 3169 "postfix": False, 3170 } 3171 3172 3173# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax 3174# https://duckdb.org/docs/sql/statements/pivot 3175class Pivot(Expression): 3176 arg_types = { 3177 "this": False, 3178 "alias": False, 3179 "expressions": True, 3180 "field": False, 3181 "unpivot": False, 3182 "using": False, 3183 "group": False, 3184 "columns": False, 3185 } 3186 3187 3188class Window(Expression): 3189 arg_types = { 3190 "this": True, 3191 "partition_by": False, 3192 "order": False, 3193 "spec": False, 3194 "alias": False, 3195 "over": False, 3196 "first": False, 3197 } 3198 3199 3200class WindowSpec(Expression): 3201 arg_types = { 3202 "kind": False, 3203 "start": False, 3204 "start_side": False, 3205 "end": False, 3206 "end_side": False, 3207 } 3208 3209 3210class Where(Expression): 3211 pass 3212 3213 3214class Star(Expression): 3215 arg_types = {"except": False, "replace": False} 3216 3217 @property 3218 def name(self) -> str: 3219 return "*" 3220 3221 @property 3222 def output_name(self) -> str: 3223 return self.name 3224 3225 3226class Parameter(Expression): 3227 arg_types = {"this": True, "wrapped": False} 3228 3229 3230class SessionParameter(Expression): 3231 arg_types = {"this": True, "kind": False} 3232 3233 3234class Placeholder(Expression): 3235 arg_types = {"this": False, "kind": False} 3236 3237 3238class Null(Condition): 3239 arg_types: t.Dict[str, t.Any] = {} 3240 3241 @property 3242 def name(self) -> str: 3243 return "NULL" 3244 3245 3246class Boolean(Condition): 3247 pass 3248 3249 3250class DataTypeSize(Expression): 3251 arg_types = {"this": True, "expression": False} 3252 3253 3254class DataType(Expression): 3255 arg_types = { 3256 "this": True, 3257 "expressions": False, 3258 "nested": False, 3259 "values": False, 3260 "prefix": False, 3261 } 3262 3263 class Type(AutoName): 3264 ARRAY = auto() 3265 BIGDECIMAL = auto() 3266 BIGINT = auto() 3267 BIGSERIAL = auto() 3268 BINARY = auto() 3269 BIT = auto() 3270 BOOLEAN = auto() 3271 CHAR = auto() 3272 DATE = auto() 3273 DATETIME = auto() 3274 DATETIME64 = auto() 3275 ENUM = auto() 3276 INT4RANGE = auto() 3277 INT4MULTIRANGE = auto() 3278 INT8RANGE = auto() 3279 INT8MULTIRANGE = auto() 3280 NUMRANGE = auto() 3281 NUMMULTIRANGE = auto() 3282 TSRANGE = auto() 3283 TSMULTIRANGE = auto() 3284 TSTZRANGE = auto() 3285 TSTZMULTIRANGE = auto() 3286 DATERANGE = auto() 3287 DATEMULTIRANGE = auto() 3288 DECIMAL = auto() 3289 DOUBLE = auto() 3290 FLOAT = auto() 3291 GEOGRAPHY = auto() 3292 GEOMETRY = auto() 3293 HLLSKETCH = auto() 3294 HSTORE = auto() 3295 IMAGE = auto() 3296 INET = auto() 3297 INT = auto() 3298 INT128 = auto() 3299 INT256 = auto() 3300 INTERVAL = auto() 3301 JSON = auto() 3302 JSONB = auto() 3303 LONGBLOB = auto() 3304 LONGTEXT = auto() 3305 MAP = auto() 3306 MEDIUMBLOB = auto() 3307 MEDIUMTEXT = auto() 3308 MONEY = auto() 3309 NCHAR = auto() 3310 NULL = auto() 3311 NULLABLE = auto() 3312 NVARCHAR = auto() 3313 OBJECT = auto() 3314 ROWVERSION = auto() 3315 SERIAL = auto() 3316 SET = auto() 3317 SMALLINT = auto() 3318 SMALLMONEY = auto() 3319 SMALLSERIAL = auto() 3320 STRUCT = auto() 3321 SUPER = auto() 3322 TEXT = auto() 3323 TIME = auto() 3324 TIMESTAMP = auto() 3325 TIMESTAMPTZ = auto() 3326 TIMESTAMPLTZ = auto() 3327 TINYINT = auto() 3328 UBIGINT = auto() 3329 UINT = auto() 3330 USMALLINT = auto() 3331 UTINYINT = auto() 3332 UNKNOWN = auto() # Sentinel value, useful for type annotation 3333 UINT128 = auto() 3334 UINT256 = auto() 3335 UNIQUEIDENTIFIER = auto() 3336 UUID = auto() 3337 VARBINARY = auto() 3338 VARCHAR = auto() 3339 VARIANT = auto() 3340 XML = auto() 3341 3342 TEXT_TYPES = { 3343 Type.CHAR, 3344 Type.NCHAR, 3345 Type.VARCHAR, 3346 Type.NVARCHAR, 3347 Type.TEXT, 3348 } 3349 3350 INTEGER_TYPES = { 3351 Type.INT, 3352 Type.TINYINT, 3353 Type.SMALLINT, 3354 Type.BIGINT, 3355 Type.INT128, 3356 Type.INT256, 3357 } 3358 3359 FLOAT_TYPES = { 3360 Type.FLOAT, 3361 Type.DOUBLE, 3362 } 3363 3364 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3365 3366 TEMPORAL_TYPES = { 3367 Type.TIME, 3368 Type.TIMESTAMP, 3369 Type.TIMESTAMPTZ, 3370 Type.TIMESTAMPLTZ, 3371 Type.DATE, 3372 Type.DATETIME, 3373 Type.DATETIME64, 3374 } 3375 3376 META_TYPES = {"UNKNOWN", "NULL"} 3377 3378 @classmethod 3379 def build( 3380 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3381 ) -> DataType: 3382 from sqlglot import parse_one 3383 3384 if isinstance(dtype, str): 3385 upper = dtype.upper() 3386 if upper in DataType.META_TYPES: 3387 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper]) 3388 else: 3389 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3390 3391 if data_type_exp is None: 3392 raise ValueError(f"Unparsable data type value: {dtype}") 3393 elif isinstance(dtype, DataType.Type): 3394 data_type_exp = DataType(this=dtype) 3395 elif isinstance(dtype, DataType): 3396 return dtype 3397 else: 3398 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3399 3400 return DataType(**{**data_type_exp.args, **kwargs}) 3401 3402 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3403 return any(self.this == DataType.build(dtype).this for dtype in dtypes) 3404 3405 3406# https://www.postgresql.org/docs/15/datatype-pseudo.html 3407class PseudoType(Expression): 3408 pass 3409 3410 3411# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 3412class SubqueryPredicate(Predicate): 3413 pass 3414 3415 3416class All(SubqueryPredicate): 3417 pass 3418 3419 3420class Any(SubqueryPredicate): 3421 pass 3422 3423 3424class Exists(SubqueryPredicate): 3425 pass 3426 3427 3428# Commands to interact with the databases or engines. For most of the command 3429# expressions we parse whatever comes after the command's name as a string. 3430class Command(Expression): 3431 arg_types = {"this": True, "expression": False} 3432 3433 3434class Transaction(Expression): 3435 arg_types = {"this": False, "modes": False} 3436 3437 3438class Commit(Expression): 3439 arg_types = {"chain": False} 3440 3441 3442class Rollback(Expression): 3443 arg_types = {"savepoint": False} 3444 3445 3446class AlterTable(Expression): 3447 arg_types = {"this": True, "actions": True, "exists": False} 3448 3449 3450class AddConstraint(Expression): 3451 arg_types = {"this": False, "expression": False, "enforced": False} 3452 3453 3454class DropPartition(Expression): 3455 arg_types = {"expressions": True, "exists": False} 3456 3457 3458# Binary expressions like (ADD a b) 3459class Binary(Condition): 3460 arg_types = {"this": True, "expression": True} 3461 3462 @property 3463 def left(self): 3464 return self.this 3465 3466 @property 3467 def right(self): 3468 return self.expression 3469 3470 3471class Add(Binary): 3472 pass 3473 3474 3475class Connector(Binary): 3476 pass 3477 3478 3479class And(Connector): 3480 pass 3481 3482 3483class Or(Connector): 3484 pass 3485 3486 3487class BitwiseAnd(Binary): 3488 pass 3489 3490 3491class BitwiseLeftShift(Binary): 3492 pass 3493 3494 3495class BitwiseOr(Binary): 3496 pass 3497 3498 3499class BitwiseRightShift(Binary): 3500 pass 3501 3502 3503class BitwiseXor(Binary): 3504 pass 3505 3506 3507class Div(Binary): 3508 pass 3509 3510 3511class Overlaps(Binary): 3512 pass 3513 3514 3515class Dot(Binary): 3516 @property 3517 def name(self) -> str: 3518 return self.expression.name 3519 3520 @property 3521 def output_name(self) -> str: 3522 return self.name 3523 3524 @classmethod 3525 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3526 """Build a Dot object with a sequence of expressions.""" 3527 if len(expressions) < 2: 3528 raise ValueError(f"Dot requires >= 2 expressions.") 3529 3530 a, b, *expressions = expressions 3531 dot = Dot(this=a, expression=b) 3532 3533 for expression in expressions: 3534 dot = Dot(this=dot, expression=expression) 3535 3536 return dot 3537 3538 3539class DPipe(Binary): 3540 pass 3541 3542 3543class SafeDPipe(DPipe): 3544 pass 3545 3546 3547class EQ(Binary, Predicate): 3548 pass 3549 3550 3551class NullSafeEQ(Binary, Predicate): 3552 pass 3553 3554 3555class NullSafeNEQ(Binary, Predicate): 3556 pass 3557 3558 3559class Distance(Binary): 3560 pass 3561 3562 3563class Escape(Binary): 3564 pass 3565 3566 3567class Glob(Binary, Predicate): 3568 pass 3569 3570 3571class GT(Binary, Predicate): 3572 pass 3573 3574 3575class GTE(Binary, Predicate): 3576 pass 3577 3578 3579class ILike(Binary, Predicate): 3580 pass 3581 3582 3583class ILikeAny(Binary, Predicate): 3584 pass 3585 3586 3587class IntDiv(Binary): 3588 pass 3589 3590 3591class Is(Binary, Predicate): 3592 pass 3593 3594 3595class Kwarg(Binary): 3596 """Kwarg in special functions like func(kwarg => y).""" 3597 3598 3599class Like(Binary, Predicate): 3600 pass 3601 3602 3603class LikeAny(Binary, Predicate): 3604 pass 3605 3606 3607class LT(Binary, Predicate): 3608 pass 3609 3610 3611class LTE(Binary, Predicate): 3612 pass 3613 3614 3615class Mod(Binary): 3616 pass 3617 3618 3619class Mul(Binary): 3620 pass 3621 3622 3623class NEQ(Binary, Predicate): 3624 pass 3625 3626 3627class SimilarTo(Binary, Predicate): 3628 pass 3629 3630 3631class Slice(Binary): 3632 arg_types = {"this": False, "expression": False} 3633 3634 3635class Sub(Binary): 3636 pass 3637 3638 3639class ArrayOverlaps(Binary): 3640 pass 3641 3642 3643# Unary Expressions 3644# (NOT a) 3645class Unary(Condition): 3646 pass 3647 3648 3649class BitwiseNot(Unary): 3650 pass 3651 3652 3653class Not(Unary): 3654 pass 3655 3656 3657class Paren(Unary): 3658 arg_types = {"this": True, "with": False} 3659 3660 @property 3661 def output_name(self) -> str: 3662 return self.this.name 3663 3664 3665class Neg(Unary): 3666 pass 3667 3668 3669class Alias(Expression): 3670 arg_types = {"this": True, "alias": False} 3671 3672 @property 3673 def output_name(self) -> str: 3674 return self.alias 3675 3676 3677class Aliases(Expression): 3678 arg_types = {"this": True, "expressions": True} 3679 3680 @property 3681 def aliases(self): 3682 return self.expressions 3683 3684 3685class AtTimeZone(Expression): 3686 arg_types = {"this": True, "zone": True} 3687 3688 3689class Between(Predicate): 3690 arg_types = {"this": True, "low": True, "high": True} 3691 3692 3693class Bracket(Condition): 3694 arg_types = {"this": True, "expressions": True} 3695 3696 3697class Distinct(Expression): 3698 arg_types = {"expressions": False, "on": False} 3699 3700 3701class In(Predicate): 3702 arg_types = { 3703 "this": True, 3704 "expressions": False, 3705 "query": False, 3706 "unnest": False, 3707 "field": False, 3708 "is_global": False, 3709 } 3710 3711 3712class TimeUnit(Expression): 3713 """Automatically converts unit arg into a var.""" 3714 3715 arg_types = {"unit": False} 3716 3717 def __init__(self, **args): 3718 unit = args.get("unit") 3719 if isinstance(unit, (Column, Literal)): 3720 args["unit"] = Var(this=unit.name) 3721 elif isinstance(unit, Week): 3722 unit.set("this", Var(this=unit.this.name)) 3723 3724 super().__init__(**args) 3725 3726 3727class Interval(TimeUnit): 3728 arg_types = {"this": False, "unit": False} 3729 3730 @property 3731 def unit(self) -> t.Optional[Var]: 3732 return self.args.get("unit") 3733 3734 3735class IgnoreNulls(Expression): 3736 pass 3737 3738 3739class RespectNulls(Expression): 3740 pass 3741 3742 3743# Functions 3744class Func(Condition): 3745 """ 3746 The base class for all function expressions. 3747 3748 Attributes: 3749 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3750 treated as a variable length argument and the argument's value will be stored as a list. 3751 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3752 for this function expression. These values are used to map this node to a name during parsing 3753 as well as to provide the function's name during SQL string generation. By default the SQL 3754 name is set to the expression's class name transformed to snake case. 3755 """ 3756 3757 is_var_len_args = False 3758 3759 @classmethod 3760 def from_arg_list(cls, args): 3761 if cls.is_var_len_args: 3762 all_arg_keys = list(cls.arg_types) 3763 # If this function supports variable length argument treat the last argument as such. 3764 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3765 num_non_var = len(non_var_len_arg_keys) 3766 3767 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3768 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3769 else: 3770 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3771 3772 return cls(**args_dict) 3773 3774 @classmethod 3775 def sql_names(cls): 3776 if cls is Func: 3777 raise NotImplementedError( 3778 "SQL name is only supported by concrete function implementations" 3779 ) 3780 if "_sql_names" not in cls.__dict__: 3781 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3782 return cls._sql_names 3783 3784 @classmethod 3785 def sql_name(cls): 3786 return cls.sql_names()[0] 3787 3788 @classmethod 3789 def default_parser_mappings(cls): 3790 return {name: cls.from_arg_list for name in cls.sql_names()} 3791 3792 3793class AggFunc(Func): 3794 pass 3795 3796 3797class ParameterizedAgg(AggFunc): 3798 arg_types = {"this": True, "expressions": True, "params": True} 3799 3800 3801class Abs(Func): 3802 pass 3803 3804 3805class Anonymous(Func): 3806 arg_types = {"this": True, "expressions": False} 3807 is_var_len_args = True 3808 3809 3810# https://docs.snowflake.com/en/sql-reference/functions/hll 3811# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3812class Hll(AggFunc): 3813 arg_types = {"this": True, "expressions": False} 3814 is_var_len_args = True 3815 3816 3817class ApproxDistinct(AggFunc): 3818 arg_types = {"this": True, "accuracy": False} 3819 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"] 3820 3821 3822class Array(Func): 3823 arg_types = {"expressions": False} 3824 is_var_len_args = True 3825 3826 3827# https://docs.snowflake.com/en/sql-reference/functions/to_char 3828class ToChar(Func): 3829 arg_types = {"this": True, "format": False} 3830 3831 3832class GenerateSeries(Func): 3833 arg_types = {"start": True, "end": True, "step": False} 3834 3835 3836class ArrayAgg(AggFunc): 3837 pass 3838 3839 3840class ArrayAll(Func): 3841 arg_types = {"this": True, "expression": True} 3842 3843 3844class ArrayAny(Func): 3845 arg_types = {"this": True, "expression": True} 3846 3847 3848class ArrayConcat(Func): 3849 arg_types = {"this": True, "expressions": False} 3850 is_var_len_args = True 3851 3852 3853class ArrayContains(Binary, Func): 3854 pass 3855 3856 3857class ArrayContained(Binary): 3858 pass 3859 3860 3861class ArrayFilter(Func): 3862 arg_types = {"this": True, "expression": True} 3863 _sql_names = ["FILTER", "ARRAY_FILTER"] 3864 3865 3866class ArrayJoin(Func): 3867 arg_types = {"this": True, "expression": True, "null": False} 3868 3869 3870class ArraySize(Func): 3871 arg_types = {"this": True, "expression": False} 3872 3873 3874class ArraySort(Func): 3875 arg_types = {"this": True, "expression": False} 3876 3877 3878class ArraySum(Func): 3879 pass 3880 3881 3882class ArrayUnionAgg(AggFunc): 3883 pass 3884 3885 3886class Avg(AggFunc): 3887 pass 3888 3889 3890class AnyValue(AggFunc): 3891 pass 3892 3893 3894class Case(Func): 3895 arg_types = {"this": False, "ifs": True, "default": False} 3896 3897 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3898 instance = _maybe_copy(self, copy) 3899 instance.append( 3900 "ifs", 3901 If( 3902 this=maybe_parse(condition, copy=copy, **opts), 3903 true=maybe_parse(then, copy=copy, **opts), 3904 ), 3905 ) 3906 return instance 3907 3908 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3909 instance = _maybe_copy(self, copy) 3910 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3911 return instance 3912 3913 3914class Cast(Func): 3915 arg_types = {"this": True, "to": True} 3916 3917 @property 3918 def name(self) -> str: 3919 return self.this.name 3920 3921 @property 3922 def to(self) -> DataType: 3923 return self.args["to"] 3924 3925 @property 3926 def output_name(self) -> str: 3927 return self.name 3928 3929 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3930 return self.to.is_type(*dtypes) 3931 3932 3933class CastToStrType(Func): 3934 arg_types = {"this": True, "expression": True} 3935 3936 3937class Collate(Binary): 3938 pass 3939 3940 3941class TryCast(Cast): 3942 pass 3943 3944 3945class Ceil(Func): 3946 arg_types = {"this": True, "decimals": False} 3947 _sql_names = ["CEIL", "CEILING"] 3948 3949 3950class Coalesce(Func): 3951 arg_types = {"this": True, "expressions": False} 3952 is_var_len_args = True 3953 _sql_names = ["COALESCE", "IFNULL", "NVL"] 3954 3955 3956class Concat(Func): 3957 arg_types = {"expressions": True} 3958 is_var_len_args = True 3959 3960 3961class SafeConcat(Concat): 3962 pass 3963 3964 3965class ConcatWs(Concat): 3966 _sql_names = ["CONCAT_WS"] 3967 3968 3969class Count(AggFunc): 3970 arg_types = {"this": False, "expressions": False} 3971 is_var_len_args = True 3972 3973 3974class CountIf(AggFunc): 3975 pass 3976 3977 3978class CurrentDate(Func): 3979 arg_types = {"this": False} 3980 3981 3982class CurrentDatetime(Func): 3983 arg_types = {"this": False} 3984 3985 3986class CurrentTime(Func): 3987 arg_types = {"this": False} 3988 3989 3990class CurrentTimestamp(Func): 3991 arg_types = {"this": False} 3992 3993 3994class CurrentUser(Func): 3995 arg_types = {"this": False} 3996 3997 3998class DateAdd(Func, TimeUnit): 3999 arg_types = {"this": True, "expression": True, "unit": False} 4000 4001 4002class DateSub(Func, TimeUnit): 4003 arg_types = {"this": True, "expression": True, "unit": False} 4004 4005 4006class DateDiff(Func, TimeUnit): 4007 _sql_names = ["DATEDIFF", "DATE_DIFF"] 4008 arg_types = {"this": True, "expression": True, "unit": False} 4009 4010 4011class DateTrunc(Func): 4012 arg_types = {"unit": True, "this": True, "zone": False} 4013 4014 4015class DatetimeAdd(Func, TimeUnit): 4016 arg_types = {"this": True, "expression": True, "unit": False} 4017 4018 4019class DatetimeSub(Func, TimeUnit): 4020 arg_types = {"this": True, "expression": True, "unit": False} 4021 4022 4023class DatetimeDiff(Func, TimeUnit): 4024 arg_types = {"this": True, "expression": True, "unit": False} 4025 4026 4027class DatetimeTrunc(Func, TimeUnit): 4028 arg_types = {"this": True, "unit": True, "zone": False} 4029 4030 4031class DayOfWeek(Func): 4032 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 4033 4034 4035class DayOfMonth(Func): 4036 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 4037 4038 4039class DayOfYear(Func): 4040 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 4041 4042 4043class WeekOfYear(Func): 4044 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 4045 4046 4047class LastDateOfMonth(Func): 4048 pass 4049 4050 4051class Extract(Func): 4052 arg_types = {"this": True, "expression": True} 4053 4054 4055class TimestampAdd(Func, TimeUnit): 4056 arg_types = {"this": True, "expression": True, "unit": False} 4057 4058 4059class TimestampSub(Func, TimeUnit): 4060 arg_types = {"this": True, "expression": True, "unit": False} 4061 4062 4063class TimestampDiff(Func, TimeUnit): 4064 arg_types = {"this": True, "expression": True, "unit": False} 4065 4066 4067class TimestampTrunc(Func, TimeUnit): 4068 arg_types = {"this": True, "unit": True, "zone": False} 4069 4070 4071class TimeAdd(Func, TimeUnit): 4072 arg_types = {"this": True, "expression": True, "unit": False} 4073 4074 4075class TimeSub(Func, TimeUnit): 4076 arg_types = {"this": True, "expression": True, "unit": False} 4077 4078 4079class TimeDiff(Func, TimeUnit): 4080 arg_types = {"this": True, "expression": True, "unit": False} 4081 4082 4083class TimeTrunc(Func, TimeUnit): 4084 arg_types = {"this": True, "unit": True, "zone": False} 4085 4086 4087class DateFromParts(Func): 4088 _sql_names = ["DATEFROMPARTS"] 4089 arg_types = {"year": True, "month": True, "day": True} 4090 4091 4092class DateStrToDate(Func): 4093 pass 4094 4095 4096class DateToDateStr(Func): 4097 pass 4098 4099 4100class DateToDi(Func): 4101 pass 4102 4103 4104class Date(Func): 4105 arg_types = {"expressions": True} 4106 is_var_len_args = True 4107 4108 4109class Day(Func): 4110 pass 4111 4112 4113class Decode(Func): 4114 arg_types = {"this": True, "charset": True, "replace": False} 4115 4116 4117class DiToDate(Func): 4118 pass 4119 4120 4121class Encode(Func): 4122 arg_types = {"this": True, "charset": True} 4123 4124 4125class Exp(Func): 4126 pass 4127 4128 4129class Explode(Func): 4130 pass 4131 4132 4133class Floor(Func): 4134 arg_types = {"this": True, "decimals": False} 4135 4136 4137class FromBase64(Func): 4138 pass 4139 4140 4141class ToBase64(Func): 4142 pass 4143 4144 4145class Greatest(Func): 4146 arg_types = {"this": True, "expressions": False} 4147 is_var_len_args = True 4148 4149 4150class GroupConcat(Func): 4151 arg_types = {"this": True, "separator": False} 4152 4153 4154class Hex(Func): 4155 pass 4156 4157 4158class If(Func): 4159 arg_types = {"this": True, "true": True, "false": False} 4160 4161 4162class Initcap(Func): 4163 arg_types = {"this": True, "expression": False} 4164 4165 4166class JSONKeyValue(Expression): 4167 arg_types = {"this": True, "expression": True} 4168 4169 4170class JSONObject(Func): 4171 arg_types = { 4172 "expressions": False, 4173 "null_handling": False, 4174 "unique_keys": False, 4175 "return_type": False, 4176 "format_json": False, 4177 "encoding": False, 4178 } 4179 4180 4181class OpenJSONColumnDef(Expression): 4182 arg_types = {"this": True, "kind": True, "path": False, "as_json": False} 4183 4184 4185class OpenJSON(Func): 4186 arg_types = {"this": True, "path": False, "expressions": False} 4187 4188 4189class JSONBContains(Binary): 4190 _sql_names = ["JSONB_CONTAINS"] 4191 4192 4193class JSONExtract(Binary, Func): 4194 _sql_names = ["JSON_EXTRACT"] 4195 4196 4197class JSONExtractScalar(JSONExtract): 4198 _sql_names = ["JSON_EXTRACT_SCALAR"] 4199 4200 4201class JSONBExtract(JSONExtract): 4202 _sql_names = ["JSONB_EXTRACT"] 4203 4204 4205class JSONBExtractScalar(JSONExtract): 4206 _sql_names = ["JSONB_EXTRACT_SCALAR"] 4207 4208 4209class JSONFormat(Func): 4210 arg_types = {"this": False, "options": False} 4211 _sql_names = ["JSON_FORMAT"] 4212 4213 4214class Least(Func): 4215 arg_types = {"expressions": False} 4216 is_var_len_args = True 4217 4218 4219class Left(Func): 4220 arg_types = {"this": True, "expression": True} 4221 4222 4223class Right(Func): 4224 arg_types = {"this": True, "expression": True} 4225 4226 4227class Length(Func): 4228 _sql_names = ["LENGTH", "LEN"] 4229 4230 4231class Levenshtein(Func): 4232 arg_types = { 4233 "this": True, 4234 "expression": False, 4235 "ins_cost": False, 4236 "del_cost": False, 4237 "sub_cost": False, 4238 } 4239 4240 4241class Ln(Func): 4242 pass 4243 4244 4245class Log(Func): 4246 arg_types = {"this": True, "expression": False} 4247 4248 4249class Log2(Func): 4250 pass 4251 4252 4253class Log10(Func): 4254 pass 4255 4256 4257class LogicalOr(AggFunc): 4258 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 4259 4260 4261class LogicalAnd(AggFunc): 4262 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 4263 4264 4265class Lower(Func): 4266 _sql_names = ["LOWER", "LCASE"] 4267 4268 4269class Map(Func): 4270 arg_types = {"keys": False, "values": False} 4271 4272 4273class StarMap(Func): 4274 pass 4275 4276 4277class VarMap(Func): 4278 arg_types = {"keys": True, "values": True} 4279 is_var_len_args = True 4280 4281 @property 4282 def keys(self) -> t.List[Expression]: 4283 return self.args["keys"].expressions 4284 4285 @property 4286 def values(self) -> t.List[Expression]: 4287 return self.args["values"].expressions 4288 4289 4290# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 4291class MatchAgainst(Func): 4292 arg_types = {"this": True, "expressions": True, "modifier": False} 4293 4294 4295class Max(AggFunc): 4296 arg_types = {"this": True, "expressions": False} 4297 is_var_len_args = True 4298 4299 4300class MD5(Func): 4301 _sql_names = ["MD5"] 4302 4303 4304class Min(AggFunc): 4305 arg_types = {"this": True, "expressions": False} 4306 is_var_len_args = True 4307 4308 4309class Month(Func): 4310 pass 4311 4312 4313class Nvl2(Func): 4314 arg_types = {"this": True, "true": True, "false": False} 4315 4316 4317class Posexplode(Func): 4318 pass 4319 4320 4321class Pow(Binary, Func): 4322 _sql_names = ["POWER", "POW"] 4323 4324 4325class PercentileCont(AggFunc): 4326 arg_types = {"this": True, "expression": False} 4327 4328 4329class PercentileDisc(AggFunc): 4330 arg_types = {"this": True, "expression": False} 4331 4332 4333class Quantile(AggFunc): 4334 arg_types = {"this": True, "quantile": True} 4335 4336 4337class ApproxQuantile(Quantile): 4338 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 4339 4340 4341class RangeN(Func): 4342 arg_types = {"this": True, "expressions": True, "each": False} 4343 4344 4345class ReadCSV(Func): 4346 _sql_names = ["READ_CSV"] 4347 is_var_len_args = True 4348 arg_types = {"this": True, "expressions": False} 4349 4350 4351class Reduce(Func): 4352 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 4353 4354 4355class RegexpExtract(Func): 4356 arg_types = { 4357 "this": True, 4358 "expression": True, 4359 "position": False, 4360 "occurrence": False, 4361 "group": False, 4362 } 4363 4364 4365class RegexpLike(Func): 4366 arg_types = {"this": True, "expression": True, "flag": False} 4367 4368 4369class RegexpILike(Func): 4370 arg_types = {"this": True, "expression": True, "flag": False} 4371 4372 4373# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 4374# limit is the number of times a pattern is applied 4375class RegexpSplit(Func): 4376 arg_types = {"this": True, "expression": True, "limit": False} 4377 4378 4379class Repeat(Func): 4380 arg_types = {"this": True, "times": True} 4381 4382 4383class Round(Func): 4384 arg_types = {"this": True, "decimals": False} 4385 4386 4387class RowNumber(Func): 4388 arg_types: t.Dict[str, t.Any] = {} 4389 4390 4391class SafeDivide(Func): 4392 arg_types = {"this": True, "expression": True} 4393 4394 4395class SetAgg(AggFunc): 4396 pass 4397 4398 4399class SHA(Func): 4400 _sql_names = ["SHA", "SHA1"] 4401 4402 4403class SHA2(Func): 4404 _sql_names = ["SHA2"] 4405 arg_types = {"this": True, "length": False} 4406 4407 4408class SortArray(Func): 4409 arg_types = {"this": True, "asc": False} 4410 4411 4412class Split(Func): 4413 arg_types = {"this": True, "expression": True, "limit": False} 4414 4415 4416# Start may be omitted in the case of postgres 4417# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 4418class Substring(Func): 4419 arg_types = {"this": True, "start": False, "length": False} 4420 4421 4422class StandardHash(Func): 4423 arg_types = {"this": True, "expression": False} 4424 4425 4426class StrPosition(Func): 4427 arg_types = { 4428 "this": True, 4429 "substr": True, 4430 "position": False, 4431 "instance": False, 4432 } 4433 4434 4435class StrToDate(Func): 4436 arg_types = {"this": True, "format": True} 4437 4438 4439class StrToTime(Func): 4440 arg_types = {"this": True, "format": True} 4441 4442 4443# Spark allows unix_timestamp() 4444# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 4445class StrToUnix(Func): 4446 arg_types = {"this": False, "format": False} 4447 4448 4449class NumberToStr(Func): 4450 arg_types = {"this": True, "format": True} 4451 4452 4453class FromBase(Func): 4454 arg_types = {"this": True, "expression": True} 4455 4456 4457class Struct(Func): 4458 arg_types = {"expressions": True} 4459 is_var_len_args = True 4460 4461 4462class StructExtract(Func): 4463 arg_types = {"this": True, "expression": True} 4464 4465 4466class Sum(AggFunc): 4467 pass 4468 4469 4470class Sqrt(Func): 4471 pass 4472 4473 4474class Stddev(AggFunc): 4475 pass 4476 4477 4478class StddevPop(AggFunc): 4479 pass 4480 4481 4482class StddevSamp(AggFunc): 4483 pass 4484 4485 4486class TimeToStr(Func): 4487 arg_types = {"this": True, "format": True} 4488 4489 4490class TimeToTimeStr(Func): 4491 pass 4492 4493 4494class TimeToUnix(Func): 4495 pass 4496 4497 4498class TimeStrToDate(Func): 4499 pass 4500 4501 4502class TimeStrToTime(Func): 4503 pass 4504 4505 4506class TimeStrToUnix(Func): 4507 pass 4508 4509 4510class Trim(Func): 4511 arg_types = { 4512 "this": True, 4513 "expression": False, 4514 "position": False, 4515 "collation": False, 4516 } 4517 4518 4519class TsOrDsAdd(Func, TimeUnit): 4520 arg_types = {"this": True, "expression": True, "unit": False} 4521 4522 4523class TsOrDsToDateStr(Func): 4524 pass 4525 4526 4527class TsOrDsToDate(Func): 4528 arg_types = {"this": True, "format": False} 4529 4530 4531class TsOrDiToDi(Func): 4532 pass 4533 4534 4535class Unhex(Func): 4536 pass 4537 4538 4539class UnixToStr(Func): 4540 arg_types = {"this": True, "format": False} 4541 4542 4543# https://prestodb.io/docs/current/functions/datetime.html 4544# presto has weird zone/hours/minutes 4545class UnixToTime(Func): 4546 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4547 4548 SECONDS = Literal.string("seconds") 4549 MILLIS = Literal.string("millis") 4550 MICROS = Literal.string("micros") 4551 4552 4553class UnixToTimeStr(Func): 4554 pass 4555 4556 4557class Upper(Func): 4558 _sql_names = ["UPPER", "UCASE"] 4559 4560 4561class Variance(AggFunc): 4562 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4563 4564 4565class VariancePop(AggFunc): 4566 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4567 4568 4569class Week(Func): 4570 arg_types = {"this": True, "mode": False} 4571 4572 4573class XMLTable(Func): 4574 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4575 4576 4577class Year(Func): 4578 pass 4579 4580 4581class Use(Expression): 4582 arg_types = {"this": True, "kind": False} 4583 4584 4585class Merge(Expression): 4586 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4587 4588 4589class When(Func): 4590 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4591 4592 4593# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html 4594# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16 4595class NextValueFor(Func): 4596 arg_types = {"this": True, "order": False} 4597 4598 4599def _norm_arg(arg): 4600 return arg.lower() if type(arg) is str else arg 4601 4602 4603ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4604 4605 4606# Helpers 4607@t.overload 4608def maybe_parse( 4609 sql_or_expression: ExpOrStr, 4610 *, 4611 into: t.Type[E], 4612 dialect: DialectType = None, 4613 prefix: t.Optional[str] = None, 4614 copy: bool = False, 4615 **opts, 4616) -> E: 4617 ... 4618 4619 4620@t.overload 4621def maybe_parse( 4622 sql_or_expression: str | E, 4623 *, 4624 into: t.Optional[IntoType] = None, 4625 dialect: DialectType = None, 4626 prefix: t.Optional[str] = None, 4627 copy: bool = False, 4628 **opts, 4629) -> E: 4630 ... 4631 4632 4633def maybe_parse( 4634 sql_or_expression: ExpOrStr, 4635 *, 4636 into: t.Optional[IntoType] = None, 4637 dialect: DialectType = None, 4638 prefix: t.Optional[str] = None, 4639 copy: bool = False, 4640 **opts, 4641) -> Expression: 4642 """Gracefully handle a possible string or expression. 4643 4644 Example: 4645 >>> maybe_parse("1") 4646 (LITERAL this: 1, is_string: False) 4647 >>> maybe_parse(to_identifier("x")) 4648 (IDENTIFIER this: x, quoted: False) 4649 4650 Args: 4651 sql_or_expression: the SQL code string or an expression 4652 into: the SQLGlot Expression to parse into 4653 dialect: the dialect used to parse the input expressions (in the case that an 4654 input expression is a SQL string). 4655 prefix: a string to prefix the sql with before it gets parsed 4656 (automatically includes a space) 4657 copy: whether or not to copy the expression. 4658 **opts: other options to use to parse the input expressions (again, in the case 4659 that an input expression is a SQL string). 4660 4661 Returns: 4662 Expression: the parsed or given expression. 4663 """ 4664 if isinstance(sql_or_expression, Expression): 4665 if copy: 4666 return sql_or_expression.copy() 4667 return sql_or_expression 4668 4669 if sql_or_expression is None: 4670 raise ParseError(f"SQL cannot be None") 4671 4672 import sqlglot 4673 4674 sql = str(sql_or_expression) 4675 if prefix: 4676 sql = f"{prefix} {sql}" 4677 4678 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4679 4680 4681def _maybe_copy(instance: E, copy: bool = True) -> E: 4682 return instance.copy() if copy else instance 4683 4684 4685def _is_wrong_expression(expression, into): 4686 return isinstance(expression, Expression) and not isinstance(expression, into) 4687 4688 4689def _apply_builder( 4690 expression, 4691 instance, 4692 arg, 4693 copy=True, 4694 prefix=None, 4695 into=None, 4696 dialect=None, 4697 **opts, 4698): 4699 if _is_wrong_expression(expression, into): 4700 expression = into(this=expression) 4701 instance = _maybe_copy(instance, copy) 4702 expression = maybe_parse( 4703 sql_or_expression=expression, 4704 prefix=prefix, 4705 into=into, 4706 dialect=dialect, 4707 **opts, 4708 ) 4709 instance.set(arg, expression) 4710 return instance 4711 4712 4713def _apply_child_list_builder( 4714 *expressions, 4715 instance, 4716 arg, 4717 append=True, 4718 copy=True, 4719 prefix=None, 4720 into=None, 4721 dialect=None, 4722 properties=None, 4723 **opts, 4724): 4725 instance = _maybe_copy(instance, copy) 4726 parsed = [] 4727 for expression in expressions: 4728 if expression is not None: 4729 if _is_wrong_expression(expression, into): 4730 expression = into(expressions=[expression]) 4731 4732 expression = maybe_parse( 4733 expression, 4734 into=into, 4735 dialect=dialect, 4736 prefix=prefix, 4737 **opts, 4738 ) 4739 parsed.extend(expression.expressions) 4740 4741 existing = instance.args.get(arg) 4742 if append and existing: 4743 parsed = existing.expressions + parsed 4744 4745 child = into(expressions=parsed) 4746 for k, v in (properties or {}).items(): 4747 child.set(k, v) 4748 instance.set(arg, child) 4749 4750 return instance 4751 4752 4753def _apply_list_builder( 4754 *expressions, 4755 instance, 4756 arg, 4757 append=True, 4758 copy=True, 4759 prefix=None, 4760 into=None, 4761 dialect=None, 4762 **opts, 4763): 4764 inst = _maybe_copy(instance, copy) 4765 4766 expressions = [ 4767 maybe_parse( 4768 sql_or_expression=expression, 4769 into=into, 4770 prefix=prefix, 4771 dialect=dialect, 4772 **opts, 4773 ) 4774 for expression in expressions 4775 if expression is not None 4776 ] 4777 4778 existing_expressions = inst.args.get(arg) 4779 if append and existing_expressions: 4780 expressions = existing_expressions + expressions 4781 4782 inst.set(arg, expressions) 4783 return inst 4784 4785 4786def _apply_conjunction_builder( 4787 *expressions, 4788 instance, 4789 arg, 4790 into=None, 4791 append=True, 4792 copy=True, 4793 dialect=None, 4794 **opts, 4795): 4796 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4797 if not expressions: 4798 return instance 4799 4800 inst = _maybe_copy(instance, copy) 4801 4802 existing = inst.args.get(arg) 4803 if append and existing is not None: 4804 expressions = [existing.this if into else existing] + list(expressions) 4805 4806 node = and_(*expressions, dialect=dialect, copy=copy, **opts) 4807 4808 inst.set(arg, into(this=node) if into else node) 4809 return inst 4810 4811 4812def _apply_cte_builder( 4813 instance: E, 4814 alias: ExpOrStr, 4815 as_: ExpOrStr, 4816 recursive: t.Optional[bool] = None, 4817 append: bool = True, 4818 dialect: DialectType = None, 4819 copy: bool = True, 4820 **opts, 4821) -> E: 4822 alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts) 4823 as_expression = maybe_parse(as_, dialect=dialect, **opts) 4824 cte = CTE(this=as_expression, alias=alias_expression) 4825 return _apply_child_list_builder( 4826 cte, 4827 instance=instance, 4828 arg="with", 4829 append=append, 4830 copy=copy, 4831 into=With, 4832 properties={"recursive": recursive or False}, 4833 ) 4834 4835 4836def _combine( 4837 expressions: t.Sequence[t.Optional[ExpOrStr]], 4838 operator: t.Type[Connector], 4839 dialect: DialectType = None, 4840 copy: bool = True, 4841 **opts, 4842) -> Expression: 4843 conditions = [ 4844 condition(expression, dialect=dialect, copy=copy, **opts) 4845 for expression in expressions 4846 if expression is not None 4847 ] 4848 4849 this, *rest = conditions 4850 if rest: 4851 this = _wrap(this, Connector) 4852 for expression in rest: 4853 this = operator(this=this, expression=_wrap(expression, Connector)) 4854 4855 return this 4856 4857 4858def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: 4859 return Paren(this=expression) if isinstance(expression, kind) else expression 4860 4861 4862def union( 4863 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4864) -> Union: 4865 """ 4866 Initializes a syntax tree from one UNION expression. 4867 4868 Example: 4869 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4870 'SELECT * FROM foo UNION SELECT * FROM bla' 4871 4872 Args: 4873 left: the SQL code string corresponding to the left-hand side. 4874 If an `Expression` instance is passed, it will be used as-is. 4875 right: the SQL code string corresponding to the right-hand side. 4876 If an `Expression` instance is passed, it will be used as-is. 4877 distinct: set the DISTINCT flag if and only if this is true. 4878 dialect: the dialect used to parse the input expression. 4879 opts: other options to use to parse the input expressions. 4880 4881 Returns: 4882 The new Union instance. 4883 """ 4884 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4885 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4886 4887 return Union(this=left, expression=right, distinct=distinct) 4888 4889 4890def intersect( 4891 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4892) -> Intersect: 4893 """ 4894 Initializes a syntax tree from one INTERSECT expression. 4895 4896 Example: 4897 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4898 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4899 4900 Args: 4901 left: the SQL code string corresponding to the left-hand side. 4902 If an `Expression` instance is passed, it will be used as-is. 4903 right: the SQL code string corresponding to the right-hand side. 4904 If an `Expression` instance is passed, it will be used as-is. 4905 distinct: set the DISTINCT flag if and only if this is true. 4906 dialect: the dialect used to parse the input expression. 4907 opts: other options to use to parse the input expressions. 4908 4909 Returns: 4910 The new Intersect instance. 4911 """ 4912 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4913 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4914 4915 return Intersect(this=left, expression=right, distinct=distinct) 4916 4917 4918def except_( 4919 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4920) -> Except: 4921 """ 4922 Initializes a syntax tree from one EXCEPT expression. 4923 4924 Example: 4925 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4926 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4927 4928 Args: 4929 left: the SQL code string corresponding to the left-hand side. 4930 If an `Expression` instance is passed, it will be used as-is. 4931 right: the SQL code string corresponding to the right-hand side. 4932 If an `Expression` instance is passed, it will be used as-is. 4933 distinct: set the DISTINCT flag if and only if this is true. 4934 dialect: the dialect used to parse the input expression. 4935 opts: other options to use to parse the input expressions. 4936 4937 Returns: 4938 The new Except instance. 4939 """ 4940 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4941 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4942 4943 return Except(this=left, expression=right, distinct=distinct) 4944 4945 4946def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4947 """ 4948 Initializes a syntax tree from one or multiple SELECT expressions. 4949 4950 Example: 4951 >>> select("col1", "col2").from_("tbl").sql() 4952 'SELECT col1, col2 FROM tbl' 4953 4954 Args: 4955 *expressions: the SQL code string to parse as the expressions of a 4956 SELECT statement. If an Expression instance is passed, this is used as-is. 4957 dialect: the dialect used to parse the input expressions (in the case that an 4958 input expression is a SQL string). 4959 **opts: other options to use to parse the input expressions (again, in the case 4960 that an input expression is a SQL string). 4961 4962 Returns: 4963 Select: the syntax tree for the SELECT statement. 4964 """ 4965 return Select().select(*expressions, dialect=dialect, **opts) 4966 4967 4968def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4969 """ 4970 Initializes a syntax tree from a FROM expression. 4971 4972 Example: 4973 >>> from_("tbl").select("col1", "col2").sql() 4974 'SELECT col1, col2 FROM tbl' 4975 4976 Args: 4977 *expression: the SQL code string to parse as the FROM expressions of a 4978 SELECT statement. If an Expression instance is passed, this is used as-is. 4979 dialect: the dialect used to parse the input expression (in the case that the 4980 input expression is a SQL string). 4981 **opts: other options to use to parse the input expressions (again, in the case 4982 that the input expression is a SQL string). 4983 4984 Returns: 4985 Select: the syntax tree for the SELECT statement. 4986 """ 4987 return Select().from_(expression, dialect=dialect, **opts) 4988 4989 4990def update( 4991 table: str | Table, 4992 properties: dict, 4993 where: t.Optional[ExpOrStr] = None, 4994 from_: t.Optional[ExpOrStr] = None, 4995 dialect: DialectType = None, 4996 **opts, 4997) -> Update: 4998 """ 4999 Creates an update statement. 5000 5001 Example: 5002 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 5003 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 5004 5005 Args: 5006 *properties: dictionary of properties to set which are 5007 auto converted to sql objects eg None -> NULL 5008 where: sql conditional parsed into a WHERE statement 5009 from_: sql statement parsed into a FROM statement 5010 dialect: the dialect used to parse the input expressions. 5011 **opts: other options to use to parse the input expressions. 5012 5013 Returns: 5014 Update: the syntax tree for the UPDATE statement. 5015 """ 5016 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 5017 update_expr.set( 5018 "expressions", 5019 [ 5020 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 5021 for k, v in properties.items() 5022 ], 5023 ) 5024 if from_: 5025 update_expr.set( 5026 "from", 5027 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 5028 ) 5029 if isinstance(where, Condition): 5030 where = Where(this=where) 5031 if where: 5032 update_expr.set( 5033 "where", 5034 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 5035 ) 5036 return update_expr 5037 5038 5039def delete( 5040 table: ExpOrStr, 5041 where: t.Optional[ExpOrStr] = None, 5042 returning: t.Optional[ExpOrStr] = None, 5043 dialect: DialectType = None, 5044 **opts, 5045) -> Delete: 5046 """ 5047 Builds a delete statement. 5048 5049 Example: 5050 >>> delete("my_table", where="id > 1").sql() 5051 'DELETE FROM my_table WHERE id > 1' 5052 5053 Args: 5054 where: sql conditional parsed into a WHERE statement 5055 returning: sql conditional parsed into a RETURNING statement 5056 dialect: the dialect used to parse the input expressions. 5057 **opts: other options to use to parse the input expressions. 5058 5059 Returns: 5060 Delete: the syntax tree for the DELETE statement. 5061 """ 5062 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5063 if where: 5064 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5065 if returning: 5066 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5067 return delete_expr 5068 5069 5070def insert( 5071 expression: ExpOrStr, 5072 into: ExpOrStr, 5073 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5074 overwrite: t.Optional[bool] = None, 5075 dialect: DialectType = None, 5076 copy: bool = True, 5077 **opts, 5078) -> Insert: 5079 """ 5080 Builds an INSERT statement. 5081 5082 Example: 5083 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5084 'INSERT INTO tbl VALUES (1, 2, 3)' 5085 5086 Args: 5087 expression: the sql string or expression of the INSERT statement 5088 into: the tbl to insert data to. 5089 columns: optionally the table's column names. 5090 overwrite: whether to INSERT OVERWRITE or not. 5091 dialect: the dialect used to parse the input expressions. 5092 copy: whether or not to copy the expression. 5093 **opts: other options to use to parse the input expressions. 5094 5095 Returns: 5096 Insert: the syntax tree for the INSERT statement. 5097 """ 5098 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5099 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5100 5101 if columns: 5102 this = _apply_list_builder( 5103 *columns, 5104 instance=Schema(this=this), 5105 arg="expressions", 5106 into=Identifier, 5107 copy=False, 5108 dialect=dialect, 5109 **opts, 5110 ) 5111 5112 return Insert(this=this, expression=expr, overwrite=overwrite) 5113 5114 5115def condition( 5116 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5117) -> Condition: 5118 """ 5119 Initialize a logical condition expression. 5120 5121 Example: 5122 >>> condition("x=1").sql() 5123 'x = 1' 5124 5125 This is helpful for composing larger logical syntax trees: 5126 >>> where = condition("x=1") 5127 >>> where = where.and_("y=1") 5128 >>> Select().from_("tbl").select("*").where(where).sql() 5129 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5130 5131 Args: 5132 *expression: the SQL code string to parse. 5133 If an Expression instance is passed, this is used as-is. 5134 dialect: the dialect used to parse the input expression (in the case that the 5135 input expression is a SQL string). 5136 copy: Whether or not to copy `expression` (only applies to expressions). 5137 **opts: other options to use to parse the input expressions (again, in the case 5138 that the input expression is a SQL string). 5139 5140 Returns: 5141 The new Condition instance 5142 """ 5143 return maybe_parse( 5144 expression, 5145 into=Condition, 5146 dialect=dialect, 5147 copy=copy, 5148 **opts, 5149 ) 5150 5151 5152def and_( 5153 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5154) -> Condition: 5155 """ 5156 Combine multiple conditions with an AND logical operator. 5157 5158 Example: 5159 >>> and_("x=1", and_("y=1", "z=1")).sql() 5160 'x = 1 AND (y = 1 AND z = 1)' 5161 5162 Args: 5163 *expressions: the SQL code strings to parse. 5164 If an Expression instance is passed, this is used as-is. 5165 dialect: the dialect used to parse the input expression. 5166 copy: whether or not to copy `expressions` (only applies to Expressions). 5167 **opts: other options to use to parse the input expressions. 5168 5169 Returns: 5170 And: the new condition 5171 """ 5172 return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts)) 5173 5174 5175def or_( 5176 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5177) -> Condition: 5178 """ 5179 Combine multiple conditions with an OR logical operator. 5180 5181 Example: 5182 >>> or_("x=1", or_("y=1", "z=1")).sql() 5183 'x = 1 OR (y = 1 OR z = 1)' 5184 5185 Args: 5186 *expressions: the SQL code strings to parse. 5187 If an Expression instance is passed, this is used as-is. 5188 dialect: the dialect used to parse the input expression. 5189 copy: whether or not to copy `expressions` (only applies to Expressions). 5190 **opts: other options to use to parse the input expressions. 5191 5192 Returns: 5193 Or: the new condition 5194 """ 5195 return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts)) 5196 5197 5198def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5199 """ 5200 Wrap a condition with a NOT operator. 5201 5202 Example: 5203 >>> not_("this_suit='black'").sql() 5204 "NOT this_suit = 'black'" 5205 5206 Args: 5207 expression: the SQL code string to parse. 5208 If an Expression instance is passed, this is used as-is. 5209 dialect: the dialect used to parse the input expression. 5210 copy: whether to copy the expression or not. 5211 **opts: other options to use to parse the input expressions. 5212 5213 Returns: 5214 The new condition. 5215 """ 5216 this = condition( 5217 expression, 5218 dialect=dialect, 5219 copy=copy, 5220 **opts, 5221 ) 5222 return Not(this=_wrap(this, Connector)) 5223 5224 5225def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5226 """ 5227 Wrap an expression in parentheses. 5228 5229 Example: 5230 >>> paren("5 + 3").sql() 5231 '(5 + 3)' 5232 5233 Args: 5234 expression: the SQL code string to parse. 5235 If an Expression instance is passed, this is used as-is. 5236 copy: whether to copy the expression or not. 5237 5238 Returns: 5239 The wrapped expression. 5240 """ 5241 return Paren(this=maybe_parse(expression, copy=copy)) 5242 5243 5244SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 5245 5246 5247@t.overload 5248def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None: 5249 ... 5250 5251 5252@t.overload 5253def to_identifier( 5254 name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True 5255) -> Identifier: 5256 ... 5257 5258 5259def to_identifier(name, quoted=None, copy=True): 5260 """Builds an identifier. 5261 5262 Args: 5263 name: The name to turn into an identifier. 5264 quoted: Whether or not force quote the identifier. 5265 copy: Whether or not to copy a passed in Identefier node. 5266 5267 Returns: 5268 The identifier ast node. 5269 """ 5270 5271 if name is None: 5272 return None 5273 5274 if isinstance(name, Identifier): 5275 identifier = _maybe_copy(name, copy) 5276 elif isinstance(name, str): 5277 identifier = Identifier( 5278 this=name, 5279 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5280 ) 5281 else: 5282 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5283 return identifier 5284 5285 5286INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 5287 5288 5289def to_interval(interval: str | Literal) -> Interval: 5290 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5291 if isinstance(interval, Literal): 5292 if not interval.is_string: 5293 raise ValueError("Invalid interval string.") 5294 5295 interval = interval.this 5296 5297 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5298 5299 if not interval_parts: 5300 raise ValueError("Invalid interval string.") 5301 5302 return Interval( 5303 this=Literal.string(interval_parts.group(1)), 5304 unit=Var(this=interval_parts.group(2)), 5305 ) 5306 5307 5308@t.overload 5309def to_table(sql_path: str | Table, **kwargs) -> Table: 5310 ... 5311 5312 5313@t.overload 5314def to_table(sql_path: None, **kwargs) -> None: 5315 ... 5316 5317 5318def to_table( 5319 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5320) -> t.Optional[Table]: 5321 """ 5322 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5323 If a table is passed in then that table is returned. 5324 5325 Args: 5326 sql_path: a `[catalog].[schema].[table]` string. 5327 dialect: the source dialect according to which the table name will be parsed. 5328 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5329 5330 Returns: 5331 A table expression. 5332 """ 5333 if sql_path is None or isinstance(sql_path, Table): 5334 return sql_path 5335 if not isinstance(sql_path, str): 5336 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5337 5338 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5339 if table: 5340 for k, v in kwargs.items(): 5341 table.set(k, v) 5342 5343 return table 5344 5345 5346def to_column(sql_path: str | Column, **kwargs) -> Column: 5347 """ 5348 Create a column from a `[table].[column]` sql path. Schema is optional. 5349 5350 If a column is passed in then that column is returned. 5351 5352 Args: 5353 sql_path: `[table].[column]` string 5354 Returns: 5355 Table: A column expression 5356 """ 5357 if sql_path is None or isinstance(sql_path, Column): 5358 return sql_path 5359 if not isinstance(sql_path, str): 5360 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5361 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 5362 5363 5364def alias_( 5365 expression: ExpOrStr, 5366 alias: str | Identifier, 5367 table: bool | t.Sequence[str | Identifier] = False, 5368 quoted: t.Optional[bool] = None, 5369 dialect: DialectType = None, 5370 copy: bool = True, 5371 **opts, 5372): 5373 """Create an Alias expression. 5374 5375 Example: 5376 >>> alias_('foo', 'bar').sql() 5377 'foo AS bar' 5378 5379 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5380 '(SELECT 1, 2) AS bar(a, b)' 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. If the name has 5386 special characters it is quoted. 5387 table: Whether or not to create a table alias, can also be a list of columns. 5388 quoted: whether or not to quote the alias 5389 dialect: the dialect used to parse the input expression. 5390 copy: Whether or not to copy the expression. 5391 **opts: other options to use to parse the input expressions. 5392 5393 Returns: 5394 Alias: the aliased expression 5395 """ 5396 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5397 alias = to_identifier(alias, quoted=quoted) 5398 5399 if table: 5400 table_alias = TableAlias(this=alias) 5401 exp.set("alias", table_alias) 5402 5403 if not isinstance(table, bool): 5404 for column in table: 5405 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5406 5407 return exp 5408 5409 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5410 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5411 # for the complete Window expression. 5412 # 5413 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5414 5415 if "alias" in exp.arg_types and not isinstance(exp, Window): 5416 exp.set("alias", alias) 5417 return exp 5418 return Alias(this=exp, alias=alias) 5419 5420 5421def subquery( 5422 expression: ExpOrStr, 5423 alias: t.Optional[Identifier | str] = None, 5424 dialect: DialectType = None, 5425 **opts, 5426) -> Select: 5427 """ 5428 Build a subquery expression. 5429 5430 Example: 5431 >>> subquery('select x from tbl', 'bar').select('x').sql() 5432 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5433 5434 Args: 5435 expression: the SQL code strings to parse. 5436 If an Expression instance is passed, this is used as-is. 5437 alias: the alias name to use. 5438 dialect: the dialect used to parse the input expression. 5439 **opts: other options to use to parse the input expressions. 5440 5441 Returns: 5442 A new Select instance with the subquery expression included. 5443 """ 5444 5445 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5446 return Select().from_(expression, dialect=dialect, **opts) 5447 5448 5449def column( 5450 col: str | Identifier, 5451 table: t.Optional[str | Identifier] = None, 5452 db: t.Optional[str | Identifier] = None, 5453 catalog: t.Optional[str | Identifier] = None, 5454 quoted: t.Optional[bool] = None, 5455) -> Column: 5456 """ 5457 Build a Column. 5458 5459 Args: 5460 col: Column name. 5461 table: Table name. 5462 db: Database name. 5463 catalog: Catalog name. 5464 quoted: Whether to force quotes on the column's identifiers. 5465 5466 Returns: 5467 The new Column instance. 5468 """ 5469 return Column( 5470 this=to_identifier(col, quoted=quoted), 5471 table=to_identifier(table, quoted=quoted), 5472 db=to_identifier(db, quoted=quoted), 5473 catalog=to_identifier(catalog, quoted=quoted), 5474 ) 5475 5476 5477def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5478 """Cast an expression to a data type. 5479 5480 Example: 5481 >>> cast('x + 1', 'int').sql() 5482 'CAST(x + 1 AS INT)' 5483 5484 Args: 5485 expression: The expression to cast. 5486 to: The datatype to cast to. 5487 5488 Returns: 5489 The new Cast instance. 5490 """ 5491 expression = maybe_parse(expression, **opts) 5492 return Cast(this=expression, to=DataType.build(to, **opts)) 5493 5494 5495def table_( 5496 table: Identifier | str, 5497 db: t.Optional[Identifier | str] = None, 5498 catalog: t.Optional[Identifier | str] = None, 5499 quoted: t.Optional[bool] = None, 5500 alias: t.Optional[Identifier | str] = None, 5501) -> Table: 5502 """Build a Table. 5503 5504 Args: 5505 table: Table name. 5506 db: Database name. 5507 catalog: Catalog name. 5508 quote: Whether to force quotes on the table's identifiers. 5509 alias: Table's alias. 5510 5511 Returns: 5512 The new Table instance. 5513 """ 5514 return Table( 5515 this=to_identifier(table, quoted=quoted), 5516 db=to_identifier(db, quoted=quoted), 5517 catalog=to_identifier(catalog, quoted=quoted), 5518 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5519 ) 5520 5521 5522def values( 5523 values: t.Iterable[t.Tuple[t.Any, ...]], 5524 alias: t.Optional[str] = None, 5525 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5526) -> Values: 5527 """Build VALUES statement. 5528 5529 Example: 5530 >>> values([(1, '2')]).sql() 5531 "VALUES (1, '2')" 5532 5533 Args: 5534 values: values statements that will be converted to SQL 5535 alias: optional alias 5536 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5537 If either are provided then an alias is also required. 5538 5539 Returns: 5540 Values: the Values expression object 5541 """ 5542 if columns and not alias: 5543 raise ValueError("Alias is required when providing columns") 5544 5545 return Values( 5546 expressions=[convert(tup) for tup in values], 5547 alias=( 5548 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5549 if columns 5550 else (TableAlias(this=to_identifier(alias)) if alias else None) 5551 ), 5552 ) 5553 5554 5555def var(name: t.Optional[ExpOrStr]) -> Var: 5556 """Build a SQL variable. 5557 5558 Example: 5559 >>> repr(var('x')) 5560 '(VAR this: x)' 5561 5562 >>> repr(var(column('x', table='y'))) 5563 '(VAR this: x)' 5564 5565 Args: 5566 name: The name of the var or an expression who's name will become the var. 5567 5568 Returns: 5569 The new variable node. 5570 """ 5571 if not name: 5572 raise ValueError("Cannot convert empty name into var.") 5573 5574 if isinstance(name, Expression): 5575 name = name.name 5576 return Var(this=name) 5577 5578 5579def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5580 """Build ALTER TABLE... RENAME... expression 5581 5582 Args: 5583 old_name: The old name of the table 5584 new_name: The new name of the table 5585 5586 Returns: 5587 Alter table expression 5588 """ 5589 old_table = to_table(old_name) 5590 new_table = to_table(new_name) 5591 return AlterTable( 5592 this=old_table, 5593 actions=[ 5594 RenameTable(this=new_table), 5595 ], 5596 ) 5597 5598 5599def convert(value: t.Any, copy: bool = False) -> Expression: 5600 """Convert a python value into an expression object. 5601 5602 Raises an error if a conversion is not possible. 5603 5604 Args: 5605 value: A python object. 5606 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5607 5608 Returns: 5609 Expression: the equivalent expression object. 5610 """ 5611 if isinstance(value, Expression): 5612 return _maybe_copy(value, copy) 5613 if isinstance(value, str): 5614 return Literal.string(value) 5615 if isinstance(value, bool): 5616 return Boolean(this=value) 5617 if value is None or (isinstance(value, float) and math.isnan(value)): 5618 return NULL 5619 if isinstance(value, numbers.Number): 5620 return Literal.number(value) 5621 if isinstance(value, datetime.datetime): 5622 datetime_literal = Literal.string( 5623 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5624 ) 5625 return TimeStrToTime(this=datetime_literal) 5626 if isinstance(value, datetime.date): 5627 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5628 return DateStrToDate(this=date_literal) 5629 if isinstance(value, tuple): 5630 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5631 if isinstance(value, list): 5632 return Array(expressions=[convert(v, copy=copy) for v in value]) 5633 if isinstance(value, dict): 5634 return Map( 5635 keys=[convert(k, copy=copy) for k in value], 5636 values=[convert(v, copy=copy) for v in value.values()], 5637 ) 5638 raise ValueError(f"Cannot convert {value}") 5639 5640 5641def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5642 """ 5643 Replace children of an expression with the result of a lambda fun(child) -> exp. 5644 """ 5645 for k, v in expression.args.items(): 5646 is_list_arg = type(v) is list 5647 5648 child_nodes = v if is_list_arg else [v] 5649 new_child_nodes = [] 5650 5651 for cn in child_nodes: 5652 if isinstance(cn, Expression): 5653 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5654 new_child_nodes.append(child_node) 5655 child_node.parent = expression 5656 child_node.arg_key = k 5657 else: 5658 new_child_nodes.append(cn) 5659 5660 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 5661 5662 5663def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]: 5664 """ 5665 Return all table names referenced through columns in an expression. 5666 5667 Example: 5668 >>> import sqlglot 5669 >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))) 5670 ['a', 'c'] 5671 5672 Args: 5673 expression: expression to find table names. 5674 exclude: a table name to exclude 5675 5676 Returns: 5677 A list of unique names. 5678 """ 5679 return { 5680 table 5681 for table in (column.table for column in expression.find_all(Column)) 5682 if table and table != exclude 5683 } 5684 5685 5686def table_name(table: Table | str) -> str: 5687 """Get the full name of a table as a string. 5688 5689 Args: 5690 table: table expression node or string. 5691 5692 Examples: 5693 >>> from sqlglot import exp, parse_one 5694 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5695 'a.b.c' 5696 5697 Returns: 5698 The table name. 5699 """ 5700 5701 table = maybe_parse(table, into=Table) 5702 5703 if not table: 5704 raise ValueError(f"Cannot parse {table}") 5705 5706 return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part) 5707 5708 5709def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E: 5710 """Replace all tables in expression according to the mapping. 5711 5712 Args: 5713 expression: expression node to be transformed and replaced. 5714 mapping: mapping of table names. 5715 copy: whether or not to copy the expression. 5716 5717 Examples: 5718 >>> from sqlglot import exp, parse_one 5719 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5720 'SELECT * FROM c' 5721 5722 Returns: 5723 The mapped expression. 5724 """ 5725 5726 def _replace_tables(node: Expression) -> Expression: 5727 if isinstance(node, Table): 5728 new_name = mapping.get(table_name(node)) 5729 if new_name: 5730 return to_table( 5731 new_name, 5732 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5733 ) 5734 return node 5735 5736 return expression.transform(_replace_tables, copy=copy) 5737 5738 5739def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5740 """Replace placeholders in an expression. 5741 5742 Args: 5743 expression: expression node to be transformed and replaced. 5744 args: positional names that will substitute unnamed placeholders in the given order. 5745 kwargs: keyword arguments that will substitute named placeholders. 5746 5747 Examples: 5748 >>> from sqlglot import exp, parse_one 5749 >>> replace_placeholders( 5750 ... parse_one("select * from :tbl where ? = ?"), 5751 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5752 ... ).sql() 5753 "SELECT * FROM foo WHERE str_col = 'b'" 5754 5755 Returns: 5756 The mapped expression. 5757 """ 5758 5759 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5760 if isinstance(node, Placeholder): 5761 if node.name: 5762 new_name = kwargs.get(node.name) 5763 if new_name: 5764 return convert(new_name) 5765 else: 5766 try: 5767 return convert(next(args)) 5768 except StopIteration: 5769 pass 5770 return node 5771 5772 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5773 5774 5775def expand( 5776 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5777) -> Expression: 5778 """Transforms an expression by expanding all referenced sources into subqueries. 5779 5780 Examples: 5781 >>> from sqlglot import parse_one 5782 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5783 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5784 5785 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5786 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5787 5788 Args: 5789 expression: The expression to expand. 5790 sources: A dictionary of name to Subqueryables. 5791 copy: Whether or not to copy the expression during transformation. Defaults to True. 5792 5793 Returns: 5794 The transformed expression. 5795 """ 5796 5797 def _expand(node: Expression): 5798 if isinstance(node, Table): 5799 name = table_name(node) 5800 source = sources.get(name) 5801 if source: 5802 subquery = source.subquery(node.alias or name) 5803 subquery.comments = [f"source: {name}"] 5804 return subquery.transform(_expand, copy=False) 5805 return node 5806 5807 return expression.transform(_expand, copy=copy) 5808 5809 5810def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5811 """ 5812 Returns a Func expression. 5813 5814 Examples: 5815 >>> func("abs", 5).sql() 5816 'ABS(5)' 5817 5818 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5819 'CAST(5 AS DOUBLE)' 5820 5821 Args: 5822 name: the name of the function to build. 5823 args: the args used to instantiate the function of interest. 5824 dialect: the source dialect. 5825 kwargs: the kwargs used to instantiate the function of interest. 5826 5827 Note: 5828 The arguments `args` and `kwargs` are mutually exclusive. 5829 5830 Returns: 5831 An instance of the function of interest, or an anonymous function, if `name` doesn't 5832 correspond to an existing `sqlglot.expressions.Func` class. 5833 """ 5834 if args and kwargs: 5835 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5836 5837 from sqlglot.dialects.dialect import Dialect 5838 5839 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5840 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5841 5842 parser = Dialect.get_or_raise(dialect)().parser() 5843 from_args_list = parser.FUNCTIONS.get(name.upper()) 5844 5845 if from_args_list: 5846 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5847 else: 5848 kwargs = kwargs or {"expressions": converted} 5849 function = Anonymous(this=name, **kwargs) 5850 5851 for error_message in function.error_messages(converted): 5852 raise ValueError(error_message) 5853 5854 return function 5855 5856 5857def true() -> Boolean: 5858 """ 5859 Returns a true Boolean expression. 5860 """ 5861 return Boolean(this=True) 5862 5863 5864def false() -> Boolean: 5865 """ 5866 Returns a false Boolean expression. 5867 """ 5868 return Boolean(this=False) 5869 5870 5871def null() -> Null: 5872 """ 5873 Returns a Null expression. 5874 """ 5875 return Null() 5876 5877 5878# TODO: deprecate this 5879TRUE = Boolean(this=True) 5880FALSE = Boolean(this=False) 5881NULL = 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 "using": False, 1505 "where": False, 1506 "columns": False, 1507 "unique": False, 1508 "primary": False, 1509 "amp": False, # teradata 1510 "partition_by": False, # teradata 1511 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1514class Insert(Expression): 1515 arg_types = { 1516 "with": False, 1517 "this": True, 1518 "expression": False, 1519 "conflict": False, 1520 "returning": False, 1521 "overwrite": False, 1522 "exists": False, 1523 "partition": False, 1524 "alternative": False, 1525 } 1526 1527 def with_( 1528 self, 1529 alias: ExpOrStr, 1530 as_: ExpOrStr, 1531 recursive: t.Optional[bool] = None, 1532 append: bool = True, 1533 dialect: DialectType = None, 1534 copy: bool = True, 1535 **opts, 1536 ) -> Insert: 1537 """ 1538 Append to or set the common table expressions. 1539 1540 Example: 1541 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1542 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1543 1544 Args: 1545 alias: the SQL code string to parse as the table name. 1546 If an `Expression` instance is passed, this is used as-is. 1547 as_: the SQL code string to parse as the table expression. 1548 If an `Expression` instance is passed, it will be used as-is. 1549 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1550 append: if `True`, add to any existing expressions. 1551 Otherwise, this resets the expressions. 1552 dialect: the dialect used to parse the input expression. 1553 copy: if `False`, modify this expression instance in-place. 1554 opts: other options to use to parse the input expressions. 1555 1556 Returns: 1557 The modified expression. 1558 """ 1559 return _apply_cte_builder( 1560 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1561 )
1527 def with_( 1528 self, 1529 alias: ExpOrStr, 1530 as_: ExpOrStr, 1531 recursive: t.Optional[bool] = None, 1532 append: bool = True, 1533 dialect: DialectType = None, 1534 copy: bool = True, 1535 **opts, 1536 ) -> Insert: 1537 """ 1538 Append to or set the common table expressions. 1539 1540 Example: 1541 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1542 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1543 1544 Args: 1545 alias: the SQL code string to parse as the table name. 1546 If an `Expression` instance is passed, this is used as-is. 1547 as_: the SQL code string to parse as the table expression. 1548 If an `Expression` instance is passed, it will be used as-is. 1549 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1550 append: if `True`, add to any existing expressions. 1551 Otherwise, this resets the expressions. 1552 dialect: the dialect used to parse the input expression. 1553 copy: if `False`, modify this expression instance in-place. 1554 opts: other options to use to parse the input expressions. 1555 1556 Returns: 1557 The modified expression. 1558 """ 1559 return _apply_cte_builder( 1560 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1561 )
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
1564class OnConflict(Expression): 1565 arg_types = { 1566 "duplicate": False, 1567 "expressions": False, 1568 "nothing": False, 1569 "key": False, 1570 "constraint": False, 1571 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1588class LoadData(Expression): 1589 arg_types = { 1590 "this": True, 1591 "local": False, 1592 "overwrite": False, 1593 "inpath": True, 1594 "partition": False, 1595 "input_format": False, 1596 "serde": False, 1597 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1604class Fetch(Expression): 1605 arg_types = { 1606 "direction": False, 1607 "count": False, 1608 "percent": False, 1609 "with_ties": False, 1610 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1613class Group(Expression): 1614 arg_types = { 1615 "expressions": False, 1616 "grouping_sets": False, 1617 "cube": False, 1618 "rollup": False, 1619 "totals": False, 1620 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1631class Literal(Condition): 1632 arg_types = {"this": True, "is_string": True} 1633 1634 @property 1635 def hashable_args(self) -> t.Any: 1636 return (self.this, self.args.get("is_string")) 1637 1638 @classmethod 1639 def number(cls, number) -> Literal: 1640 return cls(this=str(number), is_string=False) 1641 1642 @classmethod 1643 def string(cls, string) -> Literal: 1644 return cls(this=str(string), is_string=True) 1645 1646 @property 1647 def output_name(self) -> str: 1648 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
1651class Join(Expression): 1652 arg_types = { 1653 "this": True, 1654 "on": False, 1655 "side": False, 1656 "kind": False, 1657 "using": False, 1658 "method": False, 1659 "global": False, 1660 "hint": False, 1661 } 1662 1663 @property 1664 def method(self) -> str: 1665 return self.text("method").upper() 1666 1667 @property 1668 def kind(self) -> str: 1669 return self.text("kind").upper() 1670 1671 @property 1672 def side(self) -> str: 1673 return self.text("side").upper() 1674 1675 @property 1676 def hint(self) -> str: 1677 return self.text("hint").upper() 1678 1679 @property 1680 def alias_or_name(self) -> str: 1681 return self.this.alias_or_name 1682 1683 def on( 1684 self, 1685 *expressions: t.Optional[ExpOrStr], 1686 append: bool = True, 1687 dialect: DialectType = None, 1688 copy: bool = True, 1689 **opts, 1690 ) -> Join: 1691 """ 1692 Append to or set the ON expressions. 1693 1694 Example: 1695 >>> import sqlglot 1696 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1697 'JOIN x ON y = 1' 1698 1699 Args: 1700 *expressions: the SQL code strings to parse. 1701 If an `Expression` instance is passed, it will be used as-is. 1702 Multiple expressions are combined with an AND operator. 1703 append: if `True`, AND the new expressions to any existing expression. 1704 Otherwise, this resets the expression. 1705 dialect: the dialect used to parse the input expressions. 1706 copy: if `False`, modify this expression instance in-place. 1707 opts: other options to use to parse the input expressions. 1708 1709 Returns: 1710 The modified Join expression. 1711 """ 1712 join = _apply_conjunction_builder( 1713 *expressions, 1714 instance=self, 1715 arg="on", 1716 append=append, 1717 dialect=dialect, 1718 copy=copy, 1719 **opts, 1720 ) 1721 1722 if join.kind == "CROSS": 1723 join.set("kind", None) 1724 1725 return join 1726 1727 def using( 1728 self, 1729 *expressions: t.Optional[ExpOrStr], 1730 append: bool = True, 1731 dialect: DialectType = None, 1732 copy: bool = True, 1733 **opts, 1734 ) -> Join: 1735 """ 1736 Append to or set the USING expressions. 1737 1738 Example: 1739 >>> import sqlglot 1740 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1741 'JOIN x USING (foo, bla)' 1742 1743 Args: 1744 *expressions: the SQL code strings to parse. 1745 If an `Expression` instance is passed, it will be used as-is. 1746 append: if `True`, concatenate the new expressions to the existing "using" list. 1747 Otherwise, this resets the expression. 1748 dialect: the dialect used to parse the input expressions. 1749 copy: if `False`, modify this expression instance in-place. 1750 opts: other options to use to parse the input expressions. 1751 1752 Returns: 1753 The modified Join expression. 1754 """ 1755 join = _apply_list_builder( 1756 *expressions, 1757 instance=self, 1758 arg="using", 1759 append=append, 1760 dialect=dialect, 1761 copy=copy, 1762 **opts, 1763 ) 1764 1765 if join.kind == "CROSS": 1766 join.set("kind", None) 1767 1768 return join
1683 def on( 1684 self, 1685 *expressions: t.Optional[ExpOrStr], 1686 append: bool = True, 1687 dialect: DialectType = None, 1688 copy: bool = True, 1689 **opts, 1690 ) -> Join: 1691 """ 1692 Append to or set the ON expressions. 1693 1694 Example: 1695 >>> import sqlglot 1696 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1697 'JOIN x ON y = 1' 1698 1699 Args: 1700 *expressions: the SQL code strings to parse. 1701 If an `Expression` instance is passed, it will be used as-is. 1702 Multiple expressions are combined with an AND operator. 1703 append: if `True`, AND the new expressions to any existing expression. 1704 Otherwise, this resets the expression. 1705 dialect: the dialect used to parse the input expressions. 1706 copy: if `False`, modify this expression instance in-place. 1707 opts: other options to use to parse the input expressions. 1708 1709 Returns: 1710 The modified Join expression. 1711 """ 1712 join = _apply_conjunction_builder( 1713 *expressions, 1714 instance=self, 1715 arg="on", 1716 append=append, 1717 dialect=dialect, 1718 copy=copy, 1719 **opts, 1720 ) 1721 1722 if join.kind == "CROSS": 1723 join.set("kind", None) 1724 1725 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.
1727 def using( 1728 self, 1729 *expressions: t.Optional[ExpOrStr], 1730 append: bool = True, 1731 dialect: DialectType = None, 1732 copy: bool = True, 1733 **opts, 1734 ) -> Join: 1735 """ 1736 Append to or set the USING expressions. 1737 1738 Example: 1739 >>> import sqlglot 1740 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1741 'JOIN x USING (foo, bla)' 1742 1743 Args: 1744 *expressions: the SQL code strings to parse. 1745 If an `Expression` instance is passed, it will be used as-is. 1746 append: if `True`, concatenate the new expressions to the existing "using" list. 1747 Otherwise, this resets the expression. 1748 dialect: the dialect used to parse the input expressions. 1749 copy: if `False`, modify this expression instance in-place. 1750 opts: other options to use to parse the input expressions. 1751 1752 Returns: 1753 The modified Join expression. 1754 """ 1755 join = _apply_list_builder( 1756 *expressions, 1757 instance=self, 1758 arg="using", 1759 append=append, 1760 dialect=dialect, 1761 copy=copy, 1762 **opts, 1763 ) 1764 1765 if join.kind == "CROSS": 1766 join.set("kind", None) 1767 1768 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
1771class Lateral(UDTF): 1772 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
1775class MatchRecognize(Expression): 1776 arg_types = { 1777 "partition_by": False, 1778 "order": False, 1779 "measures": False, 1780 "rows": False, 1781 "after": False, 1782 "pattern": False, 1783 "define": False, 1784 "alias": False, 1785 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1832class BlockCompressionProperty(Property): 1833 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
1848class DataBlocksizeProperty(Property): 1849 arg_types = { 1850 "size": False, 1851 "units": False, 1852 "minimum": False, 1853 "maximum": False, 1854 "default": False, 1855 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1898class InputOutputFormat(Expression): 1899 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
1902class IsolatedLoadingProperty(Property): 1903 arg_types = { 1904 "no": True, 1905 "concurrent": True, 1906 "for_all": True, 1907 "for_insert": True, 1908 "for_none": True, 1909 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1912class JournalProperty(Property): 1913 arg_types = { 1914 "no": False, 1915 "dual": False, 1916 "before": False, 1917 "local": False, 1918 "after": False, 1919 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1952class LockingProperty(Property): 1953 arg_types = { 1954 "this": False, 1955 "kind": True, 1956 "for_or_in": True, 1957 "lock_type": True, 1958 "override": False, 1959 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1970class MergeBlockRatioProperty(Property): 1971 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
1986class ReturnsProperty(Property): 1987 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
1994class RowFormatDelimitedProperty(Property): 1995 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1996 arg_types = { 1997 "fields": False, 1998 "escaped": False, 1999 "collection_items": False, 2000 "map_keys": False, 2001 "lines": False, 2002 "null": False, 2003 "serde": False, 2004 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2059class Properties(Expression): 2060 arg_types = {"expressions": True} 2061 2062 NAME_TO_PROPERTY = { 2063 "ALGORITHM": AlgorithmProperty, 2064 "AUTO_INCREMENT": AutoIncrementProperty, 2065 "CHARACTER SET": CharacterSetProperty, 2066 "COLLATE": CollateProperty, 2067 "COMMENT": SchemaCommentProperty, 2068 "DEFINER": DefinerProperty, 2069 "DISTKEY": DistKeyProperty, 2070 "DISTSTYLE": DistStyleProperty, 2071 "ENGINE": EngineProperty, 2072 "EXECUTE AS": ExecuteAsProperty, 2073 "FORMAT": FileFormatProperty, 2074 "LANGUAGE": LanguageProperty, 2075 "LOCATION": LocationProperty, 2076 "PARTITIONED_BY": PartitionedByProperty, 2077 "RETURNS": ReturnsProperty, 2078 "ROW_FORMAT": RowFormatProperty, 2079 "SORTKEY": SortKeyProperty, 2080 } 2081 2082 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2083 2084 # CREATE property locations 2085 # Form: schema specified 2086 # create [POST_CREATE] 2087 # table a [POST_NAME] 2088 # (b int) [POST_SCHEMA] 2089 # with ([POST_WITH]) 2090 # index (b) [POST_INDEX] 2091 # 2092 # Form: alias selection 2093 # create [POST_CREATE] 2094 # table a [POST_NAME] 2095 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2096 # index (c) [POST_INDEX] 2097 class Location(AutoName): 2098 POST_CREATE = auto() 2099 POST_NAME = auto() 2100 POST_SCHEMA = auto() 2101 POST_WITH = auto() 2102 POST_ALIAS = auto() 2103 POST_EXPRESSION = auto() 2104 POST_INDEX = auto() 2105 UNSUPPORTED = auto() 2106 2107 @classmethod 2108 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2109 expressions = [] 2110 for key, value in properties_dict.items(): 2111 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2112 if property_cls: 2113 expressions.append(property_cls(this=convert(value))) 2114 else: 2115 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2116 2117 return cls(expressions=expressions)
2107 @classmethod 2108 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2109 expressions = [] 2110 for key, value in properties_dict.items(): 2111 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2112 if property_cls: 2113 expressions.append(property_cls(this=convert(value))) 2114 else: 2115 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2116 2117 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
2097 class Location(AutoName): 2098 POST_CREATE = auto() 2099 POST_NAME = auto() 2100 POST_SCHEMA = auto() 2101 POST_WITH = auto() 2102 POST_ALIAS = auto() 2103 POST_EXPRESSION = auto() 2104 POST_INDEX = auto() 2105 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
2129class Reference(Expression): 2130 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
2133class Tuple(Expression): 2134 arg_types = {"expressions": False} 2135 2136 def isin( 2137 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2138 ) -> In: 2139 return In( 2140 this=_maybe_copy(self, copy), 2141 expressions=[convert(e, copy=copy) for e in expressions], 2142 query=maybe_parse(query, copy=copy, **opts) if query else None, 2143 )
2136 def isin( 2137 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2138 ) -> In: 2139 return In( 2140 this=_maybe_copy(self, copy), 2141 expressions=[convert(e, copy=copy) for e in expressions], 2142 query=maybe_parse(query, copy=copy, **opts) if query else None, 2143 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2146class Subqueryable(Unionable): 2147 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2148 """ 2149 Convert this expression to an aliased expression that can be used as a Subquery. 2150 2151 Example: 2152 >>> subquery = Select().select("x").from_("tbl").subquery() 2153 >>> Select().select("x").from_(subquery).sql() 2154 'SELECT x FROM (SELECT x FROM tbl)' 2155 2156 Args: 2157 alias (str | Identifier): an optional alias for the subquery 2158 copy (bool): if `False`, modify this expression instance in-place. 2159 2160 Returns: 2161 Alias: the subquery 2162 """ 2163 instance = _maybe_copy(self, copy) 2164 if not isinstance(alias, Expression): 2165 alias = TableAlias(this=to_identifier(alias)) if alias else None 2166 2167 return Subquery(this=instance, alias=alias) 2168 2169 def limit( 2170 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2171 ) -> Select: 2172 raise NotImplementedError 2173 2174 @property 2175 def ctes(self): 2176 with_ = self.args.get("with") 2177 if not with_: 2178 return [] 2179 return with_.expressions 2180 2181 @property 2182 def selects(self): 2183 raise NotImplementedError("Subqueryable objects must implement `selects`") 2184 2185 @property 2186 def named_selects(self): 2187 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2188 2189 def with_( 2190 self, 2191 alias: ExpOrStr, 2192 as_: ExpOrStr, 2193 recursive: t.Optional[bool] = None, 2194 append: bool = True, 2195 dialect: DialectType = None, 2196 copy: bool = True, 2197 **opts, 2198 ) -> Subqueryable: 2199 """ 2200 Append to or set the common table expressions. 2201 2202 Example: 2203 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2204 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2205 2206 Args: 2207 alias: the SQL code string to parse as the table name. 2208 If an `Expression` instance is passed, this is used as-is. 2209 as_: the SQL code string to parse as the table expression. 2210 If an `Expression` instance is passed, it will be used as-is. 2211 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2212 append: if `True`, add to any existing expressions. 2213 Otherwise, this resets the expressions. 2214 dialect: the dialect used to parse the input expression. 2215 copy: if `False`, modify this expression instance in-place. 2216 opts: other options to use to parse the input expressions. 2217 2218 Returns: 2219 The modified expression. 2220 """ 2221 return _apply_cte_builder( 2222 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2223 )
2147 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2148 """ 2149 Convert this expression to an aliased expression that can be used as a Subquery. 2150 2151 Example: 2152 >>> subquery = Select().select("x").from_("tbl").subquery() 2153 >>> Select().select("x").from_(subquery).sql() 2154 'SELECT x FROM (SELECT x FROM tbl)' 2155 2156 Args: 2157 alias (str | Identifier): an optional alias for the subquery 2158 copy (bool): if `False`, modify this expression instance in-place. 2159 2160 Returns: 2161 Alias: the subquery 2162 """ 2163 instance = _maybe_copy(self, copy) 2164 if not isinstance(alias, Expression): 2165 alias = TableAlias(this=to_identifier(alias)) if alias else None 2166 2167 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
2189 def with_( 2190 self, 2191 alias: ExpOrStr, 2192 as_: ExpOrStr, 2193 recursive: t.Optional[bool] = None, 2194 append: bool = True, 2195 dialect: DialectType = None, 2196 copy: bool = True, 2197 **opts, 2198 ) -> Subqueryable: 2199 """ 2200 Append to or set the common table expressions. 2201 2202 Example: 2203 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2204 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2205 2206 Args: 2207 alias: the SQL code string to parse as the table name. 2208 If an `Expression` instance is passed, this is used as-is. 2209 as_: the SQL code string to parse as the table expression. 2210 If an `Expression` instance is passed, it will be used as-is. 2211 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2212 append: if `True`, add to any existing expressions. 2213 Otherwise, this resets the expressions. 2214 dialect: the dialect used to parse the input expression. 2215 copy: if `False`, modify this expression instance in-place. 2216 opts: other options to use to parse the input expressions. 2217 2218 Returns: 2219 The modified expression. 2220 """ 2221 return _apply_cte_builder( 2222 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2223 )
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
2249class Table(Expression): 2250 arg_types = { 2251 "this": True, 2252 "alias": False, 2253 "db": False, 2254 "catalog": False, 2255 "laterals": False, 2256 "joins": False, 2257 "pivots": False, 2258 "hints": False, 2259 "system_time": False, 2260 } 2261 2262 @property 2263 def db(self) -> str: 2264 return self.text("db") 2265 2266 @property 2267 def catalog(self) -> str: 2268 return self.text("catalog") 2269 2270 @property 2271 def parts(self) -> t.List[Identifier]: 2272 """Return the parts of a table in order catalog, db, table.""" 2273 return [ 2274 t.cast(Identifier, self.args[part]) 2275 for part in ("catalog", "db", "this") 2276 if self.args.get(part) 2277 ]
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
2281class SystemTime(Expression): 2282 arg_types = { 2283 "this": False, 2284 "expression": False, 2285 "kind": True, 2286 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2289class Union(Subqueryable): 2290 arg_types = { 2291 "with": False, 2292 "this": True, 2293 "expression": True, 2294 "distinct": False, 2295 **QUERY_MODIFIERS, 2296 } 2297 2298 def limit( 2299 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2300 ) -> Select: 2301 """ 2302 Set the LIMIT expression. 2303 2304 Example: 2305 >>> select("1").union(select("1")).limit(1).sql() 2306 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2307 2308 Args: 2309 expression: the SQL code string to parse. 2310 This can also be an integer. 2311 If a `Limit` instance is passed, this is used as-is. 2312 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2313 dialect: the dialect used to parse the input expression. 2314 copy: if `False`, modify this expression instance in-place. 2315 opts: other options to use to parse the input expressions. 2316 2317 Returns: 2318 The limited subqueryable. 2319 """ 2320 return ( 2321 select("*") 2322 .from_(self.subquery(alias="_l_0", copy=copy)) 2323 .limit(expression, dialect=dialect, copy=False, **opts) 2324 ) 2325 2326 def select( 2327 self, 2328 *expressions: t.Optional[ExpOrStr], 2329 append: bool = True, 2330 dialect: DialectType = None, 2331 copy: bool = True, 2332 **opts, 2333 ) -> Union: 2334 """Append to or set the SELECT of the union recursively. 2335 2336 Example: 2337 >>> from sqlglot import parse_one 2338 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2339 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2340 2341 Args: 2342 *expressions: the SQL code strings to parse. 2343 If an `Expression` instance is passed, it will be used as-is. 2344 append: if `True`, add to any existing expressions. 2345 Otherwise, this resets the expressions. 2346 dialect: the dialect used to parse the input expressions. 2347 copy: if `False`, modify this expression instance in-place. 2348 opts: other options to use to parse the input expressions. 2349 2350 Returns: 2351 Union: the modified expression. 2352 """ 2353 this = self.copy() if copy else self 2354 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2355 this.expression.unnest().select( 2356 *expressions, append=append, dialect=dialect, copy=False, **opts 2357 ) 2358 return this 2359 2360 @property 2361 def named_selects(self): 2362 return self.this.unnest().named_selects 2363 2364 @property 2365 def is_star(self) -> bool: 2366 return self.this.is_star or self.expression.is_star 2367 2368 @property 2369 def selects(self): 2370 return self.this.unnest().selects 2371 2372 @property 2373 def left(self): 2374 return self.this 2375 2376 @property 2377 def right(self): 2378 return self.expression
2298 def limit( 2299 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2300 ) -> Select: 2301 """ 2302 Set the LIMIT expression. 2303 2304 Example: 2305 >>> select("1").union(select("1")).limit(1).sql() 2306 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2307 2308 Args: 2309 expression: the SQL code string to parse. 2310 This can also be an integer. 2311 If a `Limit` instance is passed, this is used as-is. 2312 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2313 dialect: the dialect used to parse the input expression. 2314 copy: if `False`, modify this expression instance in-place. 2315 opts: other options to use to parse the input expressions. 2316 2317 Returns: 2318 The limited subqueryable. 2319 """ 2320 return ( 2321 select("*") 2322 .from_(self.subquery(alias="_l_0", copy=copy)) 2323 .limit(expression, dialect=dialect, copy=False, **opts) 2324 )
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.
2326 def select( 2327 self, 2328 *expressions: t.Optional[ExpOrStr], 2329 append: bool = True, 2330 dialect: DialectType = None, 2331 copy: bool = True, 2332 **opts, 2333 ) -> Union: 2334 """Append to or set the SELECT of the union recursively. 2335 2336 Example: 2337 >>> from sqlglot import parse_one 2338 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2339 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2340 2341 Args: 2342 *expressions: the SQL code strings to parse. 2343 If an `Expression` instance is passed, it will be used as-is. 2344 append: if `True`, add to any existing expressions. 2345 Otherwise, this resets the expressions. 2346 dialect: the dialect used to parse the input expressions. 2347 copy: if `False`, modify this expression instance in-place. 2348 opts: other options to use to parse the input expressions. 2349 2350 Returns: 2351 Union: the modified expression. 2352 """ 2353 this = self.copy() if copy else self 2354 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2355 this.expression.unnest().select( 2356 *expressions, append=append, dialect=dialect, copy=False, **opts 2357 ) 2358 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
2389class Unnest(UDTF): 2390 arg_types = { 2391 "expressions": True, 2392 "ordinality": False, 2393 "alias": False, 2394 "offset": False, 2395 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2398class Update(Expression): 2399 arg_types = { 2400 "with": False, 2401 "this": False, 2402 "expressions": True, 2403 "from": False, 2404 "where": False, 2405 "returning": False, 2406 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2409class Values(UDTF): 2410 arg_types = { 2411 "expressions": True, 2412 "ordinality": False, 2413 "alias": False, 2414 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2431class Select(Subqueryable): 2432 arg_types = { 2433 "with": False, 2434 "kind": False, 2435 "expressions": False, 2436 "hint": False, 2437 "distinct": False, 2438 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2439 "value": False, 2440 "into": False, 2441 "from": False, 2442 **QUERY_MODIFIERS, 2443 } 2444 2445 def from_( 2446 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2447 ) -> Select: 2448 """ 2449 Set the FROM expression. 2450 2451 Example: 2452 >>> Select().from_("tbl").select("x").sql() 2453 'SELECT x FROM tbl' 2454 2455 Args: 2456 expression : the SQL code strings to parse. 2457 If a `From` instance is passed, this is used as-is. 2458 If another `Expression` instance is passed, it will be wrapped in a `From`. 2459 dialect: the dialect used to parse the input expression. 2460 copy: if `False`, modify this expression instance in-place. 2461 opts: other options to use to parse the input expressions. 2462 2463 Returns: 2464 The modified Select expression. 2465 """ 2466 return _apply_builder( 2467 expression=expression, 2468 instance=self, 2469 arg="from", 2470 into=From, 2471 prefix="FROM", 2472 dialect=dialect, 2473 copy=copy, 2474 **opts, 2475 ) 2476 2477 def group_by( 2478 self, 2479 *expressions: t.Optional[ExpOrStr], 2480 append: bool = True, 2481 dialect: DialectType = None, 2482 copy: bool = True, 2483 **opts, 2484 ) -> Select: 2485 """ 2486 Set the GROUP BY expression. 2487 2488 Example: 2489 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2490 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2491 2492 Args: 2493 *expressions: the SQL code strings to parse. 2494 If a `Group` instance is passed, this is used as-is. 2495 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2496 If nothing is passed in then a group by is not applied to the expression 2497 append: if `True`, add to any existing expressions. 2498 Otherwise, this flattens all the `Group` expression into a single expression. 2499 dialect: the dialect used to parse the input expression. 2500 copy: if `False`, modify this expression instance in-place. 2501 opts: other options to use to parse the input expressions. 2502 2503 Returns: 2504 The modified Select expression. 2505 """ 2506 if not expressions: 2507 return self if not copy else self.copy() 2508 2509 return _apply_child_list_builder( 2510 *expressions, 2511 instance=self, 2512 arg="group", 2513 append=append, 2514 copy=copy, 2515 prefix="GROUP BY", 2516 into=Group, 2517 dialect=dialect, 2518 **opts, 2519 ) 2520 2521 def order_by( 2522 self, 2523 *expressions: t.Optional[ExpOrStr], 2524 append: bool = True, 2525 dialect: DialectType = None, 2526 copy: bool = True, 2527 **opts, 2528 ) -> Select: 2529 """ 2530 Set the ORDER BY expression. 2531 2532 Example: 2533 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2534 'SELECT x FROM tbl ORDER BY x DESC' 2535 2536 Args: 2537 *expressions: the SQL code strings to parse. 2538 If a `Group` instance is passed, this is used as-is. 2539 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2540 append: if `True`, add to any existing expressions. 2541 Otherwise, this flattens all the `Order` expression into a single expression. 2542 dialect: the dialect used to parse the input expression. 2543 copy: if `False`, modify this expression instance in-place. 2544 opts: other options to use to parse the input expressions. 2545 2546 Returns: 2547 The modified Select expression. 2548 """ 2549 return _apply_child_list_builder( 2550 *expressions, 2551 instance=self, 2552 arg="order", 2553 append=append, 2554 copy=copy, 2555 prefix="ORDER BY", 2556 into=Order, 2557 dialect=dialect, 2558 **opts, 2559 ) 2560 2561 def sort_by( 2562 self, 2563 *expressions: t.Optional[ExpOrStr], 2564 append: bool = True, 2565 dialect: DialectType = None, 2566 copy: bool = True, 2567 **opts, 2568 ) -> Select: 2569 """ 2570 Set the SORT BY expression. 2571 2572 Example: 2573 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2574 'SELECT x FROM tbl SORT BY x DESC' 2575 2576 Args: 2577 *expressions: the SQL code strings to parse. 2578 If a `Group` instance is passed, this is used as-is. 2579 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2580 append: if `True`, add to any existing expressions. 2581 Otherwise, this flattens all the `Order` expression into a single expression. 2582 dialect: the dialect used to parse the input expression. 2583 copy: if `False`, modify this expression instance in-place. 2584 opts: other options to use to parse the input expressions. 2585 2586 Returns: 2587 The modified Select expression. 2588 """ 2589 return _apply_child_list_builder( 2590 *expressions, 2591 instance=self, 2592 arg="sort", 2593 append=append, 2594 copy=copy, 2595 prefix="SORT BY", 2596 into=Sort, 2597 dialect=dialect, 2598 **opts, 2599 ) 2600 2601 def cluster_by( 2602 self, 2603 *expressions: t.Optional[ExpOrStr], 2604 append: bool = True, 2605 dialect: DialectType = None, 2606 copy: bool = True, 2607 **opts, 2608 ) -> Select: 2609 """ 2610 Set the CLUSTER BY expression. 2611 2612 Example: 2613 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2614 'SELECT x FROM tbl CLUSTER BY x DESC' 2615 2616 Args: 2617 *expressions: the SQL code strings to parse. 2618 If a `Group` instance is passed, this is used as-is. 2619 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2620 append: if `True`, add to any existing expressions. 2621 Otherwise, this flattens all the `Order` expression into a single expression. 2622 dialect: the dialect used to parse the input expression. 2623 copy: if `False`, modify this expression instance in-place. 2624 opts: other options to use to parse the input expressions. 2625 2626 Returns: 2627 The modified Select expression. 2628 """ 2629 return _apply_child_list_builder( 2630 *expressions, 2631 instance=self, 2632 arg="cluster", 2633 append=append, 2634 copy=copy, 2635 prefix="CLUSTER BY", 2636 into=Cluster, 2637 dialect=dialect, 2638 **opts, 2639 ) 2640 2641 def limit( 2642 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2643 ) -> Select: 2644 """ 2645 Set the LIMIT expression. 2646 2647 Example: 2648 >>> Select().from_("tbl").select("x").limit(10).sql() 2649 'SELECT x FROM tbl LIMIT 10' 2650 2651 Args: 2652 expression: the SQL code string to parse. 2653 This can also be an integer. 2654 If a `Limit` instance is passed, this is used as-is. 2655 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2656 dialect: the dialect used to parse the input expression. 2657 copy: if `False`, modify this expression instance in-place. 2658 opts: other options to use to parse the input expressions. 2659 2660 Returns: 2661 Select: the modified expression. 2662 """ 2663 return _apply_builder( 2664 expression=expression, 2665 instance=self, 2666 arg="limit", 2667 into=Limit, 2668 prefix="LIMIT", 2669 dialect=dialect, 2670 copy=copy, 2671 **opts, 2672 ) 2673 2674 def offset( 2675 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2676 ) -> Select: 2677 """ 2678 Set the OFFSET expression. 2679 2680 Example: 2681 >>> Select().from_("tbl").select("x").offset(10).sql() 2682 'SELECT x FROM tbl OFFSET 10' 2683 2684 Args: 2685 expression: the SQL code string to parse. 2686 This can also be an integer. 2687 If a `Offset` instance is passed, this is used as-is. 2688 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2689 dialect: the dialect used to parse the input expression. 2690 copy: if `False`, modify this expression instance in-place. 2691 opts: other options to use to parse the input expressions. 2692 2693 Returns: 2694 The modified Select expression. 2695 """ 2696 return _apply_builder( 2697 expression=expression, 2698 instance=self, 2699 arg="offset", 2700 into=Offset, 2701 prefix="OFFSET", 2702 dialect=dialect, 2703 copy=copy, 2704 **opts, 2705 ) 2706 2707 def select( 2708 self, 2709 *expressions: t.Optional[ExpOrStr], 2710 append: bool = True, 2711 dialect: DialectType = None, 2712 copy: bool = True, 2713 **opts, 2714 ) -> Select: 2715 """ 2716 Append to or set the SELECT expressions. 2717 2718 Example: 2719 >>> Select().select("x", "y").sql() 2720 'SELECT x, y' 2721 2722 Args: 2723 *expressions: the SQL code strings to parse. 2724 If an `Expression` instance is passed, it will be used as-is. 2725 append: if `True`, add to any existing expressions. 2726 Otherwise, this resets the expressions. 2727 dialect: the dialect used to parse the input expressions. 2728 copy: if `False`, modify this expression instance in-place. 2729 opts: other options to use to parse the input expressions. 2730 2731 Returns: 2732 The modified Select expression. 2733 """ 2734 return _apply_list_builder( 2735 *expressions, 2736 instance=self, 2737 arg="expressions", 2738 append=append, 2739 dialect=dialect, 2740 copy=copy, 2741 **opts, 2742 ) 2743 2744 def lateral( 2745 self, 2746 *expressions: t.Optional[ExpOrStr], 2747 append: bool = True, 2748 dialect: DialectType = None, 2749 copy: bool = True, 2750 **opts, 2751 ) -> Select: 2752 """ 2753 Append to or set the LATERAL expressions. 2754 2755 Example: 2756 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2757 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2758 2759 Args: 2760 *expressions: the SQL code strings to parse. 2761 If an `Expression` instance is passed, it will be used as-is. 2762 append: if `True`, add to any existing expressions. 2763 Otherwise, this resets the expressions. 2764 dialect: the dialect used to parse the input expressions. 2765 copy: if `False`, modify this expression instance in-place. 2766 opts: other options to use to parse the input expressions. 2767 2768 Returns: 2769 The modified Select expression. 2770 """ 2771 return _apply_list_builder( 2772 *expressions, 2773 instance=self, 2774 arg="laterals", 2775 append=append, 2776 into=Lateral, 2777 prefix="LATERAL VIEW", 2778 dialect=dialect, 2779 copy=copy, 2780 **opts, 2781 ) 2782 2783 def join( 2784 self, 2785 expression: ExpOrStr, 2786 on: t.Optional[ExpOrStr] = None, 2787 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2788 append: bool = True, 2789 join_type: t.Optional[str] = None, 2790 join_alias: t.Optional[Identifier | str] = None, 2791 dialect: DialectType = None, 2792 copy: bool = True, 2793 **opts, 2794 ) -> Select: 2795 """ 2796 Append to or set the JOIN expressions. 2797 2798 Example: 2799 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2800 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2801 2802 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2803 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2804 2805 Use `join_type` to change the type of join: 2806 2807 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2808 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2809 2810 Args: 2811 expression: the SQL code string to parse. 2812 If an `Expression` instance is passed, it will be used as-is. 2813 on: optionally specify the join "on" criteria as a SQL string. 2814 If an `Expression` instance is passed, it will be used as-is. 2815 using: optionally specify the join "using" criteria as a SQL string. 2816 If an `Expression` instance is passed, it will be used as-is. 2817 append: if `True`, add to any existing expressions. 2818 Otherwise, this resets the expressions. 2819 join_type: if set, alter the parsed join type. 2820 join_alias: an optional alias for the joined source. 2821 dialect: the dialect used to parse the input expressions. 2822 copy: if `False`, modify this expression instance in-place. 2823 opts: other options to use to parse the input expressions. 2824 2825 Returns: 2826 Select: the modified expression. 2827 """ 2828 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2829 2830 try: 2831 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2832 except ParseError: 2833 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2834 2835 join = expression if isinstance(expression, Join) else Join(this=expression) 2836 2837 if isinstance(join.this, Select): 2838 join.this.replace(join.this.subquery()) 2839 2840 if join_type: 2841 method: t.Optional[Token] 2842 side: t.Optional[Token] 2843 kind: t.Optional[Token] 2844 2845 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2846 2847 if method: 2848 join.set("method", method.text) 2849 if side: 2850 join.set("side", side.text) 2851 if kind: 2852 join.set("kind", kind.text) 2853 2854 if on: 2855 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2856 join.set("on", on) 2857 2858 if using: 2859 join = _apply_list_builder( 2860 *ensure_list(using), 2861 instance=join, 2862 arg="using", 2863 append=append, 2864 copy=copy, 2865 **opts, 2866 ) 2867 2868 if join_alias: 2869 join.set("this", alias_(join.this, join_alias, table=True)) 2870 2871 return _apply_list_builder( 2872 join, 2873 instance=self, 2874 arg="joins", 2875 append=append, 2876 copy=copy, 2877 **opts, 2878 ) 2879 2880 def where( 2881 self, 2882 *expressions: t.Optional[ExpOrStr], 2883 append: bool = True, 2884 dialect: DialectType = None, 2885 copy: bool = True, 2886 **opts, 2887 ) -> Select: 2888 """ 2889 Append to or set the WHERE expressions. 2890 2891 Example: 2892 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2893 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2894 2895 Args: 2896 *expressions: the SQL code strings to parse. 2897 If an `Expression` instance is passed, it will be used as-is. 2898 Multiple expressions are combined with an AND operator. 2899 append: if `True`, AND the new expressions to any existing expression. 2900 Otherwise, this resets the expression. 2901 dialect: the dialect used to parse the input expressions. 2902 copy: if `False`, modify this expression instance in-place. 2903 opts: other options to use to parse the input expressions. 2904 2905 Returns: 2906 Select: the modified expression. 2907 """ 2908 return _apply_conjunction_builder( 2909 *expressions, 2910 instance=self, 2911 arg="where", 2912 append=append, 2913 into=Where, 2914 dialect=dialect, 2915 copy=copy, 2916 **opts, 2917 ) 2918 2919 def having( 2920 self, 2921 *expressions: t.Optional[ExpOrStr], 2922 append: bool = True, 2923 dialect: DialectType = None, 2924 copy: bool = True, 2925 **opts, 2926 ) -> Select: 2927 """ 2928 Append to or set the HAVING expressions. 2929 2930 Example: 2931 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2932 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2933 2934 Args: 2935 *expressions: the SQL code strings to parse. 2936 If an `Expression` instance is passed, it will be used as-is. 2937 Multiple expressions are combined with an AND operator. 2938 append: if `True`, AND the new expressions to any existing expression. 2939 Otherwise, this resets the expression. 2940 dialect: the dialect used to parse the input expressions. 2941 copy: if `False`, modify this expression instance in-place. 2942 opts: other options to use to parse the input expressions. 2943 2944 Returns: 2945 The modified Select expression. 2946 """ 2947 return _apply_conjunction_builder( 2948 *expressions, 2949 instance=self, 2950 arg="having", 2951 append=append, 2952 into=Having, 2953 dialect=dialect, 2954 copy=copy, 2955 **opts, 2956 ) 2957 2958 def window( 2959 self, 2960 *expressions: t.Optional[ExpOrStr], 2961 append: bool = True, 2962 dialect: DialectType = None, 2963 copy: bool = True, 2964 **opts, 2965 ) -> Select: 2966 return _apply_list_builder( 2967 *expressions, 2968 instance=self, 2969 arg="windows", 2970 append=append, 2971 into=Window, 2972 dialect=dialect, 2973 copy=copy, 2974 **opts, 2975 ) 2976 2977 def qualify( 2978 self, 2979 *expressions: t.Optional[ExpOrStr], 2980 append: bool = True, 2981 dialect: DialectType = None, 2982 copy: bool = True, 2983 **opts, 2984 ) -> Select: 2985 return _apply_conjunction_builder( 2986 *expressions, 2987 instance=self, 2988 arg="qualify", 2989 append=append, 2990 into=Qualify, 2991 dialect=dialect, 2992 copy=copy, 2993 **opts, 2994 ) 2995 2996 def distinct( 2997 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2998 ) -> Select: 2999 """ 3000 Set the OFFSET expression. 3001 3002 Example: 3003 >>> Select().from_("tbl").select("x").distinct().sql() 3004 'SELECT DISTINCT x FROM tbl' 3005 3006 Args: 3007 ons: the expressions to distinct on 3008 distinct: whether the Select should be distinct 3009 copy: if `False`, modify this expression instance in-place. 3010 3011 Returns: 3012 Select: the modified expression. 3013 """ 3014 instance = _maybe_copy(self, copy) 3015 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3016 instance.set("distinct", Distinct(on=on) if distinct else None) 3017 return instance 3018 3019 def ctas( 3020 self, 3021 table: ExpOrStr, 3022 properties: t.Optional[t.Dict] = None, 3023 dialect: DialectType = None, 3024 copy: bool = True, 3025 **opts, 3026 ) -> Create: 3027 """ 3028 Convert this expression to a CREATE TABLE AS statement. 3029 3030 Example: 3031 >>> Select().select("*").from_("tbl").ctas("x").sql() 3032 'CREATE TABLE x AS SELECT * FROM tbl' 3033 3034 Args: 3035 table: the SQL code string to parse as the table name. 3036 If another `Expression` instance is passed, it will be used as-is. 3037 properties: an optional mapping of table properties 3038 dialect: the dialect used to parse the input table. 3039 copy: if `False`, modify this expression instance in-place. 3040 opts: other options to use to parse the input table. 3041 3042 Returns: 3043 The new Create expression. 3044 """ 3045 instance = _maybe_copy(self, copy) 3046 table_expression = maybe_parse( 3047 table, 3048 into=Table, 3049 dialect=dialect, 3050 **opts, 3051 ) 3052 properties_expression = None 3053 if properties: 3054 properties_expression = Properties.from_dict(properties) 3055 3056 return Create( 3057 this=table_expression, 3058 kind="table", 3059 expression=instance, 3060 properties=properties_expression, 3061 ) 3062 3063 def lock(self, update: bool = True, copy: bool = True) -> Select: 3064 """ 3065 Set the locking read mode for this expression. 3066 3067 Examples: 3068 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3069 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3070 3071 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3072 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3073 3074 Args: 3075 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3076 copy: if `False`, modify this expression instance in-place. 3077 3078 Returns: 3079 The modified expression. 3080 """ 3081 inst = _maybe_copy(self, copy) 3082 inst.set("locks", [Lock(update=update)]) 3083 3084 return inst 3085 3086 def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select: 3087 """ 3088 Set hints for this expression. 3089 3090 Examples: 3091 >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark") 3092 'SELECT /*+ BROADCAST(y) */ x FROM tbl' 3093 3094 Args: 3095 hints: The SQL code strings to parse as the hints. 3096 If an `Expression` instance is passed, it will be used as-is. 3097 dialect: The dialect used to parse the hints. 3098 copy: If `False`, modify this expression instance in-place. 3099 3100 Returns: 3101 The modified expression. 3102 """ 3103 inst = _maybe_copy(self, copy) 3104 inst.set( 3105 "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints]) 3106 ) 3107 3108 return inst 3109 3110 @property 3111 def named_selects(self) -> t.List[str]: 3112 return [e.output_name for e in self.expressions if e.alias_or_name] 3113 3114 @property 3115 def is_star(self) -> bool: 3116 return any(expression.is_star for expression in self.expressions) 3117 3118 @property 3119 def selects(self) -> t.List[Expression]: 3120 return self.expressions
2445 def from_( 2446 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2447 ) -> Select: 2448 """ 2449 Set the FROM expression. 2450 2451 Example: 2452 >>> Select().from_("tbl").select("x").sql() 2453 'SELECT x FROM tbl' 2454 2455 Args: 2456 expression : the SQL code strings to parse. 2457 If a `From` instance is passed, this is used as-is. 2458 If another `Expression` instance is passed, it will be wrapped in a `From`. 2459 dialect: the dialect used to parse the input expression. 2460 copy: if `False`, modify this expression instance in-place. 2461 opts: other options to use to parse the input expressions. 2462 2463 Returns: 2464 The modified Select expression. 2465 """ 2466 return _apply_builder( 2467 expression=expression, 2468 instance=self, 2469 arg="from", 2470 into=From, 2471 prefix="FROM", 2472 dialect=dialect, 2473 copy=copy, 2474 **opts, 2475 )
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.
2477 def group_by( 2478 self, 2479 *expressions: t.Optional[ExpOrStr], 2480 append: bool = True, 2481 dialect: DialectType = None, 2482 copy: bool = True, 2483 **opts, 2484 ) -> Select: 2485 """ 2486 Set the GROUP BY expression. 2487 2488 Example: 2489 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2490 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2491 2492 Args: 2493 *expressions: the SQL code strings to parse. 2494 If a `Group` instance is passed, this is used as-is. 2495 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2496 If nothing is passed in then a group by is not applied to the expression 2497 append: if `True`, add to any existing expressions. 2498 Otherwise, this flattens all the `Group` expression into a single expression. 2499 dialect: the dialect used to parse the input expression. 2500 copy: if `False`, modify this expression instance in-place. 2501 opts: other options to use to parse the input expressions. 2502 2503 Returns: 2504 The modified Select expression. 2505 """ 2506 if not expressions: 2507 return self if not copy else self.copy() 2508 2509 return _apply_child_list_builder( 2510 *expressions, 2511 instance=self, 2512 arg="group", 2513 append=append, 2514 copy=copy, 2515 prefix="GROUP BY", 2516 into=Group, 2517 dialect=dialect, 2518 **opts, 2519 )
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.
2521 def order_by( 2522 self, 2523 *expressions: t.Optional[ExpOrStr], 2524 append: bool = True, 2525 dialect: DialectType = None, 2526 copy: bool = True, 2527 **opts, 2528 ) -> Select: 2529 """ 2530 Set the ORDER BY expression. 2531 2532 Example: 2533 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2534 'SELECT x FROM tbl ORDER BY x DESC' 2535 2536 Args: 2537 *expressions: the SQL code strings to parse. 2538 If a `Group` instance is passed, this is used as-is. 2539 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2540 append: if `True`, add to any existing expressions. 2541 Otherwise, this flattens all the `Order` expression into a single expression. 2542 dialect: the dialect used to parse the input expression. 2543 copy: if `False`, modify this expression instance in-place. 2544 opts: other options to use to parse the input expressions. 2545 2546 Returns: 2547 The modified Select expression. 2548 """ 2549 return _apply_child_list_builder( 2550 *expressions, 2551 instance=self, 2552 arg="order", 2553 append=append, 2554 copy=copy, 2555 prefix="ORDER BY", 2556 into=Order, 2557 dialect=dialect, 2558 **opts, 2559 )
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.
2561 def sort_by( 2562 self, 2563 *expressions: t.Optional[ExpOrStr], 2564 append: bool = True, 2565 dialect: DialectType = None, 2566 copy: bool = True, 2567 **opts, 2568 ) -> Select: 2569 """ 2570 Set the SORT BY expression. 2571 2572 Example: 2573 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2574 'SELECT x FROM tbl SORT BY x DESC' 2575 2576 Args: 2577 *expressions: the SQL code strings to parse. 2578 If a `Group` instance is passed, this is used as-is. 2579 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2580 append: if `True`, add to any existing expressions. 2581 Otherwise, this flattens all the `Order` expression into a single expression. 2582 dialect: the dialect used to parse the input expression. 2583 copy: if `False`, modify this expression instance in-place. 2584 opts: other options to use to parse the input expressions. 2585 2586 Returns: 2587 The modified Select expression. 2588 """ 2589 return _apply_child_list_builder( 2590 *expressions, 2591 instance=self, 2592 arg="sort", 2593 append=append, 2594 copy=copy, 2595 prefix="SORT BY", 2596 into=Sort, 2597 dialect=dialect, 2598 **opts, 2599 )
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.
2601 def cluster_by( 2602 self, 2603 *expressions: t.Optional[ExpOrStr], 2604 append: bool = True, 2605 dialect: DialectType = None, 2606 copy: bool = True, 2607 **opts, 2608 ) -> Select: 2609 """ 2610 Set the CLUSTER BY expression. 2611 2612 Example: 2613 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2614 'SELECT x FROM tbl CLUSTER BY x DESC' 2615 2616 Args: 2617 *expressions: the SQL code strings to parse. 2618 If a `Group` instance is passed, this is used as-is. 2619 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2620 append: if `True`, add to any existing expressions. 2621 Otherwise, this flattens all the `Order` expression into a single expression. 2622 dialect: the dialect used to parse the input expression. 2623 copy: if `False`, modify this expression instance in-place. 2624 opts: other options to use to parse the input expressions. 2625 2626 Returns: 2627 The modified Select expression. 2628 """ 2629 return _apply_child_list_builder( 2630 *expressions, 2631 instance=self, 2632 arg="cluster", 2633 append=append, 2634 copy=copy, 2635 prefix="CLUSTER BY", 2636 into=Cluster, 2637 dialect=dialect, 2638 **opts, 2639 )
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.
2641 def limit( 2642 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2643 ) -> Select: 2644 """ 2645 Set the LIMIT expression. 2646 2647 Example: 2648 >>> Select().from_("tbl").select("x").limit(10).sql() 2649 'SELECT x FROM tbl LIMIT 10' 2650 2651 Args: 2652 expression: the SQL code string to parse. 2653 This can also be an integer. 2654 If a `Limit` instance is passed, this is used as-is. 2655 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2656 dialect: the dialect used to parse the input expression. 2657 copy: if `False`, modify this expression instance in-place. 2658 opts: other options to use to parse the input expressions. 2659 2660 Returns: 2661 Select: the modified expression. 2662 """ 2663 return _apply_builder( 2664 expression=expression, 2665 instance=self, 2666 arg="limit", 2667 into=Limit, 2668 prefix="LIMIT", 2669 dialect=dialect, 2670 copy=copy, 2671 **opts, 2672 )
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.
2674 def offset( 2675 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2676 ) -> Select: 2677 """ 2678 Set the OFFSET expression. 2679 2680 Example: 2681 >>> Select().from_("tbl").select("x").offset(10).sql() 2682 'SELECT x FROM tbl OFFSET 10' 2683 2684 Args: 2685 expression: the SQL code string to parse. 2686 This can also be an integer. 2687 If a `Offset` instance is passed, this is used as-is. 2688 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2689 dialect: the dialect used to parse the input expression. 2690 copy: if `False`, modify this expression instance in-place. 2691 opts: other options to use to parse the input expressions. 2692 2693 Returns: 2694 The modified Select expression. 2695 """ 2696 return _apply_builder( 2697 expression=expression, 2698 instance=self, 2699 arg="offset", 2700 into=Offset, 2701 prefix="OFFSET", 2702 dialect=dialect, 2703 copy=copy, 2704 **opts, 2705 )
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.
2707 def select( 2708 self, 2709 *expressions: t.Optional[ExpOrStr], 2710 append: bool = True, 2711 dialect: DialectType = None, 2712 copy: bool = True, 2713 **opts, 2714 ) -> Select: 2715 """ 2716 Append to or set the SELECT expressions. 2717 2718 Example: 2719 >>> Select().select("x", "y").sql() 2720 'SELECT x, y' 2721 2722 Args: 2723 *expressions: the SQL code strings to parse. 2724 If an `Expression` instance is passed, it will be used as-is. 2725 append: if `True`, add to any existing expressions. 2726 Otherwise, this resets the expressions. 2727 dialect: the dialect used to parse the input expressions. 2728 copy: if `False`, modify this expression instance in-place. 2729 opts: other options to use to parse the input expressions. 2730 2731 Returns: 2732 The modified Select expression. 2733 """ 2734 return _apply_list_builder( 2735 *expressions, 2736 instance=self, 2737 arg="expressions", 2738 append=append, 2739 dialect=dialect, 2740 copy=copy, 2741 **opts, 2742 )
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.
2744 def lateral( 2745 self, 2746 *expressions: t.Optional[ExpOrStr], 2747 append: bool = True, 2748 dialect: DialectType = None, 2749 copy: bool = True, 2750 **opts, 2751 ) -> Select: 2752 """ 2753 Append to or set the LATERAL expressions. 2754 2755 Example: 2756 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2757 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2758 2759 Args: 2760 *expressions: the SQL code strings to parse. 2761 If an `Expression` instance is passed, it will be used as-is. 2762 append: if `True`, add to any existing expressions. 2763 Otherwise, this resets the expressions. 2764 dialect: the dialect used to parse the input expressions. 2765 copy: if `False`, modify this expression instance in-place. 2766 opts: other options to use to parse the input expressions. 2767 2768 Returns: 2769 The modified Select expression. 2770 """ 2771 return _apply_list_builder( 2772 *expressions, 2773 instance=self, 2774 arg="laterals", 2775 append=append, 2776 into=Lateral, 2777 prefix="LATERAL VIEW", 2778 dialect=dialect, 2779 copy=copy, 2780 **opts, 2781 )
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.
2783 def join( 2784 self, 2785 expression: ExpOrStr, 2786 on: t.Optional[ExpOrStr] = None, 2787 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2788 append: bool = True, 2789 join_type: t.Optional[str] = None, 2790 join_alias: t.Optional[Identifier | str] = None, 2791 dialect: DialectType = None, 2792 copy: bool = True, 2793 **opts, 2794 ) -> Select: 2795 """ 2796 Append to or set the JOIN expressions. 2797 2798 Example: 2799 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2800 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2801 2802 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2803 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2804 2805 Use `join_type` to change the type of join: 2806 2807 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2808 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2809 2810 Args: 2811 expression: the SQL code string to parse. 2812 If an `Expression` instance is passed, it will be used as-is. 2813 on: optionally specify the join "on" criteria as a SQL string. 2814 If an `Expression` instance is passed, it will be used as-is. 2815 using: optionally specify the join "using" criteria as a SQL string. 2816 If an `Expression` instance is passed, it will be used as-is. 2817 append: if `True`, add to any existing expressions. 2818 Otherwise, this resets the expressions. 2819 join_type: if set, alter the parsed join type. 2820 join_alias: an optional alias for the joined source. 2821 dialect: the dialect used to parse the input expressions. 2822 copy: if `False`, modify this expression instance in-place. 2823 opts: other options to use to parse the input expressions. 2824 2825 Returns: 2826 Select: the modified expression. 2827 """ 2828 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2829 2830 try: 2831 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2832 except ParseError: 2833 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2834 2835 join = expression if isinstance(expression, Join) else Join(this=expression) 2836 2837 if isinstance(join.this, Select): 2838 join.this.replace(join.this.subquery()) 2839 2840 if join_type: 2841 method: t.Optional[Token] 2842 side: t.Optional[Token] 2843 kind: t.Optional[Token] 2844 2845 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2846 2847 if method: 2848 join.set("method", method.text) 2849 if side: 2850 join.set("side", side.text) 2851 if kind: 2852 join.set("kind", kind.text) 2853 2854 if on: 2855 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2856 join.set("on", on) 2857 2858 if using: 2859 join = _apply_list_builder( 2860 *ensure_list(using), 2861 instance=join, 2862 arg="using", 2863 append=append, 2864 copy=copy, 2865 **opts, 2866 ) 2867 2868 if join_alias: 2869 join.set("this", alias_(join.this, join_alias, table=True)) 2870 2871 return _apply_list_builder( 2872 join, 2873 instance=self, 2874 arg="joins", 2875 append=append, 2876 copy=copy, 2877 **opts, 2878 )
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.
2880 def where( 2881 self, 2882 *expressions: t.Optional[ExpOrStr], 2883 append: bool = True, 2884 dialect: DialectType = None, 2885 copy: bool = True, 2886 **opts, 2887 ) -> Select: 2888 """ 2889 Append to or set the WHERE expressions. 2890 2891 Example: 2892 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2893 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2894 2895 Args: 2896 *expressions: the SQL code strings to parse. 2897 If an `Expression` instance is passed, it will be used as-is. 2898 Multiple expressions are combined with an AND operator. 2899 append: if `True`, AND the new expressions to any existing expression. 2900 Otherwise, this resets the expression. 2901 dialect: the dialect used to parse the input expressions. 2902 copy: if `False`, modify this expression instance in-place. 2903 opts: other options to use to parse the input expressions. 2904 2905 Returns: 2906 Select: the modified expression. 2907 """ 2908 return _apply_conjunction_builder( 2909 *expressions, 2910 instance=self, 2911 arg="where", 2912 append=append, 2913 into=Where, 2914 dialect=dialect, 2915 copy=copy, 2916 **opts, 2917 )
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.
2919 def having( 2920 self, 2921 *expressions: t.Optional[ExpOrStr], 2922 append: bool = True, 2923 dialect: DialectType = None, 2924 copy: bool = True, 2925 **opts, 2926 ) -> Select: 2927 """ 2928 Append to or set the HAVING expressions. 2929 2930 Example: 2931 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2932 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2933 2934 Args: 2935 *expressions: the SQL code strings to parse. 2936 If an `Expression` instance is passed, it will be used as-is. 2937 Multiple expressions are combined with an AND operator. 2938 append: if `True`, AND the new expressions to any existing expression. 2939 Otherwise, this resets the expression. 2940 dialect: the dialect used to parse the input expressions. 2941 copy: if `False`, modify this expression instance in-place. 2942 opts: other options to use to parse the input expressions. 2943 2944 Returns: 2945 The modified Select expression. 2946 """ 2947 return _apply_conjunction_builder( 2948 *expressions, 2949 instance=self, 2950 arg="having", 2951 append=append, 2952 into=Having, 2953 dialect=dialect, 2954 copy=copy, 2955 **opts, 2956 )
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.
2958 def window( 2959 self, 2960 *expressions: t.Optional[ExpOrStr], 2961 append: bool = True, 2962 dialect: DialectType = None, 2963 copy: bool = True, 2964 **opts, 2965 ) -> Select: 2966 return _apply_list_builder( 2967 *expressions, 2968 instance=self, 2969 arg="windows", 2970 append=append, 2971 into=Window, 2972 dialect=dialect, 2973 copy=copy, 2974 **opts, 2975 )
2977 def qualify( 2978 self, 2979 *expressions: t.Optional[ExpOrStr], 2980 append: bool = True, 2981 dialect: DialectType = None, 2982 copy: bool = True, 2983 **opts, 2984 ) -> Select: 2985 return _apply_conjunction_builder( 2986 *expressions, 2987 instance=self, 2988 arg="qualify", 2989 append=append, 2990 into=Qualify, 2991 dialect=dialect, 2992 copy=copy, 2993 **opts, 2994 )
2996 def distinct( 2997 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2998 ) -> Select: 2999 """ 3000 Set the OFFSET expression. 3001 3002 Example: 3003 >>> Select().from_("tbl").select("x").distinct().sql() 3004 'SELECT DISTINCT x FROM tbl' 3005 3006 Args: 3007 ons: the expressions to distinct on 3008 distinct: whether the Select should be distinct 3009 copy: if `False`, modify this expression instance in-place. 3010 3011 Returns: 3012 Select: the modified expression. 3013 """ 3014 instance = _maybe_copy(self, copy) 3015 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3016 instance.set("distinct", Distinct(on=on) if distinct else None) 3017 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.
3019 def ctas( 3020 self, 3021 table: ExpOrStr, 3022 properties: t.Optional[t.Dict] = None, 3023 dialect: DialectType = None, 3024 copy: bool = True, 3025 **opts, 3026 ) -> Create: 3027 """ 3028 Convert this expression to a CREATE TABLE AS statement. 3029 3030 Example: 3031 >>> Select().select("*").from_("tbl").ctas("x").sql() 3032 'CREATE TABLE x AS SELECT * FROM tbl' 3033 3034 Args: 3035 table: the SQL code string to parse as the table name. 3036 If another `Expression` instance is passed, it will be used as-is. 3037 properties: an optional mapping of table properties 3038 dialect: the dialect used to parse the input table. 3039 copy: if `False`, modify this expression instance in-place. 3040 opts: other options to use to parse the input table. 3041 3042 Returns: 3043 The new Create expression. 3044 """ 3045 instance = _maybe_copy(self, copy) 3046 table_expression = maybe_parse( 3047 table, 3048 into=Table, 3049 dialect=dialect, 3050 **opts, 3051 ) 3052 properties_expression = None 3053 if properties: 3054 properties_expression = Properties.from_dict(properties) 3055 3056 return Create( 3057 this=table_expression, 3058 kind="table", 3059 expression=instance, 3060 properties=properties_expression, 3061 )
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.
3063 def lock(self, update: bool = True, copy: bool = True) -> Select: 3064 """ 3065 Set the locking read mode for this expression. 3066 3067 Examples: 3068 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3069 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3070 3071 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3072 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3073 3074 Args: 3075 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3076 copy: if `False`, modify this expression instance in-place. 3077 3078 Returns: 3079 The modified expression. 3080 """ 3081 inst = _maybe_copy(self, copy) 3082 inst.set("locks", [Lock(update=update)]) 3083 3084 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.
3086 def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select: 3087 """ 3088 Set hints for this expression. 3089 3090 Examples: 3091 >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark") 3092 'SELECT /*+ BROADCAST(y) */ x FROM tbl' 3093 3094 Args: 3095 hints: The SQL code strings to parse as the hints. 3096 If an `Expression` instance is passed, it will be used as-is. 3097 dialect: The dialect used to parse the hints. 3098 copy: If `False`, modify this expression instance in-place. 3099 3100 Returns: 3101 The modified expression. 3102 """ 3103 inst = _maybe_copy(self, copy) 3104 inst.set( 3105 "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints]) 3106 ) 3107 3108 return inst
Set hints for this expression.
Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark") 'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
- hints: The SQL code strings to parse as the hints.
If an
Expression
instance is passed, it will be used as-is. - dialect: The dialect used to parse the hints.
- copy: If
False
, modify this expression instance in-place.
Returns:
The modified expression.
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
3123class Subquery(DerivedTable, Unionable): 3124 arg_types = { 3125 "this": True, 3126 "alias": False, 3127 "with": False, 3128 **QUERY_MODIFIERS, 3129 } 3130 3131 def unnest(self): 3132 """ 3133 Returns the first non subquery. 3134 """ 3135 expression = self 3136 while isinstance(expression, Subquery): 3137 expression = expression.this 3138 return expression 3139 3140 @property 3141 def is_star(self) -> bool: 3142 return self.this.is_star 3143 3144 @property 3145 def output_name(self) -> str: 3146 return self.alias
3131 def unnest(self): 3132 """ 3133 Returns the first non subquery. 3134 """ 3135 expression = self 3136 while isinstance(expression, Subquery): 3137 expression = expression.this 3138 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
3149class TableSample(Expression): 3150 arg_types = { 3151 "this": False, 3152 "method": False, 3153 "bucket_numerator": False, 3154 "bucket_denominator": False, 3155 "bucket_field": False, 3156 "percent": False, 3157 "rows": False, 3158 "size": False, 3159 "seed": False, 3160 "kind": False, 3161 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3164class Tag(Expression): 3165 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3166 3167 arg_types = { 3168 "this": False, 3169 "prefix": False, 3170 "postfix": False, 3171 }
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
3176class Pivot(Expression): 3177 arg_types = { 3178 "this": False, 3179 "alias": False, 3180 "expressions": True, 3181 "field": False, 3182 "unpivot": False, 3183 "using": False, 3184 "group": False, 3185 "columns": False, 3186 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3189class Window(Expression): 3190 arg_types = { 3191 "this": True, 3192 "partition_by": False, 3193 "order": False, 3194 "spec": False, 3195 "alias": False, 3196 "over": False, 3197 "first": False, 3198 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3201class WindowSpec(Expression): 3202 arg_types = { 3203 "kind": False, 3204 "start": False, 3205 "start_side": False, 3206 "end": False, 3207 "end_side": False, 3208 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3215class Star(Expression): 3216 arg_types = {"except": False, "replace": False} 3217 3218 @property 3219 def name(self) -> str: 3220 return "*" 3221 3222 @property 3223 def output_name(self) -> str: 3224 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
3239class Null(Condition): 3240 arg_types: t.Dict[str, t.Any] = {} 3241 3242 @property 3243 def name(self) -> str: 3244 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
3255class DataType(Expression): 3256 arg_types = { 3257 "this": True, 3258 "expressions": False, 3259 "nested": False, 3260 "values": False, 3261 "prefix": False, 3262 } 3263 3264 class Type(AutoName): 3265 ARRAY = auto() 3266 BIGDECIMAL = auto() 3267 BIGINT = auto() 3268 BIGSERIAL = auto() 3269 BINARY = auto() 3270 BIT = auto() 3271 BOOLEAN = auto() 3272 CHAR = auto() 3273 DATE = auto() 3274 DATETIME = auto() 3275 DATETIME64 = auto() 3276 ENUM = auto() 3277 INT4RANGE = auto() 3278 INT4MULTIRANGE = auto() 3279 INT8RANGE = auto() 3280 INT8MULTIRANGE = auto() 3281 NUMRANGE = auto() 3282 NUMMULTIRANGE = auto() 3283 TSRANGE = auto() 3284 TSMULTIRANGE = auto() 3285 TSTZRANGE = auto() 3286 TSTZMULTIRANGE = auto() 3287 DATERANGE = auto() 3288 DATEMULTIRANGE = auto() 3289 DECIMAL = auto() 3290 DOUBLE = auto() 3291 FLOAT = auto() 3292 GEOGRAPHY = auto() 3293 GEOMETRY = auto() 3294 HLLSKETCH = auto() 3295 HSTORE = auto() 3296 IMAGE = auto() 3297 INET = auto() 3298 INT = auto() 3299 INT128 = auto() 3300 INT256 = auto() 3301 INTERVAL = auto() 3302 JSON = auto() 3303 JSONB = auto() 3304 LONGBLOB = auto() 3305 LONGTEXT = auto() 3306 MAP = auto() 3307 MEDIUMBLOB = auto() 3308 MEDIUMTEXT = auto() 3309 MONEY = auto() 3310 NCHAR = auto() 3311 NULL = auto() 3312 NULLABLE = auto() 3313 NVARCHAR = auto() 3314 OBJECT = auto() 3315 ROWVERSION = auto() 3316 SERIAL = auto() 3317 SET = auto() 3318 SMALLINT = auto() 3319 SMALLMONEY = auto() 3320 SMALLSERIAL = auto() 3321 STRUCT = auto() 3322 SUPER = auto() 3323 TEXT = auto() 3324 TIME = auto() 3325 TIMESTAMP = auto() 3326 TIMESTAMPTZ = auto() 3327 TIMESTAMPLTZ = auto() 3328 TINYINT = auto() 3329 UBIGINT = auto() 3330 UINT = auto() 3331 USMALLINT = auto() 3332 UTINYINT = auto() 3333 UNKNOWN = auto() # Sentinel value, useful for type annotation 3334 UINT128 = auto() 3335 UINT256 = auto() 3336 UNIQUEIDENTIFIER = auto() 3337 UUID = auto() 3338 VARBINARY = auto() 3339 VARCHAR = auto() 3340 VARIANT = auto() 3341 XML = auto() 3342 3343 TEXT_TYPES = { 3344 Type.CHAR, 3345 Type.NCHAR, 3346 Type.VARCHAR, 3347 Type.NVARCHAR, 3348 Type.TEXT, 3349 } 3350 3351 INTEGER_TYPES = { 3352 Type.INT, 3353 Type.TINYINT, 3354 Type.SMALLINT, 3355 Type.BIGINT, 3356 Type.INT128, 3357 Type.INT256, 3358 } 3359 3360 FLOAT_TYPES = { 3361 Type.FLOAT, 3362 Type.DOUBLE, 3363 } 3364 3365 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3366 3367 TEMPORAL_TYPES = { 3368 Type.TIME, 3369 Type.TIMESTAMP, 3370 Type.TIMESTAMPTZ, 3371 Type.TIMESTAMPLTZ, 3372 Type.DATE, 3373 Type.DATETIME, 3374 Type.DATETIME64, 3375 } 3376 3377 META_TYPES = {"UNKNOWN", "NULL"} 3378 3379 @classmethod 3380 def build( 3381 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3382 ) -> DataType: 3383 from sqlglot import parse_one 3384 3385 if isinstance(dtype, str): 3386 upper = dtype.upper() 3387 if upper in DataType.META_TYPES: 3388 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper]) 3389 else: 3390 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3391 3392 if data_type_exp is None: 3393 raise ValueError(f"Unparsable data type value: {dtype}") 3394 elif isinstance(dtype, DataType.Type): 3395 data_type_exp = DataType(this=dtype) 3396 elif isinstance(dtype, DataType): 3397 return dtype 3398 else: 3399 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3400 3401 return DataType(**{**data_type_exp.args, **kwargs}) 3402 3403 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3404 return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3379 @classmethod 3380 def build( 3381 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3382 ) -> DataType: 3383 from sqlglot import parse_one 3384 3385 if isinstance(dtype, str): 3386 upper = dtype.upper() 3387 if upper in DataType.META_TYPES: 3388 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper]) 3389 else: 3390 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3391 3392 if data_type_exp is None: 3393 raise ValueError(f"Unparsable data type value: {dtype}") 3394 elif isinstance(dtype, DataType.Type): 3395 data_type_exp = DataType(this=dtype) 3396 elif isinstance(dtype, DataType): 3397 return dtype 3398 else: 3399 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3400 3401 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
3264 class Type(AutoName): 3265 ARRAY = auto() 3266 BIGDECIMAL = auto() 3267 BIGINT = auto() 3268 BIGSERIAL = auto() 3269 BINARY = auto() 3270 BIT = auto() 3271 BOOLEAN = auto() 3272 CHAR = auto() 3273 DATE = auto() 3274 DATETIME = auto() 3275 DATETIME64 = auto() 3276 ENUM = auto() 3277 INT4RANGE = auto() 3278 INT4MULTIRANGE = auto() 3279 INT8RANGE = auto() 3280 INT8MULTIRANGE = auto() 3281 NUMRANGE = auto() 3282 NUMMULTIRANGE = auto() 3283 TSRANGE = auto() 3284 TSMULTIRANGE = auto() 3285 TSTZRANGE = auto() 3286 TSTZMULTIRANGE = auto() 3287 DATERANGE = auto() 3288 DATEMULTIRANGE = auto() 3289 DECIMAL = auto() 3290 DOUBLE = auto() 3291 FLOAT = auto() 3292 GEOGRAPHY = auto() 3293 GEOMETRY = auto() 3294 HLLSKETCH = auto() 3295 HSTORE = auto() 3296 IMAGE = auto() 3297 INET = auto() 3298 INT = auto() 3299 INT128 = auto() 3300 INT256 = auto() 3301 INTERVAL = auto() 3302 JSON = auto() 3303 JSONB = auto() 3304 LONGBLOB = auto() 3305 LONGTEXT = auto() 3306 MAP = auto() 3307 MEDIUMBLOB = auto() 3308 MEDIUMTEXT = auto() 3309 MONEY = auto() 3310 NCHAR = auto() 3311 NULL = auto() 3312 NULLABLE = auto() 3313 NVARCHAR = auto() 3314 OBJECT = auto() 3315 ROWVERSION = auto() 3316 SERIAL = auto() 3317 SET = auto() 3318 SMALLINT = auto() 3319 SMALLMONEY = auto() 3320 SMALLSERIAL = auto() 3321 STRUCT = auto() 3322 SUPER = auto() 3323 TEXT = auto() 3324 TIME = auto() 3325 TIMESTAMP = auto() 3326 TIMESTAMPTZ = auto() 3327 TIMESTAMPLTZ = auto() 3328 TINYINT = auto() 3329 UBIGINT = auto() 3330 UINT = auto() 3331 USMALLINT = auto() 3332 UTINYINT = auto() 3333 UNKNOWN = auto() # Sentinel value, useful for type annotation 3334 UINT128 = auto() 3335 UINT256 = auto() 3336 UNIQUEIDENTIFIER = auto() 3337 UUID = auto() 3338 VARBINARY = auto() 3339 VARCHAR = auto() 3340 VARIANT = auto() 3341 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
3451class AddConstraint(Expression): 3452 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
3460class Binary(Condition): 3461 arg_types = {"this": True, "expression": True} 3462 3463 @property 3464 def left(self): 3465 return self.this 3466 3467 @property 3468 def right(self): 3469 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
3516class Dot(Binary): 3517 @property 3518 def name(self) -> str: 3519 return self.expression.name 3520 3521 @property 3522 def output_name(self) -> str: 3523 return self.name 3524 3525 @classmethod 3526 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3527 """Build a Dot object with a sequence of expressions.""" 3528 if len(expressions) < 2: 3529 raise ValueError(f"Dot requires >= 2 expressions.") 3530 3531 a, b, *expressions = expressions 3532 dot = Dot(this=a, expression=b) 3533 3534 for expression in expressions: 3535 dot = Dot(this=dot, expression=expression) 3536 3537 return dot
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 ''
3525 @classmethod 3526 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3527 """Build a Dot object with a sequence of expressions.""" 3528 if len(expressions) < 2: 3529 raise ValueError(f"Dot requires >= 2 expressions.") 3530 3531 a, b, *expressions = expressions 3532 dot = Dot(this=a, expression=b) 3533 3534 for expression in expressions: 3535 dot = Dot(this=dot, expression=expression) 3536 3537 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
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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
3658class Paren(Unary): 3659 arg_types = {"this": True, "with": False} 3660 3661 @property 3662 def output_name(self) -> str: 3663 return self.this.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
3670class Alias(Expression): 3671 arg_types = {"this": True, "alias": False} 3672 3673 @property 3674 def output_name(self) -> str: 3675 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
3678class Aliases(Expression): 3679 arg_types = {"this": True, "expressions": True} 3680 3681 @property 3682 def aliases(self): 3683 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
3702class In(Predicate): 3703 arg_types = { 3704 "this": True, 3705 "expressions": False, 3706 "query": False, 3707 "unnest": False, 3708 "field": False, 3709 "is_global": False, 3710 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3713class TimeUnit(Expression): 3714 """Automatically converts unit arg into a var.""" 3715 3716 arg_types = {"unit": False} 3717 3718 def __init__(self, **args): 3719 unit = args.get("unit") 3720 if isinstance(unit, (Column, Literal)): 3721 args["unit"] = Var(this=unit.name) 3722 elif isinstance(unit, Week): 3723 unit.set("this", Var(this=unit.this.name)) 3724 3725 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
3728class Interval(TimeUnit): 3729 arg_types = {"this": False, "unit": False} 3730 3731 @property 3732 def unit(self) -> t.Optional[Var]: 3733 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
3745class Func(Condition): 3746 """ 3747 The base class for all function expressions. 3748 3749 Attributes: 3750 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3751 treated as a variable length argument and the argument's value will be stored as a list. 3752 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3753 for this function expression. These values are used to map this node to a name during parsing 3754 as well as to provide the function's name during SQL string generation. By default the SQL 3755 name is set to the expression's class name transformed to snake case. 3756 """ 3757 3758 is_var_len_args = False 3759 3760 @classmethod 3761 def from_arg_list(cls, args): 3762 if cls.is_var_len_args: 3763 all_arg_keys = list(cls.arg_types) 3764 # If this function supports variable length argument treat the last argument as such. 3765 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3766 num_non_var = len(non_var_len_arg_keys) 3767 3768 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3769 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3770 else: 3771 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3772 3773 return cls(**args_dict) 3774 3775 @classmethod 3776 def sql_names(cls): 3777 if cls is Func: 3778 raise NotImplementedError( 3779 "SQL name is only supported by concrete function implementations" 3780 ) 3781 if "_sql_names" not in cls.__dict__: 3782 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3783 return cls._sql_names 3784 3785 @classmethod 3786 def sql_name(cls): 3787 return cls.sql_names()[0] 3788 3789 @classmethod 3790 def default_parser_mappings(cls): 3791 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.
3760 @classmethod 3761 def from_arg_list(cls, args): 3762 if cls.is_var_len_args: 3763 all_arg_keys = list(cls.arg_types) 3764 # If this function supports variable length argument treat the last argument as such. 3765 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3766 num_non_var = len(non_var_len_arg_keys) 3767 3768 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3769 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3770 else: 3771 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3772 3773 return cls(**args_dict)
3775 @classmethod 3776 def sql_names(cls): 3777 if cls is Func: 3778 raise NotImplementedError( 3779 "SQL name is only supported by concrete function implementations" 3780 ) 3781 if "_sql_names" not in cls.__dict__: 3782 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3783 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
3798class ParameterizedAgg(AggFunc): 3799 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
3806class Anonymous(Func): 3807 arg_types = {"this": True, "expressions": False} 3808 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
3813class Hll(AggFunc): 3814 arg_types = {"this": True, "expressions": False} 3815 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
3818class ApproxDistinct(AggFunc): 3819 arg_types = {"this": True, "accuracy": False} 3820 _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
3849class ArrayConcat(Func): 3850 arg_types = {"this": True, "expressions": False} 3851 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
3862class ArrayFilter(Func): 3863 arg_types = {"this": True, "expression": True} 3864 _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
3895class Case(Func): 3896 arg_types = {"this": False, "ifs": True, "default": False} 3897 3898 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3899 instance = _maybe_copy(self, copy) 3900 instance.append( 3901 "ifs", 3902 If( 3903 this=maybe_parse(condition, copy=copy, **opts), 3904 true=maybe_parse(then, copy=copy, **opts), 3905 ), 3906 ) 3907 return instance 3908 3909 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3910 instance = _maybe_copy(self, copy) 3911 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3912 return instance
3898 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3899 instance = _maybe_copy(self, copy) 3900 instance.append( 3901 "ifs", 3902 If( 3903 this=maybe_parse(condition, copy=copy, **opts), 3904 true=maybe_parse(then, copy=copy, **opts), 3905 ), 3906 ) 3907 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
3915class Cast(Func): 3916 arg_types = {"this": True, "to": True} 3917 3918 @property 3919 def name(self) -> str: 3920 return self.this.name 3921 3922 @property 3923 def to(self) -> DataType: 3924 return self.args["to"] 3925 3926 @property 3927 def output_name(self) -> str: 3928 return self.name 3929 3930 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3931 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
3946class Ceil(Func): 3947 arg_types = {"this": True, "decimals": False} 3948 _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
3951class Coalesce(Func): 3952 arg_types = {"this": True, "expressions": False} 3953 is_var_len_args = True 3954 _sql_names = ["COALESCE", "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
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3970class Count(AggFunc): 3971 arg_types = {"this": False, "expressions": False} 3972 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
3999class DateAdd(Func, TimeUnit): 4000 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
4003class DateSub(Func, TimeUnit): 4004 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
4007class DateDiff(Func, TimeUnit): 4008 _sql_names = ["DATEDIFF", "DATE_DIFF"] 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
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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 DatetimeAdd(Func, TimeUnit): 4017 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
4020class DatetimeSub(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 DatetimeDiff(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 DatetimeTrunc(Func, TimeUnit): 4029 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
4056class TimestampAdd(Func, TimeUnit): 4057 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
4060class TimestampSub(Func, TimeUnit): 4061 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
4064class TimestampDiff(Func, TimeUnit): 4065 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
4068class TimestampTrunc(Func, TimeUnit): 4069 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
4072class TimeAdd(Func, TimeUnit): 4073 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
4076class TimeSub(Func, TimeUnit): 4077 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
4080class TimeDiff(Func, TimeUnit): 4081 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
4088class DateFromParts(Func): 4089 _sql_names = ["DATEFROMPARTS"] 4090 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
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4146class Greatest(Func): 4147 arg_types = {"this": True, "expressions": False} 4148 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
4171class JSONObject(Func): 4172 arg_types = { 4173 "expressions": False, 4174 "null_handling": False, 4175 "unique_keys": False, 4176 "return_type": False, 4177 "format_json": False, 4178 "encoding": False, 4179 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4182class OpenJSONColumnDef(Expression): 4183 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
4210class JSONFormat(Func): 4211 arg_types = {"this": False, "options": False} 4212 _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
4232class Levenshtein(Func): 4233 arg_types = { 4234 "this": True, 4235 "expression": False, 4236 "ins_cost": False, 4237 "del_cost": False, 4238 "sub_cost": False, 4239 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4278class VarMap(Func): 4279 arg_types = {"keys": True, "values": True} 4280 is_var_len_args = True 4281 4282 @property 4283 def keys(self) -> t.List[Expression]: 4284 return self.args["keys"].expressions 4285 4286 @property 4287 def values(self) -> t.List[Expression]: 4288 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
4292class MatchAgainst(Func): 4293 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
4296class Max(AggFunc): 4297 arg_types = {"this": True, "expressions": False} 4298 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
4305class Min(AggFunc): 4306 arg_types = {"this": True, "expressions": False} 4307 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
4338class ApproxQuantile(Quantile): 4339 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
4346class ReadCSV(Func): 4347 _sql_names = ["READ_CSV"] 4348 is_var_len_args = True 4349 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
4352class Reduce(Func): 4353 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
4356class RegexpExtract(Func): 4357 arg_types = { 4358 "this": True, 4359 "expression": True, 4360 "position": False, 4361 "occurrence": False, 4362 "group": False, 4363 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4427class StrPosition(Func): 4428 arg_types = { 4429 "this": True, 4430 "substr": True, 4431 "position": False, 4432 "instance": False, 4433 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4511class Trim(Func): 4512 arg_types = { 4513 "this": True, 4514 "expression": False, 4515 "position": False, 4516 "collation": False, 4517 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4520class TsOrDsAdd(Func, TimeUnit): 4521 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
4546class UnixToTime(Func): 4547 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4548 4549 SECONDS = Literal.string("seconds") 4550 MILLIS = Literal.string("millis") 4551 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
4574class XMLTable(Func): 4575 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
4586class Merge(Expression): 4587 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
4590class When(Func): 4591 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
4634def maybe_parse( 4635 sql_or_expression: ExpOrStr, 4636 *, 4637 into: t.Optional[IntoType] = None, 4638 dialect: DialectType = None, 4639 prefix: t.Optional[str] = None, 4640 copy: bool = False, 4641 **opts, 4642) -> Expression: 4643 """Gracefully handle a possible string or expression. 4644 4645 Example: 4646 >>> maybe_parse("1") 4647 (LITERAL this: 1, is_string: False) 4648 >>> maybe_parse(to_identifier("x")) 4649 (IDENTIFIER this: x, quoted: False) 4650 4651 Args: 4652 sql_or_expression: the SQL code string or an expression 4653 into: the SQLGlot Expression to parse into 4654 dialect: the dialect used to parse the input expressions (in the case that an 4655 input expression is a SQL string). 4656 prefix: a string to prefix the sql with before it gets parsed 4657 (automatically includes a space) 4658 copy: whether or not to copy the expression. 4659 **opts: other options to use to parse the input expressions (again, in the case 4660 that an input expression is a SQL string). 4661 4662 Returns: 4663 Expression: the parsed or given expression. 4664 """ 4665 if isinstance(sql_or_expression, Expression): 4666 if copy: 4667 return sql_or_expression.copy() 4668 return sql_or_expression 4669 4670 if sql_or_expression is None: 4671 raise ParseError(f"SQL cannot be None") 4672 4673 import sqlglot 4674 4675 sql = str(sql_or_expression) 4676 if prefix: 4677 sql = f"{prefix} {sql}" 4678 4679 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.
4863def union( 4864 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4865) -> Union: 4866 """ 4867 Initializes a syntax tree from one UNION expression. 4868 4869 Example: 4870 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4871 'SELECT * FROM foo UNION SELECT * FROM bla' 4872 4873 Args: 4874 left: the SQL code string corresponding to the left-hand side. 4875 If an `Expression` instance is passed, it will be used as-is. 4876 right: the SQL code string corresponding to the right-hand side. 4877 If an `Expression` instance is passed, it will be used as-is. 4878 distinct: set the DISTINCT flag if and only if this is true. 4879 dialect: the dialect used to parse the input expression. 4880 opts: other options to use to parse the input expressions. 4881 4882 Returns: 4883 The new Union instance. 4884 """ 4885 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4886 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4887 4888 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.
4891def intersect( 4892 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4893) -> Intersect: 4894 """ 4895 Initializes a syntax tree from one INTERSECT expression. 4896 4897 Example: 4898 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4899 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4900 4901 Args: 4902 left: the SQL code string corresponding to the left-hand side. 4903 If an `Expression` instance is passed, it will be used as-is. 4904 right: the SQL code string corresponding to the right-hand side. 4905 If an `Expression` instance is passed, it will be used as-is. 4906 distinct: set the DISTINCT flag if and only if this is true. 4907 dialect: the dialect used to parse the input expression. 4908 opts: other options to use to parse the input expressions. 4909 4910 Returns: 4911 The new Intersect instance. 4912 """ 4913 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4914 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4915 4916 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.
4919def except_( 4920 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4921) -> Except: 4922 """ 4923 Initializes a syntax tree from one EXCEPT expression. 4924 4925 Example: 4926 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4927 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4928 4929 Args: 4930 left: the SQL code string corresponding to the left-hand side. 4931 If an `Expression` instance is passed, it will be used as-is. 4932 right: the SQL code string corresponding to the right-hand side. 4933 If an `Expression` instance is passed, it will be used as-is. 4934 distinct: set the DISTINCT flag if and only if this is true. 4935 dialect: the dialect used to parse the input expression. 4936 opts: other options to use to parse the input expressions. 4937 4938 Returns: 4939 The new Except instance. 4940 """ 4941 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4942 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4943 4944 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.
4947def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4948 """ 4949 Initializes a syntax tree from one or multiple SELECT expressions. 4950 4951 Example: 4952 >>> select("col1", "col2").from_("tbl").sql() 4953 'SELECT col1, col2 FROM tbl' 4954 4955 Args: 4956 *expressions: the SQL code string to parse as the expressions of a 4957 SELECT statement. If an Expression instance is passed, this is used as-is. 4958 dialect: the dialect used to parse the input expressions (in the case that an 4959 input expression is a SQL string). 4960 **opts: other options to use to parse the input expressions (again, in the case 4961 that an input expression is a SQL string). 4962 4963 Returns: 4964 Select: the syntax tree for the SELECT statement. 4965 """ 4966 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.
4969def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4970 """ 4971 Initializes a syntax tree from a FROM expression. 4972 4973 Example: 4974 >>> from_("tbl").select("col1", "col2").sql() 4975 'SELECT col1, col2 FROM tbl' 4976 4977 Args: 4978 *expression: the SQL code string to parse as the FROM expressions of a 4979 SELECT statement. If an Expression instance is passed, this is used as-is. 4980 dialect: the dialect used to parse the input expression (in the case that the 4981 input expression is a SQL string). 4982 **opts: other options to use to parse the input expressions (again, in the case 4983 that the input expression is a SQL string). 4984 4985 Returns: 4986 Select: the syntax tree for the SELECT statement. 4987 """ 4988 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.
4991def update( 4992 table: str | Table, 4993 properties: dict, 4994 where: t.Optional[ExpOrStr] = None, 4995 from_: t.Optional[ExpOrStr] = None, 4996 dialect: DialectType = None, 4997 **opts, 4998) -> Update: 4999 """ 5000 Creates an update statement. 5001 5002 Example: 5003 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 5004 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 5005 5006 Args: 5007 *properties: dictionary of properties to set which are 5008 auto converted to sql objects eg None -> NULL 5009 where: sql conditional parsed into a WHERE statement 5010 from_: sql statement parsed into a FROM statement 5011 dialect: the dialect used to parse the input expressions. 5012 **opts: other options to use to parse the input expressions. 5013 5014 Returns: 5015 Update: the syntax tree for the UPDATE statement. 5016 """ 5017 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 5018 update_expr.set( 5019 "expressions", 5020 [ 5021 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 5022 for k, v in properties.items() 5023 ], 5024 ) 5025 if from_: 5026 update_expr.set( 5027 "from", 5028 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 5029 ) 5030 if isinstance(where, Condition): 5031 where = Where(this=where) 5032 if where: 5033 update_expr.set( 5034 "where", 5035 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 5036 ) 5037 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.
5040def delete( 5041 table: ExpOrStr, 5042 where: t.Optional[ExpOrStr] = None, 5043 returning: t.Optional[ExpOrStr] = None, 5044 dialect: DialectType = None, 5045 **opts, 5046) -> Delete: 5047 """ 5048 Builds a delete statement. 5049 5050 Example: 5051 >>> delete("my_table", where="id > 1").sql() 5052 'DELETE FROM my_table WHERE id > 1' 5053 5054 Args: 5055 where: sql conditional parsed into a WHERE statement 5056 returning: sql conditional parsed into a RETURNING statement 5057 dialect: the dialect used to parse the input expressions. 5058 **opts: other options to use to parse the input expressions. 5059 5060 Returns: 5061 Delete: the syntax tree for the DELETE statement. 5062 """ 5063 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5064 if where: 5065 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5066 if returning: 5067 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5068 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.
5071def insert( 5072 expression: ExpOrStr, 5073 into: ExpOrStr, 5074 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5075 overwrite: t.Optional[bool] = None, 5076 dialect: DialectType = None, 5077 copy: bool = True, 5078 **opts, 5079) -> Insert: 5080 """ 5081 Builds an INSERT statement. 5082 5083 Example: 5084 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5085 'INSERT INTO tbl VALUES (1, 2, 3)' 5086 5087 Args: 5088 expression: the sql string or expression of the INSERT statement 5089 into: the tbl to insert data to. 5090 columns: optionally the table's column names. 5091 overwrite: whether to INSERT OVERWRITE or not. 5092 dialect: the dialect used to parse the input expressions. 5093 copy: whether or not to copy the expression. 5094 **opts: other options to use to parse the input expressions. 5095 5096 Returns: 5097 Insert: the syntax tree for the INSERT statement. 5098 """ 5099 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5100 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5101 5102 if columns: 5103 this = _apply_list_builder( 5104 *columns, 5105 instance=Schema(this=this), 5106 arg="expressions", 5107 into=Identifier, 5108 copy=False, 5109 dialect=dialect, 5110 **opts, 5111 ) 5112 5113 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.
5116def condition( 5117 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5118) -> Condition: 5119 """ 5120 Initialize a logical condition expression. 5121 5122 Example: 5123 >>> condition("x=1").sql() 5124 'x = 1' 5125 5126 This is helpful for composing larger logical syntax trees: 5127 >>> where = condition("x=1") 5128 >>> where = where.and_("y=1") 5129 >>> Select().from_("tbl").select("*").where(where).sql() 5130 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5131 5132 Args: 5133 *expression: the SQL code string to parse. 5134 If an Expression instance is passed, this is used as-is. 5135 dialect: the dialect used to parse the input expression (in the case that the 5136 input expression is a SQL string). 5137 copy: Whether or not to copy `expression` (only applies to expressions). 5138 **opts: other options to use to parse the input expressions (again, in the case 5139 that the input expression is a SQL string). 5140 5141 Returns: 5142 The new Condition instance 5143 """ 5144 return maybe_parse( 5145 expression, 5146 into=Condition, 5147 dialect=dialect, 5148 copy=copy, 5149 **opts, 5150 )
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
5153def and_( 5154 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5155) -> Condition: 5156 """ 5157 Combine multiple conditions with an AND logical operator. 5158 5159 Example: 5160 >>> and_("x=1", and_("y=1", "z=1")).sql() 5161 'x = 1 AND (y = 1 AND z = 1)' 5162 5163 Args: 5164 *expressions: the SQL code strings to parse. 5165 If an Expression instance is passed, this is used as-is. 5166 dialect: the dialect used to parse the input expression. 5167 copy: whether or not to copy `expressions` (only applies to Expressions). 5168 **opts: other options to use to parse the input expressions. 5169 5170 Returns: 5171 And: the new condition 5172 """ 5173 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
5176def or_( 5177 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5178) -> Condition: 5179 """ 5180 Combine multiple conditions with an OR logical operator. 5181 5182 Example: 5183 >>> or_("x=1", or_("y=1", "z=1")).sql() 5184 'x = 1 OR (y = 1 OR z = 1)' 5185 5186 Args: 5187 *expressions: the SQL code strings to parse. 5188 If an Expression instance is passed, this is used as-is. 5189 dialect: the dialect used to parse the input expression. 5190 copy: whether or not to copy `expressions` (only applies to Expressions). 5191 **opts: other options to use to parse the input expressions. 5192 5193 Returns: 5194 Or: the new condition 5195 """ 5196 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
5199def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5200 """ 5201 Wrap a condition with a NOT operator. 5202 5203 Example: 5204 >>> not_("this_suit='black'").sql() 5205 "NOT this_suit = 'black'" 5206 5207 Args: 5208 expression: the SQL code string to parse. 5209 If an Expression instance is passed, this is used as-is. 5210 dialect: the dialect used to parse the input expression. 5211 copy: whether to copy the expression or not. 5212 **opts: other options to use to parse the input expressions. 5213 5214 Returns: 5215 The new condition. 5216 """ 5217 this = condition( 5218 expression, 5219 dialect=dialect, 5220 copy=copy, 5221 **opts, 5222 ) 5223 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.
5226def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5227 """ 5228 Wrap an expression in parentheses. 5229 5230 Example: 5231 >>> paren("5 + 3").sql() 5232 '(5 + 3)' 5233 5234 Args: 5235 expression: the SQL code string to parse. 5236 If an Expression instance is passed, this is used as-is. 5237 copy: whether to copy the expression or not. 5238 5239 Returns: 5240 The wrapped expression. 5241 """ 5242 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.
5260def to_identifier(name, quoted=None, copy=True): 5261 """Builds an identifier. 5262 5263 Args: 5264 name: The name to turn into an identifier. 5265 quoted: Whether or not force quote the identifier. 5266 copy: Whether or not to copy a passed in Identefier node. 5267 5268 Returns: 5269 The identifier ast node. 5270 """ 5271 5272 if name is None: 5273 return None 5274 5275 if isinstance(name, Identifier): 5276 identifier = _maybe_copy(name, copy) 5277 elif isinstance(name, str): 5278 identifier = Identifier( 5279 this=name, 5280 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5281 ) 5282 else: 5283 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5284 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.
5290def to_interval(interval: str | Literal) -> Interval: 5291 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5292 if isinstance(interval, Literal): 5293 if not interval.is_string: 5294 raise ValueError("Invalid interval string.") 5295 5296 interval = interval.this 5297 5298 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5299 5300 if not interval_parts: 5301 raise ValueError("Invalid interval string.") 5302 5303 return Interval( 5304 this=Literal.string(interval_parts.group(1)), 5305 unit=Var(this=interval_parts.group(2)), 5306 )
Builds an interval expression from a string like '1 day' or '5 months'.
5319def to_table( 5320 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5321) -> t.Optional[Table]: 5322 """ 5323 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5324 If a table is passed in then that table is returned. 5325 5326 Args: 5327 sql_path: a `[catalog].[schema].[table]` string. 5328 dialect: the source dialect according to which the table name will be parsed. 5329 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5330 5331 Returns: 5332 A table expression. 5333 """ 5334 if sql_path is None or isinstance(sql_path, Table): 5335 return sql_path 5336 if not isinstance(sql_path, str): 5337 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5338 5339 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5340 if table: 5341 for k, v in kwargs.items(): 5342 table.set(k, v) 5343 5344 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.
5347def to_column(sql_path: str | Column, **kwargs) -> Column: 5348 """ 5349 Create a column from a `[table].[column]` sql path. Schema is optional. 5350 5351 If a column is passed in then that column is returned. 5352 5353 Args: 5354 sql_path: `[table].[column]` string 5355 Returns: 5356 Table: A column expression 5357 """ 5358 if sql_path is None or isinstance(sql_path, Column): 5359 return sql_path 5360 if not isinstance(sql_path, str): 5361 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5362 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
5365def alias_( 5366 expression: ExpOrStr, 5367 alias: str | Identifier, 5368 table: bool | t.Sequence[str | Identifier] = False, 5369 quoted: t.Optional[bool] = None, 5370 dialect: DialectType = None, 5371 copy: bool = True, 5372 **opts, 5373): 5374 """Create an Alias expression. 5375 5376 Example: 5377 >>> alias_('foo', 'bar').sql() 5378 'foo AS bar' 5379 5380 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5381 '(SELECT 1, 2) AS bar(a, b)' 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. If the name has 5387 special characters it is quoted. 5388 table: Whether or not to create a table alias, can also be a list of columns. 5389 quoted: whether or not to quote the alias 5390 dialect: the dialect used to parse the input expression. 5391 copy: Whether or not to copy the expression. 5392 **opts: other options to use to parse the input expressions. 5393 5394 Returns: 5395 Alias: the aliased expression 5396 """ 5397 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5398 alias = to_identifier(alias, quoted=quoted) 5399 5400 if table: 5401 table_alias = TableAlias(this=alias) 5402 exp.set("alias", table_alias) 5403 5404 if not isinstance(table, bool): 5405 for column in table: 5406 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5407 5408 return exp 5409 5410 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5411 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5412 # for the complete Window expression. 5413 # 5414 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5415 5416 if "alias" in exp.arg_types and not isinstance(exp, Window): 5417 exp.set("alias", alias) 5418 return exp 5419 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
5422def subquery( 5423 expression: ExpOrStr, 5424 alias: t.Optional[Identifier | str] = None, 5425 dialect: DialectType = None, 5426 **opts, 5427) -> Select: 5428 """ 5429 Build a subquery expression. 5430 5431 Example: 5432 >>> subquery('select x from tbl', 'bar').select('x').sql() 5433 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5434 5435 Args: 5436 expression: the SQL code strings to parse. 5437 If an Expression instance is passed, this is used as-is. 5438 alias: the alias name to use. 5439 dialect: the dialect used to parse the input expression. 5440 **opts: other options to use to parse the input expressions. 5441 5442 Returns: 5443 A new Select instance with the subquery expression included. 5444 """ 5445 5446 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5447 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.
5450def column( 5451 col: str | Identifier, 5452 table: t.Optional[str | Identifier] = None, 5453 db: t.Optional[str | Identifier] = None, 5454 catalog: t.Optional[str | Identifier] = None, 5455 quoted: t.Optional[bool] = None, 5456) -> Column: 5457 """ 5458 Build a Column. 5459 5460 Args: 5461 col: Column name. 5462 table: Table name. 5463 db: Database name. 5464 catalog: Catalog name. 5465 quoted: Whether to force quotes on the column's identifiers. 5466 5467 Returns: 5468 The new Column instance. 5469 """ 5470 return Column( 5471 this=to_identifier(col, quoted=quoted), 5472 table=to_identifier(table, quoted=quoted), 5473 db=to_identifier(db, quoted=quoted), 5474 catalog=to_identifier(catalog, quoted=quoted), 5475 )
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.
5478def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5479 """Cast an expression to a data type. 5480 5481 Example: 5482 >>> cast('x + 1', 'int').sql() 5483 'CAST(x + 1 AS INT)' 5484 5485 Args: 5486 expression: The expression to cast. 5487 to: The datatype to cast to. 5488 5489 Returns: 5490 The new Cast instance. 5491 """ 5492 expression = maybe_parse(expression, **opts) 5493 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.
5496def table_( 5497 table: Identifier | str, 5498 db: t.Optional[Identifier | str] = None, 5499 catalog: t.Optional[Identifier | str] = None, 5500 quoted: t.Optional[bool] = None, 5501 alias: t.Optional[Identifier | str] = None, 5502) -> Table: 5503 """Build a Table. 5504 5505 Args: 5506 table: Table name. 5507 db: Database name. 5508 catalog: Catalog name. 5509 quote: Whether to force quotes on the table's identifiers. 5510 alias: Table's alias. 5511 5512 Returns: 5513 The new Table instance. 5514 """ 5515 return Table( 5516 this=to_identifier(table, quoted=quoted), 5517 db=to_identifier(db, quoted=quoted), 5518 catalog=to_identifier(catalog, quoted=quoted), 5519 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5520 )
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.
5523def values( 5524 values: t.Iterable[t.Tuple[t.Any, ...]], 5525 alias: t.Optional[str] = None, 5526 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5527) -> Values: 5528 """Build VALUES statement. 5529 5530 Example: 5531 >>> values([(1, '2')]).sql() 5532 "VALUES (1, '2')" 5533 5534 Args: 5535 values: values statements that will be converted to SQL 5536 alias: optional alias 5537 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5538 If either are provided then an alias is also required. 5539 5540 Returns: 5541 Values: the Values expression object 5542 """ 5543 if columns and not alias: 5544 raise ValueError("Alias is required when providing columns") 5545 5546 return Values( 5547 expressions=[convert(tup) for tup in values], 5548 alias=( 5549 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5550 if columns 5551 else (TableAlias(this=to_identifier(alias)) if alias else None) 5552 ), 5553 )
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
5556def var(name: t.Optional[ExpOrStr]) -> Var: 5557 """Build a SQL variable. 5558 5559 Example: 5560 >>> repr(var('x')) 5561 '(VAR this: x)' 5562 5563 >>> repr(var(column('x', table='y'))) 5564 '(VAR this: x)' 5565 5566 Args: 5567 name: The name of the var or an expression who's name will become the var. 5568 5569 Returns: 5570 The new variable node. 5571 """ 5572 if not name: 5573 raise ValueError("Cannot convert empty name into var.") 5574 5575 if isinstance(name, Expression): 5576 name = name.name 5577 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.
5580def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5581 """Build ALTER TABLE... RENAME... expression 5582 5583 Args: 5584 old_name: The old name of the table 5585 new_name: The new name of the table 5586 5587 Returns: 5588 Alter table expression 5589 """ 5590 old_table = to_table(old_name) 5591 new_table = to_table(new_name) 5592 return AlterTable( 5593 this=old_table, 5594 actions=[ 5595 RenameTable(this=new_table), 5596 ], 5597 )
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
5600def convert(value: t.Any, copy: bool = False) -> Expression: 5601 """Convert a python value into an expression object. 5602 5603 Raises an error if a conversion is not possible. 5604 5605 Args: 5606 value: A python object. 5607 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5608 5609 Returns: 5610 Expression: the equivalent expression object. 5611 """ 5612 if isinstance(value, Expression): 5613 return _maybe_copy(value, copy) 5614 if isinstance(value, str): 5615 return Literal.string(value) 5616 if isinstance(value, bool): 5617 return Boolean(this=value) 5618 if value is None or (isinstance(value, float) and math.isnan(value)): 5619 return NULL 5620 if isinstance(value, numbers.Number): 5621 return Literal.number(value) 5622 if isinstance(value, datetime.datetime): 5623 datetime_literal = Literal.string( 5624 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5625 ) 5626 return TimeStrToTime(this=datetime_literal) 5627 if isinstance(value, datetime.date): 5628 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5629 return DateStrToDate(this=date_literal) 5630 if isinstance(value, tuple): 5631 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5632 if isinstance(value, list): 5633 return Array(expressions=[convert(v, copy=copy) for v in value]) 5634 if isinstance(value, dict): 5635 return Map( 5636 keys=[convert(k, copy=copy) for k in value], 5637 values=[convert(v, copy=copy) for v in value.values()], 5638 ) 5639 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.
5642def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5643 """ 5644 Replace children of an expression with the result of a lambda fun(child) -> exp. 5645 """ 5646 for k, v in expression.args.items(): 5647 is_list_arg = type(v) is list 5648 5649 child_nodes = v if is_list_arg else [v] 5650 new_child_nodes = [] 5651 5652 for cn in child_nodes: 5653 if isinstance(cn, Expression): 5654 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5655 new_child_nodes.append(child_node) 5656 child_node.parent = expression 5657 child_node.arg_key = k 5658 else: 5659 new_child_nodes.append(cn) 5660 5661 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.
5664def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]: 5665 """ 5666 Return all table names referenced through columns in an expression. 5667 5668 Example: 5669 >>> import sqlglot 5670 >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))) 5671 ['a', 'c'] 5672 5673 Args: 5674 expression: expression to find table names. 5675 exclude: a table name to exclude 5676 5677 Returns: 5678 A list of unique names. 5679 """ 5680 return { 5681 table 5682 for table in (column.table for column in expression.find_all(Column)) 5683 if table and table != exclude 5684 }
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))) ['a', 'c']
Arguments:
- expression: expression to find table names.
- exclude: a table name to exclude
Returns:
A list of unique names.
5687def table_name(table: Table | str) -> str: 5688 """Get the full name of a table as a string. 5689 5690 Args: 5691 table: table expression node or string. 5692 5693 Examples: 5694 >>> from sqlglot import exp, parse_one 5695 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5696 'a.b.c' 5697 5698 Returns: 5699 The table name. 5700 """ 5701 5702 table = maybe_parse(table, into=Table) 5703 5704 if not table: 5705 raise ValueError(f"Cannot parse {table}") 5706 5707 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.
5710def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E: 5711 """Replace all tables in expression according to the mapping. 5712 5713 Args: 5714 expression: expression node to be transformed and replaced. 5715 mapping: mapping of table names. 5716 copy: whether or not to copy the expression. 5717 5718 Examples: 5719 >>> from sqlglot import exp, parse_one 5720 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5721 'SELECT * FROM c' 5722 5723 Returns: 5724 The mapped expression. 5725 """ 5726 5727 def _replace_tables(node: Expression) -> Expression: 5728 if isinstance(node, Table): 5729 new_name = mapping.get(table_name(node)) 5730 if new_name: 5731 return to_table( 5732 new_name, 5733 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5734 ) 5735 return node 5736 5737 return expression.transform(_replace_tables, copy=copy)
Replace all tables in expression according to the mapping.
Arguments:
- expression: expression node to be transformed and replaced.
- mapping: mapping of table names.
- copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
5740def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5741 """Replace placeholders in an expression. 5742 5743 Args: 5744 expression: expression node to be transformed and replaced. 5745 args: positional names that will substitute unnamed placeholders in the given order. 5746 kwargs: keyword arguments that will substitute named placeholders. 5747 5748 Examples: 5749 >>> from sqlglot import exp, parse_one 5750 >>> replace_placeholders( 5751 ... parse_one("select * from :tbl where ? = ?"), 5752 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5753 ... ).sql() 5754 "SELECT * FROM foo WHERE str_col = 'b'" 5755 5756 Returns: 5757 The mapped expression. 5758 """ 5759 5760 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5761 if isinstance(node, Placeholder): 5762 if node.name: 5763 new_name = kwargs.get(node.name) 5764 if new_name: 5765 return convert(new_name) 5766 else: 5767 try: 5768 return convert(next(args)) 5769 except StopIteration: 5770 pass 5771 return node 5772 5773 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.
5776def expand( 5777 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5778) -> Expression: 5779 """Transforms an expression by expanding all referenced sources into subqueries. 5780 5781 Examples: 5782 >>> from sqlglot import parse_one 5783 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5784 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5785 5786 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5787 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5788 5789 Args: 5790 expression: The expression to expand. 5791 sources: A dictionary of name to Subqueryables. 5792 copy: Whether or not to copy the expression during transformation. Defaults to True. 5793 5794 Returns: 5795 The transformed expression. 5796 """ 5797 5798 def _expand(node: Expression): 5799 if isinstance(node, Table): 5800 name = table_name(node) 5801 source = sources.get(name) 5802 if source: 5803 subquery = source.subquery(node.alias or name) 5804 subquery.comments = [f"source: {name}"] 5805 return subquery.transform(_expand, copy=False) 5806 return node 5807 5808 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.
5811def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5812 """ 5813 Returns a Func expression. 5814 5815 Examples: 5816 >>> func("abs", 5).sql() 5817 'ABS(5)' 5818 5819 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5820 'CAST(5 AS DOUBLE)' 5821 5822 Args: 5823 name: the name of the function to build. 5824 args: the args used to instantiate the function of interest. 5825 dialect: the source dialect. 5826 kwargs: the kwargs used to instantiate the function of interest. 5827 5828 Note: 5829 The arguments `args` and `kwargs` are mutually exclusive. 5830 5831 Returns: 5832 An instance of the function of interest, or an anonymous function, if `name` doesn't 5833 correspond to an existing `sqlglot.expressions.Func` class. 5834 """ 5835 if args and kwargs: 5836 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5837 5838 from sqlglot.dialects.dialect import Dialect 5839 5840 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5841 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5842 5843 parser = Dialect.get_or_raise(dialect)().parser() 5844 from_args_list = parser.FUNCTIONS.get(name.upper()) 5845 5846 if from_args_list: 5847 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5848 else: 5849 kwargs = kwargs or {"expressions": converted} 5850 function = Anonymous(this=name, **kwargs) 5851 5852 for error_message in function.error_messages(converted): 5853 raise ValueError(error_message) 5854 5855 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.
5858def true() -> Boolean: 5859 """ 5860 Returns a true Boolean expression. 5861 """ 5862 return Boolean(this=True)
Returns a true Boolean expression.
5865def false() -> Boolean: 5866 """ 5867 Returns a false Boolean expression. 5868 """ 5869 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.