Expressions
Every AST node in SQLGlot is represented by a subclass of Expression
.
This module contains the implementation of all supported Expression
types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select
.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot._typing import E 25from sqlglot.errors import ParseError 26from sqlglot.helper import ( 27 AutoName, 28 camel_to_snake_case, 29 ensure_collection, 30 ensure_list, 31 seq_get, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39 40class _Expression(type): 41 def __new__(cls, clsname, bases, attrs): 42 klass = super().__new__(cls, clsname, bases, attrs) 43 44 # When an Expression class is created, its key is automatically set to be 45 # the lowercase version of the class' name. 46 klass.key = clsname.lower() 47 48 # This is so that docstrings are not inherited in pdoc 49 klass.__doc__ = klass.__doc__ or "" 50 51 return klass 52 53 54class Expression(metaclass=_Expression): 55 """ 56 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 57 context, such as its child expressions, their names (arg keys), and whether a given child expression 58 is optional or not. 59 60 Attributes: 61 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 62 and representing expressions as strings. 63 arg_types: determines what arguments (child nodes) are supported by an expression. It 64 maps arg keys to booleans that indicate whether the corresponding args are optional. 65 parent: a reference to the parent expression (or None, in case of root expressions). 66 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 67 uses to refer to it. 68 comments: a list of comments that are associated with a given expression. This is used in 69 order to preserve comments when transpiling SQL code. 70 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 71 optimizer, in order to enable some transformations that require type information. 72 73 Example: 74 >>> class Foo(Expression): 75 ... arg_types = {"this": True, "expression": False} 76 77 The above definition informs us that Foo is an Expression that requires an argument called 78 "this" and may also optionally receive an argument called "expression". 79 80 Args: 81 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 82 """ 83 84 key = "expression" 85 arg_types = {"this": True} 86 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 87 88 def __init__(self, **args: t.Any): 89 self.args: t.Dict[str, t.Any] = args 90 self.parent: t.Optional[Expression] = None 91 self.arg_key: t.Optional[str] = None 92 self.comments: t.Optional[t.List[str]] = None 93 self._type: t.Optional[DataType] = None 94 self._meta: t.Optional[t.Dict[str, t.Any]] = None 95 self._hash: t.Optional[int] = None 96 97 for arg_key, value in self.args.items(): 98 self._set_parent(arg_key, value) 99 100 def __eq__(self, other) -> bool: 101 return type(self) is type(other) and hash(self) == hash(other) 102 103 @property 104 def hashable_args(self) -> t.Any: 105 args = (self.args.get(k) for k in self.arg_types) 106 107 return tuple( 108 (tuple(_norm_arg(a) for a in arg) if arg else None) 109 if type(arg) is list 110 else (_norm_arg(arg) if arg is not None and arg is not False else None) 111 for arg in args 112 ) 113 114 def __hash__(self) -> int: 115 if self._hash is not None: 116 return self._hash 117 118 return hash((self.__class__, self.hashable_args)) 119 120 @property 121 def this(self): 122 """ 123 Retrieves the argument with key "this". 124 """ 125 return self.args.get("this") 126 127 @property 128 def expression(self): 129 """ 130 Retrieves the argument with key "expression". 131 """ 132 return self.args.get("expression") 133 134 @property 135 def expressions(self): 136 """ 137 Retrieves the argument with key "expressions". 138 """ 139 return self.args.get("expressions") or [] 140 141 def text(self, key) -> str: 142 """ 143 Returns a textual representation of the argument corresponding to "key". This can only be used 144 for args that are strings or leaf Expression instances, such as identifiers and literals. 145 """ 146 field = self.args.get(key) 147 if isinstance(field, str): 148 return field 149 if isinstance(field, (Identifier, Literal, Var)): 150 return field.this 151 if isinstance(field, (Star, Null)): 152 return field.name 153 return "" 154 155 @property 156 def is_string(self) -> bool: 157 """ 158 Checks whether a Literal expression is a string. 159 """ 160 return isinstance(self, Literal) and self.args["is_string"] 161 162 @property 163 def is_number(self) -> bool: 164 """ 165 Checks whether a Literal expression is a number. 166 """ 167 return isinstance(self, Literal) and not self.args["is_string"] 168 169 @property 170 def is_int(self) -> bool: 171 """ 172 Checks whether a Literal expression is an integer. 173 """ 174 if self.is_number: 175 try: 176 int(self.name) 177 return True 178 except ValueError: 179 pass 180 return False 181 182 @property 183 def is_star(self) -> bool: 184 """Checks whether an expression is a star.""" 185 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 186 187 @property 188 def alias(self) -> str: 189 """ 190 Returns the alias of the expression, or an empty string if it's not aliased. 191 """ 192 if isinstance(self.args.get("alias"), TableAlias): 193 return self.args["alias"].name 194 return self.text("alias") 195 196 @property 197 def name(self) -> str: 198 return self.text("this") 199 200 @property 201 def alias_or_name(self) -> str: 202 return self.alias or self.name 203 204 @property 205 def output_name(self) -> str: 206 """ 207 Name of the output column if this expression is a selection. 208 209 If the Expression has no output name, an empty string is returned. 210 211 Example: 212 >>> from sqlglot import parse_one 213 >>> parse_one("SELECT a").expressions[0].output_name 214 'a' 215 >>> parse_one("SELECT b AS c").expressions[0].output_name 216 'c' 217 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 218 '' 219 """ 220 return "" 221 222 @property 223 def type(self) -> t.Optional[DataType]: 224 return self._type 225 226 @type.setter 227 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 228 if dtype and not isinstance(dtype, DataType): 229 dtype = DataType.build(dtype) 230 self._type = dtype # type: ignore 231 232 @property 233 def meta(self) -> t.Dict[str, t.Any]: 234 if self._meta is None: 235 self._meta = {} 236 return self._meta 237 238 def __deepcopy__(self, memo): 239 copy = self.__class__(**deepcopy(self.args)) 240 if self.comments is not None: 241 copy.comments = deepcopy(self.comments) 242 243 if self._type is not None: 244 copy._type = self._type.copy() 245 246 if self._meta is not None: 247 copy._meta = deepcopy(self._meta) 248 249 return copy 250 251 def copy(self): 252 """ 253 Returns a deep copy of the expression. 254 """ 255 new = deepcopy(self) 256 new.parent = self.parent 257 return new 258 259 def add_comments(self, comments: t.Optional[t.List[str]]) -> None: 260 if self.comments is None: 261 self.comments = [] 262 if comments: 263 self.comments.extend(comments) 264 265 def append(self, arg_key: str, value: t.Any) -> None: 266 """ 267 Appends value to arg_key if it's a list or sets it as a new list. 268 269 Args: 270 arg_key (str): name of the list expression arg 271 value (Any): value to append to the list 272 """ 273 if not isinstance(self.args.get(arg_key), list): 274 self.args[arg_key] = [] 275 self.args[arg_key].append(value) 276 self._set_parent(arg_key, value) 277 278 def set(self, arg_key: str, value: t.Any) -> None: 279 """ 280 Sets `arg_key` to `value`. 281 282 Args: 283 arg_key (str): name of the expression arg. 284 value: value to set the arg to. 285 """ 286 self.args[arg_key] = value 287 self._set_parent(arg_key, value) 288 289 def _set_parent(self, arg_key: str, value: t.Any) -> None: 290 if hasattr(value, "parent"): 291 value.parent = self 292 value.arg_key = arg_key 293 elif type(value) is list: 294 for v in value: 295 if hasattr(v, "parent"): 296 v.parent = self 297 v.arg_key = arg_key 298 299 @property 300 def depth(self) -> int: 301 """ 302 Returns the depth of this tree. 303 """ 304 if self.parent: 305 return self.parent.depth + 1 306 return 0 307 308 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 309 """Yields the key and expression for all arguments, exploding list args.""" 310 for k, vs in self.args.items(): 311 if type(vs) is list: 312 for v in vs: 313 if hasattr(v, "parent"): 314 yield k, v 315 else: 316 if hasattr(vs, "parent"): 317 yield k, vs 318 319 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 320 """ 321 Returns the first node in this tree which matches at least one of 322 the specified types. 323 324 Args: 325 expression_types: the expression type(s) to match. 326 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 327 328 Returns: 329 The node which matches the criteria or None if no such node was found. 330 """ 331 return next(self.find_all(*expression_types, bfs=bfs), None) 332 333 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 334 """ 335 Returns a generator object which visits all nodes in this tree and only 336 yields those that match at least one of the specified expression types. 337 338 Args: 339 expression_types: the expression type(s) to match. 340 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 341 342 Returns: 343 The generator object. 344 """ 345 for expression, *_ in self.walk(bfs=bfs): 346 if isinstance(expression, expression_types): 347 yield expression 348 349 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 350 """ 351 Returns a nearest parent matching expression_types. 352 353 Args: 354 expression_types: the expression type(s) to match. 355 356 Returns: 357 The parent node. 358 """ 359 ancestor = self.parent 360 while ancestor and not isinstance(ancestor, expression_types): 361 ancestor = ancestor.parent 362 return t.cast(E, ancestor) 363 364 @property 365 def parent_select(self) -> t.Optional[Select]: 366 """ 367 Returns the parent select statement. 368 """ 369 return self.find_ancestor(Select) 370 371 @property 372 def same_parent(self) -> bool: 373 """Returns if the parent is the same class as itself.""" 374 return type(self.parent) is self.__class__ 375 376 def root(self) -> Expression: 377 """ 378 Returns the root expression of this tree. 379 """ 380 expression = self 381 while expression.parent: 382 expression = expression.parent 383 return expression 384 385 def walk(self, bfs=True, prune=None): 386 """ 387 Returns a generator object which visits all nodes in this tree. 388 389 Args: 390 bfs (bool): if set to True the BFS traversal order will be applied, 391 otherwise the DFS traversal will be used instead. 392 prune ((node, parent, arg_key) -> bool): callable that returns True if 393 the generator should stop traversing this branch of the tree. 394 395 Returns: 396 the generator object. 397 """ 398 if bfs: 399 yield from self.bfs(prune=prune) 400 else: 401 yield from self.dfs(prune=prune) 402 403 def dfs(self, parent=None, key=None, prune=None): 404 """ 405 Returns a generator object which visits all nodes in this tree in 406 the DFS (Depth-first) order. 407 408 Returns: 409 The generator object. 410 """ 411 parent = parent or self.parent 412 yield self, parent, key 413 if prune and prune(self, parent, key): 414 return 415 416 for k, v in self.iter_expressions(): 417 yield from v.dfs(self, k, prune) 418 419 def bfs(self, prune=None): 420 """ 421 Returns a generator object which visits all nodes in this tree in 422 the BFS (Breadth-first) order. 423 424 Returns: 425 The generator object. 426 """ 427 queue = deque([(self, self.parent, None)]) 428 429 while queue: 430 item, parent, key = queue.popleft() 431 432 yield item, parent, key 433 if prune and prune(item, parent, key): 434 continue 435 436 for k, v in item.iter_expressions(): 437 queue.append((v, item, k)) 438 439 def unnest(self): 440 """ 441 Returns the first non parenthesis child or self. 442 """ 443 expression = self 444 while type(expression) is Paren: 445 expression = expression.this 446 return expression 447 448 def unalias(self): 449 """ 450 Returns the inner expression if this is an Alias. 451 """ 452 if isinstance(self, Alias): 453 return self.this 454 return self 455 456 def unnest_operands(self): 457 """ 458 Returns unnested operands as a tuple. 459 """ 460 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 461 462 def flatten(self, unnest=True): 463 """ 464 Returns a generator which yields child nodes who's parents are the same class. 465 466 A AND B AND C -> [A, B, C] 467 """ 468 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 469 if not type(node) is self.__class__: 470 yield node.unnest() if unnest else node 471 472 def __str__(self) -> str: 473 return self.sql() 474 475 def __repr__(self) -> str: 476 return self._to_s() 477 478 def sql(self, dialect: DialectType = None, **opts) -> str: 479 """ 480 Returns SQL string representation of this tree. 481 482 Args: 483 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 484 opts: other `sqlglot.generator.Generator` options. 485 486 Returns: 487 The SQL string. 488 """ 489 from sqlglot.dialects import Dialect 490 491 return Dialect.get_or_raise(dialect)().generate(self, **opts) 492 493 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 494 indent = "" if not level else "\n" 495 indent += "".join([" "] * level) 496 left = f"({self.key.upper()} " 497 498 args: t.Dict[str, t.Any] = { 499 k: ", ".join( 500 v._to_s(hide_missing=hide_missing, level=level + 1) 501 if hasattr(v, "_to_s") 502 else str(v) 503 for v in ensure_list(vs) 504 if v is not None 505 ) 506 for k, vs in self.args.items() 507 } 508 args["comments"] = self.comments 509 args["type"] = self.type 510 args = {k: v for k, v in args.items() if v or not hide_missing} 511 512 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 513 right += ")" 514 515 return indent + left + right 516 517 def transform(self, fun, *args, copy=True, **kwargs): 518 """ 519 Recursively visits all tree nodes (excluding already transformed ones) 520 and applies the given transformation function to each node. 521 522 Args: 523 fun (function): a function which takes a node as an argument and returns a 524 new transformed node or the same node without modifications. If the function 525 returns None, then the corresponding node will be removed from the syntax tree. 526 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 527 modified in place. 528 529 Returns: 530 The transformed tree. 531 """ 532 node = self.copy() if copy else self 533 new_node = fun(node, *args, **kwargs) 534 535 if new_node is None or not isinstance(new_node, Expression): 536 return new_node 537 if new_node is not node: 538 new_node.parent = node.parent 539 return new_node 540 541 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 542 return new_node 543 544 @t.overload 545 def replace(self, expression: E) -> E: 546 ... 547 548 @t.overload 549 def replace(self, expression: None) -> None: 550 ... 551 552 def replace(self, expression): 553 """ 554 Swap out this expression with a new expression. 555 556 For example:: 557 558 >>> tree = Select().select("x").from_("tbl") 559 >>> tree.find(Column).replace(Column(this="y")) 560 (COLUMN this: y) 561 >>> tree.sql() 562 'SELECT y FROM tbl' 563 564 Args: 565 expression: new node 566 567 Returns: 568 The new expression or expressions. 569 """ 570 if not self.parent: 571 return expression 572 573 parent = self.parent 574 self.parent = None 575 576 replace_children(parent, lambda child: expression if child is self else child) 577 return expression 578 579 def pop(self: E) -> E: 580 """ 581 Remove this expression from its AST. 582 583 Returns: 584 The popped expression. 585 """ 586 self.replace(None) 587 return self 588 589 def assert_is(self, type_: t.Type[E]) -> E: 590 """ 591 Assert that this `Expression` is an instance of `type_`. 592 593 If it is NOT an instance of `type_`, this raises an assertion error. 594 Otherwise, this returns this expression. 595 596 Examples: 597 This is useful for type security in chained expressions: 598 599 >>> import sqlglot 600 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 601 'SELECT x, z FROM y' 602 """ 603 assert isinstance(self, type_) 604 return self 605 606 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 607 """ 608 Checks if this expression is valid (e.g. all mandatory args are set). 609 610 Args: 611 args: a sequence of values that were used to instantiate a Func expression. This is used 612 to check that the provided arguments don't exceed the function argument limit. 613 614 Returns: 615 A list of error messages for all possible errors that were found. 616 """ 617 errors: t.List[str] = [] 618 619 for k in self.args: 620 if k not in self.arg_types: 621 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 622 for k, mandatory in self.arg_types.items(): 623 v = self.args.get(k) 624 if mandatory and (v is None or (isinstance(v, list) and not v)): 625 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 626 627 if ( 628 args 629 and isinstance(self, Func) 630 and len(args) > len(self.arg_types) 631 and not self.is_var_len_args 632 ): 633 errors.append( 634 f"The number of provided arguments ({len(args)}) is greater than " 635 f"the maximum number of supported arguments ({len(self.arg_types)})" 636 ) 637 638 return errors 639 640 def dump(self): 641 """ 642 Dump this Expression to a JSON-serializable dict. 643 """ 644 from sqlglot.serde import dump 645 646 return dump(self) 647 648 @classmethod 649 def load(cls, obj): 650 """ 651 Load a dict (as returned by `Expression.dump`) into an Expression instance. 652 """ 653 from sqlglot.serde import load 654 655 return load(obj) 656 657 658IntoType = t.Union[ 659 str, 660 t.Type[Expression], 661 t.Collection[t.Union[str, t.Type[Expression]]], 662] 663ExpOrStr = t.Union[str, Expression] 664 665 666class Condition(Expression): 667 def and_( 668 self, 669 *expressions: t.Optional[ExpOrStr], 670 dialect: DialectType = None, 671 copy: bool = True, 672 **opts, 673 ) -> Condition: 674 """ 675 AND this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").and_("y=1").sql() 679 'x = 1 AND y = 1' 680 681 Args: 682 *expressions: the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect: the dialect used to parse the input expression. 685 copy: whether or not to copy the involved expressions (only applies to Expressions). 686 opts: other options to use to parse the input expressions. 687 688 Returns: 689 The new And condition. 690 """ 691 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 692 693 def or_( 694 self, 695 *expressions: t.Optional[ExpOrStr], 696 dialect: DialectType = None, 697 copy: bool = True, 698 **opts, 699 ) -> Condition: 700 """ 701 OR this condition with one or multiple expressions. 702 703 Example: 704 >>> condition("x=1").or_("y=1").sql() 705 'x = 1 OR y = 1' 706 707 Args: 708 *expressions: the SQL code strings to parse. 709 If an `Expression` instance is passed, it will be used as-is. 710 dialect: the dialect used to parse the input expression. 711 copy: whether or not to copy the involved expressions (only applies to Expressions). 712 opts: other options to use to parse the input expressions. 713 714 Returns: 715 The new Or condition. 716 """ 717 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 718 719 def not_(self, copy: bool = True): 720 """ 721 Wrap this condition with NOT. 722 723 Example: 724 >>> condition("x=1").not_().sql() 725 'NOT x = 1' 726 727 Args: 728 copy: whether or not to copy this object. 729 730 Returns: 731 The new Not instance. 732 """ 733 return not_(self, copy=copy) 734 735 def as_( 736 self, 737 alias: str | Identifier, 738 quoted: t.Optional[bool] = None, 739 dialect: DialectType = None, 740 copy: bool = True, 741 **opts, 742 ) -> Alias: 743 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 744 745 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 746 this = self.copy() 747 other = convert(other, copy=True) 748 if not isinstance(this, klass) and not isinstance(other, klass): 749 this = _wrap(this, Binary) 750 other = _wrap(other, Binary) 751 if reverse: 752 return klass(this=other, expression=this) 753 return klass(this=this, expression=other) 754 755 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 756 return Bracket( 757 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 758 ) 759 760 def isin( 761 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 762 ) -> In: 763 return In( 764 this=_maybe_copy(self, copy), 765 expressions=[convert(e, copy=copy) for e in expressions], 766 query=maybe_parse(query, copy=copy, **opts) if query else None, 767 ) 768 769 def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between: 770 return Between( 771 this=_maybe_copy(self, copy), 772 low=convert(low, copy=copy, **opts), 773 high=convert(high, copy=copy, **opts), 774 ) 775 776 def is_(self, other: ExpOrStr) -> Is: 777 return self._binop(Is, other) 778 779 def like(self, other: ExpOrStr) -> Like: 780 return self._binop(Like, other) 781 782 def ilike(self, other: ExpOrStr) -> ILike: 783 return self._binop(ILike, other) 784 785 def eq(self, other: t.Any) -> EQ: 786 return self._binop(EQ, other) 787 788 def neq(self, other: t.Any) -> NEQ: 789 return self._binop(NEQ, other) 790 791 def rlike(self, other: ExpOrStr) -> RegexpLike: 792 return self._binop(RegexpLike, other) 793 794 def __lt__(self, other: t.Any) -> LT: 795 return self._binop(LT, other) 796 797 def __le__(self, other: t.Any) -> LTE: 798 return self._binop(LTE, other) 799 800 def __gt__(self, other: t.Any) -> GT: 801 return self._binop(GT, other) 802 803 def __ge__(self, other: t.Any) -> GTE: 804 return self._binop(GTE, other) 805 806 def __add__(self, other: t.Any) -> Add: 807 return self._binop(Add, other) 808 809 def __radd__(self, other: t.Any) -> Add: 810 return self._binop(Add, other, reverse=True) 811 812 def __sub__(self, other: t.Any) -> Sub: 813 return self._binop(Sub, other) 814 815 def __rsub__(self, other: t.Any) -> Sub: 816 return self._binop(Sub, other, reverse=True) 817 818 def __mul__(self, other: t.Any) -> Mul: 819 return self._binop(Mul, other) 820 821 def __rmul__(self, other: t.Any) -> Mul: 822 return self._binop(Mul, other, reverse=True) 823 824 def __truediv__(self, other: t.Any) -> Div: 825 return self._binop(Div, other) 826 827 def __rtruediv__(self, other: t.Any) -> Div: 828 return self._binop(Div, other, reverse=True) 829 830 def __floordiv__(self, other: t.Any) -> IntDiv: 831 return self._binop(IntDiv, other) 832 833 def __rfloordiv__(self, other: t.Any) -> IntDiv: 834 return self._binop(IntDiv, other, reverse=True) 835 836 def __mod__(self, other: t.Any) -> Mod: 837 return self._binop(Mod, other) 838 839 def __rmod__(self, other: t.Any) -> Mod: 840 return self._binop(Mod, other, reverse=True) 841 842 def __pow__(self, other: t.Any) -> Pow: 843 return self._binop(Pow, other) 844 845 def __rpow__(self, other: t.Any) -> Pow: 846 return self._binop(Pow, other, reverse=True) 847 848 def __and__(self, other: t.Any) -> And: 849 return self._binop(And, other) 850 851 def __rand__(self, other: t.Any) -> And: 852 return self._binop(And, other, reverse=True) 853 854 def __or__(self, other: t.Any) -> Or: 855 return self._binop(Or, other) 856 857 def __ror__(self, other: t.Any) -> Or: 858 return self._binop(Or, other, reverse=True) 859 860 def __neg__(self) -> Neg: 861 return Neg(this=_wrap(self.copy(), Binary)) 862 863 def __invert__(self) -> Not: 864 return not_(self.copy()) 865 866 867class Predicate(Condition): 868 """Relationships like x = y, x > 1, x >= y.""" 869 870 871class DerivedTable(Expression): 872 @property 873 def alias_column_names(self) -> t.List[str]: 874 table_alias = self.args.get("alias") 875 if not table_alias: 876 return [] 877 return [c.name for c in table_alias.args.get("columns") or []] 878 879 @property 880 def selects(self): 881 return self.this.selects if isinstance(self.this, Subqueryable) else [] 882 883 @property 884 def named_selects(self): 885 return [select.output_name for select in self.selects] 886 887 888class Unionable(Expression): 889 def union( 890 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 891 ) -> Unionable: 892 """ 893 Builds a UNION expression. 894 895 Example: 896 >>> import sqlglot 897 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 898 'SELECT * FROM foo UNION SELECT * FROM bla' 899 900 Args: 901 expression: the SQL code string. 902 If an `Expression` instance is passed, it will be used as-is. 903 distinct: set the DISTINCT flag if and only if this is true. 904 dialect: the dialect used to parse the input expression. 905 opts: other options to use to parse the input expressions. 906 907 Returns: 908 The new Union expression. 909 """ 910 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 911 912 def intersect( 913 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 914 ) -> Unionable: 915 """ 916 Builds an INTERSECT expression. 917 918 Example: 919 >>> import sqlglot 920 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 921 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 922 923 Args: 924 expression: the SQL code string. 925 If an `Expression` instance is passed, it will be used as-is. 926 distinct: set the DISTINCT flag if and only if this is true. 927 dialect: the dialect used to parse the input expression. 928 opts: other options to use to parse the input expressions. 929 930 Returns: 931 The new Intersect expression. 932 """ 933 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 934 935 def except_( 936 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 937 ) -> Unionable: 938 """ 939 Builds an EXCEPT expression. 940 941 Example: 942 >>> import sqlglot 943 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 944 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 945 946 Args: 947 expression: the SQL code string. 948 If an `Expression` instance is passed, it will be used as-is. 949 distinct: set the DISTINCT flag if and only if this is true. 950 dialect: the dialect used to parse the input expression. 951 opts: other options to use to parse the input expressions. 952 953 Returns: 954 The new Except expression. 955 """ 956 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 957 958 959class UDTF(DerivedTable, Unionable): 960 @property 961 def selects(self): 962 alias = self.args.get("alias") 963 return alias.columns if alias else [] 964 965 966class Cache(Expression): 967 arg_types = { 968 "with": False, 969 "this": True, 970 "lazy": False, 971 "options": False, 972 "expression": False, 973 } 974 975 976class Uncache(Expression): 977 arg_types = {"this": True, "exists": False} 978 979 980class Create(Expression): 981 arg_types = { 982 "with": False, 983 "this": True, 984 "kind": True, 985 "expression": False, 986 "exists": False, 987 "properties": False, 988 "replace": False, 989 "unique": False, 990 "indexes": False, 991 "no_schema_binding": False, 992 "begin": False, 993 "clone": False, 994 } 995 996 997# https://docs.snowflake.com/en/sql-reference/sql/create-clone 998class Clone(Expression): 999 arg_types = { 1000 "this": True, 1001 "when": False, 1002 "kind": False, 1003 "expression": False, 1004 } 1005 1006 1007class Describe(Expression): 1008 arg_types = {"this": True, "kind": False} 1009 1010 1011class Pragma(Expression): 1012 pass 1013 1014 1015class Set(Expression): 1016 arg_types = {"expressions": False} 1017 1018 1019class SetItem(Expression): 1020 arg_types = { 1021 "this": False, 1022 "expressions": False, 1023 "kind": False, 1024 "collate": False, # MySQL SET NAMES statement 1025 "global": False, 1026 } 1027 1028 1029class Show(Expression): 1030 arg_types = { 1031 "this": True, 1032 "target": False, 1033 "offset": False, 1034 "limit": False, 1035 "like": False, 1036 "where": False, 1037 "db": False, 1038 "full": False, 1039 "mutex": False, 1040 "query": False, 1041 "channel": False, 1042 "global": False, 1043 "log": False, 1044 "position": False, 1045 "types": False, 1046 } 1047 1048 1049class UserDefinedFunction(Expression): 1050 arg_types = {"this": True, "expressions": False, "wrapped": False} 1051 1052 1053class CharacterSet(Expression): 1054 arg_types = {"this": True, "default": False} 1055 1056 1057class With(Expression): 1058 arg_types = {"expressions": True, "recursive": False} 1059 1060 @property 1061 def recursive(self) -> bool: 1062 return bool(self.args.get("recursive")) 1063 1064 1065class WithinGroup(Expression): 1066 arg_types = {"this": True, "expression": False} 1067 1068 1069class CTE(DerivedTable): 1070 arg_types = {"this": True, "alias": True} 1071 1072 1073class TableAlias(Expression): 1074 arg_types = {"this": False, "columns": False} 1075 1076 @property 1077 def columns(self): 1078 return self.args.get("columns") or [] 1079 1080 1081class BitString(Condition): 1082 pass 1083 1084 1085class HexString(Condition): 1086 pass 1087 1088 1089class ByteString(Condition): 1090 pass 1091 1092 1093class RawString(Condition): 1094 pass 1095 1096 1097class Column(Condition): 1098 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1099 1100 @property 1101 def table(self) -> str: 1102 return self.text("table") 1103 1104 @property 1105 def db(self) -> str: 1106 return self.text("db") 1107 1108 @property 1109 def catalog(self) -> str: 1110 return self.text("catalog") 1111 1112 @property 1113 def output_name(self) -> str: 1114 return self.name 1115 1116 @property 1117 def parts(self) -> t.List[Identifier]: 1118 """Return the parts of a column in order catalog, db, table, name.""" 1119 return [ 1120 t.cast(Identifier, self.args[part]) 1121 for part in ("catalog", "db", "table", "this") 1122 if self.args.get(part) 1123 ] 1124 1125 def to_dot(self) -> Dot: 1126 """Converts the column into a dot expression.""" 1127 parts = self.parts 1128 parent = self.parent 1129 1130 while parent: 1131 if isinstance(parent, Dot): 1132 parts.append(parent.expression) 1133 parent = parent.parent 1134 1135 return Dot.build(parts) 1136 1137 1138class ColumnPosition(Expression): 1139 arg_types = {"this": False, "position": True} 1140 1141 1142class ColumnDef(Expression): 1143 arg_types = { 1144 "this": True, 1145 "kind": False, 1146 "constraints": False, 1147 "exists": False, 1148 "position": False, 1149 } 1150 1151 @property 1152 def constraints(self) -> t.List[ColumnConstraint]: 1153 return self.args.get("constraints") or [] 1154 1155 1156class AlterColumn(Expression): 1157 arg_types = { 1158 "this": True, 1159 "dtype": False, 1160 "collate": False, 1161 "using": False, 1162 "default": False, 1163 "drop": False, 1164 } 1165 1166 1167class RenameTable(Expression): 1168 pass 1169 1170 1171class SetTag(Expression): 1172 arg_types = {"expressions": True, "unset": False} 1173 1174 1175class Comment(Expression): 1176 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 1177 1178 1179# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1180class MergeTreeTTLAction(Expression): 1181 arg_types = { 1182 "this": True, 1183 "delete": False, 1184 "recompress": False, 1185 "to_disk": False, 1186 "to_volume": False, 1187 } 1188 1189 1190# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1191class MergeTreeTTL(Expression): 1192 arg_types = { 1193 "expressions": True, 1194 "where": False, 1195 "group": False, 1196 "aggregates": False, 1197 } 1198 1199 1200class ColumnConstraint(Expression): 1201 arg_types = {"this": False, "kind": True} 1202 1203 @property 1204 def kind(self) -> ColumnConstraintKind: 1205 return self.args["kind"] 1206 1207 1208class ColumnConstraintKind(Expression): 1209 pass 1210 1211 1212class AutoIncrementColumnConstraint(ColumnConstraintKind): 1213 pass 1214 1215 1216class CaseSpecificColumnConstraint(ColumnConstraintKind): 1217 arg_types = {"not_": True} 1218 1219 1220class CharacterSetColumnConstraint(ColumnConstraintKind): 1221 arg_types = {"this": True} 1222 1223 1224class CheckColumnConstraint(ColumnConstraintKind): 1225 pass 1226 1227 1228class CollateColumnConstraint(ColumnConstraintKind): 1229 pass 1230 1231 1232class CommentColumnConstraint(ColumnConstraintKind): 1233 pass 1234 1235 1236class CompressColumnConstraint(ColumnConstraintKind): 1237 pass 1238 1239 1240class DateFormatColumnConstraint(ColumnConstraintKind): 1241 arg_types = {"this": True} 1242 1243 1244class DefaultColumnConstraint(ColumnConstraintKind): 1245 pass 1246 1247 1248class EncodeColumnConstraint(ColumnConstraintKind): 1249 pass 1250 1251 1252class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1253 # this: True -> ALWAYS, this: False -> BY DEFAULT 1254 arg_types = { 1255 "this": False, 1256 "expression": False, 1257 "on_null": False, 1258 "start": False, 1259 "increment": False, 1260 "minvalue": False, 1261 "maxvalue": False, 1262 "cycle": False, 1263 } 1264 1265 1266class InlineLengthColumnConstraint(ColumnConstraintKind): 1267 pass 1268 1269 1270class NotNullColumnConstraint(ColumnConstraintKind): 1271 arg_types = {"allow_null": False} 1272 1273 1274# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 1275class OnUpdateColumnConstraint(ColumnConstraintKind): 1276 pass 1277 1278 1279class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1280 arg_types = {"desc": False} 1281 1282 1283class TitleColumnConstraint(ColumnConstraintKind): 1284 pass 1285 1286 1287class UniqueColumnConstraint(ColumnConstraintKind): 1288 arg_types = {"this": False} 1289 1290 1291class UppercaseColumnConstraint(ColumnConstraintKind): 1292 arg_types: t.Dict[str, t.Any] = {} 1293 1294 1295class PathColumnConstraint(ColumnConstraintKind): 1296 pass 1297 1298 1299class Constraint(Expression): 1300 arg_types = {"this": True, "expressions": True} 1301 1302 1303class Delete(Expression): 1304 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1305 1306 def delete( 1307 self, 1308 table: ExpOrStr, 1309 dialect: DialectType = None, 1310 copy: bool = True, 1311 **opts, 1312 ) -> Delete: 1313 """ 1314 Create a DELETE expression or replace the table on an existing DELETE expression. 1315 1316 Example: 1317 >>> delete("tbl").sql() 1318 'DELETE FROM tbl' 1319 1320 Args: 1321 table: the table from which to delete. 1322 dialect: the dialect used to parse the input expression. 1323 copy: if `False`, modify this expression instance in-place. 1324 opts: other options to use to parse the input expressions. 1325 1326 Returns: 1327 Delete: the modified expression. 1328 """ 1329 return _apply_builder( 1330 expression=table, 1331 instance=self, 1332 arg="this", 1333 dialect=dialect, 1334 into=Table, 1335 copy=copy, 1336 **opts, 1337 ) 1338 1339 def where( 1340 self, 1341 *expressions: t.Optional[ExpOrStr], 1342 append: bool = True, 1343 dialect: DialectType = None, 1344 copy: bool = True, 1345 **opts, 1346 ) -> Delete: 1347 """ 1348 Append to or set the WHERE expressions. 1349 1350 Example: 1351 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1352 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1353 1354 Args: 1355 *expressions: the SQL code strings to parse. 1356 If an `Expression` instance is passed, it will be used as-is. 1357 Multiple expressions are combined with an AND operator. 1358 append: if `True`, AND the new expressions to any existing expression. 1359 Otherwise, this resets the expression. 1360 dialect: the dialect used to parse the input expressions. 1361 copy: if `False`, modify this expression instance in-place. 1362 opts: other options to use to parse the input expressions. 1363 1364 Returns: 1365 Delete: the modified expression. 1366 """ 1367 return _apply_conjunction_builder( 1368 *expressions, 1369 instance=self, 1370 arg="where", 1371 append=append, 1372 into=Where, 1373 dialect=dialect, 1374 copy=copy, 1375 **opts, 1376 ) 1377 1378 def returning( 1379 self, 1380 expression: ExpOrStr, 1381 dialect: DialectType = None, 1382 copy: bool = True, 1383 **opts, 1384 ) -> Delete: 1385 """ 1386 Set the RETURNING expression. Not supported by all dialects. 1387 1388 Example: 1389 >>> delete("tbl").returning("*", dialect="postgres").sql() 1390 'DELETE FROM tbl RETURNING *' 1391 1392 Args: 1393 expression: the SQL code strings to parse. 1394 If an `Expression` instance is passed, it will be used as-is. 1395 dialect: the dialect used to parse the input expressions. 1396 copy: if `False`, modify this expression instance in-place. 1397 opts: other options to use to parse the input expressions. 1398 1399 Returns: 1400 Delete: the modified expression. 1401 """ 1402 return _apply_builder( 1403 expression=expression, 1404 instance=self, 1405 arg="returning", 1406 prefix="RETURNING", 1407 dialect=dialect, 1408 copy=copy, 1409 into=Returning, 1410 **opts, 1411 ) 1412 1413 1414class Drop(Expression): 1415 arg_types = { 1416 "this": False, 1417 "kind": False, 1418 "exists": False, 1419 "temporary": False, 1420 "materialized": False, 1421 "cascade": False, 1422 "constraints": False, 1423 "purge": False, 1424 } 1425 1426 1427class Filter(Expression): 1428 arg_types = {"this": True, "expression": True} 1429 1430 1431class Check(Expression): 1432 pass 1433 1434 1435class Directory(Expression): 1436 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1437 arg_types = {"this": True, "local": False, "row_format": False} 1438 1439 1440class ForeignKey(Expression): 1441 arg_types = { 1442 "expressions": True, 1443 "reference": False, 1444 "delete": False, 1445 "update": False, 1446 } 1447 1448 1449class PrimaryKey(Expression): 1450 arg_types = {"expressions": True, "options": False} 1451 1452 1453# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1454# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1455class Into(Expression): 1456 arg_types = {"this": True, "temporary": False, "unlogged": False} 1457 1458 1459class From(Expression): 1460 @property 1461 def name(self) -> str: 1462 return self.this.name 1463 1464 @property 1465 def alias_or_name(self) -> str: 1466 return self.this.alias_or_name 1467 1468 1469class Having(Expression): 1470 pass 1471 1472 1473class Hint(Expression): 1474 arg_types = {"expressions": True} 1475 1476 1477class JoinHint(Expression): 1478 arg_types = {"this": True, "expressions": True} 1479 1480 1481class Identifier(Expression): 1482 arg_types = {"this": True, "quoted": False} 1483 1484 @property 1485 def quoted(self) -> bool: 1486 return bool(self.args.get("quoted")) 1487 1488 @property 1489 def hashable_args(self) -> t.Any: 1490 if self.quoted and any(char.isupper() for char in self.this): 1491 return (self.this, self.quoted) 1492 return self.this.lower() 1493 1494 @property 1495 def output_name(self) -> str: 1496 return self.name 1497 1498 1499class Index(Expression): 1500 arg_types = { 1501 "this": False, 1502 "table": False, 1503 "where": False, 1504 "columns": False, 1505 "unique": False, 1506 "primary": False, 1507 "amp": False, # teradata 1508 "partition_by": False, # teradata 1509 } 1510 1511 1512class Insert(Expression): 1513 arg_types = { 1514 "with": False, 1515 "this": True, 1516 "expression": False, 1517 "conflict": False, 1518 "returning": False, 1519 "overwrite": False, 1520 "exists": False, 1521 "partition": False, 1522 "alternative": False, 1523 } 1524 1525 def with_( 1526 self, 1527 alias: ExpOrStr, 1528 as_: ExpOrStr, 1529 recursive: t.Optional[bool] = None, 1530 append: bool = True, 1531 dialect: DialectType = None, 1532 copy: bool = True, 1533 **opts, 1534 ) -> Insert: 1535 """ 1536 Append to or set the common table expressions. 1537 1538 Example: 1539 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1540 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1541 1542 Args: 1543 alias: the SQL code string to parse as the table name. 1544 If an `Expression` instance is passed, this is used as-is. 1545 as_: the SQL code string to parse as the table expression. 1546 If an `Expression` instance is passed, it will be used as-is. 1547 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1548 append: if `True`, add to any existing expressions. 1549 Otherwise, this resets the expressions. 1550 dialect: the dialect used to parse the input expression. 1551 copy: if `False`, modify this expression instance in-place. 1552 opts: other options to use to parse the input expressions. 1553 1554 Returns: 1555 The modified expression. 1556 """ 1557 return _apply_cte_builder( 1558 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1559 ) 1560 1561 1562class OnConflict(Expression): 1563 arg_types = { 1564 "duplicate": False, 1565 "expressions": False, 1566 "nothing": False, 1567 "key": False, 1568 "constraint": False, 1569 } 1570 1571 1572class Returning(Expression): 1573 arg_types = {"expressions": True} 1574 1575 1576# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1577class Introducer(Expression): 1578 arg_types = {"this": True, "expression": True} 1579 1580 1581# national char, like n'utf8' 1582class National(Expression): 1583 pass 1584 1585 1586class LoadData(Expression): 1587 arg_types = { 1588 "this": True, 1589 "local": False, 1590 "overwrite": False, 1591 "inpath": True, 1592 "partition": False, 1593 "input_format": False, 1594 "serde": False, 1595 } 1596 1597 1598class Partition(Expression): 1599 arg_types = {"expressions": True} 1600 1601 1602class Fetch(Expression): 1603 arg_types = { 1604 "direction": False, 1605 "count": False, 1606 "percent": False, 1607 "with_ties": False, 1608 } 1609 1610 1611class Group(Expression): 1612 arg_types = { 1613 "expressions": False, 1614 "grouping_sets": False, 1615 "cube": False, 1616 "rollup": False, 1617 "totals": False, 1618 } 1619 1620 1621class Lambda(Expression): 1622 arg_types = {"this": True, "expressions": True} 1623 1624 1625class Limit(Expression): 1626 arg_types = {"this": False, "expression": True} 1627 1628 1629class Literal(Condition): 1630 arg_types = {"this": True, "is_string": True} 1631 1632 @property 1633 def hashable_args(self) -> t.Any: 1634 return (self.this, self.args.get("is_string")) 1635 1636 @classmethod 1637 def number(cls, number) -> Literal: 1638 return cls(this=str(number), is_string=False) 1639 1640 @classmethod 1641 def string(cls, string) -> Literal: 1642 return cls(this=str(string), is_string=True) 1643 1644 @property 1645 def output_name(self) -> str: 1646 return self.name 1647 1648 1649class Join(Expression): 1650 arg_types = { 1651 "this": True, 1652 "on": False, 1653 "side": False, 1654 "kind": False, 1655 "using": False, 1656 "method": False, 1657 "global": False, 1658 "hint": False, 1659 } 1660 1661 @property 1662 def method(self) -> str: 1663 return self.text("method").upper() 1664 1665 @property 1666 def kind(self) -> str: 1667 return self.text("kind").upper() 1668 1669 @property 1670 def side(self) -> str: 1671 return self.text("side").upper() 1672 1673 @property 1674 def hint(self) -> str: 1675 return self.text("hint").upper() 1676 1677 @property 1678 def alias_or_name(self) -> str: 1679 return self.this.alias_or_name 1680 1681 def on( 1682 self, 1683 *expressions: t.Optional[ExpOrStr], 1684 append: bool = True, 1685 dialect: DialectType = None, 1686 copy: bool = True, 1687 **opts, 1688 ) -> Join: 1689 """ 1690 Append to or set the ON expressions. 1691 1692 Example: 1693 >>> import sqlglot 1694 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1695 'JOIN x ON y = 1' 1696 1697 Args: 1698 *expressions: the SQL code strings to parse. 1699 If an `Expression` instance is passed, it will be used as-is. 1700 Multiple expressions are combined with an AND operator. 1701 append: if `True`, AND the new expressions to any existing expression. 1702 Otherwise, this resets the expression. 1703 dialect: the dialect used to parse the input expressions. 1704 copy: if `False`, modify this expression instance in-place. 1705 opts: other options to use to parse the input expressions. 1706 1707 Returns: 1708 The modified Join expression. 1709 """ 1710 join = _apply_conjunction_builder( 1711 *expressions, 1712 instance=self, 1713 arg="on", 1714 append=append, 1715 dialect=dialect, 1716 copy=copy, 1717 **opts, 1718 ) 1719 1720 if join.kind == "CROSS": 1721 join.set("kind", None) 1722 1723 return join 1724 1725 def using( 1726 self, 1727 *expressions: t.Optional[ExpOrStr], 1728 append: bool = True, 1729 dialect: DialectType = None, 1730 copy: bool = True, 1731 **opts, 1732 ) -> Join: 1733 """ 1734 Append to or set the USING expressions. 1735 1736 Example: 1737 >>> import sqlglot 1738 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1739 'JOIN x USING (foo, bla)' 1740 1741 Args: 1742 *expressions: the SQL code strings to parse. 1743 If an `Expression` instance is passed, it will be used as-is. 1744 append: if `True`, concatenate the new expressions to the existing "using" list. 1745 Otherwise, this resets the expression. 1746 dialect: the dialect used to parse the input expressions. 1747 copy: if `False`, modify this expression instance in-place. 1748 opts: other options to use to parse the input expressions. 1749 1750 Returns: 1751 The modified Join expression. 1752 """ 1753 join = _apply_list_builder( 1754 *expressions, 1755 instance=self, 1756 arg="using", 1757 append=append, 1758 dialect=dialect, 1759 copy=copy, 1760 **opts, 1761 ) 1762 1763 if join.kind == "CROSS": 1764 join.set("kind", None) 1765 1766 return join 1767 1768 1769class Lateral(UDTF): 1770 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1771 1772 1773class MatchRecognize(Expression): 1774 arg_types = { 1775 "partition_by": False, 1776 "order": False, 1777 "measures": False, 1778 "rows": False, 1779 "after": False, 1780 "pattern": False, 1781 "define": False, 1782 "alias": False, 1783 } 1784 1785 1786# Clickhouse FROM FINAL modifier 1787# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1788class Final(Expression): 1789 pass 1790 1791 1792class Offset(Expression): 1793 arg_types = {"this": False, "expression": True} 1794 1795 1796class Order(Expression): 1797 arg_types = {"this": False, "expressions": True} 1798 1799 1800# hive specific sorts 1801# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1802class Cluster(Order): 1803 pass 1804 1805 1806class Distribute(Order): 1807 pass 1808 1809 1810class Sort(Order): 1811 pass 1812 1813 1814class Ordered(Expression): 1815 arg_types = {"this": True, "desc": True, "nulls_first": True} 1816 1817 1818class Property(Expression): 1819 arg_types = {"this": True, "value": True} 1820 1821 1822class AlgorithmProperty(Property): 1823 arg_types = {"this": True} 1824 1825 1826class AutoIncrementProperty(Property): 1827 arg_types = {"this": True} 1828 1829 1830class BlockCompressionProperty(Property): 1831 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1832 1833 1834class CharacterSetProperty(Property): 1835 arg_types = {"this": True, "default": True} 1836 1837 1838class ChecksumProperty(Property): 1839 arg_types = {"on": False, "default": False} 1840 1841 1842class CollateProperty(Property): 1843 arg_types = {"this": True} 1844 1845 1846class DataBlocksizeProperty(Property): 1847 arg_types = { 1848 "size": False, 1849 "units": False, 1850 "minimum": False, 1851 "maximum": False, 1852 "default": False, 1853 } 1854 1855 1856class DefinerProperty(Property): 1857 arg_types = {"this": True} 1858 1859 1860class DistKeyProperty(Property): 1861 arg_types = {"this": True} 1862 1863 1864class DistStyleProperty(Property): 1865 arg_types = {"this": True} 1866 1867 1868class EngineProperty(Property): 1869 arg_types = {"this": True} 1870 1871 1872class ExecuteAsProperty(Property): 1873 arg_types = {"this": True} 1874 1875 1876class ExternalProperty(Property): 1877 arg_types = {"this": False} 1878 1879 1880class FallbackProperty(Property): 1881 arg_types = {"no": True, "protection": False} 1882 1883 1884class FileFormatProperty(Property): 1885 arg_types = {"this": True} 1886 1887 1888class FreespaceProperty(Property): 1889 arg_types = {"this": True, "percent": False} 1890 1891 1892class InputOutputFormat(Expression): 1893 arg_types = {"input_format": False, "output_format": False} 1894 1895 1896class IsolatedLoadingProperty(Property): 1897 arg_types = { 1898 "no": True, 1899 "concurrent": True, 1900 "for_all": True, 1901 "for_insert": True, 1902 "for_none": True, 1903 } 1904 1905 1906class JournalProperty(Property): 1907 arg_types = { 1908 "no": False, 1909 "dual": False, 1910 "before": False, 1911 "local": False, 1912 "after": False, 1913 } 1914 1915 1916class LanguageProperty(Property): 1917 arg_types = {"this": True} 1918 1919 1920class DictProperty(Property): 1921 arg_types = {"this": True, "kind": True, "settings": False} 1922 1923 1924class DictSubProperty(Property): 1925 pass 1926 1927 1928class DictRange(Property): 1929 arg_types = {"this": True, "min": True, "max": True} 1930 1931 1932class LikeProperty(Property): 1933 arg_types = {"this": True, "expressions": False} 1934 1935 1936class LocationProperty(Property): 1937 arg_types = {"this": True} 1938 1939 1940class LockingProperty(Property): 1941 arg_types = { 1942 "this": False, 1943 "kind": True, 1944 "for_or_in": True, 1945 "lock_type": True, 1946 "override": False, 1947 } 1948 1949 1950class LogProperty(Property): 1951 arg_types = {"no": True} 1952 1953 1954class MaterializedProperty(Property): 1955 arg_types = {"this": False} 1956 1957 1958class MergeBlockRatioProperty(Property): 1959 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1960 1961 1962class NoPrimaryIndexProperty(Property): 1963 arg_types = {} 1964 1965 1966class OnCommitProperty(Property): 1967 arg_type = {"delete": False} 1968 1969 1970class PartitionedByProperty(Property): 1971 arg_types = {"this": True} 1972 1973 1974class ReturnsProperty(Property): 1975 arg_types = {"this": True, "is_table": False, "table": False} 1976 1977 1978class RowFormatProperty(Property): 1979 arg_types = {"this": True} 1980 1981 1982class RowFormatDelimitedProperty(Property): 1983 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1984 arg_types = { 1985 "fields": False, 1986 "escaped": False, 1987 "collection_items": False, 1988 "map_keys": False, 1989 "lines": False, 1990 "null": False, 1991 "serde": False, 1992 } 1993 1994 1995class RowFormatSerdeProperty(Property): 1996 arg_types = {"this": True} 1997 1998 1999class SchemaCommentProperty(Property): 2000 arg_types = {"this": True} 2001 2002 2003class SerdeProperties(Property): 2004 arg_types = {"expressions": True} 2005 2006 2007class SetProperty(Property): 2008 arg_types = {"multi": True} 2009 2010 2011class SettingsProperty(Property): 2012 arg_types = {"expressions": True} 2013 2014 2015class SortKeyProperty(Property): 2016 arg_types = {"this": True, "compound": False} 2017 2018 2019class SqlSecurityProperty(Property): 2020 arg_types = {"definer": True} 2021 2022 2023class StabilityProperty(Property): 2024 arg_types = {"this": True} 2025 2026 2027class TemporaryProperty(Property): 2028 arg_types = {} 2029 2030 2031class TransientProperty(Property): 2032 arg_types = {"this": False} 2033 2034 2035class VolatileProperty(Property): 2036 arg_types = {"this": False} 2037 2038 2039class WithDataProperty(Property): 2040 arg_types = {"no": True, "statistics": False} 2041 2042 2043class WithJournalTableProperty(Property): 2044 arg_types = {"this": True} 2045 2046 2047class Properties(Expression): 2048 arg_types = {"expressions": True} 2049 2050 NAME_TO_PROPERTY = { 2051 "ALGORITHM": AlgorithmProperty, 2052 "AUTO_INCREMENT": AutoIncrementProperty, 2053 "CHARACTER SET": CharacterSetProperty, 2054 "COLLATE": CollateProperty, 2055 "COMMENT": SchemaCommentProperty, 2056 "DEFINER": DefinerProperty, 2057 "DISTKEY": DistKeyProperty, 2058 "DISTSTYLE": DistStyleProperty, 2059 "ENGINE": EngineProperty, 2060 "EXECUTE AS": ExecuteAsProperty, 2061 "FORMAT": FileFormatProperty, 2062 "LANGUAGE": LanguageProperty, 2063 "LOCATION": LocationProperty, 2064 "PARTITIONED_BY": PartitionedByProperty, 2065 "RETURNS": ReturnsProperty, 2066 "ROW_FORMAT": RowFormatProperty, 2067 "SORTKEY": SortKeyProperty, 2068 } 2069 2070 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2071 2072 # CREATE property locations 2073 # Form: schema specified 2074 # create [POST_CREATE] 2075 # table a [POST_NAME] 2076 # (b int) [POST_SCHEMA] 2077 # with ([POST_WITH]) 2078 # index (b) [POST_INDEX] 2079 # 2080 # Form: alias selection 2081 # create [POST_CREATE] 2082 # table a [POST_NAME] 2083 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2084 # index (c) [POST_INDEX] 2085 class Location(AutoName): 2086 POST_CREATE = auto() 2087 POST_NAME = auto() 2088 POST_SCHEMA = auto() 2089 POST_WITH = auto() 2090 POST_ALIAS = auto() 2091 POST_EXPRESSION = auto() 2092 POST_INDEX = auto() 2093 UNSUPPORTED = auto() 2094 2095 @classmethod 2096 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2097 expressions = [] 2098 for key, value in properties_dict.items(): 2099 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2100 if property_cls: 2101 expressions.append(property_cls(this=convert(value))) 2102 else: 2103 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2104 2105 return cls(expressions=expressions) 2106 2107 2108class Qualify(Expression): 2109 pass 2110 2111 2112# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 2113class Return(Expression): 2114 pass 2115 2116 2117class Reference(Expression): 2118 arg_types = {"this": True, "expressions": False, "options": False} 2119 2120 2121class Tuple(Expression): 2122 arg_types = {"expressions": False} 2123 2124 def isin( 2125 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2126 ) -> In: 2127 return In( 2128 this=_maybe_copy(self, copy), 2129 expressions=[convert(e, copy=copy) for e in expressions], 2130 query=maybe_parse(query, copy=copy, **opts) if query else None, 2131 ) 2132 2133 2134class Subqueryable(Unionable): 2135 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2136 """ 2137 Convert this expression to an aliased expression that can be used as a Subquery. 2138 2139 Example: 2140 >>> subquery = Select().select("x").from_("tbl").subquery() 2141 >>> Select().select("x").from_(subquery).sql() 2142 'SELECT x FROM (SELECT x FROM tbl)' 2143 2144 Args: 2145 alias (str | Identifier): an optional alias for the subquery 2146 copy (bool): if `False`, modify this expression instance in-place. 2147 2148 Returns: 2149 Alias: the subquery 2150 """ 2151 instance = _maybe_copy(self, copy) 2152 if not isinstance(alias, Expression): 2153 alias = TableAlias(this=to_identifier(alias)) if alias else None 2154 2155 return Subquery(this=instance, alias=alias) 2156 2157 def limit( 2158 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2159 ) -> Select: 2160 raise NotImplementedError 2161 2162 @property 2163 def ctes(self): 2164 with_ = self.args.get("with") 2165 if not with_: 2166 return [] 2167 return with_.expressions 2168 2169 @property 2170 def selects(self): 2171 raise NotImplementedError("Subqueryable objects must implement `selects`") 2172 2173 @property 2174 def named_selects(self): 2175 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2176 2177 def with_( 2178 self, 2179 alias: ExpOrStr, 2180 as_: ExpOrStr, 2181 recursive: t.Optional[bool] = None, 2182 append: bool = True, 2183 dialect: DialectType = None, 2184 copy: bool = True, 2185 **opts, 2186 ) -> Subqueryable: 2187 """ 2188 Append to or set the common table expressions. 2189 2190 Example: 2191 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2192 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2193 2194 Args: 2195 alias: the SQL code string to parse as the table name. 2196 If an `Expression` instance is passed, this is used as-is. 2197 as_: the SQL code string to parse as the table expression. 2198 If an `Expression` instance is passed, it will be used as-is. 2199 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2200 append: if `True`, add to any existing expressions. 2201 Otherwise, this resets the expressions. 2202 dialect: the dialect used to parse the input expression. 2203 copy: if `False`, modify this expression instance in-place. 2204 opts: other options to use to parse the input expressions. 2205 2206 Returns: 2207 The modified expression. 2208 """ 2209 return _apply_cte_builder( 2210 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2211 ) 2212 2213 2214QUERY_MODIFIERS = { 2215 "match": False, 2216 "laterals": False, 2217 "joins": False, 2218 "pivots": False, 2219 "where": False, 2220 "group": False, 2221 "having": False, 2222 "qualify": False, 2223 "windows": False, 2224 "distribute": False, 2225 "sort": False, 2226 "cluster": False, 2227 "order": False, 2228 "limit": False, 2229 "offset": False, 2230 "locks": False, 2231 "sample": False, 2232 "settings": False, 2233 "format": False, 2234} 2235 2236 2237class Table(Expression): 2238 arg_types = { 2239 "this": True, 2240 "alias": False, 2241 "db": False, 2242 "catalog": False, 2243 "laterals": False, 2244 "joins": False, 2245 "pivots": False, 2246 "hints": False, 2247 "system_time": False, 2248 } 2249 2250 @property 2251 def db(self) -> str: 2252 return self.text("db") 2253 2254 @property 2255 def catalog(self) -> str: 2256 return self.text("catalog") 2257 2258 @property 2259 def parts(self) -> t.List[Identifier]: 2260 """Return the parts of a table in order catalog, db, table.""" 2261 return [ 2262 t.cast(Identifier, self.args[part]) 2263 for part in ("catalog", "db", "this") 2264 if self.args.get(part) 2265 ] 2266 2267 2268# See the TSQL "Querying data in a system-versioned temporal table" page 2269class SystemTime(Expression): 2270 arg_types = { 2271 "this": False, 2272 "expression": False, 2273 "kind": True, 2274 } 2275 2276 2277class Union(Subqueryable): 2278 arg_types = { 2279 "with": False, 2280 "this": True, 2281 "expression": True, 2282 "distinct": False, 2283 **QUERY_MODIFIERS, 2284 } 2285 2286 def limit( 2287 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2288 ) -> Select: 2289 """ 2290 Set the LIMIT expression. 2291 2292 Example: 2293 >>> select("1").union(select("1")).limit(1).sql() 2294 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2295 2296 Args: 2297 expression: the SQL code string to parse. 2298 This can also be an integer. 2299 If a `Limit` instance is passed, this is used as-is. 2300 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2301 dialect: the dialect used to parse the input expression. 2302 copy: if `False`, modify this expression instance in-place. 2303 opts: other options to use to parse the input expressions. 2304 2305 Returns: 2306 The limited subqueryable. 2307 """ 2308 return ( 2309 select("*") 2310 .from_(self.subquery(alias="_l_0", copy=copy)) 2311 .limit(expression, dialect=dialect, copy=False, **opts) 2312 ) 2313 2314 def select( 2315 self, 2316 *expressions: t.Optional[ExpOrStr], 2317 append: bool = True, 2318 dialect: DialectType = None, 2319 copy: bool = True, 2320 **opts, 2321 ) -> Union: 2322 """Append to or set the SELECT of the union recursively. 2323 2324 Example: 2325 >>> from sqlglot import parse_one 2326 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2327 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2328 2329 Args: 2330 *expressions: the SQL code strings to parse. 2331 If an `Expression` instance is passed, it will be used as-is. 2332 append: if `True`, add to any existing expressions. 2333 Otherwise, this resets the expressions. 2334 dialect: the dialect used to parse the input expressions. 2335 copy: if `False`, modify this expression instance in-place. 2336 opts: other options to use to parse the input expressions. 2337 2338 Returns: 2339 Union: the modified expression. 2340 """ 2341 this = self.copy() if copy else self 2342 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2343 this.expression.unnest().select( 2344 *expressions, append=append, dialect=dialect, copy=False, **opts 2345 ) 2346 return this 2347 2348 @property 2349 def named_selects(self): 2350 return self.this.unnest().named_selects 2351 2352 @property 2353 def is_star(self) -> bool: 2354 return self.this.is_star or self.expression.is_star 2355 2356 @property 2357 def selects(self): 2358 return self.this.unnest().selects 2359 2360 @property 2361 def left(self): 2362 return self.this 2363 2364 @property 2365 def right(self): 2366 return self.expression 2367 2368 2369class Except(Union): 2370 pass 2371 2372 2373class Intersect(Union): 2374 pass 2375 2376 2377class Unnest(UDTF): 2378 arg_types = { 2379 "expressions": True, 2380 "ordinality": False, 2381 "alias": False, 2382 "offset": False, 2383 } 2384 2385 2386class Update(Expression): 2387 arg_types = { 2388 "with": False, 2389 "this": False, 2390 "expressions": True, 2391 "from": False, 2392 "where": False, 2393 "returning": False, 2394 } 2395 2396 2397class Values(UDTF): 2398 arg_types = { 2399 "expressions": True, 2400 "ordinality": False, 2401 "alias": False, 2402 } 2403 2404 2405class Var(Expression): 2406 pass 2407 2408 2409class Schema(Expression): 2410 arg_types = {"this": False, "expressions": False} 2411 2412 2413# https://dev.mysql.com/doc/refman/8.0/en/select.html 2414# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html 2415class Lock(Expression): 2416 arg_types = {"update": True, "expressions": False, "wait": False} 2417 2418 2419class Select(Subqueryable): 2420 arg_types = { 2421 "with": False, 2422 "kind": False, 2423 "expressions": False, 2424 "hint": False, 2425 "distinct": False, 2426 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2427 "value": False, 2428 "into": False, 2429 "from": False, 2430 **QUERY_MODIFIERS, 2431 } 2432 2433 def from_( 2434 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2435 ) -> Select: 2436 """ 2437 Set the FROM expression. 2438 2439 Example: 2440 >>> Select().from_("tbl").select("x").sql() 2441 'SELECT x FROM tbl' 2442 2443 Args: 2444 expression : the SQL code strings to parse. 2445 If a `From` instance is passed, this is used as-is. 2446 If another `Expression` instance is passed, it will be wrapped in a `From`. 2447 dialect: the dialect used to parse the input expression. 2448 copy: if `False`, modify this expression instance in-place. 2449 opts: other options to use to parse the input expressions. 2450 2451 Returns: 2452 The modified Select expression. 2453 """ 2454 return _apply_builder( 2455 expression=expression, 2456 instance=self, 2457 arg="from", 2458 into=From, 2459 prefix="FROM", 2460 dialect=dialect, 2461 copy=copy, 2462 **opts, 2463 ) 2464 2465 def group_by( 2466 self, 2467 *expressions: t.Optional[ExpOrStr], 2468 append: bool = True, 2469 dialect: DialectType = None, 2470 copy: bool = True, 2471 **opts, 2472 ) -> Select: 2473 """ 2474 Set the GROUP BY expression. 2475 2476 Example: 2477 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2478 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2479 2480 Args: 2481 *expressions: the SQL code strings to parse. 2482 If a `Group` instance is passed, this is used as-is. 2483 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2484 If nothing is passed in then a group by is not applied to the expression 2485 append: if `True`, add to any existing expressions. 2486 Otherwise, this flattens all the `Group` expression into a single expression. 2487 dialect: the dialect used to parse the input expression. 2488 copy: if `False`, modify this expression instance in-place. 2489 opts: other options to use to parse the input expressions. 2490 2491 Returns: 2492 The modified Select expression. 2493 """ 2494 if not expressions: 2495 return self if not copy else self.copy() 2496 2497 return _apply_child_list_builder( 2498 *expressions, 2499 instance=self, 2500 arg="group", 2501 append=append, 2502 copy=copy, 2503 prefix="GROUP BY", 2504 into=Group, 2505 dialect=dialect, 2506 **opts, 2507 ) 2508 2509 def order_by( 2510 self, 2511 *expressions: t.Optional[ExpOrStr], 2512 append: bool = True, 2513 dialect: DialectType = None, 2514 copy: bool = True, 2515 **opts, 2516 ) -> Select: 2517 """ 2518 Set the ORDER BY expression. 2519 2520 Example: 2521 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2522 'SELECT x FROM tbl ORDER BY x DESC' 2523 2524 Args: 2525 *expressions: the SQL code strings to parse. 2526 If a `Group` instance is passed, this is used as-is. 2527 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2528 append: if `True`, add to any existing expressions. 2529 Otherwise, this flattens all the `Order` expression into a single expression. 2530 dialect: the dialect used to parse the input expression. 2531 copy: if `False`, modify this expression instance in-place. 2532 opts: other options to use to parse the input expressions. 2533 2534 Returns: 2535 The modified Select expression. 2536 """ 2537 return _apply_child_list_builder( 2538 *expressions, 2539 instance=self, 2540 arg="order", 2541 append=append, 2542 copy=copy, 2543 prefix="ORDER BY", 2544 into=Order, 2545 dialect=dialect, 2546 **opts, 2547 ) 2548 2549 def sort_by( 2550 self, 2551 *expressions: t.Optional[ExpOrStr], 2552 append: bool = True, 2553 dialect: DialectType = None, 2554 copy: bool = True, 2555 **opts, 2556 ) -> Select: 2557 """ 2558 Set the SORT BY expression. 2559 2560 Example: 2561 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2562 'SELECT x FROM tbl SORT BY x DESC' 2563 2564 Args: 2565 *expressions: the SQL code strings to parse. 2566 If a `Group` instance is passed, this is used as-is. 2567 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2568 append: if `True`, add to any existing expressions. 2569 Otherwise, this flattens all the `Order` expression into a single expression. 2570 dialect: the dialect used to parse the input expression. 2571 copy: if `False`, modify this expression instance in-place. 2572 opts: other options to use to parse the input expressions. 2573 2574 Returns: 2575 The modified Select expression. 2576 """ 2577 return _apply_child_list_builder( 2578 *expressions, 2579 instance=self, 2580 arg="sort", 2581 append=append, 2582 copy=copy, 2583 prefix="SORT BY", 2584 into=Sort, 2585 dialect=dialect, 2586 **opts, 2587 ) 2588 2589 def cluster_by( 2590 self, 2591 *expressions: t.Optional[ExpOrStr], 2592 append: bool = True, 2593 dialect: DialectType = None, 2594 copy: bool = True, 2595 **opts, 2596 ) -> Select: 2597 """ 2598 Set the CLUSTER BY expression. 2599 2600 Example: 2601 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2602 'SELECT x FROM tbl CLUSTER BY x DESC' 2603 2604 Args: 2605 *expressions: the SQL code strings to parse. 2606 If a `Group` instance is passed, this is used as-is. 2607 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2608 append: if `True`, add to any existing expressions. 2609 Otherwise, this flattens all the `Order` expression into a single expression. 2610 dialect: the dialect used to parse the input expression. 2611 copy: if `False`, modify this expression instance in-place. 2612 opts: other options to use to parse the input expressions. 2613 2614 Returns: 2615 The modified Select expression. 2616 """ 2617 return _apply_child_list_builder( 2618 *expressions, 2619 instance=self, 2620 arg="cluster", 2621 append=append, 2622 copy=copy, 2623 prefix="CLUSTER BY", 2624 into=Cluster, 2625 dialect=dialect, 2626 **opts, 2627 ) 2628 2629 def limit( 2630 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2631 ) -> Select: 2632 """ 2633 Set the LIMIT expression. 2634 2635 Example: 2636 >>> Select().from_("tbl").select("x").limit(10).sql() 2637 'SELECT x FROM tbl LIMIT 10' 2638 2639 Args: 2640 expression: the SQL code string to parse. 2641 This can also be an integer. 2642 If a `Limit` instance is passed, this is used as-is. 2643 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2644 dialect: the dialect used to parse the input expression. 2645 copy: if `False`, modify this expression instance in-place. 2646 opts: other options to use to parse the input expressions. 2647 2648 Returns: 2649 Select: the modified expression. 2650 """ 2651 return _apply_builder( 2652 expression=expression, 2653 instance=self, 2654 arg="limit", 2655 into=Limit, 2656 prefix="LIMIT", 2657 dialect=dialect, 2658 copy=copy, 2659 **opts, 2660 ) 2661 2662 def offset( 2663 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2664 ) -> Select: 2665 """ 2666 Set the OFFSET expression. 2667 2668 Example: 2669 >>> Select().from_("tbl").select("x").offset(10).sql() 2670 'SELECT x FROM tbl OFFSET 10' 2671 2672 Args: 2673 expression: the SQL code string to parse. 2674 This can also be an integer. 2675 If a `Offset` instance is passed, this is used as-is. 2676 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2677 dialect: the dialect used to parse the input expression. 2678 copy: if `False`, modify this expression instance in-place. 2679 opts: other options to use to parse the input expressions. 2680 2681 Returns: 2682 The modified Select expression. 2683 """ 2684 return _apply_builder( 2685 expression=expression, 2686 instance=self, 2687 arg="offset", 2688 into=Offset, 2689 prefix="OFFSET", 2690 dialect=dialect, 2691 copy=copy, 2692 **opts, 2693 ) 2694 2695 def select( 2696 self, 2697 *expressions: t.Optional[ExpOrStr], 2698 append: bool = True, 2699 dialect: DialectType = None, 2700 copy: bool = True, 2701 **opts, 2702 ) -> Select: 2703 """ 2704 Append to or set the SELECT expressions. 2705 2706 Example: 2707 >>> Select().select("x", "y").sql() 2708 'SELECT x, y' 2709 2710 Args: 2711 *expressions: the SQL code strings to parse. 2712 If an `Expression` instance is passed, it will be used as-is. 2713 append: if `True`, add to any existing expressions. 2714 Otherwise, this resets the expressions. 2715 dialect: the dialect used to parse the input expressions. 2716 copy: if `False`, modify this expression instance in-place. 2717 opts: other options to use to parse the input expressions. 2718 2719 Returns: 2720 The modified Select expression. 2721 """ 2722 return _apply_list_builder( 2723 *expressions, 2724 instance=self, 2725 arg="expressions", 2726 append=append, 2727 dialect=dialect, 2728 copy=copy, 2729 **opts, 2730 ) 2731 2732 def lateral( 2733 self, 2734 *expressions: t.Optional[ExpOrStr], 2735 append: bool = True, 2736 dialect: DialectType = None, 2737 copy: bool = True, 2738 **opts, 2739 ) -> Select: 2740 """ 2741 Append to or set the LATERAL expressions. 2742 2743 Example: 2744 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2745 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2746 2747 Args: 2748 *expressions: the SQL code strings to parse. 2749 If an `Expression` instance is passed, it will be used as-is. 2750 append: if `True`, add to any existing expressions. 2751 Otherwise, this resets the expressions. 2752 dialect: the dialect used to parse the input expressions. 2753 copy: if `False`, modify this expression instance in-place. 2754 opts: other options to use to parse the input expressions. 2755 2756 Returns: 2757 The modified Select expression. 2758 """ 2759 return _apply_list_builder( 2760 *expressions, 2761 instance=self, 2762 arg="laterals", 2763 append=append, 2764 into=Lateral, 2765 prefix="LATERAL VIEW", 2766 dialect=dialect, 2767 copy=copy, 2768 **opts, 2769 ) 2770 2771 def join( 2772 self, 2773 expression: ExpOrStr, 2774 on: t.Optional[ExpOrStr] = None, 2775 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2776 append: bool = True, 2777 join_type: t.Optional[str] = None, 2778 join_alias: t.Optional[Identifier | str] = None, 2779 dialect: DialectType = None, 2780 copy: bool = True, 2781 **opts, 2782 ) -> Select: 2783 """ 2784 Append to or set the JOIN expressions. 2785 2786 Example: 2787 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2788 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2789 2790 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2791 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2792 2793 Use `join_type` to change the type of join: 2794 2795 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2796 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2797 2798 Args: 2799 expression: the SQL code string to parse. 2800 If an `Expression` instance is passed, it will be used as-is. 2801 on: optionally specify the join "on" criteria as a SQL string. 2802 If an `Expression` instance is passed, it will be used as-is. 2803 using: optionally specify the join "using" criteria as a SQL string. 2804 If an `Expression` instance is passed, it will be used as-is. 2805 append: if `True`, add to any existing expressions. 2806 Otherwise, this resets the expressions. 2807 join_type: if set, alter the parsed join type. 2808 join_alias: an optional alias for the joined source. 2809 dialect: the dialect used to parse the input expressions. 2810 copy: if `False`, modify this expression instance in-place. 2811 opts: other options to use to parse the input expressions. 2812 2813 Returns: 2814 Select: the modified expression. 2815 """ 2816 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2817 2818 try: 2819 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2820 except ParseError: 2821 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2822 2823 join = expression if isinstance(expression, Join) else Join(this=expression) 2824 2825 if isinstance(join.this, Select): 2826 join.this.replace(join.this.subquery()) 2827 2828 if join_type: 2829 method: t.Optional[Token] 2830 side: t.Optional[Token] 2831 kind: t.Optional[Token] 2832 2833 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2834 2835 if method: 2836 join.set("method", method.text) 2837 if side: 2838 join.set("side", side.text) 2839 if kind: 2840 join.set("kind", kind.text) 2841 2842 if on: 2843 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2844 join.set("on", on) 2845 2846 if using: 2847 join = _apply_list_builder( 2848 *ensure_list(using), 2849 instance=join, 2850 arg="using", 2851 append=append, 2852 copy=copy, 2853 **opts, 2854 ) 2855 2856 if join_alias: 2857 join.set("this", alias_(join.this, join_alias, table=True)) 2858 2859 return _apply_list_builder( 2860 join, 2861 instance=self, 2862 arg="joins", 2863 append=append, 2864 copy=copy, 2865 **opts, 2866 ) 2867 2868 def where( 2869 self, 2870 *expressions: t.Optional[ExpOrStr], 2871 append: bool = True, 2872 dialect: DialectType = None, 2873 copy: bool = True, 2874 **opts, 2875 ) -> Select: 2876 """ 2877 Append to or set the WHERE expressions. 2878 2879 Example: 2880 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2881 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2882 2883 Args: 2884 *expressions: the SQL code strings to parse. 2885 If an `Expression` instance is passed, it will be used as-is. 2886 Multiple expressions are combined with an AND operator. 2887 append: if `True`, AND the new expressions to any existing expression. 2888 Otherwise, this resets the expression. 2889 dialect: the dialect used to parse the input expressions. 2890 copy: if `False`, modify this expression instance in-place. 2891 opts: other options to use to parse the input expressions. 2892 2893 Returns: 2894 Select: the modified expression. 2895 """ 2896 return _apply_conjunction_builder( 2897 *expressions, 2898 instance=self, 2899 arg="where", 2900 append=append, 2901 into=Where, 2902 dialect=dialect, 2903 copy=copy, 2904 **opts, 2905 ) 2906 2907 def having( 2908 self, 2909 *expressions: t.Optional[ExpOrStr], 2910 append: bool = True, 2911 dialect: DialectType = None, 2912 copy: bool = True, 2913 **opts, 2914 ) -> Select: 2915 """ 2916 Append to or set the HAVING expressions. 2917 2918 Example: 2919 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2920 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2921 2922 Args: 2923 *expressions: the SQL code strings to parse. 2924 If an `Expression` instance is passed, it will be used as-is. 2925 Multiple expressions are combined with an AND operator. 2926 append: if `True`, AND the new expressions to any existing expression. 2927 Otherwise, this resets the expression. 2928 dialect: the dialect used to parse the input expressions. 2929 copy: if `False`, modify this expression instance in-place. 2930 opts: other options to use to parse the input expressions. 2931 2932 Returns: 2933 The modified Select expression. 2934 """ 2935 return _apply_conjunction_builder( 2936 *expressions, 2937 instance=self, 2938 arg="having", 2939 append=append, 2940 into=Having, 2941 dialect=dialect, 2942 copy=copy, 2943 **opts, 2944 ) 2945 2946 def window( 2947 self, 2948 *expressions: t.Optional[ExpOrStr], 2949 append: bool = True, 2950 dialect: DialectType = None, 2951 copy: bool = True, 2952 **opts, 2953 ) -> Select: 2954 return _apply_list_builder( 2955 *expressions, 2956 instance=self, 2957 arg="windows", 2958 append=append, 2959 into=Window, 2960 dialect=dialect, 2961 copy=copy, 2962 **opts, 2963 ) 2964 2965 def qualify( 2966 self, 2967 *expressions: t.Optional[ExpOrStr], 2968 append: bool = True, 2969 dialect: DialectType = None, 2970 copy: bool = True, 2971 **opts, 2972 ) -> Select: 2973 return _apply_conjunction_builder( 2974 *expressions, 2975 instance=self, 2976 arg="qualify", 2977 append=append, 2978 into=Qualify, 2979 dialect=dialect, 2980 copy=copy, 2981 **opts, 2982 ) 2983 2984 def distinct( 2985 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2986 ) -> Select: 2987 """ 2988 Set the OFFSET expression. 2989 2990 Example: 2991 >>> Select().from_("tbl").select("x").distinct().sql() 2992 'SELECT DISTINCT x FROM tbl' 2993 2994 Args: 2995 ons: the expressions to distinct on 2996 distinct: whether the Select should be distinct 2997 copy: if `False`, modify this expression instance in-place. 2998 2999 Returns: 3000 Select: the modified expression. 3001 """ 3002 instance = _maybe_copy(self, copy) 3003 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3004 instance.set("distinct", Distinct(on=on) if distinct else None) 3005 return instance 3006 3007 def ctas( 3008 self, 3009 table: ExpOrStr, 3010 properties: t.Optional[t.Dict] = None, 3011 dialect: DialectType = None, 3012 copy: bool = True, 3013 **opts, 3014 ) -> Create: 3015 """ 3016 Convert this expression to a CREATE TABLE AS statement. 3017 3018 Example: 3019 >>> Select().select("*").from_("tbl").ctas("x").sql() 3020 'CREATE TABLE x AS SELECT * FROM tbl' 3021 3022 Args: 3023 table: the SQL code string to parse as the table name. 3024 If another `Expression` instance is passed, it will be used as-is. 3025 properties: an optional mapping of table properties 3026 dialect: the dialect used to parse the input table. 3027 copy: if `False`, modify this expression instance in-place. 3028 opts: other options to use to parse the input table. 3029 3030 Returns: 3031 The new Create expression. 3032 """ 3033 instance = _maybe_copy(self, copy) 3034 table_expression = maybe_parse( 3035 table, 3036 into=Table, 3037 dialect=dialect, 3038 **opts, 3039 ) 3040 properties_expression = None 3041 if properties: 3042 properties_expression = Properties.from_dict(properties) 3043 3044 return Create( 3045 this=table_expression, 3046 kind="table", 3047 expression=instance, 3048 properties=properties_expression, 3049 ) 3050 3051 def lock(self, update: bool = True, copy: bool = True) -> Select: 3052 """ 3053 Set the locking read mode for this expression. 3054 3055 Examples: 3056 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3057 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3058 3059 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3060 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3061 3062 Args: 3063 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3064 copy: if `False`, modify this expression instance in-place. 3065 3066 Returns: 3067 The modified expression. 3068 """ 3069 3070 inst = _maybe_copy(self, copy) 3071 inst.set("locks", [Lock(update=update)]) 3072 3073 return inst 3074 3075 @property 3076 def named_selects(self) -> t.List[str]: 3077 return [e.output_name for e in self.expressions if e.alias_or_name] 3078 3079 @property 3080 def is_star(self) -> bool: 3081 return any(expression.is_star for expression in self.expressions) 3082 3083 @property 3084 def selects(self) -> t.List[Expression]: 3085 return self.expressions 3086 3087 3088class Subquery(DerivedTable, Unionable): 3089 arg_types = { 3090 "this": True, 3091 "alias": False, 3092 "with": False, 3093 **QUERY_MODIFIERS, 3094 } 3095 3096 def unnest(self): 3097 """ 3098 Returns the first non subquery. 3099 """ 3100 expression = self 3101 while isinstance(expression, Subquery): 3102 expression = expression.this 3103 return expression 3104 3105 @property 3106 def is_star(self) -> bool: 3107 return self.this.is_star 3108 3109 @property 3110 def output_name(self) -> str: 3111 return self.alias 3112 3113 3114class TableSample(Expression): 3115 arg_types = { 3116 "this": False, 3117 "method": False, 3118 "bucket_numerator": False, 3119 "bucket_denominator": False, 3120 "bucket_field": False, 3121 "percent": False, 3122 "rows": False, 3123 "size": False, 3124 "seed": False, 3125 "kind": False, 3126 } 3127 3128 3129class Tag(Expression): 3130 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3131 3132 arg_types = { 3133 "this": False, 3134 "prefix": False, 3135 "postfix": False, 3136 } 3137 3138 3139# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax 3140# https://duckdb.org/docs/sql/statements/pivot 3141class Pivot(Expression): 3142 arg_types = { 3143 "this": False, 3144 "alias": False, 3145 "expressions": True, 3146 "field": False, 3147 "unpivot": False, 3148 "using": False, 3149 "group": False, 3150 "columns": False, 3151 } 3152 3153 3154class Window(Expression): 3155 arg_types = { 3156 "this": True, 3157 "partition_by": False, 3158 "order": False, 3159 "spec": False, 3160 "alias": False, 3161 "over": False, 3162 "first": False, 3163 } 3164 3165 3166class WindowSpec(Expression): 3167 arg_types = { 3168 "kind": False, 3169 "start": False, 3170 "start_side": False, 3171 "end": False, 3172 "end_side": False, 3173 } 3174 3175 3176class Where(Expression): 3177 pass 3178 3179 3180class Star(Expression): 3181 arg_types = {"except": False, "replace": False} 3182 3183 @property 3184 def name(self) -> str: 3185 return "*" 3186 3187 @property 3188 def output_name(self) -> str: 3189 return self.name 3190 3191 3192class Parameter(Expression): 3193 arg_types = {"this": True, "wrapped": False} 3194 3195 3196class SessionParameter(Expression): 3197 arg_types = {"this": True, "kind": False} 3198 3199 3200class Placeholder(Expression): 3201 arg_types = {"this": False, "kind": False} 3202 3203 3204class Null(Condition): 3205 arg_types: t.Dict[str, t.Any] = {} 3206 3207 @property 3208 def name(self) -> str: 3209 return "NULL" 3210 3211 3212class Boolean(Condition): 3213 pass 3214 3215 3216class DataTypeSize(Expression): 3217 arg_types = {"this": True, "expression": False} 3218 3219 3220class DataType(Expression): 3221 arg_types = { 3222 "this": True, 3223 "expressions": False, 3224 "nested": False, 3225 "values": False, 3226 "prefix": False, 3227 } 3228 3229 class Type(AutoName): 3230 ARRAY = auto() 3231 BIGDECIMAL = auto() 3232 BIGINT = auto() 3233 BIGSERIAL = auto() 3234 BINARY = auto() 3235 BIT = auto() 3236 BOOLEAN = auto() 3237 CHAR = auto() 3238 DATE = auto() 3239 DATETIME = auto() 3240 DATETIME64 = auto() 3241 INT4RANGE = auto() 3242 INT4MULTIRANGE = auto() 3243 INT8RANGE = auto() 3244 INT8MULTIRANGE = auto() 3245 NUMRANGE = auto() 3246 NUMMULTIRANGE = auto() 3247 TSRANGE = auto() 3248 TSMULTIRANGE = auto() 3249 TSTZRANGE = auto() 3250 TSTZMULTIRANGE = auto() 3251 DATERANGE = auto() 3252 DATEMULTIRANGE = auto() 3253 DECIMAL = auto() 3254 DOUBLE = auto() 3255 FLOAT = auto() 3256 GEOGRAPHY = auto() 3257 GEOMETRY = auto() 3258 HLLSKETCH = auto() 3259 HSTORE = auto() 3260 IMAGE = auto() 3261 INET = auto() 3262 INT = auto() 3263 INT128 = auto() 3264 INT256 = auto() 3265 INTERVAL = auto() 3266 JSON = auto() 3267 JSONB = auto() 3268 LONGBLOB = auto() 3269 LONGTEXT = auto() 3270 MAP = auto() 3271 MEDIUMBLOB = auto() 3272 MEDIUMTEXT = auto() 3273 MONEY = auto() 3274 NCHAR = auto() 3275 NULL = auto() 3276 NULLABLE = auto() 3277 NVARCHAR = auto() 3278 OBJECT = auto() 3279 ROWVERSION = auto() 3280 SERIAL = auto() 3281 SMALLINT = auto() 3282 SMALLMONEY = auto() 3283 SMALLSERIAL = auto() 3284 STRUCT = auto() 3285 SUPER = auto() 3286 TEXT = auto() 3287 TIME = auto() 3288 TIMESTAMP = auto() 3289 TIMESTAMPTZ = auto() 3290 TIMESTAMPLTZ = auto() 3291 TINYINT = auto() 3292 UBIGINT = auto() 3293 UINT = auto() 3294 USMALLINT = auto() 3295 UTINYINT = auto() 3296 UNKNOWN = auto() # Sentinel value, useful for type annotation 3297 UINT128 = auto() 3298 UINT256 = auto() 3299 UNIQUEIDENTIFIER = auto() 3300 UUID = auto() 3301 VARBINARY = auto() 3302 VARCHAR = auto() 3303 VARIANT = auto() 3304 XML = auto() 3305 3306 TEXT_TYPES = { 3307 Type.CHAR, 3308 Type.NCHAR, 3309 Type.VARCHAR, 3310 Type.NVARCHAR, 3311 Type.TEXT, 3312 } 3313 3314 INTEGER_TYPES = { 3315 Type.INT, 3316 Type.TINYINT, 3317 Type.SMALLINT, 3318 Type.BIGINT, 3319 Type.INT128, 3320 Type.INT256, 3321 } 3322 3323 FLOAT_TYPES = { 3324 Type.FLOAT, 3325 Type.DOUBLE, 3326 } 3327 3328 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3329 3330 TEMPORAL_TYPES = { 3331 Type.TIMESTAMP, 3332 Type.TIMESTAMPTZ, 3333 Type.TIMESTAMPLTZ, 3334 Type.DATE, 3335 Type.DATETIME, 3336 Type.DATETIME64, 3337 } 3338 3339 @classmethod 3340 def build( 3341 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3342 ) -> DataType: 3343 from sqlglot import parse_one 3344 3345 if isinstance(dtype, str): 3346 if dtype.upper() in cls.Type.__members__: 3347 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3348 else: 3349 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3350 3351 if data_type_exp is None: 3352 raise ValueError(f"Unparsable data type value: {dtype}") 3353 elif isinstance(dtype, DataType.Type): 3354 data_type_exp = DataType(this=dtype) 3355 elif isinstance(dtype, DataType): 3356 return dtype 3357 else: 3358 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3359 3360 return DataType(**{**data_type_exp.args, **kwargs}) 3361 3362 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3363 return any(self.this == DataType.build(dtype).this for dtype in dtypes) 3364 3365 3366# https://www.postgresql.org/docs/15/datatype-pseudo.html 3367class PseudoType(Expression): 3368 pass 3369 3370 3371# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 3372class SubqueryPredicate(Predicate): 3373 pass 3374 3375 3376class All(SubqueryPredicate): 3377 pass 3378 3379 3380class Any(SubqueryPredicate): 3381 pass 3382 3383 3384class Exists(SubqueryPredicate): 3385 pass 3386 3387 3388# Commands to interact with the databases or engines. For most of the command 3389# expressions we parse whatever comes after the command's name as a string. 3390class Command(Expression): 3391 arg_types = {"this": True, "expression": False} 3392 3393 3394class Transaction(Expression): 3395 arg_types = {"this": False, "modes": False} 3396 3397 3398class Commit(Expression): 3399 arg_types = {"chain": False} 3400 3401 3402class Rollback(Expression): 3403 arg_types = {"savepoint": False} 3404 3405 3406class AlterTable(Expression): 3407 arg_types = {"this": True, "actions": True, "exists": False} 3408 3409 3410class AddConstraint(Expression): 3411 arg_types = {"this": False, "expression": False, "enforced": False} 3412 3413 3414class DropPartition(Expression): 3415 arg_types = {"expressions": True, "exists": False} 3416 3417 3418# Binary expressions like (ADD a b) 3419class Binary(Condition): 3420 arg_types = {"this": True, "expression": True} 3421 3422 @property 3423 def left(self): 3424 return self.this 3425 3426 @property 3427 def right(self): 3428 return self.expression 3429 3430 3431class Add(Binary): 3432 pass 3433 3434 3435class Connector(Binary): 3436 pass 3437 3438 3439class And(Connector): 3440 pass 3441 3442 3443class Or(Connector): 3444 pass 3445 3446 3447class BitwiseAnd(Binary): 3448 pass 3449 3450 3451class BitwiseLeftShift(Binary): 3452 pass 3453 3454 3455class BitwiseOr(Binary): 3456 pass 3457 3458 3459class BitwiseRightShift(Binary): 3460 pass 3461 3462 3463class BitwiseXor(Binary): 3464 pass 3465 3466 3467class Div(Binary): 3468 pass 3469 3470 3471class Overlaps(Binary): 3472 pass 3473 3474 3475class Dot(Binary): 3476 @property 3477 def name(self) -> str: 3478 return self.expression.name 3479 3480 @classmethod 3481 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3482 """Build a Dot object with a sequence of expressions.""" 3483 if len(expressions) < 2: 3484 raise ValueError(f"Dot requires >= 2 expressions.") 3485 3486 a, b, *expressions = expressions 3487 dot = Dot(this=a, expression=b) 3488 3489 for expression in expressions: 3490 dot = Dot(this=dot, expression=expression) 3491 3492 return dot 3493 3494 3495class DPipe(Binary): 3496 pass 3497 3498 3499class EQ(Binary, Predicate): 3500 pass 3501 3502 3503class NullSafeEQ(Binary, Predicate): 3504 pass 3505 3506 3507class NullSafeNEQ(Binary, Predicate): 3508 pass 3509 3510 3511class Distance(Binary): 3512 pass 3513 3514 3515class Escape(Binary): 3516 pass 3517 3518 3519class Glob(Binary, Predicate): 3520 pass 3521 3522 3523class GT(Binary, Predicate): 3524 pass 3525 3526 3527class GTE(Binary, Predicate): 3528 pass 3529 3530 3531class ILike(Binary, Predicate): 3532 pass 3533 3534 3535class ILikeAny(Binary, Predicate): 3536 pass 3537 3538 3539class IntDiv(Binary): 3540 pass 3541 3542 3543class Is(Binary, Predicate): 3544 pass 3545 3546 3547class Kwarg(Binary): 3548 """Kwarg in special functions like func(kwarg => y).""" 3549 3550 3551class Like(Binary, Predicate): 3552 pass 3553 3554 3555class LikeAny(Binary, Predicate): 3556 pass 3557 3558 3559class LT(Binary, Predicate): 3560 pass 3561 3562 3563class LTE(Binary, Predicate): 3564 pass 3565 3566 3567class Mod(Binary): 3568 pass 3569 3570 3571class Mul(Binary): 3572 pass 3573 3574 3575class NEQ(Binary, Predicate): 3576 pass 3577 3578 3579class SimilarTo(Binary, Predicate): 3580 pass 3581 3582 3583class Slice(Binary): 3584 arg_types = {"this": False, "expression": False} 3585 3586 3587class Sub(Binary): 3588 pass 3589 3590 3591class ArrayOverlaps(Binary): 3592 pass 3593 3594 3595# Unary Expressions 3596# (NOT a) 3597class Unary(Condition): 3598 pass 3599 3600 3601class BitwiseNot(Unary): 3602 pass 3603 3604 3605class Not(Unary): 3606 pass 3607 3608 3609class Paren(Unary): 3610 arg_types = {"this": True, "with": False} 3611 3612 3613class Neg(Unary): 3614 pass 3615 3616 3617class Alias(Expression): 3618 arg_types = {"this": True, "alias": False} 3619 3620 @property 3621 def output_name(self) -> str: 3622 return self.alias 3623 3624 3625class Aliases(Expression): 3626 arg_types = {"this": True, "expressions": True} 3627 3628 @property 3629 def aliases(self): 3630 return self.expressions 3631 3632 3633class AtTimeZone(Expression): 3634 arg_types = {"this": True, "zone": True} 3635 3636 3637class Between(Predicate): 3638 arg_types = {"this": True, "low": True, "high": True} 3639 3640 3641class Bracket(Condition): 3642 arg_types = {"this": True, "expressions": True} 3643 3644 3645class Distinct(Expression): 3646 arg_types = {"expressions": False, "on": False} 3647 3648 3649class In(Predicate): 3650 arg_types = { 3651 "this": True, 3652 "expressions": False, 3653 "query": False, 3654 "unnest": False, 3655 "field": False, 3656 "is_global": False, 3657 } 3658 3659 3660class TimeUnit(Expression): 3661 """Automatically converts unit arg into a var.""" 3662 3663 arg_types = {"unit": False} 3664 3665 def __init__(self, **args): 3666 unit = args.get("unit") 3667 if isinstance(unit, (Column, Literal)): 3668 args["unit"] = Var(this=unit.name) 3669 elif isinstance(unit, Week): 3670 unit.set("this", Var(this=unit.this.name)) 3671 3672 super().__init__(**args) 3673 3674 3675class Interval(TimeUnit): 3676 arg_types = {"this": False, "unit": False} 3677 3678 @property 3679 def unit(self) -> t.Optional[Var]: 3680 return self.args.get("unit") 3681 3682 3683class IgnoreNulls(Expression): 3684 pass 3685 3686 3687class RespectNulls(Expression): 3688 pass 3689 3690 3691# Functions 3692class Func(Condition): 3693 """ 3694 The base class for all function expressions. 3695 3696 Attributes: 3697 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3698 treated as a variable length argument and the argument's value will be stored as a list. 3699 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3700 for this function expression. These values are used to map this node to a name during parsing 3701 as well as to provide the function's name during SQL string generation. By default the SQL 3702 name is set to the expression's class name transformed to snake case. 3703 """ 3704 3705 is_var_len_args = False 3706 3707 @classmethod 3708 def from_arg_list(cls, args): 3709 if cls.is_var_len_args: 3710 all_arg_keys = list(cls.arg_types) 3711 # If this function supports variable length argument treat the last argument as such. 3712 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3713 num_non_var = len(non_var_len_arg_keys) 3714 3715 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3716 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3717 else: 3718 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3719 3720 return cls(**args_dict) 3721 3722 @classmethod 3723 def sql_names(cls): 3724 if cls is Func: 3725 raise NotImplementedError( 3726 "SQL name is only supported by concrete function implementations" 3727 ) 3728 if "_sql_names" not in cls.__dict__: 3729 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3730 return cls._sql_names 3731 3732 @classmethod 3733 def sql_name(cls): 3734 return cls.sql_names()[0] 3735 3736 @classmethod 3737 def default_parser_mappings(cls): 3738 return {name: cls.from_arg_list for name in cls.sql_names()} 3739 3740 3741class AggFunc(Func): 3742 pass 3743 3744 3745class ParameterizedAgg(AggFunc): 3746 arg_types = {"this": True, "expressions": True, "params": True} 3747 3748 3749class Abs(Func): 3750 pass 3751 3752 3753class Anonymous(Func): 3754 arg_types = {"this": True, "expressions": False} 3755 is_var_len_args = True 3756 3757 3758# https://docs.snowflake.com/en/sql-reference/functions/hll 3759# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3760class Hll(AggFunc): 3761 arg_types = {"this": True, "expressions": False} 3762 is_var_len_args = True 3763 3764 3765class ApproxDistinct(AggFunc): 3766 arg_types = {"this": True, "accuracy": False} 3767 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"] 3768 3769 3770class Array(Func): 3771 arg_types = {"expressions": False} 3772 is_var_len_args = True 3773 3774 3775# https://docs.snowflake.com/en/sql-reference/functions/to_char 3776class ToChar(Func): 3777 arg_types = {"this": True, "format": False} 3778 3779 3780class GenerateSeries(Func): 3781 arg_types = {"start": True, "end": True, "step": False} 3782 3783 3784class ArrayAgg(AggFunc): 3785 pass 3786 3787 3788class ArrayAll(Func): 3789 arg_types = {"this": True, "expression": True} 3790 3791 3792class ArrayAny(Func): 3793 arg_types = {"this": True, "expression": True} 3794 3795 3796class ArrayConcat(Func): 3797 arg_types = {"this": True, "expressions": False} 3798 is_var_len_args = True 3799 3800 3801class ArrayContains(Binary, Func): 3802 pass 3803 3804 3805class ArrayContained(Binary): 3806 pass 3807 3808 3809class ArrayFilter(Func): 3810 arg_types = {"this": True, "expression": True} 3811 _sql_names = ["FILTER", "ARRAY_FILTER"] 3812 3813 3814class ArrayJoin(Func): 3815 arg_types = {"this": True, "expression": True, "null": False} 3816 3817 3818class ArraySize(Func): 3819 arg_types = {"this": True, "expression": False} 3820 3821 3822class ArraySort(Func): 3823 arg_types = {"this": True, "expression": False} 3824 3825 3826class ArraySum(Func): 3827 pass 3828 3829 3830class ArrayUnionAgg(AggFunc): 3831 pass 3832 3833 3834class Avg(AggFunc): 3835 pass 3836 3837 3838class AnyValue(AggFunc): 3839 pass 3840 3841 3842class Case(Func): 3843 arg_types = {"this": False, "ifs": True, "default": False} 3844 3845 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3846 instance = _maybe_copy(self, copy) 3847 instance.append( 3848 "ifs", 3849 If( 3850 this=maybe_parse(condition, copy=copy, **opts), 3851 true=maybe_parse(then, copy=copy, **opts), 3852 ), 3853 ) 3854 return instance 3855 3856 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3857 instance = _maybe_copy(self, copy) 3858 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3859 return instance 3860 3861 3862class Cast(Func): 3863 arg_types = {"this": True, "to": True} 3864 3865 @property 3866 def name(self) -> str: 3867 return self.this.name 3868 3869 @property 3870 def to(self) -> DataType: 3871 return self.args["to"] 3872 3873 @property 3874 def output_name(self) -> str: 3875 return self.name 3876 3877 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3878 return self.to.is_type(*dtypes) 3879 3880 3881class CastToStrType(Func): 3882 arg_types = {"this": True, "expression": True} 3883 3884 3885class Collate(Binary): 3886 pass 3887 3888 3889class TryCast(Cast): 3890 pass 3891 3892 3893class Ceil(Func): 3894 arg_types = {"this": True, "decimals": False} 3895 _sql_names = ["CEIL", "CEILING"] 3896 3897 3898class Coalesce(Func): 3899 arg_types = {"this": True, "expressions": False} 3900 is_var_len_args = True 3901 3902 3903class Concat(Func): 3904 arg_types = {"expressions": True} 3905 is_var_len_args = True 3906 3907 3908class ConcatWs(Concat): 3909 _sql_names = ["CONCAT_WS"] 3910 3911 3912class Count(AggFunc): 3913 arg_types = {"this": False} 3914 3915 3916class CountIf(AggFunc): 3917 pass 3918 3919 3920class CurrentDate(Func): 3921 arg_types = {"this": False} 3922 3923 3924class CurrentDatetime(Func): 3925 arg_types = {"this": False} 3926 3927 3928class CurrentTime(Func): 3929 arg_types = {"this": False} 3930 3931 3932class CurrentTimestamp(Func): 3933 arg_types = {"this": False} 3934 3935 3936class CurrentUser(Func): 3937 arg_types = {"this": False} 3938 3939 3940class DateAdd(Func, TimeUnit): 3941 arg_types = {"this": True, "expression": True, "unit": False} 3942 3943 3944class DateSub(Func, TimeUnit): 3945 arg_types = {"this": True, "expression": True, "unit": False} 3946 3947 3948class DateDiff(Func, TimeUnit): 3949 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3950 arg_types = {"this": True, "expression": True, "unit": False} 3951 3952 3953class DateTrunc(Func): 3954 arg_types = {"unit": True, "this": True, "zone": False} 3955 3956 3957class DatetimeAdd(Func, TimeUnit): 3958 arg_types = {"this": True, "expression": True, "unit": False} 3959 3960 3961class DatetimeSub(Func, TimeUnit): 3962 arg_types = {"this": True, "expression": True, "unit": False} 3963 3964 3965class DatetimeDiff(Func, TimeUnit): 3966 arg_types = {"this": True, "expression": True, "unit": False} 3967 3968 3969class DatetimeTrunc(Func, TimeUnit): 3970 arg_types = {"this": True, "unit": True, "zone": False} 3971 3972 3973class DayOfWeek(Func): 3974 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3975 3976 3977class DayOfMonth(Func): 3978 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3979 3980 3981class DayOfYear(Func): 3982 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3983 3984 3985class WeekOfYear(Func): 3986 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3987 3988 3989class LastDateOfMonth(Func): 3990 pass 3991 3992 3993class Extract(Func): 3994 arg_types = {"this": True, "expression": True} 3995 3996 3997class TimestampAdd(Func, TimeUnit): 3998 arg_types = {"this": True, "expression": True, "unit": False} 3999 4000 4001class TimestampSub(Func, TimeUnit): 4002 arg_types = {"this": True, "expression": True, "unit": False} 4003 4004 4005class TimestampDiff(Func, TimeUnit): 4006 arg_types = {"this": True, "expression": True, "unit": False} 4007 4008 4009class TimestampTrunc(Func, TimeUnit): 4010 arg_types = {"this": True, "unit": True, "zone": False} 4011 4012 4013class TimeAdd(Func, TimeUnit): 4014 arg_types = {"this": True, "expression": True, "unit": False} 4015 4016 4017class TimeSub(Func, TimeUnit): 4018 arg_types = {"this": True, "expression": True, "unit": False} 4019 4020 4021class TimeDiff(Func, TimeUnit): 4022 arg_types = {"this": True, "expression": True, "unit": False} 4023 4024 4025class TimeTrunc(Func, TimeUnit): 4026 arg_types = {"this": True, "unit": True, "zone": False} 4027 4028 4029class DateFromParts(Func): 4030 _sql_names = ["DATEFROMPARTS"] 4031 arg_types = {"year": True, "month": True, "day": True} 4032 4033 4034class DateStrToDate(Func): 4035 pass 4036 4037 4038class DateToDateStr(Func): 4039 pass 4040 4041 4042class DateToDi(Func): 4043 pass 4044 4045 4046class Day(Func): 4047 pass 4048 4049 4050class Decode(Func): 4051 arg_types = {"this": True, "charset": True, "replace": False} 4052 4053 4054class DiToDate(Func): 4055 pass 4056 4057 4058class Encode(Func): 4059 arg_types = {"this": True, "charset": True} 4060 4061 4062class Exp(Func): 4063 pass 4064 4065 4066class Explode(Func): 4067 pass 4068 4069 4070class Floor(Func): 4071 arg_types = {"this": True, "decimals": False} 4072 4073 4074class FromBase64(Func): 4075 pass 4076 4077 4078class ToBase64(Func): 4079 pass 4080 4081 4082class Greatest(Func): 4083 arg_types = {"this": True, "expressions": False} 4084 is_var_len_args = True 4085 4086 4087class GroupConcat(Func): 4088 arg_types = {"this": True, "separator": False} 4089 4090 4091class Hex(Func): 4092 pass 4093 4094 4095class If(Func): 4096 arg_types = {"this": True, "true": True, "false": False} 4097 4098 4099class IfNull(Func): 4100 arg_types = {"this": True, "expression": False} 4101 _sql_names = ["IFNULL", "NVL"] 4102 4103 4104class Initcap(Func): 4105 arg_types = {"this": True, "expression": False} 4106 4107 4108class JSONKeyValue(Expression): 4109 arg_types = {"this": True, "expression": True} 4110 4111 4112class JSONObject(Func): 4113 arg_types = { 4114 "expressions": False, 4115 "null_handling": False, 4116 "unique_keys": False, 4117 "return_type": False, 4118 "format_json": False, 4119 "encoding": False, 4120 } 4121 4122 4123class OpenJSONColumnDef(Expression): 4124 arg_types = {"this": True, "kind": True, "path": False, "as_json": False} 4125 4126 4127class OpenJSON(Func): 4128 arg_types = {"this": True, "path": False, "expressions": False} 4129 4130 4131class JSONBContains(Binary): 4132 _sql_names = ["JSONB_CONTAINS"] 4133 4134 4135class JSONExtract(Binary, Func): 4136 _sql_names = ["JSON_EXTRACT"] 4137 4138 4139class JSONExtractScalar(JSONExtract): 4140 _sql_names = ["JSON_EXTRACT_SCALAR"] 4141 4142 4143class JSONBExtract(JSONExtract): 4144 _sql_names = ["JSONB_EXTRACT"] 4145 4146 4147class JSONBExtractScalar(JSONExtract): 4148 _sql_names = ["JSONB_EXTRACT_SCALAR"] 4149 4150 4151class JSONFormat(Func): 4152 arg_types = {"this": False, "options": False} 4153 _sql_names = ["JSON_FORMAT"] 4154 4155 4156class Least(Func): 4157 arg_types = {"expressions": False} 4158 is_var_len_args = True 4159 4160 4161class Left(Func): 4162 arg_types = {"this": True, "expression": True} 4163 4164 4165class Right(Func): 4166 arg_types = {"this": True, "expression": True} 4167 4168 4169class Length(Func): 4170 pass 4171 4172 4173class Levenshtein(Func): 4174 arg_types = { 4175 "this": True, 4176 "expression": False, 4177 "ins_cost": False, 4178 "del_cost": False, 4179 "sub_cost": False, 4180 } 4181 4182 4183class Ln(Func): 4184 pass 4185 4186 4187class Log(Func): 4188 arg_types = {"this": True, "expression": False} 4189 4190 4191class Log2(Func): 4192 pass 4193 4194 4195class Log10(Func): 4196 pass 4197 4198 4199class LogicalOr(AggFunc): 4200 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 4201 4202 4203class LogicalAnd(AggFunc): 4204 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 4205 4206 4207class Lower(Func): 4208 _sql_names = ["LOWER", "LCASE"] 4209 4210 4211class Map(Func): 4212 arg_types = {"keys": False, "values": False} 4213 4214 4215class StarMap(Func): 4216 pass 4217 4218 4219class VarMap(Func): 4220 arg_types = {"keys": True, "values": True} 4221 is_var_len_args = True 4222 4223 @property 4224 def keys(self) -> t.List[Expression]: 4225 return self.args["keys"].expressions 4226 4227 @property 4228 def values(self) -> t.List[Expression]: 4229 return self.args["values"].expressions 4230 4231 4232# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 4233class MatchAgainst(Func): 4234 arg_types = {"this": True, "expressions": True, "modifier": False} 4235 4236 4237class Max(AggFunc): 4238 arg_types = {"this": True, "expressions": False} 4239 is_var_len_args = True 4240 4241 4242class MD5(Func): 4243 _sql_names = ["MD5"] 4244 4245 4246class Min(AggFunc): 4247 arg_types = {"this": True, "expressions": False} 4248 is_var_len_args = True 4249 4250 4251class Month(Func): 4252 pass 4253 4254 4255class Nvl2(Func): 4256 arg_types = {"this": True, "true": True, "false": False} 4257 4258 4259class Posexplode(Func): 4260 pass 4261 4262 4263class Pow(Binary, Func): 4264 _sql_names = ["POWER", "POW"] 4265 4266 4267class PercentileCont(AggFunc): 4268 arg_types = {"this": True, "expression": False} 4269 4270 4271class PercentileDisc(AggFunc): 4272 arg_types = {"this": True, "expression": False} 4273 4274 4275class Quantile(AggFunc): 4276 arg_types = {"this": True, "quantile": True} 4277 4278 4279class ApproxQuantile(Quantile): 4280 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 4281 4282 4283class RangeN(Func): 4284 arg_types = {"this": True, "expressions": True, "each": False} 4285 4286 4287class ReadCSV(Func): 4288 _sql_names = ["READ_CSV"] 4289 is_var_len_args = True 4290 arg_types = {"this": True, "expressions": False} 4291 4292 4293class Reduce(Func): 4294 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 4295 4296 4297class RegexpExtract(Func): 4298 arg_types = { 4299 "this": True, 4300 "expression": True, 4301 "position": False, 4302 "occurrence": False, 4303 "group": False, 4304 } 4305 4306 4307class RegexpLike(Func): 4308 arg_types = {"this": True, "expression": True, "flag": False} 4309 4310 4311class RegexpILike(Func): 4312 arg_types = {"this": True, "expression": True, "flag": False} 4313 4314 4315# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 4316# limit is the number of times a pattern is applied 4317class RegexpSplit(Func): 4318 arg_types = {"this": True, "expression": True, "limit": False} 4319 4320 4321class Repeat(Func): 4322 arg_types = {"this": True, "times": True} 4323 4324 4325class Round(Func): 4326 arg_types = {"this": True, "decimals": False} 4327 4328 4329class RowNumber(Func): 4330 arg_types: t.Dict[str, t.Any] = {} 4331 4332 4333class SafeDivide(Func): 4334 arg_types = {"this": True, "expression": True} 4335 4336 4337class SetAgg(AggFunc): 4338 pass 4339 4340 4341class SHA(Func): 4342 _sql_names = ["SHA", "SHA1"] 4343 4344 4345class SHA2(Func): 4346 _sql_names = ["SHA2"] 4347 arg_types = {"this": True, "length": False} 4348 4349 4350class SortArray(Func): 4351 arg_types = {"this": True, "asc": False} 4352 4353 4354class Split(Func): 4355 arg_types = {"this": True, "expression": True, "limit": False} 4356 4357 4358# Start may be omitted in the case of postgres 4359# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 4360class Substring(Func): 4361 arg_types = {"this": True, "start": False, "length": False} 4362 4363 4364class StandardHash(Func): 4365 arg_types = {"this": True, "expression": False} 4366 4367 4368class StrPosition(Func): 4369 arg_types = { 4370 "this": True, 4371 "substr": True, 4372 "position": False, 4373 "instance": False, 4374 } 4375 4376 4377class StrToDate(Func): 4378 arg_types = {"this": True, "format": True} 4379 4380 4381class StrToTime(Func): 4382 arg_types = {"this": True, "format": True} 4383 4384 4385# Spark allows unix_timestamp() 4386# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 4387class StrToUnix(Func): 4388 arg_types = {"this": False, "format": False} 4389 4390 4391class NumberToStr(Func): 4392 arg_types = {"this": True, "format": True} 4393 4394 4395class Struct(Func): 4396 arg_types = {"expressions": True} 4397 is_var_len_args = True 4398 4399 4400class StructExtract(Func): 4401 arg_types = {"this": True, "expression": True} 4402 4403 4404class Sum(AggFunc): 4405 pass 4406 4407 4408class Sqrt(Func): 4409 pass 4410 4411 4412class Stddev(AggFunc): 4413 pass 4414 4415 4416class StddevPop(AggFunc): 4417 pass 4418 4419 4420class StddevSamp(AggFunc): 4421 pass 4422 4423 4424class TimeToStr(Func): 4425 arg_types = {"this": True, "format": True} 4426 4427 4428class TimeToTimeStr(Func): 4429 pass 4430 4431 4432class TimeToUnix(Func): 4433 pass 4434 4435 4436class TimeStrToDate(Func): 4437 pass 4438 4439 4440class TimeStrToTime(Func): 4441 pass 4442 4443 4444class TimeStrToUnix(Func): 4445 pass 4446 4447 4448class Trim(Func): 4449 arg_types = { 4450 "this": True, 4451 "expression": False, 4452 "position": False, 4453 "collation": False, 4454 } 4455 4456 4457class TsOrDsAdd(Func, TimeUnit): 4458 arg_types = {"this": True, "expression": True, "unit": False} 4459 4460 4461class TsOrDsToDateStr(Func): 4462 pass 4463 4464 4465class TsOrDsToDate(Func): 4466 arg_types = {"this": True, "format": False} 4467 4468 4469class TsOrDiToDi(Func): 4470 pass 4471 4472 4473class Unhex(Func): 4474 pass 4475 4476 4477class UnixToStr(Func): 4478 arg_types = {"this": True, "format": False} 4479 4480 4481# https://prestodb.io/docs/current/functions/datetime.html 4482# presto has weird zone/hours/minutes 4483class UnixToTime(Func): 4484 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4485 4486 SECONDS = Literal.string("seconds") 4487 MILLIS = Literal.string("millis") 4488 MICROS = Literal.string("micros") 4489 4490 4491class UnixToTimeStr(Func): 4492 pass 4493 4494 4495class Upper(Func): 4496 _sql_names = ["UPPER", "UCASE"] 4497 4498 4499class Variance(AggFunc): 4500 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4501 4502 4503class VariancePop(AggFunc): 4504 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4505 4506 4507class Week(Func): 4508 arg_types = {"this": True, "mode": False} 4509 4510 4511class XMLTable(Func): 4512 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4513 4514 4515class Year(Func): 4516 pass 4517 4518 4519class Use(Expression): 4520 arg_types = {"this": True, "kind": False} 4521 4522 4523class Merge(Expression): 4524 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4525 4526 4527class When(Func): 4528 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4529 4530 4531# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html 4532# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16 4533class NextValueFor(Func): 4534 arg_types = {"this": True, "order": False} 4535 4536 4537def _norm_arg(arg): 4538 return arg.lower() if type(arg) is str else arg 4539 4540 4541ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4542 4543 4544# Helpers 4545@t.overload 4546def maybe_parse( 4547 sql_or_expression: ExpOrStr, 4548 *, 4549 into: t.Type[E], 4550 dialect: DialectType = None, 4551 prefix: t.Optional[str] = None, 4552 copy: bool = False, 4553 **opts, 4554) -> E: 4555 ... 4556 4557 4558@t.overload 4559def maybe_parse( 4560 sql_or_expression: str | E, 4561 *, 4562 into: t.Optional[IntoType] = None, 4563 dialect: DialectType = None, 4564 prefix: t.Optional[str] = None, 4565 copy: bool = False, 4566 **opts, 4567) -> E: 4568 ... 4569 4570 4571def maybe_parse( 4572 sql_or_expression: ExpOrStr, 4573 *, 4574 into: t.Optional[IntoType] = None, 4575 dialect: DialectType = None, 4576 prefix: t.Optional[str] = None, 4577 copy: bool = False, 4578 **opts, 4579) -> Expression: 4580 """Gracefully handle a possible string or expression. 4581 4582 Example: 4583 >>> maybe_parse("1") 4584 (LITERAL this: 1, is_string: False) 4585 >>> maybe_parse(to_identifier("x")) 4586 (IDENTIFIER this: x, quoted: False) 4587 4588 Args: 4589 sql_or_expression: the SQL code string or an expression 4590 into: the SQLGlot Expression to parse into 4591 dialect: the dialect used to parse the input expressions (in the case that an 4592 input expression is a SQL string). 4593 prefix: a string to prefix the sql with before it gets parsed 4594 (automatically includes a space) 4595 copy: whether or not to copy the expression. 4596 **opts: other options to use to parse the input expressions (again, in the case 4597 that an input expression is a SQL string). 4598 4599 Returns: 4600 Expression: the parsed or given expression. 4601 """ 4602 if isinstance(sql_or_expression, Expression): 4603 if copy: 4604 return sql_or_expression.copy() 4605 return sql_or_expression 4606 4607 if sql_or_expression is None: 4608 raise ParseError(f"SQL cannot be None") 4609 4610 import sqlglot 4611 4612 sql = str(sql_or_expression) 4613 if prefix: 4614 sql = f"{prefix} {sql}" 4615 4616 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4617 4618 4619def _maybe_copy(instance: E, copy: bool = True) -> E: 4620 return instance.copy() if copy else instance 4621 4622 4623def _is_wrong_expression(expression, into): 4624 return isinstance(expression, Expression) and not isinstance(expression, into) 4625 4626 4627def _apply_builder( 4628 expression, 4629 instance, 4630 arg, 4631 copy=True, 4632 prefix=None, 4633 into=None, 4634 dialect=None, 4635 **opts, 4636): 4637 if _is_wrong_expression(expression, into): 4638 expression = into(this=expression) 4639 instance = _maybe_copy(instance, copy) 4640 expression = maybe_parse( 4641 sql_or_expression=expression, 4642 prefix=prefix, 4643 into=into, 4644 dialect=dialect, 4645 **opts, 4646 ) 4647 instance.set(arg, expression) 4648 return instance 4649 4650 4651def _apply_child_list_builder( 4652 *expressions, 4653 instance, 4654 arg, 4655 append=True, 4656 copy=True, 4657 prefix=None, 4658 into=None, 4659 dialect=None, 4660 properties=None, 4661 **opts, 4662): 4663 instance = _maybe_copy(instance, copy) 4664 parsed = [] 4665 for expression in expressions: 4666 if expression is not None: 4667 if _is_wrong_expression(expression, into): 4668 expression = into(expressions=[expression]) 4669 4670 expression = maybe_parse( 4671 expression, 4672 into=into, 4673 dialect=dialect, 4674 prefix=prefix, 4675 **opts, 4676 ) 4677 parsed.extend(expression.expressions) 4678 4679 existing = instance.args.get(arg) 4680 if append and existing: 4681 parsed = existing.expressions + parsed 4682 4683 child = into(expressions=parsed) 4684 for k, v in (properties or {}).items(): 4685 child.set(k, v) 4686 instance.set(arg, child) 4687 4688 return instance 4689 4690 4691def _apply_list_builder( 4692 *expressions, 4693 instance, 4694 arg, 4695 append=True, 4696 copy=True, 4697 prefix=None, 4698 into=None, 4699 dialect=None, 4700 **opts, 4701): 4702 inst = _maybe_copy(instance, copy) 4703 4704 expressions = [ 4705 maybe_parse( 4706 sql_or_expression=expression, 4707 into=into, 4708 prefix=prefix, 4709 dialect=dialect, 4710 **opts, 4711 ) 4712 for expression in expressions 4713 if expression is not None 4714 ] 4715 4716 existing_expressions = inst.args.get(arg) 4717 if append and existing_expressions: 4718 expressions = existing_expressions + expressions 4719 4720 inst.set(arg, expressions) 4721 return inst 4722 4723 4724def _apply_conjunction_builder( 4725 *expressions, 4726 instance, 4727 arg, 4728 into=None, 4729 append=True, 4730 copy=True, 4731 dialect=None, 4732 **opts, 4733): 4734 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4735 if not expressions: 4736 return instance 4737 4738 inst = _maybe_copy(instance, copy) 4739 4740 existing = inst.args.get(arg) 4741 if append and existing is not None: 4742 expressions = [existing.this if into else existing] + list(expressions) 4743 4744 node = and_(*expressions, dialect=dialect, copy=copy, **opts) 4745 4746 inst.set(arg, into(this=node) if into else node) 4747 return inst 4748 4749 4750def _apply_cte_builder( 4751 instance: E, 4752 alias: ExpOrStr, 4753 as_: ExpOrStr, 4754 recursive: t.Optional[bool] = None, 4755 append: bool = True, 4756 dialect: DialectType = None, 4757 copy: bool = True, 4758 **opts, 4759) -> E: 4760 alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts) 4761 as_expression = maybe_parse(as_, dialect=dialect, **opts) 4762 cte = CTE(this=as_expression, alias=alias_expression) 4763 return _apply_child_list_builder( 4764 cte, 4765 instance=instance, 4766 arg="with", 4767 append=append, 4768 copy=copy, 4769 into=With, 4770 properties={"recursive": recursive or False}, 4771 ) 4772 4773 4774def _combine( 4775 expressions: t.Sequence[t.Optional[ExpOrStr]], 4776 operator: t.Type[Connector], 4777 dialect: DialectType = None, 4778 copy: bool = True, 4779 **opts, 4780) -> Expression: 4781 conditions = [ 4782 condition(expression, dialect=dialect, copy=copy, **opts) 4783 for expression in expressions 4784 if expression is not None 4785 ] 4786 4787 this, *rest = conditions 4788 if rest: 4789 this = _wrap(this, Connector) 4790 for expression in rest: 4791 this = operator(this=this, expression=_wrap(expression, Connector)) 4792 4793 return this 4794 4795 4796def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: 4797 return Paren(this=expression) if isinstance(expression, kind) else expression 4798 4799 4800def union( 4801 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4802) -> Union: 4803 """ 4804 Initializes a syntax tree from one UNION expression. 4805 4806 Example: 4807 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4808 'SELECT * FROM foo UNION SELECT * FROM bla' 4809 4810 Args: 4811 left: the SQL code string corresponding to the left-hand side. 4812 If an `Expression` instance is passed, it will be used as-is. 4813 right: the SQL code string corresponding to the right-hand side. 4814 If an `Expression` instance is passed, it will be used as-is. 4815 distinct: set the DISTINCT flag if and only if this is true. 4816 dialect: the dialect used to parse the input expression. 4817 opts: other options to use to parse the input expressions. 4818 4819 Returns: 4820 The new Union instance. 4821 """ 4822 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4823 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4824 4825 return Union(this=left, expression=right, distinct=distinct) 4826 4827 4828def intersect( 4829 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4830) -> Intersect: 4831 """ 4832 Initializes a syntax tree from one INTERSECT expression. 4833 4834 Example: 4835 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4836 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4837 4838 Args: 4839 left: the SQL code string corresponding to the left-hand side. 4840 If an `Expression` instance is passed, it will be used as-is. 4841 right: the SQL code string corresponding to the right-hand side. 4842 If an `Expression` instance is passed, it will be used as-is. 4843 distinct: set the DISTINCT flag if and only if this is true. 4844 dialect: the dialect used to parse the input expression. 4845 opts: other options to use to parse the input expressions. 4846 4847 Returns: 4848 The new Intersect instance. 4849 """ 4850 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4851 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4852 4853 return Intersect(this=left, expression=right, distinct=distinct) 4854 4855 4856def except_( 4857 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4858) -> Except: 4859 """ 4860 Initializes a syntax tree from one EXCEPT expression. 4861 4862 Example: 4863 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4864 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4865 4866 Args: 4867 left: the SQL code string corresponding to the left-hand side. 4868 If an `Expression` instance is passed, it will be used as-is. 4869 right: the SQL code string corresponding to the right-hand side. 4870 If an `Expression` instance is passed, it will be used as-is. 4871 distinct: set the DISTINCT flag if and only if this is true. 4872 dialect: the dialect used to parse the input expression. 4873 opts: other options to use to parse the input expressions. 4874 4875 Returns: 4876 The new Except instance. 4877 """ 4878 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4879 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4880 4881 return Except(this=left, expression=right, distinct=distinct) 4882 4883 4884def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4885 """ 4886 Initializes a syntax tree from one or multiple SELECT expressions. 4887 4888 Example: 4889 >>> select("col1", "col2").from_("tbl").sql() 4890 'SELECT col1, col2 FROM tbl' 4891 4892 Args: 4893 *expressions: the SQL code string to parse as the expressions of a 4894 SELECT statement. If an Expression instance is passed, this is used as-is. 4895 dialect: the dialect used to parse the input expressions (in the case that an 4896 input expression is a SQL string). 4897 **opts: other options to use to parse the input expressions (again, in the case 4898 that an input expression is a SQL string). 4899 4900 Returns: 4901 Select: the syntax tree for the SELECT statement. 4902 """ 4903 return Select().select(*expressions, dialect=dialect, **opts) 4904 4905 4906def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4907 """ 4908 Initializes a syntax tree from a FROM expression. 4909 4910 Example: 4911 >>> from_("tbl").select("col1", "col2").sql() 4912 'SELECT col1, col2 FROM tbl' 4913 4914 Args: 4915 *expression: the SQL code string to parse as the FROM expressions of a 4916 SELECT statement. If an Expression instance is passed, this is used as-is. 4917 dialect: the dialect used to parse the input expression (in the case that the 4918 input expression is a SQL string). 4919 **opts: other options to use to parse the input expressions (again, in the case 4920 that the input expression is a SQL string). 4921 4922 Returns: 4923 Select: the syntax tree for the SELECT statement. 4924 """ 4925 return Select().from_(expression, dialect=dialect, **opts) 4926 4927 4928def update( 4929 table: str | Table, 4930 properties: dict, 4931 where: t.Optional[ExpOrStr] = None, 4932 from_: t.Optional[ExpOrStr] = None, 4933 dialect: DialectType = None, 4934 **opts, 4935) -> Update: 4936 """ 4937 Creates an update statement. 4938 4939 Example: 4940 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4941 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4942 4943 Args: 4944 *properties: dictionary of properties to set which are 4945 auto converted to sql objects eg None -> NULL 4946 where: sql conditional parsed into a WHERE statement 4947 from_: sql statement parsed into a FROM statement 4948 dialect: the dialect used to parse the input expressions. 4949 **opts: other options to use to parse the input expressions. 4950 4951 Returns: 4952 Update: the syntax tree for the UPDATE statement. 4953 """ 4954 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4955 update_expr.set( 4956 "expressions", 4957 [ 4958 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4959 for k, v in properties.items() 4960 ], 4961 ) 4962 if from_: 4963 update_expr.set( 4964 "from", 4965 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4966 ) 4967 if isinstance(where, Condition): 4968 where = Where(this=where) 4969 if where: 4970 update_expr.set( 4971 "where", 4972 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4973 ) 4974 return update_expr 4975 4976 4977def delete( 4978 table: ExpOrStr, 4979 where: t.Optional[ExpOrStr] = None, 4980 returning: t.Optional[ExpOrStr] = None, 4981 dialect: DialectType = None, 4982 **opts, 4983) -> Delete: 4984 """ 4985 Builds a delete statement. 4986 4987 Example: 4988 >>> delete("my_table", where="id > 1").sql() 4989 'DELETE FROM my_table WHERE id > 1' 4990 4991 Args: 4992 where: sql conditional parsed into a WHERE statement 4993 returning: sql conditional parsed into a RETURNING statement 4994 dialect: the dialect used to parse the input expressions. 4995 **opts: other options to use to parse the input expressions. 4996 4997 Returns: 4998 Delete: the syntax tree for the DELETE statement. 4999 """ 5000 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5001 if where: 5002 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5003 if returning: 5004 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5005 return delete_expr 5006 5007 5008def insert( 5009 expression: ExpOrStr, 5010 into: ExpOrStr, 5011 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5012 overwrite: t.Optional[bool] = None, 5013 dialect: DialectType = None, 5014 copy: bool = True, 5015 **opts, 5016) -> Insert: 5017 """ 5018 Builds an INSERT statement. 5019 5020 Example: 5021 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5022 'INSERT INTO tbl VALUES (1, 2, 3)' 5023 5024 Args: 5025 expression: the sql string or expression of the INSERT statement 5026 into: the tbl to insert data to. 5027 columns: optionally the table's column names. 5028 overwrite: whether to INSERT OVERWRITE or not. 5029 dialect: the dialect used to parse the input expressions. 5030 copy: whether or not to copy the expression. 5031 **opts: other options to use to parse the input expressions. 5032 5033 Returns: 5034 Insert: the syntax tree for the INSERT statement. 5035 """ 5036 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5037 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5038 5039 if columns: 5040 this = _apply_list_builder( 5041 *columns, 5042 instance=Schema(this=this), 5043 arg="expressions", 5044 into=Identifier, 5045 copy=False, 5046 dialect=dialect, 5047 **opts, 5048 ) 5049 5050 return Insert(this=this, expression=expr, overwrite=overwrite) 5051 5052 5053def condition( 5054 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5055) -> Condition: 5056 """ 5057 Initialize a logical condition expression. 5058 5059 Example: 5060 >>> condition("x=1").sql() 5061 'x = 1' 5062 5063 This is helpful for composing larger logical syntax trees: 5064 >>> where = condition("x=1") 5065 >>> where = where.and_("y=1") 5066 >>> Select().from_("tbl").select("*").where(where).sql() 5067 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5068 5069 Args: 5070 *expression: the SQL code string to parse. 5071 If an Expression instance is passed, this is used as-is. 5072 dialect: the dialect used to parse the input expression (in the case that the 5073 input expression is a SQL string). 5074 copy: Whether or not to copy `expression` (only applies to expressions). 5075 **opts: other options to use to parse the input expressions (again, in the case 5076 that the input expression is a SQL string). 5077 5078 Returns: 5079 The new Condition instance 5080 """ 5081 return maybe_parse( 5082 expression, 5083 into=Condition, 5084 dialect=dialect, 5085 copy=copy, 5086 **opts, 5087 ) 5088 5089 5090def and_( 5091 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5092) -> Condition: 5093 """ 5094 Combine multiple conditions with an AND logical operator. 5095 5096 Example: 5097 >>> and_("x=1", and_("y=1", "z=1")).sql() 5098 'x = 1 AND (y = 1 AND z = 1)' 5099 5100 Args: 5101 *expressions: the SQL code strings to parse. 5102 If an Expression instance is passed, this is used as-is. 5103 dialect: the dialect used to parse the input expression. 5104 copy: whether or not to copy `expressions` (only applies to Expressions). 5105 **opts: other options to use to parse the input expressions. 5106 5107 Returns: 5108 And: the new condition 5109 """ 5110 return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts)) 5111 5112 5113def or_( 5114 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5115) -> Condition: 5116 """ 5117 Combine multiple conditions with an OR logical operator. 5118 5119 Example: 5120 >>> or_("x=1", or_("y=1", "z=1")).sql() 5121 'x = 1 OR (y = 1 OR z = 1)' 5122 5123 Args: 5124 *expressions: the SQL code strings to parse. 5125 If an Expression instance is passed, this is used as-is. 5126 dialect: the dialect used to parse the input expression. 5127 copy: whether or not to copy `expressions` (only applies to Expressions). 5128 **opts: other options to use to parse the input expressions. 5129 5130 Returns: 5131 Or: the new condition 5132 """ 5133 return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts)) 5134 5135 5136def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5137 """ 5138 Wrap a condition with a NOT operator. 5139 5140 Example: 5141 >>> not_("this_suit='black'").sql() 5142 "NOT this_suit = 'black'" 5143 5144 Args: 5145 expression: the SQL code string to parse. 5146 If an Expression instance is passed, this is used as-is. 5147 dialect: the dialect used to parse the input expression. 5148 copy: whether to copy the expression or not. 5149 **opts: other options to use to parse the input expressions. 5150 5151 Returns: 5152 The new condition. 5153 """ 5154 this = condition( 5155 expression, 5156 dialect=dialect, 5157 copy=copy, 5158 **opts, 5159 ) 5160 return Not(this=_wrap(this, Connector)) 5161 5162 5163def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5164 """ 5165 Wrap an expression in parentheses. 5166 5167 Example: 5168 >>> paren("5 + 3").sql() 5169 '(5 + 3)' 5170 5171 Args: 5172 expression: the SQL code string to parse. 5173 If an Expression instance is passed, this is used as-is. 5174 copy: whether to copy the expression or not. 5175 5176 Returns: 5177 The wrapped expression. 5178 """ 5179 return Paren(this=maybe_parse(expression, copy=copy)) 5180 5181 5182SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 5183 5184 5185@t.overload 5186def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None: 5187 ... 5188 5189 5190@t.overload 5191def to_identifier( 5192 name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True 5193) -> Identifier: 5194 ... 5195 5196 5197def to_identifier(name, quoted=None, copy=True): 5198 """Builds an identifier. 5199 5200 Args: 5201 name: The name to turn into an identifier. 5202 quoted: Whether or not force quote the identifier. 5203 copy: Whether or not to copy a passed in Identefier node. 5204 5205 Returns: 5206 The identifier ast node. 5207 """ 5208 5209 if name is None: 5210 return None 5211 5212 if isinstance(name, Identifier): 5213 identifier = _maybe_copy(name, copy) 5214 elif isinstance(name, str): 5215 identifier = Identifier( 5216 this=name, 5217 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5218 ) 5219 else: 5220 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5221 return identifier 5222 5223 5224INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 5225 5226 5227def to_interval(interval: str | Literal) -> Interval: 5228 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5229 if isinstance(interval, Literal): 5230 if not interval.is_string: 5231 raise ValueError("Invalid interval string.") 5232 5233 interval = interval.this 5234 5235 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5236 5237 if not interval_parts: 5238 raise ValueError("Invalid interval string.") 5239 5240 return Interval( 5241 this=Literal.string(interval_parts.group(1)), 5242 unit=Var(this=interval_parts.group(2)), 5243 ) 5244 5245 5246@t.overload 5247def to_table(sql_path: str | Table, **kwargs) -> Table: 5248 ... 5249 5250 5251@t.overload 5252def to_table(sql_path: None, **kwargs) -> None: 5253 ... 5254 5255 5256def to_table( 5257 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5258) -> t.Optional[Table]: 5259 """ 5260 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5261 If a table is passed in then that table is returned. 5262 5263 Args: 5264 sql_path: a `[catalog].[schema].[table]` string. 5265 dialect: the source dialect according to which the table name will be parsed. 5266 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5267 5268 Returns: 5269 A table expression. 5270 """ 5271 if sql_path is None or isinstance(sql_path, Table): 5272 return sql_path 5273 if not isinstance(sql_path, str): 5274 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5275 5276 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5277 if table: 5278 for k, v in kwargs.items(): 5279 table.set(k, v) 5280 5281 return table 5282 5283 5284def to_column(sql_path: str | Column, **kwargs) -> Column: 5285 """ 5286 Create a column from a `[table].[column]` sql path. Schema is optional. 5287 5288 If a column is passed in then that column is returned. 5289 5290 Args: 5291 sql_path: `[table].[column]` string 5292 Returns: 5293 Table: A column expression 5294 """ 5295 if sql_path is None or isinstance(sql_path, Column): 5296 return sql_path 5297 if not isinstance(sql_path, str): 5298 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5299 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 5300 5301 5302def alias_( 5303 expression: ExpOrStr, 5304 alias: str | Identifier, 5305 table: bool | t.Sequence[str | Identifier] = False, 5306 quoted: t.Optional[bool] = None, 5307 dialect: DialectType = None, 5308 copy: bool = True, 5309 **opts, 5310): 5311 """Create an Alias expression. 5312 5313 Example: 5314 >>> alias_('foo', 'bar').sql() 5315 'foo AS bar' 5316 5317 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5318 '(SELECT 1, 2) AS bar(a, b)' 5319 5320 Args: 5321 expression: the SQL code strings to parse. 5322 If an Expression instance is passed, this is used as-is. 5323 alias: the alias name to use. If the name has 5324 special characters it is quoted. 5325 table: Whether or not to create a table alias, can also be a list of columns. 5326 quoted: whether or not to quote the alias 5327 dialect: the dialect used to parse the input expression. 5328 copy: Whether or not to copy the expression. 5329 **opts: other options to use to parse the input expressions. 5330 5331 Returns: 5332 Alias: the aliased expression 5333 """ 5334 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5335 alias = to_identifier(alias, quoted=quoted) 5336 5337 if table: 5338 table_alias = TableAlias(this=alias) 5339 exp.set("alias", table_alias) 5340 5341 if not isinstance(table, bool): 5342 for column in table: 5343 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5344 5345 return exp 5346 5347 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5348 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5349 # for the complete Window expression. 5350 # 5351 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5352 5353 if "alias" in exp.arg_types and not isinstance(exp, Window): 5354 exp.set("alias", alias) 5355 return exp 5356 return Alias(this=exp, alias=alias) 5357 5358 5359def subquery( 5360 expression: ExpOrStr, 5361 alias: t.Optional[Identifier | str] = None, 5362 dialect: DialectType = None, 5363 **opts, 5364) -> Select: 5365 """ 5366 Build a subquery expression. 5367 5368 Example: 5369 >>> subquery('select x from tbl', 'bar').select('x').sql() 5370 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5371 5372 Args: 5373 expression: the SQL code strings to parse. 5374 If an Expression instance is passed, this is used as-is. 5375 alias: the alias name to use. 5376 dialect: the dialect used to parse the input expression. 5377 **opts: other options to use to parse the input expressions. 5378 5379 Returns: 5380 A new Select instance with the subquery expression included. 5381 """ 5382 5383 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5384 return Select().from_(expression, dialect=dialect, **opts) 5385 5386 5387def column( 5388 col: str | Identifier, 5389 table: t.Optional[str | Identifier] = None, 5390 db: t.Optional[str | Identifier] = None, 5391 catalog: t.Optional[str | Identifier] = None, 5392 quoted: t.Optional[bool] = None, 5393) -> Column: 5394 """ 5395 Build a Column. 5396 5397 Args: 5398 col: Column name. 5399 table: Table name. 5400 db: Database name. 5401 catalog: Catalog name. 5402 quoted: Whether to force quotes on the column's identifiers. 5403 5404 Returns: 5405 The new Column instance. 5406 """ 5407 return Column( 5408 this=to_identifier(col, quoted=quoted), 5409 table=to_identifier(table, quoted=quoted), 5410 db=to_identifier(db, quoted=quoted), 5411 catalog=to_identifier(catalog, quoted=quoted), 5412 ) 5413 5414 5415def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5416 """Cast an expression to a data type. 5417 5418 Example: 5419 >>> cast('x + 1', 'int').sql() 5420 'CAST(x + 1 AS INT)' 5421 5422 Args: 5423 expression: The expression to cast. 5424 to: The datatype to cast to. 5425 5426 Returns: 5427 The new Cast instance. 5428 """ 5429 expression = maybe_parse(expression, **opts) 5430 return Cast(this=expression, to=DataType.build(to, **opts)) 5431 5432 5433def table_( 5434 table: Identifier | str, 5435 db: t.Optional[Identifier | str] = None, 5436 catalog: t.Optional[Identifier | str] = None, 5437 quoted: t.Optional[bool] = None, 5438 alias: t.Optional[Identifier | str] = None, 5439) -> Table: 5440 """Build a Table. 5441 5442 Args: 5443 table: Table name. 5444 db: Database name. 5445 catalog: Catalog name. 5446 quote: Whether to force quotes on the table's identifiers. 5447 alias: Table's alias. 5448 5449 Returns: 5450 The new Table instance. 5451 """ 5452 return Table( 5453 this=to_identifier(table, quoted=quoted), 5454 db=to_identifier(db, quoted=quoted), 5455 catalog=to_identifier(catalog, quoted=quoted), 5456 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5457 ) 5458 5459 5460def values( 5461 values: t.Iterable[t.Tuple[t.Any, ...]], 5462 alias: t.Optional[str] = None, 5463 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5464) -> Values: 5465 """Build VALUES statement. 5466 5467 Example: 5468 >>> values([(1, '2')]).sql() 5469 "VALUES (1, '2')" 5470 5471 Args: 5472 values: values statements that will be converted to SQL 5473 alias: optional alias 5474 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5475 If either are provided then an alias is also required. 5476 5477 Returns: 5478 Values: the Values expression object 5479 """ 5480 if columns and not alias: 5481 raise ValueError("Alias is required when providing columns") 5482 5483 return Values( 5484 expressions=[convert(tup) for tup in values], 5485 alias=( 5486 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5487 if columns 5488 else (TableAlias(this=to_identifier(alias)) if alias else None) 5489 ), 5490 ) 5491 5492 5493def var(name: t.Optional[ExpOrStr]) -> Var: 5494 """Build a SQL variable. 5495 5496 Example: 5497 >>> repr(var('x')) 5498 '(VAR this: x)' 5499 5500 >>> repr(var(column('x', table='y'))) 5501 '(VAR this: x)' 5502 5503 Args: 5504 name: The name of the var or an expression who's name will become the var. 5505 5506 Returns: 5507 The new variable node. 5508 """ 5509 if not name: 5510 raise ValueError("Cannot convert empty name into var.") 5511 5512 if isinstance(name, Expression): 5513 name = name.name 5514 return Var(this=name) 5515 5516 5517def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5518 """Build ALTER TABLE... RENAME... expression 5519 5520 Args: 5521 old_name: The old name of the table 5522 new_name: The new name of the table 5523 5524 Returns: 5525 Alter table expression 5526 """ 5527 old_table = to_table(old_name) 5528 new_table = to_table(new_name) 5529 return AlterTable( 5530 this=old_table, 5531 actions=[ 5532 RenameTable(this=new_table), 5533 ], 5534 ) 5535 5536 5537def convert(value: t.Any, copy: bool = False) -> Expression: 5538 """Convert a python value into an expression object. 5539 5540 Raises an error if a conversion is not possible. 5541 5542 Args: 5543 value: A python object. 5544 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5545 5546 Returns: 5547 Expression: the equivalent expression object. 5548 """ 5549 if isinstance(value, Expression): 5550 return _maybe_copy(value, copy) 5551 if isinstance(value, str): 5552 return Literal.string(value) 5553 if isinstance(value, bool): 5554 return Boolean(this=value) 5555 if value is None or (isinstance(value, float) and math.isnan(value)): 5556 return NULL 5557 if isinstance(value, numbers.Number): 5558 return Literal.number(value) 5559 if isinstance(value, datetime.datetime): 5560 datetime_literal = Literal.string( 5561 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5562 ) 5563 return TimeStrToTime(this=datetime_literal) 5564 if isinstance(value, datetime.date): 5565 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5566 return DateStrToDate(this=date_literal) 5567 if isinstance(value, tuple): 5568 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5569 if isinstance(value, list): 5570 return Array(expressions=[convert(v, copy=copy) for v in value]) 5571 if isinstance(value, dict): 5572 return Map( 5573 keys=[convert(k, copy=copy) for k in value], 5574 values=[convert(v, copy=copy) for v in value.values()], 5575 ) 5576 raise ValueError(f"Cannot convert {value}") 5577 5578 5579def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5580 """ 5581 Replace children of an expression with the result of a lambda fun(child) -> exp. 5582 """ 5583 for k, v in expression.args.items(): 5584 is_list_arg = type(v) is list 5585 5586 child_nodes = v if is_list_arg else [v] 5587 new_child_nodes = [] 5588 5589 for cn in child_nodes: 5590 if isinstance(cn, Expression): 5591 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5592 new_child_nodes.append(child_node) 5593 child_node.parent = expression 5594 child_node.arg_key = k 5595 else: 5596 new_child_nodes.append(cn) 5597 5598 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 5599 5600 5601def column_table_names(expression: Expression) -> t.List[str]: 5602 """ 5603 Return all table names referenced through columns in an expression. 5604 5605 Example: 5606 >>> import sqlglot 5607 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5608 ['c', 'a'] 5609 5610 Args: 5611 expression: expression to find table names. 5612 5613 Returns: 5614 A list of unique names. 5615 """ 5616 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 5617 5618 5619def table_name(table: Table | str) -> str: 5620 """Get the full name of a table as a string. 5621 5622 Args: 5623 table: table expression node or string. 5624 5625 Examples: 5626 >>> from sqlglot import exp, parse_one 5627 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5628 'a.b.c' 5629 5630 Returns: 5631 The table name. 5632 """ 5633 5634 table = maybe_parse(table, into=Table) 5635 5636 if not table: 5637 raise ValueError(f"Cannot parse {table}") 5638 5639 return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part) 5640 5641 5642def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E: 5643 """Replace all tables in expression according to the mapping. 5644 5645 Args: 5646 expression: expression node to be transformed and replaced. 5647 mapping: mapping of table names. 5648 5649 Examples: 5650 >>> from sqlglot import exp, parse_one 5651 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5652 'SELECT * FROM c' 5653 5654 Returns: 5655 The mapped expression. 5656 """ 5657 5658 def _replace_tables(node: Expression) -> Expression: 5659 if isinstance(node, Table): 5660 new_name = mapping.get(table_name(node)) 5661 if new_name: 5662 return to_table( 5663 new_name, 5664 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5665 ) 5666 return node 5667 5668 return expression.transform(_replace_tables) 5669 5670 5671def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5672 """Replace placeholders in an expression. 5673 5674 Args: 5675 expression: expression node to be transformed and replaced. 5676 args: positional names that will substitute unnamed placeholders in the given order. 5677 kwargs: keyword arguments that will substitute named placeholders. 5678 5679 Examples: 5680 >>> from sqlglot import exp, parse_one 5681 >>> replace_placeholders( 5682 ... parse_one("select * from :tbl where ? = ?"), 5683 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5684 ... ).sql() 5685 "SELECT * FROM foo WHERE str_col = 'b'" 5686 5687 Returns: 5688 The mapped expression. 5689 """ 5690 5691 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5692 if isinstance(node, Placeholder): 5693 if node.name: 5694 new_name = kwargs.get(node.name) 5695 if new_name: 5696 return convert(new_name) 5697 else: 5698 try: 5699 return convert(next(args)) 5700 except StopIteration: 5701 pass 5702 return node 5703 5704 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5705 5706 5707def expand( 5708 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5709) -> Expression: 5710 """Transforms an expression by expanding all referenced sources into subqueries. 5711 5712 Examples: 5713 >>> from sqlglot import parse_one 5714 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5715 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5716 5717 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5718 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5719 5720 Args: 5721 expression: The expression to expand. 5722 sources: A dictionary of name to Subqueryables. 5723 copy: Whether or not to copy the expression during transformation. Defaults to True. 5724 5725 Returns: 5726 The transformed expression. 5727 """ 5728 5729 def _expand(node: Expression): 5730 if isinstance(node, Table): 5731 name = table_name(node) 5732 source = sources.get(name) 5733 if source: 5734 subquery = source.subquery(node.alias or name) 5735 subquery.comments = [f"source: {name}"] 5736 return subquery.transform(_expand, copy=False) 5737 return node 5738 5739 return expression.transform(_expand, copy=copy) 5740 5741 5742def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5743 """ 5744 Returns a Func expression. 5745 5746 Examples: 5747 >>> func("abs", 5).sql() 5748 'ABS(5)' 5749 5750 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5751 'CAST(5 AS DOUBLE)' 5752 5753 Args: 5754 name: the name of the function to build. 5755 args: the args used to instantiate the function of interest. 5756 dialect: the source dialect. 5757 kwargs: the kwargs used to instantiate the function of interest. 5758 5759 Note: 5760 The arguments `args` and `kwargs` are mutually exclusive. 5761 5762 Returns: 5763 An instance of the function of interest, or an anonymous function, if `name` doesn't 5764 correspond to an existing `sqlglot.expressions.Func` class. 5765 """ 5766 if args and kwargs: 5767 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5768 5769 from sqlglot.dialects.dialect import Dialect 5770 5771 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5772 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5773 5774 parser = Dialect.get_or_raise(dialect)().parser() 5775 from_args_list = parser.FUNCTIONS.get(name.upper()) 5776 5777 if from_args_list: 5778 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5779 else: 5780 kwargs = kwargs or {"expressions": converted} 5781 function = Anonymous(this=name, **kwargs) 5782 5783 for error_message in function.error_messages(converted): 5784 raise ValueError(error_message) 5785 5786 return function 5787 5788 5789def true() -> Boolean: 5790 """ 5791 Returns a true Boolean expression. 5792 """ 5793 return Boolean(this=True) 5794 5795 5796def false() -> Boolean: 5797 """ 5798 Returns a false Boolean expression. 5799 """ 5800 return Boolean(this=False) 5801 5802 5803def null() -> Null: 5804 """ 5805 Returns a Null expression. 5806 """ 5807 return Null() 5808 5809 5810# TODO: deprecate this 5811TRUE = Boolean(this=True) 5812FALSE = Boolean(this=False) 5813NULL = Null()
55class Expression(metaclass=_Expression): 56 """ 57 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 58 context, such as its child expressions, their names (arg keys), and whether a given child expression 59 is optional or not. 60 61 Attributes: 62 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 63 and representing expressions as strings. 64 arg_types: determines what arguments (child nodes) are supported by an expression. It 65 maps arg keys to booleans that indicate whether the corresponding args are optional. 66 parent: a reference to the parent expression (or None, in case of root expressions). 67 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 68 uses to refer to it. 69 comments: a list of comments that are associated with a given expression. This is used in 70 order to preserve comments when transpiling SQL code. 71 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 72 optimizer, in order to enable some transformations that require type information. 73 74 Example: 75 >>> class Foo(Expression): 76 ... arg_types = {"this": True, "expression": False} 77 78 The above definition informs us that Foo is an Expression that requires an argument called 79 "this" and may also optionally receive an argument called "expression". 80 81 Args: 82 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 83 """ 84 85 key = "expression" 86 arg_types = {"this": True} 87 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 88 89 def __init__(self, **args: t.Any): 90 self.args: t.Dict[str, t.Any] = args 91 self.parent: t.Optional[Expression] = None 92 self.arg_key: t.Optional[str] = None 93 self.comments: t.Optional[t.List[str]] = None 94 self._type: t.Optional[DataType] = None 95 self._meta: t.Optional[t.Dict[str, t.Any]] = None 96 self._hash: t.Optional[int] = None 97 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value) 100 101 def __eq__(self, other) -> bool: 102 return type(self) is type(other) and hash(self) == hash(other) 103 104 @property 105 def hashable_args(self) -> t.Any: 106 args = (self.args.get(k) for k in self.arg_types) 107 108 return tuple( 109 (tuple(_norm_arg(a) for a in arg) if arg else None) 110 if type(arg) is list 111 else (_norm_arg(arg) if arg is not None and arg is not False else None) 112 for arg in args 113 ) 114 115 def __hash__(self) -> int: 116 if self._hash is not None: 117 return self._hash 118 119 return hash((self.__class__, self.hashable_args)) 120 121 @property 122 def this(self): 123 """ 124 Retrieves the argument with key "this". 125 """ 126 return self.args.get("this") 127 128 @property 129 def expression(self): 130 """ 131 Retrieves the argument with key "expression". 132 """ 133 return self.args.get("expression") 134 135 @property 136 def expressions(self): 137 """ 138 Retrieves the argument with key "expressions". 139 """ 140 return self.args.get("expressions") or [] 141 142 def text(self, key) -> str: 143 """ 144 Returns a textual representation of the argument corresponding to "key". This can only be used 145 for args that are strings or leaf Expression instances, such as identifiers and literals. 146 """ 147 field = self.args.get(key) 148 if isinstance(field, str): 149 return field 150 if isinstance(field, (Identifier, Literal, Var)): 151 return field.this 152 if isinstance(field, (Star, Null)): 153 return field.name 154 return "" 155 156 @property 157 def is_string(self) -> bool: 158 """ 159 Checks whether a Literal expression is a string. 160 """ 161 return isinstance(self, Literal) and self.args["is_string"] 162 163 @property 164 def is_number(self) -> bool: 165 """ 166 Checks whether a Literal expression is a number. 167 """ 168 return isinstance(self, Literal) and not self.args["is_string"] 169 170 @property 171 def is_int(self) -> bool: 172 """ 173 Checks whether a Literal expression is an integer. 174 """ 175 if self.is_number: 176 try: 177 int(self.name) 178 return True 179 except ValueError: 180 pass 181 return False 182 183 @property 184 def is_star(self) -> bool: 185 """Checks whether an expression is a star.""" 186 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 187 188 @property 189 def alias(self) -> str: 190 """ 191 Returns the alias of the expression, or an empty string if it's not aliased. 192 """ 193 if isinstance(self.args.get("alias"), TableAlias): 194 return self.args["alias"].name 195 return self.text("alias") 196 197 @property 198 def name(self) -> str: 199 return self.text("this") 200 201 @property 202 def alias_or_name(self) -> str: 203 return self.alias or self.name 204 205 @property 206 def output_name(self) -> str: 207 """ 208 Name of the output column if this expression is a selection. 209 210 If the Expression has no output name, an empty string is returned. 211 212 Example: 213 >>> from sqlglot import parse_one 214 >>> parse_one("SELECT a").expressions[0].output_name 215 'a' 216 >>> parse_one("SELECT b AS c").expressions[0].output_name 217 'c' 218 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 219 '' 220 """ 221 return "" 222 223 @property 224 def type(self) -> t.Optional[DataType]: 225 return self._type 226 227 @type.setter 228 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 229 if dtype and not isinstance(dtype, DataType): 230 dtype = DataType.build(dtype) 231 self._type = dtype # type: ignore 232 233 @property 234 def meta(self) -> t.Dict[str, t.Any]: 235 if self._meta is None: 236 self._meta = {} 237 return self._meta 238 239 def __deepcopy__(self, memo): 240 copy = self.__class__(**deepcopy(self.args)) 241 if self.comments is not None: 242 copy.comments = deepcopy(self.comments) 243 244 if self._type is not None: 245 copy._type = self._type.copy() 246 247 if self._meta is not None: 248 copy._meta = deepcopy(self._meta) 249 250 return copy 251 252 def copy(self): 253 """ 254 Returns a deep copy of the expression. 255 """ 256 new = deepcopy(self) 257 new.parent = self.parent 258 return new 259 260 def add_comments(self, comments: t.Optional[t.List[str]]) -> None: 261 if self.comments is None: 262 self.comments = [] 263 if comments: 264 self.comments.extend(comments) 265 266 def append(self, arg_key: str, value: t.Any) -> None: 267 """ 268 Appends value to arg_key if it's a list or sets it as a new list. 269 270 Args: 271 arg_key (str): name of the list expression arg 272 value (Any): value to append to the list 273 """ 274 if not isinstance(self.args.get(arg_key), list): 275 self.args[arg_key] = [] 276 self.args[arg_key].append(value) 277 self._set_parent(arg_key, value) 278 279 def set(self, arg_key: str, value: t.Any) -> None: 280 """ 281 Sets `arg_key` to `value`. 282 283 Args: 284 arg_key (str): name of the expression arg. 285 value: value to set the arg to. 286 """ 287 self.args[arg_key] = value 288 self._set_parent(arg_key, value) 289 290 def _set_parent(self, arg_key: str, value: t.Any) -> None: 291 if hasattr(value, "parent"): 292 value.parent = self 293 value.arg_key = arg_key 294 elif type(value) is list: 295 for v in value: 296 if hasattr(v, "parent"): 297 v.parent = self 298 v.arg_key = arg_key 299 300 @property 301 def depth(self) -> int: 302 """ 303 Returns the depth of this tree. 304 """ 305 if self.parent: 306 return self.parent.depth + 1 307 return 0 308 309 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 310 """Yields the key and expression for all arguments, exploding list args.""" 311 for k, vs in self.args.items(): 312 if type(vs) is list: 313 for v in vs: 314 if hasattr(v, "parent"): 315 yield k, v 316 else: 317 if hasattr(vs, "parent"): 318 yield k, vs 319 320 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 321 """ 322 Returns the first node in this tree which matches at least one of 323 the specified types. 324 325 Args: 326 expression_types: the expression type(s) to match. 327 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 328 329 Returns: 330 The node which matches the criteria or None if no such node was found. 331 """ 332 return next(self.find_all(*expression_types, bfs=bfs), None) 333 334 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 335 """ 336 Returns a generator object which visits all nodes in this tree and only 337 yields those that match at least one of the specified expression types. 338 339 Args: 340 expression_types: the expression type(s) to match. 341 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression 349 350 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor) 364 365 @property 366 def parent_select(self) -> t.Optional[Select]: 367 """ 368 Returns the parent select statement. 369 """ 370 return self.find_ancestor(Select) 371 372 @property 373 def same_parent(self) -> bool: 374 """Returns if the parent is the same class as itself.""" 375 return type(self.parent) is self.__class__ 376 377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression 385 386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune) 403 404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune) 419 420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k)) 439 440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression 448 449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self 456 457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 462 463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node 472 473 def __str__(self) -> str: 474 return self.sql() 475 476 def __repr__(self) -> str: 477 return self._to_s() 478 479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts) 493 494 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 495 indent = "" if not level else "\n" 496 indent += "".join([" "] * level) 497 left = f"({self.key.upper()} " 498 499 args: t.Dict[str, t.Any] = { 500 k: ", ".join( 501 v._to_s(hide_missing=hide_missing, level=level + 1) 502 if hasattr(v, "_to_s") 503 else str(v) 504 for v in ensure_list(vs) 505 if v is not None 506 ) 507 for k, vs in self.args.items() 508 } 509 args["comments"] = self.comments 510 args["type"] = self.type 511 args = {k: v for k, v in args.items() if v or not hide_missing} 512 513 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 514 right += ")" 515 516 return indent + left + right 517 518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node 544 545 @t.overload 546 def replace(self, expression: E) -> E: 547 ... 548 549 @t.overload 550 def replace(self, expression: None) -> None: 551 ... 552 553 def replace(self, expression): 554 """ 555 Swap out this expression with a new expression. 556 557 For example:: 558 559 >>> tree = Select().select("x").from_("tbl") 560 >>> tree.find(Column).replace(Column(this="y")) 561 (COLUMN this: y) 562 >>> tree.sql() 563 'SELECT y FROM tbl' 564 565 Args: 566 expression: new node 567 568 Returns: 569 The new expression or expressions. 570 """ 571 if not self.parent: 572 return expression 573 574 parent = self.parent 575 self.parent = None 576 577 replace_children(parent, lambda child: expression if child is self else child) 578 return expression 579 580 def pop(self: E) -> E: 581 """ 582 Remove this expression from its AST. 583 584 Returns: 585 The popped expression. 586 """ 587 self.replace(None) 588 return self 589 590 def assert_is(self, type_: t.Type[E]) -> E: 591 """ 592 Assert that this `Expression` is an instance of `type_`. 593 594 If it is NOT an instance of `type_`, this raises an assertion error. 595 Otherwise, this returns this expression. 596 597 Examples: 598 This is useful for type security in chained expressions: 599 600 >>> import sqlglot 601 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 602 'SELECT x, z FROM y' 603 """ 604 assert isinstance(self, type_) 605 return self 606 607 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 608 """ 609 Checks if this expression is valid (e.g. all mandatory args are set). 610 611 Args: 612 args: a sequence of values that were used to instantiate a Func expression. This is used 613 to check that the provided arguments don't exceed the function argument limit. 614 615 Returns: 616 A list of error messages for all possible errors that were found. 617 """ 618 errors: t.List[str] = [] 619 620 for k in self.args: 621 if k not in self.arg_types: 622 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 623 for k, mandatory in self.arg_types.items(): 624 v = self.args.get(k) 625 if mandatory and (v is None or (isinstance(v, list) and not v)): 626 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 627 628 if ( 629 args 630 and isinstance(self, Func) 631 and len(args) > len(self.arg_types) 632 and not self.is_var_len_args 633 ): 634 errors.append( 635 f"The number of provided arguments ({len(args)}) is greater than " 636 f"the maximum number of supported arguments ({len(self.arg_types)})" 637 ) 638 639 return errors 640 641 def dump(self): 642 """ 643 Dump this Expression to a JSON-serializable dict. 644 """ 645 from sqlglot.serde import dump 646 647 return dump(self) 648 649 @classmethod 650 def load(cls, obj): 651 """ 652 Load a dict (as returned by `Expression.dump`) into an Expression instance. 653 """ 654 from sqlglot.serde import load 655 656 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataType
type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
89 def __init__(self, **args: t.Any): 90 self.args: t.Dict[str, t.Any] = args 91 self.parent: t.Optional[Expression] = None 92 self.arg_key: t.Optional[str] = None 93 self.comments: t.Optional[t.List[str]] = None 94 self._type: t.Optional[DataType] = None 95 self._meta: t.Optional[t.Dict[str, t.Any]] = None 96 self._hash: t.Optional[int] = None 97 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value)
142 def text(self, key) -> str: 143 """ 144 Returns a textual representation of the argument corresponding to "key". This can only be used 145 for args that are strings or leaf Expression instances, such as identifiers and literals. 146 """ 147 field = self.args.get(key) 148 if isinstance(field, str): 149 return field 150 if isinstance(field, (Identifier, Literal, Var)): 151 return field.this 152 if isinstance(field, (Star, Null)): 153 return field.name 154 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
252 def copy(self): 253 """ 254 Returns a deep copy of the expression. 255 """ 256 new = deepcopy(self) 257 new.parent = self.parent 258 return new
Returns a deep copy of the expression.
266 def append(self, arg_key: str, value: t.Any) -> None: 267 """ 268 Appends value to arg_key if it's a list or sets it as a new list. 269 270 Args: 271 arg_key (str): name of the list expression arg 272 value (Any): value to append to the list 273 """ 274 if not isinstance(self.args.get(arg_key), list): 275 self.args[arg_key] = [] 276 self.args[arg_key].append(value) 277 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
279 def set(self, arg_key: str, value: t.Any) -> None: 280 """ 281 Sets `arg_key` to `value`. 282 283 Args: 284 arg_key (str): name of the expression arg. 285 value: value to set the arg to. 286 """ 287 self.args[arg_key] = value 288 self._set_parent(arg_key, value)
Sets arg_key
to value
.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
309 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 310 """Yields the key and expression for all arguments, exploding list args.""" 311 for k, vs in self.args.items(): 312 if type(vs) is list: 313 for v in vs: 314 if hasattr(v, "parent"): 315 yield k, v 316 else: 317 if hasattr(vs, "parent"): 318 yield k, vs
Yields the key and expression for all arguments, exploding list args.
320 def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]: 321 """ 322 Returns the first node in this tree which matches at least one of 323 the specified types. 324 325 Args: 326 expression_types: the expression type(s) to match. 327 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 328 329 Returns: 330 The node which matches the criteria or None if no such node was found. 331 """ 332 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
- bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:
The node which matches the criteria or None if no such node was found.
334 def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]: 335 """ 336 Returns a generator object which visits all nodes in this tree and only 337 yields those that match at least one of the specified expression types. 338 339 Args: 340 expression_types: the expression type(s) to match. 341 bfs: whether to search the AST using the BFS algorithm (DFS is used if false). 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
- bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:
The generator object.
350 def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression
Returns the root expression of this tree.
386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression
Returns the first non parenthesis child or self.
449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self
Returns the inner expression if this is an Alias.
457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generator
options.
Returns:
The SQL string.
518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
553 def replace(self, expression): 554 """ 555 Swap out this expression with a new expression. 556 557 For example:: 558 559 >>> tree = Select().select("x").from_("tbl") 560 >>> tree.find(Column).replace(Column(this="y")) 561 (COLUMN this: y) 562 >>> tree.sql() 563 'SELECT y FROM tbl' 564 565 Args: 566 expression: new node 567 568 Returns: 569 The new expression or expressions. 570 """ 571 if not self.parent: 572 return expression 573 574 parent = self.parent 575 self.parent = None 576 577 replace_children(parent, lambda child: expression if child is self else child) 578 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression: new node
Returns:
The new expression or expressions.
580 def pop(self: E) -> E: 581 """ 582 Remove this expression from its AST. 583 584 Returns: 585 The popped expression. 586 """ 587 self.replace(None) 588 return self
Remove this expression from its AST.
Returns:
The popped expression.
590 def assert_is(self, type_: t.Type[E]) -> E: 591 """ 592 Assert that this `Expression` is an instance of `type_`. 593 594 If it is NOT an instance of `type_`, this raises an assertion error. 595 Otherwise, this returns this expression. 596 597 Examples: 598 This is useful for type security in chained expressions: 599 600 >>> import sqlglot 601 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 602 'SELECT x, z FROM y' 603 """ 604 assert isinstance(self, type_) 605 return self
Assert that this Expression
is an instance of type_
.
If it is NOT an instance of type_
, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
607 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 608 """ 609 Checks if this expression is valid (e.g. all mandatory args are set). 610 611 Args: 612 args: a sequence of values that were used to instantiate a Func expression. This is used 613 to check that the provided arguments don't exceed the function argument limit. 614 615 Returns: 616 A list of error messages for all possible errors that were found. 617 """ 618 errors: t.List[str] = [] 619 620 for k in self.args: 621 if k not in self.arg_types: 622 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 623 for k, mandatory in self.arg_types.items(): 624 v = self.args.get(k) 625 if mandatory and (v is None or (isinstance(v, list) and not v)): 626 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 627 628 if ( 629 args 630 and isinstance(self, Func) 631 and len(args) > len(self.arg_types) 632 and not self.is_var_len_args 633 ): 634 errors.append( 635 f"The number of provided arguments ({len(args)}) is greater than " 636 f"the maximum number of supported arguments ({len(self.arg_types)})" 637 ) 638 639 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
641 def dump(self): 642 """ 643 Dump this Expression to a JSON-serializable dict. 644 """ 645 from sqlglot.serde import dump 646 647 return dump(self)
Dump this Expression to a JSON-serializable dict.
649 @classmethod 650 def load(cls, obj): 651 """ 652 Load a dict (as returned by `Expression.dump`) into an Expression instance. 653 """ 654 from sqlglot.serde import load 655 656 return load(obj)
Load a dict (as returned by Expression.dump
) into an Expression instance.
667class Condition(Expression): 668 def and_( 669 self, 670 *expressions: t.Optional[ExpOrStr], 671 dialect: DialectType = None, 672 copy: bool = True, 673 **opts, 674 ) -> Condition: 675 """ 676 AND this condition with one or multiple expressions. 677 678 Example: 679 >>> condition("x=1").and_("y=1").sql() 680 'x = 1 AND y = 1' 681 682 Args: 683 *expressions: the SQL code strings to parse. 684 If an `Expression` instance is passed, it will be used as-is. 685 dialect: the dialect used to parse the input expression. 686 copy: whether or not to copy the involved expressions (only applies to Expressions). 687 opts: other options to use to parse the input expressions. 688 689 Returns: 690 The new And condition. 691 """ 692 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 693 694 def or_( 695 self, 696 *expressions: t.Optional[ExpOrStr], 697 dialect: DialectType = None, 698 copy: bool = True, 699 **opts, 700 ) -> Condition: 701 """ 702 OR this condition with one or multiple expressions. 703 704 Example: 705 >>> condition("x=1").or_("y=1").sql() 706 'x = 1 OR y = 1' 707 708 Args: 709 *expressions: the SQL code strings to parse. 710 If an `Expression` instance is passed, it will be used as-is. 711 dialect: the dialect used to parse the input expression. 712 copy: whether or not to copy the involved expressions (only applies to Expressions). 713 opts: other options to use to parse the input expressions. 714 715 Returns: 716 The new Or condition. 717 """ 718 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 719 720 def not_(self, copy: bool = True): 721 """ 722 Wrap this condition with NOT. 723 724 Example: 725 >>> condition("x=1").not_().sql() 726 'NOT x = 1' 727 728 Args: 729 copy: whether or not to copy this object. 730 731 Returns: 732 The new Not instance. 733 """ 734 return not_(self, copy=copy) 735 736 def as_( 737 self, 738 alias: str | Identifier, 739 quoted: t.Optional[bool] = None, 740 dialect: DialectType = None, 741 copy: bool = True, 742 **opts, 743 ) -> Alias: 744 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 745 746 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 747 this = self.copy() 748 other = convert(other, copy=True) 749 if not isinstance(this, klass) and not isinstance(other, klass): 750 this = _wrap(this, Binary) 751 other = _wrap(other, Binary) 752 if reverse: 753 return klass(this=other, expression=this) 754 return klass(this=this, expression=other) 755 756 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 757 return Bracket( 758 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 759 ) 760 761 def isin( 762 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 763 ) -> In: 764 return In( 765 this=_maybe_copy(self, copy), 766 expressions=[convert(e, copy=copy) for e in expressions], 767 query=maybe_parse(query, copy=copy, **opts) if query else None, 768 ) 769 770 def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between: 771 return Between( 772 this=_maybe_copy(self, copy), 773 low=convert(low, copy=copy, **opts), 774 high=convert(high, copy=copy, **opts), 775 ) 776 777 def is_(self, other: ExpOrStr) -> Is: 778 return self._binop(Is, other) 779 780 def like(self, other: ExpOrStr) -> Like: 781 return self._binop(Like, other) 782 783 def ilike(self, other: ExpOrStr) -> ILike: 784 return self._binop(ILike, other) 785 786 def eq(self, other: t.Any) -> EQ: 787 return self._binop(EQ, other) 788 789 def neq(self, other: t.Any) -> NEQ: 790 return self._binop(NEQ, other) 791 792 def rlike(self, other: ExpOrStr) -> RegexpLike: 793 return self._binop(RegexpLike, other) 794 795 def __lt__(self, other: t.Any) -> LT: 796 return self._binop(LT, other) 797 798 def __le__(self, other: t.Any) -> LTE: 799 return self._binop(LTE, other) 800 801 def __gt__(self, other: t.Any) -> GT: 802 return self._binop(GT, other) 803 804 def __ge__(self, other: t.Any) -> GTE: 805 return self._binop(GTE, other) 806 807 def __add__(self, other: t.Any) -> Add: 808 return self._binop(Add, other) 809 810 def __radd__(self, other: t.Any) -> Add: 811 return self._binop(Add, other, reverse=True) 812 813 def __sub__(self, other: t.Any) -> Sub: 814 return self._binop(Sub, other) 815 816 def __rsub__(self, other: t.Any) -> Sub: 817 return self._binop(Sub, other, reverse=True) 818 819 def __mul__(self, other: t.Any) -> Mul: 820 return self._binop(Mul, other) 821 822 def __rmul__(self, other: t.Any) -> Mul: 823 return self._binop(Mul, other, reverse=True) 824 825 def __truediv__(self, other: t.Any) -> Div: 826 return self._binop(Div, other) 827 828 def __rtruediv__(self, other: t.Any) -> Div: 829 return self._binop(Div, other, reverse=True) 830 831 def __floordiv__(self, other: t.Any) -> IntDiv: 832 return self._binop(IntDiv, other) 833 834 def __rfloordiv__(self, other: t.Any) -> IntDiv: 835 return self._binop(IntDiv, other, reverse=True) 836 837 def __mod__(self, other: t.Any) -> Mod: 838 return self._binop(Mod, other) 839 840 def __rmod__(self, other: t.Any) -> Mod: 841 return self._binop(Mod, other, reverse=True) 842 843 def __pow__(self, other: t.Any) -> Pow: 844 return self._binop(Pow, other) 845 846 def __rpow__(self, other: t.Any) -> Pow: 847 return self._binop(Pow, other, reverse=True) 848 849 def __and__(self, other: t.Any) -> And: 850 return self._binop(And, other) 851 852 def __rand__(self, other: t.Any) -> And: 853 return self._binop(And, other, reverse=True) 854 855 def __or__(self, other: t.Any) -> Or: 856 return self._binop(Or, other) 857 858 def __ror__(self, other: t.Any) -> Or: 859 return self._binop(Or, other, reverse=True) 860 861 def __neg__(self) -> Neg: 862 return Neg(this=_wrap(self.copy(), Binary)) 863 864 def __invert__(self) -> Not: 865 return not_(self.copy())
668 def and_( 669 self, 670 *expressions: t.Optional[ExpOrStr], 671 dialect: DialectType = None, 672 copy: bool = True, 673 **opts, 674 ) -> Condition: 675 """ 676 AND this condition with one or multiple expressions. 677 678 Example: 679 >>> condition("x=1").and_("y=1").sql() 680 'x = 1 AND y = 1' 681 682 Args: 683 *expressions: the SQL code strings to parse. 684 If an `Expression` instance is passed, it will be used as-is. 685 dialect: the dialect used to parse the input expression. 686 copy: whether or not to copy the involved expressions (only applies to Expressions). 687 opts: other options to use to parse the input expressions. 688 689 Returns: 690 The new And condition. 691 """ 692 return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expression.
- copy: whether or not to copy the involved expressions (only applies to Expressions).
- opts: other options to use to parse the input expressions.
Returns:
The new And condition.
694 def or_( 695 self, 696 *expressions: t.Optional[ExpOrStr], 697 dialect: DialectType = None, 698 copy: bool = True, 699 **opts, 700 ) -> Condition: 701 """ 702 OR this condition with one or multiple expressions. 703 704 Example: 705 >>> condition("x=1").or_("y=1").sql() 706 'x = 1 OR y = 1' 707 708 Args: 709 *expressions: the SQL code strings to parse. 710 If an `Expression` instance is passed, it will be used as-is. 711 dialect: the dialect used to parse the input expression. 712 copy: whether or not to copy the involved expressions (only applies to Expressions). 713 opts: other options to use to parse the input expressions. 714 715 Returns: 716 The new Or condition. 717 """ 718 return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expression.
- copy: whether or not to copy the involved expressions (only applies to Expressions).
- opts: other options to use to parse the input expressions.
Returns:
The new Or condition.
720 def not_(self, copy: bool = True): 721 """ 722 Wrap this condition with NOT. 723 724 Example: 725 >>> condition("x=1").not_().sql() 726 'NOT x = 1' 727 728 Args: 729 copy: whether or not to copy this object. 730 731 Returns: 732 The new Not instance. 733 """ 734 return not_(self, copy=copy)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Arguments:
- copy: whether or not to copy this object.
Returns:
The new Not instance.
761 def isin( 762 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 763 ) -> In: 764 return In( 765 this=_maybe_copy(self, copy), 766 expressions=[convert(e, copy=copy) for e in expressions], 767 query=maybe_parse(query, copy=copy, **opts) if query else None, 768 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
872class DerivedTable(Expression): 873 @property 874 def alias_column_names(self) -> t.List[str]: 875 table_alias = self.args.get("alias") 876 if not table_alias: 877 return [] 878 return [c.name for c in table_alias.args.get("columns") or []] 879 880 @property 881 def selects(self): 882 return self.this.selects if isinstance(self.this, Subqueryable) else [] 883 884 @property 885 def named_selects(self): 886 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
889class Unionable(Expression): 890 def union( 891 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 892 ) -> Unionable: 893 """ 894 Builds a UNION expression. 895 896 Example: 897 >>> import sqlglot 898 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 899 'SELECT * FROM foo UNION SELECT * FROM bla' 900 901 Args: 902 expression: the SQL code string. 903 If an `Expression` instance is passed, it will be used as-is. 904 distinct: set the DISTINCT flag if and only if this is true. 905 dialect: the dialect used to parse the input expression. 906 opts: other options to use to parse the input expressions. 907 908 Returns: 909 The new Union expression. 910 """ 911 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 912 913 def intersect( 914 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 915 ) -> Unionable: 916 """ 917 Builds an INTERSECT expression. 918 919 Example: 920 >>> import sqlglot 921 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 922 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 923 924 Args: 925 expression: the SQL code string. 926 If an `Expression` instance is passed, it will be used as-is. 927 distinct: set the DISTINCT flag if and only if this is true. 928 dialect: the dialect used to parse the input expression. 929 opts: other options to use to parse the input expressions. 930 931 Returns: 932 The new Intersect expression. 933 """ 934 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 935 936 def except_( 937 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 938 ) -> Unionable: 939 """ 940 Builds an EXCEPT expression. 941 942 Example: 943 >>> import sqlglot 944 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 945 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 946 947 Args: 948 expression: the SQL code string. 949 If an `Expression` instance is passed, it will be used as-is. 950 distinct: set the DISTINCT flag if and only if this is true. 951 dialect: the dialect used to parse the input expression. 952 opts: other options to use to parse the input expressions. 953 954 Returns: 955 The new Except expression. 956 """ 957 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
890 def union( 891 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 892 ) -> Unionable: 893 """ 894 Builds a UNION expression. 895 896 Example: 897 >>> import sqlglot 898 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 899 'SELECT * FROM foo UNION SELECT * FROM bla' 900 901 Args: 902 expression: the SQL code string. 903 If an `Expression` instance is passed, it will be used as-is. 904 distinct: set the DISTINCT flag if and only if this is true. 905 dialect: the dialect used to parse the input expression. 906 opts: other options to use to parse the input expressions. 907 908 Returns: 909 The new Union expression. 910 """ 911 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Union expression.
913 def intersect( 914 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 915 ) -> Unionable: 916 """ 917 Builds an INTERSECT expression. 918 919 Example: 920 >>> import sqlglot 921 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 922 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 923 924 Args: 925 expression: the SQL code string. 926 If an `Expression` instance is passed, it will be used as-is. 927 distinct: set the DISTINCT flag if and only if this is true. 928 dialect: the dialect used to parse the input expression. 929 opts: other options to use to parse the input expressions. 930 931 Returns: 932 The new Intersect expression. 933 """ 934 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Intersect expression.
936 def except_( 937 self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 938 ) -> Unionable: 939 """ 940 Builds an EXCEPT expression. 941 942 Example: 943 >>> import sqlglot 944 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 945 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 946 947 Args: 948 expression: the SQL code string. 949 If an `Expression` instance is passed, it will be used as-is. 950 distinct: set the DISTINCT flag if and only if this is true. 951 dialect: the dialect used to parse the input expression. 952 opts: other options to use to parse the input expressions. 953 954 Returns: 955 The new Except expression. 956 """ 957 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression: the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct: set the DISTINCT flag if and only if this is true.
- dialect: the dialect used to parse the input expression.
- opts: other options to use to parse the input expressions.
Returns:
The new Except expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
960class UDTF(DerivedTable, Unionable): 961 @property 962 def selects(self): 963 alias = self.args.get("alias") 964 return alias.columns if alias else []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
967class Cache(Expression): 968 arg_types = { 969 "with": False, 970 "this": True, 971 "lazy": False, 972 "options": False, 973 "expression": False, 974 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
981class Create(Expression): 982 arg_types = { 983 "with": False, 984 "this": True, 985 "kind": True, 986 "expression": False, 987 "exists": False, 988 "properties": False, 989 "replace": False, 990 "unique": False, 991 "indexes": False, 992 "no_schema_binding": False, 993 "begin": False, 994 "clone": False, 995 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
999class Clone(Expression): 1000 arg_types = { 1001 "this": True, 1002 "when": False, 1003 "kind": False, 1004 "expression": False, 1005 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1020class SetItem(Expression): 1021 arg_types = { 1022 "this": False, 1023 "expressions": False, 1024 "kind": False, 1025 "collate": False, # MySQL SET NAMES statement 1026 "global": False, 1027 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1030class Show(Expression): 1031 arg_types = { 1032 "this": True, 1033 "target": False, 1034 "offset": False, 1035 "limit": False, 1036 "like": False, 1037 "where": False, 1038 "db": False, 1039 "full": False, 1040 "mutex": False, 1041 "query": False, 1042 "channel": False, 1043 "global": False, 1044 "log": False, 1045 "position": False, 1046 "types": False, 1047 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1050class UserDefinedFunction(Expression): 1051 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1058class With(Expression): 1059 arg_types = {"expressions": True, "recursive": False} 1060 1061 @property 1062 def recursive(self) -> bool: 1063 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1074class TableAlias(Expression): 1075 arg_types = {"this": False, "columns": False} 1076 1077 @property 1078 def columns(self): 1079 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1098class Column(Condition): 1099 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1100 1101 @property 1102 def table(self) -> str: 1103 return self.text("table") 1104 1105 @property 1106 def db(self) -> str: 1107 return self.text("db") 1108 1109 @property 1110 def catalog(self) -> str: 1111 return self.text("catalog") 1112 1113 @property 1114 def output_name(self) -> str: 1115 return self.name 1116 1117 @property 1118 def parts(self) -> t.List[Identifier]: 1119 """Return the parts of a column in order catalog, db, table, name.""" 1120 return [ 1121 t.cast(Identifier, self.args[part]) 1122 for part in ("catalog", "db", "table", "this") 1123 if self.args.get(part) 1124 ] 1125 1126 def to_dot(self) -> Dot: 1127 """Converts the column into a dot expression.""" 1128 parts = self.parts 1129 parent = self.parent 1130 1131 while parent: 1132 if isinstance(parent, Dot): 1133 parts.append(parent.expression) 1134 parent = parent.parent 1135 1136 return Dot.build(parts)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Return the parts of a column in order catalog, db, table, name.
1126 def to_dot(self) -> Dot: 1127 """Converts the column into a dot expression.""" 1128 parts = self.parts 1129 parent = self.parent 1130 1131 while parent: 1132 if isinstance(parent, Dot): 1133 parts.append(parent.expression) 1134 parent = parent.parent 1135 1136 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1143class ColumnDef(Expression): 1144 arg_types = { 1145 "this": True, 1146 "kind": False, 1147 "constraints": False, 1148 "exists": False, 1149 "position": False, 1150 } 1151 1152 @property 1153 def constraints(self) -> t.List[ColumnConstraint]: 1154 return self.args.get("constraints") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1157class AlterColumn(Expression): 1158 arg_types = { 1159 "this": True, 1160 "dtype": False, 1161 "collate": False, 1162 "using": False, 1163 "default": False, 1164 "drop": False, 1165 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1176class Comment(Expression): 1177 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1181class MergeTreeTTLAction(Expression): 1182 arg_types = { 1183 "this": True, 1184 "delete": False, 1185 "recompress": False, 1186 "to_disk": False, 1187 "to_volume": False, 1188 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1192class MergeTreeTTL(Expression): 1193 arg_types = { 1194 "expressions": True, 1195 "where": False, 1196 "group": False, 1197 "aggregates": False, 1198 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1201class ColumnConstraint(Expression): 1202 arg_types = {"this": False, "kind": True} 1203 1204 @property 1205 def kind(self) -> ColumnConstraintKind: 1206 return self.args["kind"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1253class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1254 # this: True -> ALWAYS, this: False -> BY DEFAULT 1255 arg_types = { 1256 "this": False, 1257 "expression": False, 1258 "on_null": False, 1259 "start": False, 1260 "increment": False, 1261 "minvalue": False, 1262 "maxvalue": False, 1263 "cycle": False, 1264 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1304class Delete(Expression): 1305 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1306 1307 def delete( 1308 self, 1309 table: ExpOrStr, 1310 dialect: DialectType = None, 1311 copy: bool = True, 1312 **opts, 1313 ) -> Delete: 1314 """ 1315 Create a DELETE expression or replace the table on an existing DELETE expression. 1316 1317 Example: 1318 >>> delete("tbl").sql() 1319 'DELETE FROM tbl' 1320 1321 Args: 1322 table: the table from which to delete. 1323 dialect: the dialect used to parse the input expression. 1324 copy: if `False`, modify this expression instance in-place. 1325 opts: other options to use to parse the input expressions. 1326 1327 Returns: 1328 Delete: the modified expression. 1329 """ 1330 return _apply_builder( 1331 expression=table, 1332 instance=self, 1333 arg="this", 1334 dialect=dialect, 1335 into=Table, 1336 copy=copy, 1337 **opts, 1338 ) 1339 1340 def where( 1341 self, 1342 *expressions: t.Optional[ExpOrStr], 1343 append: bool = True, 1344 dialect: DialectType = None, 1345 copy: bool = True, 1346 **opts, 1347 ) -> Delete: 1348 """ 1349 Append to or set the WHERE expressions. 1350 1351 Example: 1352 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1353 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1354 1355 Args: 1356 *expressions: the SQL code strings to parse. 1357 If an `Expression` instance is passed, it will be used as-is. 1358 Multiple expressions are combined with an AND operator. 1359 append: if `True`, AND the new expressions to any existing expression. 1360 Otherwise, this resets the expression. 1361 dialect: the dialect used to parse the input expressions. 1362 copy: if `False`, modify this expression instance in-place. 1363 opts: other options to use to parse the input expressions. 1364 1365 Returns: 1366 Delete: the modified expression. 1367 """ 1368 return _apply_conjunction_builder( 1369 *expressions, 1370 instance=self, 1371 arg="where", 1372 append=append, 1373 into=Where, 1374 dialect=dialect, 1375 copy=copy, 1376 **opts, 1377 ) 1378 1379 def returning( 1380 self, 1381 expression: ExpOrStr, 1382 dialect: DialectType = None, 1383 copy: bool = True, 1384 **opts, 1385 ) -> Delete: 1386 """ 1387 Set the RETURNING expression. Not supported by all dialects. 1388 1389 Example: 1390 >>> delete("tbl").returning("*", dialect="postgres").sql() 1391 'DELETE FROM tbl RETURNING *' 1392 1393 Args: 1394 expression: the SQL code strings to parse. 1395 If an `Expression` instance is passed, it will be used as-is. 1396 dialect: the dialect used to parse the input expressions. 1397 copy: if `False`, modify this expression instance in-place. 1398 opts: other options to use to parse the input expressions. 1399 1400 Returns: 1401 Delete: the modified expression. 1402 """ 1403 return _apply_builder( 1404 expression=expression, 1405 instance=self, 1406 arg="returning", 1407 prefix="RETURNING", 1408 dialect=dialect, 1409 copy=copy, 1410 into=Returning, 1411 **opts, 1412 )
1307 def delete( 1308 self, 1309 table: ExpOrStr, 1310 dialect: DialectType = None, 1311 copy: bool = True, 1312 **opts, 1313 ) -> Delete: 1314 """ 1315 Create a DELETE expression or replace the table on an existing DELETE expression. 1316 1317 Example: 1318 >>> delete("tbl").sql() 1319 'DELETE FROM tbl' 1320 1321 Args: 1322 table: the table from which to delete. 1323 dialect: the dialect used to parse the input expression. 1324 copy: if `False`, modify this expression instance in-place. 1325 opts: other options to use to parse the input expressions. 1326 1327 Returns: 1328 Delete: the modified expression. 1329 """ 1330 return _apply_builder( 1331 expression=table, 1332 instance=self, 1333 arg="this", 1334 dialect=dialect, 1335 into=Table, 1336 copy=copy, 1337 **opts, 1338 )
Create a DELETE expression or replace the table on an existing DELETE expression.
Example:
>>> delete("tbl").sql() 'DELETE FROM tbl'
Arguments:
- table: the table from which to delete.
- dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1340 def where( 1341 self, 1342 *expressions: t.Optional[ExpOrStr], 1343 append: bool = True, 1344 dialect: DialectType = None, 1345 copy: bool = True, 1346 **opts, 1347 ) -> Delete: 1348 """ 1349 Append to or set the WHERE expressions. 1350 1351 Example: 1352 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1353 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1354 1355 Args: 1356 *expressions: the SQL code strings to parse. 1357 If an `Expression` instance is passed, it will be used as-is. 1358 Multiple expressions are combined with an AND operator. 1359 append: if `True`, AND the new expressions to any existing expression. 1360 Otherwise, this resets the expression. 1361 dialect: the dialect used to parse the input expressions. 1362 copy: if `False`, modify this expression instance in-place. 1363 opts: other options to use to parse the input expressions. 1364 1365 Returns: 1366 Delete: the modified expression. 1367 """ 1368 return _apply_conjunction_builder( 1369 *expressions, 1370 instance=self, 1371 arg="where", 1372 append=append, 1373 into=Where, 1374 dialect=dialect, 1375 copy=copy, 1376 **opts, 1377 )
Append to or set the WHERE expressions.
Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1379 def returning( 1380 self, 1381 expression: ExpOrStr, 1382 dialect: DialectType = None, 1383 copy: bool = True, 1384 **opts, 1385 ) -> Delete: 1386 """ 1387 Set the RETURNING expression. Not supported by all dialects. 1388 1389 Example: 1390 >>> delete("tbl").returning("*", dialect="postgres").sql() 1391 'DELETE FROM tbl RETURNING *' 1392 1393 Args: 1394 expression: the SQL code strings to parse. 1395 If an `Expression` instance is passed, it will be used as-is. 1396 dialect: the dialect used to parse the input expressions. 1397 copy: if `False`, modify this expression instance in-place. 1398 opts: other options to use to parse the input expressions. 1399 1400 Returns: 1401 Delete: the modified expression. 1402 """ 1403 return _apply_builder( 1404 expression=expression, 1405 instance=self, 1406 arg="returning", 1407 prefix="RETURNING", 1408 dialect=dialect, 1409 copy=copy, 1410 into=Returning, 1411 **opts, 1412 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1415class Drop(Expression): 1416 arg_types = { 1417 "this": False, 1418 "kind": False, 1419 "exists": False, 1420 "temporary": False, 1421 "materialized": False, 1422 "cascade": False, 1423 "constraints": False, 1424 "purge": False, 1425 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1436class Directory(Expression): 1437 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1438 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1441class ForeignKey(Expression): 1442 arg_types = { 1443 "expressions": True, 1444 "reference": False, 1445 "delete": False, 1446 "update": False, 1447 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1460class From(Expression): 1461 @property 1462 def name(self) -> str: 1463 return self.this.name 1464 1465 @property 1466 def alias_or_name(self) -> str: 1467 return self.this.alias_or_name
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1482class Identifier(Expression): 1483 arg_types = {"this": True, "quoted": False} 1484 1485 @property 1486 def quoted(self) -> bool: 1487 return bool(self.args.get("quoted")) 1488 1489 @property 1490 def hashable_args(self) -> t.Any: 1491 if self.quoted and any(char.isupper() for char in self.this): 1492 return (self.this, self.quoted) 1493 return self.this.lower() 1494 1495 @property 1496 def output_name(self) -> str: 1497 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1500class Index(Expression): 1501 arg_types = { 1502 "this": False, 1503 "table": False, 1504 "where": False, 1505 "columns": False, 1506 "unique": False, 1507 "primary": False, 1508 "amp": False, # teradata 1509 "partition_by": False, # teradata 1510 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1513class Insert(Expression): 1514 arg_types = { 1515 "with": False, 1516 "this": True, 1517 "expression": False, 1518 "conflict": False, 1519 "returning": False, 1520 "overwrite": False, 1521 "exists": False, 1522 "partition": False, 1523 "alternative": False, 1524 } 1525 1526 def with_( 1527 self, 1528 alias: ExpOrStr, 1529 as_: ExpOrStr, 1530 recursive: t.Optional[bool] = None, 1531 append: bool = True, 1532 dialect: DialectType = None, 1533 copy: bool = True, 1534 **opts, 1535 ) -> Insert: 1536 """ 1537 Append to or set the common table expressions. 1538 1539 Example: 1540 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1541 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1542 1543 Args: 1544 alias: the SQL code string to parse as the table name. 1545 If an `Expression` instance is passed, this is used as-is. 1546 as_: the SQL code string to parse as the table expression. 1547 If an `Expression` instance is passed, it will be used as-is. 1548 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1549 append: if `True`, add to any existing expressions. 1550 Otherwise, this resets the expressions. 1551 dialect: the dialect used to parse the input expression. 1552 copy: if `False`, modify this expression instance in-place. 1553 opts: other options to use to parse the input expressions. 1554 1555 Returns: 1556 The modified expression. 1557 """ 1558 return _apply_cte_builder( 1559 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1560 )
1526 def with_( 1527 self, 1528 alias: ExpOrStr, 1529 as_: ExpOrStr, 1530 recursive: t.Optional[bool] = None, 1531 append: bool = True, 1532 dialect: DialectType = None, 1533 copy: bool = True, 1534 **opts, 1535 ) -> Insert: 1536 """ 1537 Append to or set the common table expressions. 1538 1539 Example: 1540 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1541 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1542 1543 Args: 1544 alias: the SQL code string to parse as the table name. 1545 If an `Expression` instance is passed, this is used as-is. 1546 as_: the SQL code string to parse as the table expression. 1547 If an `Expression` instance is passed, it will be used as-is. 1548 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1549 append: if `True`, add to any existing expressions. 1550 Otherwise, this resets the expressions. 1551 dialect: the dialect used to parse the input expression. 1552 copy: if `False`, modify this expression instance in-place. 1553 opts: other options to use to parse the input expressions. 1554 1555 Returns: 1556 The modified expression. 1557 """ 1558 return _apply_cte_builder( 1559 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1560 )
Append to or set the common table expressions.
Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
- alias: the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_: the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive: set the RECURSIVE part of the expression. Defaults to
False
. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1563class OnConflict(Expression): 1564 arg_types = { 1565 "duplicate": False, 1566 "expressions": False, 1567 "nothing": False, 1568 "key": False, 1569 "constraint": False, 1570 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1587class LoadData(Expression): 1588 arg_types = { 1589 "this": True, 1590 "local": False, 1591 "overwrite": False, 1592 "inpath": True, 1593 "partition": False, 1594 "input_format": False, 1595 "serde": False, 1596 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1603class Fetch(Expression): 1604 arg_types = { 1605 "direction": False, 1606 "count": False, 1607 "percent": False, 1608 "with_ties": False, 1609 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1612class Group(Expression): 1613 arg_types = { 1614 "expressions": False, 1615 "grouping_sets": False, 1616 "cube": False, 1617 "rollup": False, 1618 "totals": False, 1619 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1630class Literal(Condition): 1631 arg_types = {"this": True, "is_string": True} 1632 1633 @property 1634 def hashable_args(self) -> t.Any: 1635 return (self.this, self.args.get("is_string")) 1636 1637 @classmethod 1638 def number(cls, number) -> Literal: 1639 return cls(this=str(number), is_string=False) 1640 1641 @classmethod 1642 def string(cls, string) -> Literal: 1643 return cls(this=str(string), is_string=True) 1644 1645 @property 1646 def output_name(self) -> str: 1647 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1650class Join(Expression): 1651 arg_types = { 1652 "this": True, 1653 "on": False, 1654 "side": False, 1655 "kind": False, 1656 "using": False, 1657 "method": False, 1658 "global": False, 1659 "hint": False, 1660 } 1661 1662 @property 1663 def method(self) -> str: 1664 return self.text("method").upper() 1665 1666 @property 1667 def kind(self) -> str: 1668 return self.text("kind").upper() 1669 1670 @property 1671 def side(self) -> str: 1672 return self.text("side").upper() 1673 1674 @property 1675 def hint(self) -> str: 1676 return self.text("hint").upper() 1677 1678 @property 1679 def alias_or_name(self) -> str: 1680 return self.this.alias_or_name 1681 1682 def on( 1683 self, 1684 *expressions: t.Optional[ExpOrStr], 1685 append: bool = True, 1686 dialect: DialectType = None, 1687 copy: bool = True, 1688 **opts, 1689 ) -> Join: 1690 """ 1691 Append to or set the ON expressions. 1692 1693 Example: 1694 >>> import sqlglot 1695 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1696 'JOIN x ON y = 1' 1697 1698 Args: 1699 *expressions: the SQL code strings to parse. 1700 If an `Expression` instance is passed, it will be used as-is. 1701 Multiple expressions are combined with an AND operator. 1702 append: if `True`, AND the new expressions to any existing expression. 1703 Otherwise, this resets the expression. 1704 dialect: the dialect used to parse the input expressions. 1705 copy: if `False`, modify this expression instance in-place. 1706 opts: other options to use to parse the input expressions. 1707 1708 Returns: 1709 The modified Join expression. 1710 """ 1711 join = _apply_conjunction_builder( 1712 *expressions, 1713 instance=self, 1714 arg="on", 1715 append=append, 1716 dialect=dialect, 1717 copy=copy, 1718 **opts, 1719 ) 1720 1721 if join.kind == "CROSS": 1722 join.set("kind", None) 1723 1724 return join 1725 1726 def using( 1727 self, 1728 *expressions: t.Optional[ExpOrStr], 1729 append: bool = True, 1730 dialect: DialectType = None, 1731 copy: bool = True, 1732 **opts, 1733 ) -> Join: 1734 """ 1735 Append to or set the USING expressions. 1736 1737 Example: 1738 >>> import sqlglot 1739 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1740 'JOIN x USING (foo, bla)' 1741 1742 Args: 1743 *expressions: the SQL code strings to parse. 1744 If an `Expression` instance is passed, it will be used as-is. 1745 append: if `True`, concatenate the new expressions to the existing "using" list. 1746 Otherwise, this resets the expression. 1747 dialect: the dialect used to parse the input expressions. 1748 copy: if `False`, modify this expression instance in-place. 1749 opts: other options to use to parse the input expressions. 1750 1751 Returns: 1752 The modified Join expression. 1753 """ 1754 join = _apply_list_builder( 1755 *expressions, 1756 instance=self, 1757 arg="using", 1758 append=append, 1759 dialect=dialect, 1760 copy=copy, 1761 **opts, 1762 ) 1763 1764 if join.kind == "CROSS": 1765 join.set("kind", None) 1766 1767 return join
1682 def on( 1683 self, 1684 *expressions: t.Optional[ExpOrStr], 1685 append: bool = True, 1686 dialect: DialectType = None, 1687 copy: bool = True, 1688 **opts, 1689 ) -> Join: 1690 """ 1691 Append to or set the ON expressions. 1692 1693 Example: 1694 >>> import sqlglot 1695 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1696 'JOIN x ON y = 1' 1697 1698 Args: 1699 *expressions: the SQL code strings to parse. 1700 If an `Expression` instance is passed, it will be used as-is. 1701 Multiple expressions are combined with an AND operator. 1702 append: if `True`, AND the new expressions to any existing expression. 1703 Otherwise, this resets the expression. 1704 dialect: the dialect used to parse the input expressions. 1705 copy: if `False`, modify this expression instance in-place. 1706 opts: other options to use to parse the input expressions. 1707 1708 Returns: 1709 The modified Join expression. 1710 """ 1711 join = _apply_conjunction_builder( 1712 *expressions, 1713 instance=self, 1714 arg="on", 1715 append=append, 1716 dialect=dialect, 1717 copy=copy, 1718 **opts, 1719 ) 1720 1721 if join.kind == "CROSS": 1722 join.set("kind", None) 1723 1724 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Join expression.
1726 def using( 1727 self, 1728 *expressions: t.Optional[ExpOrStr], 1729 append: bool = True, 1730 dialect: DialectType = None, 1731 copy: bool = True, 1732 **opts, 1733 ) -> Join: 1734 """ 1735 Append to or set the USING expressions. 1736 1737 Example: 1738 >>> import sqlglot 1739 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1740 'JOIN x USING (foo, bla)' 1741 1742 Args: 1743 *expressions: the SQL code strings to parse. 1744 If an `Expression` instance is passed, it will be used as-is. 1745 append: if `True`, concatenate the new expressions to the existing "using" list. 1746 Otherwise, this resets the expression. 1747 dialect: the dialect used to parse the input expressions. 1748 copy: if `False`, modify this expression instance in-place. 1749 opts: other options to use to parse the input expressions. 1750 1751 Returns: 1752 The modified Join expression. 1753 """ 1754 join = _apply_list_builder( 1755 *expressions, 1756 instance=self, 1757 arg="using", 1758 append=append, 1759 dialect=dialect, 1760 copy=copy, 1761 **opts, 1762 ) 1763 1764 if join.kind == "CROSS": 1765 join.set("kind", None) 1766 1767 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified Join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1770class Lateral(UDTF): 1771 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1774class MatchRecognize(Expression): 1775 arg_types = { 1776 "partition_by": False, 1777 "order": False, 1778 "measures": False, 1779 "rows": False, 1780 "after": False, 1781 "pattern": False, 1782 "define": False, 1783 "alias": False, 1784 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1831class BlockCompressionProperty(Property): 1832 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1847class DataBlocksizeProperty(Property): 1848 arg_types = { 1849 "size": False, 1850 "units": False, 1851 "minimum": False, 1852 "maximum": False, 1853 "default": False, 1854 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1893class InputOutputFormat(Expression): 1894 arg_types = {"input_format": False, "output_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1897class IsolatedLoadingProperty(Property): 1898 arg_types = { 1899 "no": True, 1900 "concurrent": True, 1901 "for_all": True, 1902 "for_insert": True, 1903 "for_none": True, 1904 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1907class JournalProperty(Property): 1908 arg_types = { 1909 "no": False, 1910 "dual": False, 1911 "before": False, 1912 "local": False, 1913 "after": False, 1914 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1941class LockingProperty(Property): 1942 arg_types = { 1943 "this": False, 1944 "kind": True, 1945 "for_or_in": True, 1946 "lock_type": True, 1947 "override": False, 1948 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1959class MergeBlockRatioProperty(Property): 1960 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
1975class ReturnsProperty(Property): 1976 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
1983class RowFormatDelimitedProperty(Property): 1984 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1985 arg_types = { 1986 "fields": False, 1987 "escaped": False, 1988 "collection_items": False, 1989 "map_keys": False, 1990 "lines": False, 1991 "null": False, 1992 "serde": False, 1993 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2048class Properties(Expression): 2049 arg_types = {"expressions": True} 2050 2051 NAME_TO_PROPERTY = { 2052 "ALGORITHM": AlgorithmProperty, 2053 "AUTO_INCREMENT": AutoIncrementProperty, 2054 "CHARACTER SET": CharacterSetProperty, 2055 "COLLATE": CollateProperty, 2056 "COMMENT": SchemaCommentProperty, 2057 "DEFINER": DefinerProperty, 2058 "DISTKEY": DistKeyProperty, 2059 "DISTSTYLE": DistStyleProperty, 2060 "ENGINE": EngineProperty, 2061 "EXECUTE AS": ExecuteAsProperty, 2062 "FORMAT": FileFormatProperty, 2063 "LANGUAGE": LanguageProperty, 2064 "LOCATION": LocationProperty, 2065 "PARTITIONED_BY": PartitionedByProperty, 2066 "RETURNS": ReturnsProperty, 2067 "ROW_FORMAT": RowFormatProperty, 2068 "SORTKEY": SortKeyProperty, 2069 } 2070 2071 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2072 2073 # CREATE property locations 2074 # Form: schema specified 2075 # create [POST_CREATE] 2076 # table a [POST_NAME] 2077 # (b int) [POST_SCHEMA] 2078 # with ([POST_WITH]) 2079 # index (b) [POST_INDEX] 2080 # 2081 # Form: alias selection 2082 # create [POST_CREATE] 2083 # table a [POST_NAME] 2084 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2085 # index (c) [POST_INDEX] 2086 class Location(AutoName): 2087 POST_CREATE = auto() 2088 POST_NAME = auto() 2089 POST_SCHEMA = auto() 2090 POST_WITH = auto() 2091 POST_ALIAS = auto() 2092 POST_EXPRESSION = auto() 2093 POST_INDEX = auto() 2094 UNSUPPORTED = auto() 2095 2096 @classmethod 2097 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2098 expressions = [] 2099 for key, value in properties_dict.items(): 2100 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2101 if property_cls: 2102 expressions.append(property_cls(this=convert(value))) 2103 else: 2104 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2105 2106 return cls(expressions=expressions)
2096 @classmethod 2097 def from_dict(cls, properties_dict: t.Dict) -> Properties: 2098 expressions = [] 2099 for key, value in properties_dict.items(): 2100 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2101 if property_cls: 2102 expressions.append(property_cls(this=convert(value))) 2103 else: 2104 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2105 2106 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
2086 class Location(AutoName): 2087 POST_CREATE = auto() 2088 POST_NAME = auto() 2089 POST_SCHEMA = auto() 2090 POST_WITH = auto() 2091 POST_ALIAS = auto() 2092 POST_EXPRESSION = auto() 2093 POST_INDEX = auto() 2094 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
2118class Reference(Expression): 2119 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
2122class Tuple(Expression): 2123 arg_types = {"expressions": False} 2124 2125 def isin( 2126 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2127 ) -> In: 2128 return In( 2129 this=_maybe_copy(self, copy), 2130 expressions=[convert(e, copy=copy) for e in expressions], 2131 query=maybe_parse(query, copy=copy, **opts) if query else None, 2132 )
2125 def isin( 2126 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts 2127 ) -> In: 2128 return In( 2129 this=_maybe_copy(self, copy), 2130 expressions=[convert(e, copy=copy) for e in expressions], 2131 query=maybe_parse(query, copy=copy, **opts) if query else None, 2132 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2135class Subqueryable(Unionable): 2136 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2137 """ 2138 Convert this expression to an aliased expression that can be used as a Subquery. 2139 2140 Example: 2141 >>> subquery = Select().select("x").from_("tbl").subquery() 2142 >>> Select().select("x").from_(subquery).sql() 2143 'SELECT x FROM (SELECT x FROM tbl)' 2144 2145 Args: 2146 alias (str | Identifier): an optional alias for the subquery 2147 copy (bool): if `False`, modify this expression instance in-place. 2148 2149 Returns: 2150 Alias: the subquery 2151 """ 2152 instance = _maybe_copy(self, copy) 2153 if not isinstance(alias, Expression): 2154 alias = TableAlias(this=to_identifier(alias)) if alias else None 2155 2156 return Subquery(this=instance, alias=alias) 2157 2158 def limit( 2159 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2160 ) -> Select: 2161 raise NotImplementedError 2162 2163 @property 2164 def ctes(self): 2165 with_ = self.args.get("with") 2166 if not with_: 2167 return [] 2168 return with_.expressions 2169 2170 @property 2171 def selects(self): 2172 raise NotImplementedError("Subqueryable objects must implement `selects`") 2173 2174 @property 2175 def named_selects(self): 2176 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2177 2178 def with_( 2179 self, 2180 alias: ExpOrStr, 2181 as_: ExpOrStr, 2182 recursive: t.Optional[bool] = None, 2183 append: bool = True, 2184 dialect: DialectType = None, 2185 copy: bool = True, 2186 **opts, 2187 ) -> Subqueryable: 2188 """ 2189 Append to or set the common table expressions. 2190 2191 Example: 2192 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2193 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2194 2195 Args: 2196 alias: the SQL code string to parse as the table name. 2197 If an `Expression` instance is passed, this is used as-is. 2198 as_: the SQL code string to parse as the table expression. 2199 If an `Expression` instance is passed, it will be used as-is. 2200 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2201 append: if `True`, add to any existing expressions. 2202 Otherwise, this resets the expressions. 2203 dialect: the dialect used to parse the input expression. 2204 copy: if `False`, modify this expression instance in-place. 2205 opts: other options to use to parse the input expressions. 2206 2207 Returns: 2208 The modified expression. 2209 """ 2210 return _apply_cte_builder( 2211 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2212 )
2136 def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery: 2137 """ 2138 Convert this expression to an aliased expression that can be used as a Subquery. 2139 2140 Example: 2141 >>> subquery = Select().select("x").from_("tbl").subquery() 2142 >>> Select().select("x").from_(subquery).sql() 2143 'SELECT x FROM (SELECT x FROM tbl)' 2144 2145 Args: 2146 alias (str | Identifier): an optional alias for the subquery 2147 copy (bool): if `False`, modify this expression instance in-place. 2148 2149 Returns: 2150 Alias: the subquery 2151 """ 2152 instance = _maybe_copy(self, copy) 2153 if not isinstance(alias, Expression): 2154 alias = TableAlias(this=to_identifier(alias)) if alias else None 2155 2156 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
2178 def with_( 2179 self, 2180 alias: ExpOrStr, 2181 as_: ExpOrStr, 2182 recursive: t.Optional[bool] = None, 2183 append: bool = True, 2184 dialect: DialectType = None, 2185 copy: bool = True, 2186 **opts, 2187 ) -> Subqueryable: 2188 """ 2189 Append to or set the common table expressions. 2190 2191 Example: 2192 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2193 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2194 2195 Args: 2196 alias: the SQL code string to parse as the table name. 2197 If an `Expression` instance is passed, this is used as-is. 2198 as_: the SQL code string to parse as the table expression. 2199 If an `Expression` instance is passed, it will be used as-is. 2200 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2201 append: if `True`, add to any existing expressions. 2202 Otherwise, this resets the expressions. 2203 dialect: the dialect used to parse the input expression. 2204 copy: if `False`, modify this expression instance in-place. 2205 opts: other options to use to parse the input expressions. 2206 2207 Returns: 2208 The modified expression. 2209 """ 2210 return _apply_cte_builder( 2211 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2212 )
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
2238class Table(Expression): 2239 arg_types = { 2240 "this": True, 2241 "alias": False, 2242 "db": False, 2243 "catalog": False, 2244 "laterals": False, 2245 "joins": False, 2246 "pivots": False, 2247 "hints": False, 2248 "system_time": False, 2249 } 2250 2251 @property 2252 def db(self) -> str: 2253 return self.text("db") 2254 2255 @property 2256 def catalog(self) -> str: 2257 return self.text("catalog") 2258 2259 @property 2260 def parts(self) -> t.List[Identifier]: 2261 """Return the parts of a table in order catalog, db, table.""" 2262 return [ 2263 t.cast(Identifier, self.args[part]) 2264 for part in ("catalog", "db", "this") 2265 if self.args.get(part) 2266 ]
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
2270class SystemTime(Expression): 2271 arg_types = { 2272 "this": False, 2273 "expression": False, 2274 "kind": True, 2275 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2278class Union(Subqueryable): 2279 arg_types = { 2280 "with": False, 2281 "this": True, 2282 "expression": True, 2283 "distinct": False, 2284 **QUERY_MODIFIERS, 2285 } 2286 2287 def limit( 2288 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2289 ) -> Select: 2290 """ 2291 Set the LIMIT expression. 2292 2293 Example: 2294 >>> select("1").union(select("1")).limit(1).sql() 2295 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2296 2297 Args: 2298 expression: the SQL code string to parse. 2299 This can also be an integer. 2300 If a `Limit` instance is passed, this is used as-is. 2301 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2302 dialect: the dialect used to parse the input expression. 2303 copy: if `False`, modify this expression instance in-place. 2304 opts: other options to use to parse the input expressions. 2305 2306 Returns: 2307 The limited subqueryable. 2308 """ 2309 return ( 2310 select("*") 2311 .from_(self.subquery(alias="_l_0", copy=copy)) 2312 .limit(expression, dialect=dialect, copy=False, **opts) 2313 ) 2314 2315 def select( 2316 self, 2317 *expressions: t.Optional[ExpOrStr], 2318 append: bool = True, 2319 dialect: DialectType = None, 2320 copy: bool = True, 2321 **opts, 2322 ) -> Union: 2323 """Append to or set the SELECT of the union recursively. 2324 2325 Example: 2326 >>> from sqlglot import parse_one 2327 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2328 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2329 2330 Args: 2331 *expressions: the SQL code strings to parse. 2332 If an `Expression` instance is passed, it will be used as-is. 2333 append: if `True`, add to any existing expressions. 2334 Otherwise, this resets the expressions. 2335 dialect: the dialect used to parse the input expressions. 2336 copy: if `False`, modify this expression instance in-place. 2337 opts: other options to use to parse the input expressions. 2338 2339 Returns: 2340 Union: the modified expression. 2341 """ 2342 this = self.copy() if copy else self 2343 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2344 this.expression.unnest().select( 2345 *expressions, append=append, dialect=dialect, copy=False, **opts 2346 ) 2347 return this 2348 2349 @property 2350 def named_selects(self): 2351 return self.this.unnest().named_selects 2352 2353 @property 2354 def is_star(self) -> bool: 2355 return self.this.is_star or self.expression.is_star 2356 2357 @property 2358 def selects(self): 2359 return self.this.unnest().selects 2360 2361 @property 2362 def left(self): 2363 return self.this 2364 2365 @property 2366 def right(self): 2367 return self.expression
2287 def limit( 2288 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2289 ) -> Select: 2290 """ 2291 Set the LIMIT expression. 2292 2293 Example: 2294 >>> select("1").union(select("1")).limit(1).sql() 2295 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2296 2297 Args: 2298 expression: the SQL code string to parse. 2299 This can also be an integer. 2300 If a `Limit` instance is passed, this is used as-is. 2301 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2302 dialect: the dialect used to parse the input expression. 2303 copy: if `False`, modify this expression instance in-place. 2304 opts: other options to use to parse the input expressions. 2305 2306 Returns: 2307 The limited subqueryable. 2308 """ 2309 return ( 2310 select("*") 2311 .from_(self.subquery(alias="_l_0", copy=copy)) 2312 .limit(expression, dialect=dialect, copy=False, **opts) 2313 )
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.
2315 def select( 2316 self, 2317 *expressions: t.Optional[ExpOrStr], 2318 append: bool = True, 2319 dialect: DialectType = None, 2320 copy: bool = True, 2321 **opts, 2322 ) -> Union: 2323 """Append to or set the SELECT of the union recursively. 2324 2325 Example: 2326 >>> from sqlglot import parse_one 2327 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2328 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2329 2330 Args: 2331 *expressions: the SQL code strings to parse. 2332 If an `Expression` instance is passed, it will be used as-is. 2333 append: if `True`, add to any existing expressions. 2334 Otherwise, this resets the expressions. 2335 dialect: the dialect used to parse the input expressions. 2336 copy: if `False`, modify this expression instance in-place. 2337 opts: other options to use to parse the input expressions. 2338 2339 Returns: 2340 Union: the modified expression. 2341 """ 2342 this = self.copy() if copy else self 2343 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2344 this.expression.unnest().select( 2345 *expressions, append=append, dialect=dialect, copy=False, **opts 2346 ) 2347 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
2378class Unnest(UDTF): 2379 arg_types = { 2380 "expressions": True, 2381 "ordinality": False, 2382 "alias": False, 2383 "offset": False, 2384 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2387class Update(Expression): 2388 arg_types = { 2389 "with": False, 2390 "this": False, 2391 "expressions": True, 2392 "from": False, 2393 "where": False, 2394 "returning": 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 Values(UDTF): 2399 arg_types = { 2400 "expressions": True, 2401 "ordinality": False, 2402 "alias": False, 2403 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2420class Select(Subqueryable): 2421 arg_types = { 2422 "with": False, 2423 "kind": False, 2424 "expressions": False, 2425 "hint": False, 2426 "distinct": False, 2427 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2428 "value": False, 2429 "into": False, 2430 "from": False, 2431 **QUERY_MODIFIERS, 2432 } 2433 2434 def from_( 2435 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2436 ) -> Select: 2437 """ 2438 Set the FROM expression. 2439 2440 Example: 2441 >>> Select().from_("tbl").select("x").sql() 2442 'SELECT x FROM tbl' 2443 2444 Args: 2445 expression : the SQL code strings to parse. 2446 If a `From` instance is passed, this is used as-is. 2447 If another `Expression` instance is passed, it will be wrapped in a `From`. 2448 dialect: the dialect used to parse the input expression. 2449 copy: if `False`, modify this expression instance in-place. 2450 opts: other options to use to parse the input expressions. 2451 2452 Returns: 2453 The modified Select expression. 2454 """ 2455 return _apply_builder( 2456 expression=expression, 2457 instance=self, 2458 arg="from", 2459 into=From, 2460 prefix="FROM", 2461 dialect=dialect, 2462 copy=copy, 2463 **opts, 2464 ) 2465 2466 def group_by( 2467 self, 2468 *expressions: t.Optional[ExpOrStr], 2469 append: bool = True, 2470 dialect: DialectType = None, 2471 copy: bool = True, 2472 **opts, 2473 ) -> Select: 2474 """ 2475 Set the GROUP BY expression. 2476 2477 Example: 2478 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2479 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2480 2481 Args: 2482 *expressions: the SQL code strings to parse. 2483 If a `Group` instance is passed, this is used as-is. 2484 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2485 If nothing is passed in then a group by is not applied to the expression 2486 append: if `True`, add to any existing expressions. 2487 Otherwise, this flattens all the `Group` expression into a single expression. 2488 dialect: the dialect used to parse the input expression. 2489 copy: if `False`, modify this expression instance in-place. 2490 opts: other options to use to parse the input expressions. 2491 2492 Returns: 2493 The modified Select expression. 2494 """ 2495 if not expressions: 2496 return self if not copy else self.copy() 2497 2498 return _apply_child_list_builder( 2499 *expressions, 2500 instance=self, 2501 arg="group", 2502 append=append, 2503 copy=copy, 2504 prefix="GROUP BY", 2505 into=Group, 2506 dialect=dialect, 2507 **opts, 2508 ) 2509 2510 def order_by( 2511 self, 2512 *expressions: t.Optional[ExpOrStr], 2513 append: bool = True, 2514 dialect: DialectType = None, 2515 copy: bool = True, 2516 **opts, 2517 ) -> Select: 2518 """ 2519 Set the ORDER BY expression. 2520 2521 Example: 2522 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2523 'SELECT x FROM tbl ORDER BY x DESC' 2524 2525 Args: 2526 *expressions: the SQL code strings to parse. 2527 If a `Group` instance is passed, this is used as-is. 2528 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2529 append: if `True`, add to any existing expressions. 2530 Otherwise, this flattens all the `Order` expression into a single expression. 2531 dialect: the dialect used to parse the input expression. 2532 copy: if `False`, modify this expression instance in-place. 2533 opts: other options to use to parse the input expressions. 2534 2535 Returns: 2536 The modified Select expression. 2537 """ 2538 return _apply_child_list_builder( 2539 *expressions, 2540 instance=self, 2541 arg="order", 2542 append=append, 2543 copy=copy, 2544 prefix="ORDER BY", 2545 into=Order, 2546 dialect=dialect, 2547 **opts, 2548 ) 2549 2550 def sort_by( 2551 self, 2552 *expressions: t.Optional[ExpOrStr], 2553 append: bool = True, 2554 dialect: DialectType = None, 2555 copy: bool = True, 2556 **opts, 2557 ) -> Select: 2558 """ 2559 Set the SORT BY expression. 2560 2561 Example: 2562 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2563 'SELECT x FROM tbl SORT BY x DESC' 2564 2565 Args: 2566 *expressions: the SQL code strings to parse. 2567 If a `Group` instance is passed, this is used as-is. 2568 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2569 append: if `True`, add to any existing expressions. 2570 Otherwise, this flattens all the `Order` expression into a single expression. 2571 dialect: the dialect used to parse the input expression. 2572 copy: if `False`, modify this expression instance in-place. 2573 opts: other options to use to parse the input expressions. 2574 2575 Returns: 2576 The modified Select expression. 2577 """ 2578 return _apply_child_list_builder( 2579 *expressions, 2580 instance=self, 2581 arg="sort", 2582 append=append, 2583 copy=copy, 2584 prefix="SORT BY", 2585 into=Sort, 2586 dialect=dialect, 2587 **opts, 2588 ) 2589 2590 def cluster_by( 2591 self, 2592 *expressions: t.Optional[ExpOrStr], 2593 append: bool = True, 2594 dialect: DialectType = None, 2595 copy: bool = True, 2596 **opts, 2597 ) -> Select: 2598 """ 2599 Set the CLUSTER BY expression. 2600 2601 Example: 2602 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2603 'SELECT x FROM tbl CLUSTER BY x DESC' 2604 2605 Args: 2606 *expressions: the SQL code strings to parse. 2607 If a `Group` instance is passed, this is used as-is. 2608 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2609 append: if `True`, add to any existing expressions. 2610 Otherwise, this flattens all the `Order` expression into a single expression. 2611 dialect: the dialect used to parse the input expression. 2612 copy: if `False`, modify this expression instance in-place. 2613 opts: other options to use to parse the input expressions. 2614 2615 Returns: 2616 The modified Select expression. 2617 """ 2618 return _apply_child_list_builder( 2619 *expressions, 2620 instance=self, 2621 arg="cluster", 2622 append=append, 2623 copy=copy, 2624 prefix="CLUSTER BY", 2625 into=Cluster, 2626 dialect=dialect, 2627 **opts, 2628 ) 2629 2630 def limit( 2631 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2632 ) -> Select: 2633 """ 2634 Set the LIMIT expression. 2635 2636 Example: 2637 >>> Select().from_("tbl").select("x").limit(10).sql() 2638 'SELECT x FROM tbl LIMIT 10' 2639 2640 Args: 2641 expression: the SQL code string to parse. 2642 This can also be an integer. 2643 If a `Limit` instance is passed, this is used as-is. 2644 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2645 dialect: the dialect used to parse the input expression. 2646 copy: if `False`, modify this expression instance in-place. 2647 opts: other options to use to parse the input expressions. 2648 2649 Returns: 2650 Select: the modified expression. 2651 """ 2652 return _apply_builder( 2653 expression=expression, 2654 instance=self, 2655 arg="limit", 2656 into=Limit, 2657 prefix="LIMIT", 2658 dialect=dialect, 2659 copy=copy, 2660 **opts, 2661 ) 2662 2663 def offset( 2664 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2665 ) -> Select: 2666 """ 2667 Set the OFFSET expression. 2668 2669 Example: 2670 >>> Select().from_("tbl").select("x").offset(10).sql() 2671 'SELECT x FROM tbl OFFSET 10' 2672 2673 Args: 2674 expression: the SQL code string to parse. 2675 This can also be an integer. 2676 If a `Offset` instance is passed, this is used as-is. 2677 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2678 dialect: the dialect used to parse the input expression. 2679 copy: if `False`, modify this expression instance in-place. 2680 opts: other options to use to parse the input expressions. 2681 2682 Returns: 2683 The modified Select expression. 2684 """ 2685 return _apply_builder( 2686 expression=expression, 2687 instance=self, 2688 arg="offset", 2689 into=Offset, 2690 prefix="OFFSET", 2691 dialect=dialect, 2692 copy=copy, 2693 **opts, 2694 ) 2695 2696 def select( 2697 self, 2698 *expressions: t.Optional[ExpOrStr], 2699 append: bool = True, 2700 dialect: DialectType = None, 2701 copy: bool = True, 2702 **opts, 2703 ) -> Select: 2704 """ 2705 Append to or set the SELECT expressions. 2706 2707 Example: 2708 >>> Select().select("x", "y").sql() 2709 'SELECT x, y' 2710 2711 Args: 2712 *expressions: the SQL code strings to parse. 2713 If an `Expression` instance is passed, it will be used as-is. 2714 append: if `True`, add to any existing expressions. 2715 Otherwise, this resets the expressions. 2716 dialect: the dialect used to parse the input expressions. 2717 copy: if `False`, modify this expression instance in-place. 2718 opts: other options to use to parse the input expressions. 2719 2720 Returns: 2721 The modified Select expression. 2722 """ 2723 return _apply_list_builder( 2724 *expressions, 2725 instance=self, 2726 arg="expressions", 2727 append=append, 2728 dialect=dialect, 2729 copy=copy, 2730 **opts, 2731 ) 2732 2733 def lateral( 2734 self, 2735 *expressions: t.Optional[ExpOrStr], 2736 append: bool = True, 2737 dialect: DialectType = None, 2738 copy: bool = True, 2739 **opts, 2740 ) -> Select: 2741 """ 2742 Append to or set the LATERAL expressions. 2743 2744 Example: 2745 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2746 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2747 2748 Args: 2749 *expressions: the SQL code strings to parse. 2750 If an `Expression` instance is passed, it will be used as-is. 2751 append: if `True`, add to any existing expressions. 2752 Otherwise, this resets the expressions. 2753 dialect: the dialect used to parse the input expressions. 2754 copy: if `False`, modify this expression instance in-place. 2755 opts: other options to use to parse the input expressions. 2756 2757 Returns: 2758 The modified Select expression. 2759 """ 2760 return _apply_list_builder( 2761 *expressions, 2762 instance=self, 2763 arg="laterals", 2764 append=append, 2765 into=Lateral, 2766 prefix="LATERAL VIEW", 2767 dialect=dialect, 2768 copy=copy, 2769 **opts, 2770 ) 2771 2772 def join( 2773 self, 2774 expression: ExpOrStr, 2775 on: t.Optional[ExpOrStr] = None, 2776 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2777 append: bool = True, 2778 join_type: t.Optional[str] = None, 2779 join_alias: t.Optional[Identifier | str] = None, 2780 dialect: DialectType = None, 2781 copy: bool = True, 2782 **opts, 2783 ) -> Select: 2784 """ 2785 Append to or set the JOIN expressions. 2786 2787 Example: 2788 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2789 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2790 2791 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2792 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2793 2794 Use `join_type` to change the type of join: 2795 2796 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2797 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2798 2799 Args: 2800 expression: the SQL code string to parse. 2801 If an `Expression` instance is passed, it will be used as-is. 2802 on: optionally specify the join "on" criteria as a SQL string. 2803 If an `Expression` instance is passed, it will be used as-is. 2804 using: optionally specify the join "using" criteria as a SQL string. 2805 If an `Expression` instance is passed, it will be used as-is. 2806 append: if `True`, add to any existing expressions. 2807 Otherwise, this resets the expressions. 2808 join_type: if set, alter the parsed join type. 2809 join_alias: an optional alias for the joined source. 2810 dialect: the dialect used to parse the input expressions. 2811 copy: if `False`, modify this expression instance in-place. 2812 opts: other options to use to parse the input expressions. 2813 2814 Returns: 2815 Select: the modified expression. 2816 """ 2817 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2818 2819 try: 2820 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2821 except ParseError: 2822 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2823 2824 join = expression if isinstance(expression, Join) else Join(this=expression) 2825 2826 if isinstance(join.this, Select): 2827 join.this.replace(join.this.subquery()) 2828 2829 if join_type: 2830 method: t.Optional[Token] 2831 side: t.Optional[Token] 2832 kind: t.Optional[Token] 2833 2834 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2835 2836 if method: 2837 join.set("method", method.text) 2838 if side: 2839 join.set("side", side.text) 2840 if kind: 2841 join.set("kind", kind.text) 2842 2843 if on: 2844 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2845 join.set("on", on) 2846 2847 if using: 2848 join = _apply_list_builder( 2849 *ensure_list(using), 2850 instance=join, 2851 arg="using", 2852 append=append, 2853 copy=copy, 2854 **opts, 2855 ) 2856 2857 if join_alias: 2858 join.set("this", alias_(join.this, join_alias, table=True)) 2859 2860 return _apply_list_builder( 2861 join, 2862 instance=self, 2863 arg="joins", 2864 append=append, 2865 copy=copy, 2866 **opts, 2867 ) 2868 2869 def where( 2870 self, 2871 *expressions: t.Optional[ExpOrStr], 2872 append: bool = True, 2873 dialect: DialectType = None, 2874 copy: bool = True, 2875 **opts, 2876 ) -> Select: 2877 """ 2878 Append to or set the WHERE expressions. 2879 2880 Example: 2881 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2882 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2883 2884 Args: 2885 *expressions: the SQL code strings to parse. 2886 If an `Expression` instance is passed, it will be used as-is. 2887 Multiple expressions are combined with an AND operator. 2888 append: if `True`, AND the new expressions to any existing expression. 2889 Otherwise, this resets the expression. 2890 dialect: the dialect used to parse the input expressions. 2891 copy: if `False`, modify this expression instance in-place. 2892 opts: other options to use to parse the input expressions. 2893 2894 Returns: 2895 Select: the modified expression. 2896 """ 2897 return _apply_conjunction_builder( 2898 *expressions, 2899 instance=self, 2900 arg="where", 2901 append=append, 2902 into=Where, 2903 dialect=dialect, 2904 copy=copy, 2905 **opts, 2906 ) 2907 2908 def having( 2909 self, 2910 *expressions: t.Optional[ExpOrStr], 2911 append: bool = True, 2912 dialect: DialectType = None, 2913 copy: bool = True, 2914 **opts, 2915 ) -> Select: 2916 """ 2917 Append to or set the HAVING expressions. 2918 2919 Example: 2920 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2921 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2922 2923 Args: 2924 *expressions: the SQL code strings to parse. 2925 If an `Expression` instance is passed, it will be used as-is. 2926 Multiple expressions are combined with an AND operator. 2927 append: if `True`, AND the new expressions to any existing expression. 2928 Otherwise, this resets the expression. 2929 dialect: the dialect used to parse the input expressions. 2930 copy: if `False`, modify this expression instance in-place. 2931 opts: other options to use to parse the input expressions. 2932 2933 Returns: 2934 The modified Select expression. 2935 """ 2936 return _apply_conjunction_builder( 2937 *expressions, 2938 instance=self, 2939 arg="having", 2940 append=append, 2941 into=Having, 2942 dialect=dialect, 2943 copy=copy, 2944 **opts, 2945 ) 2946 2947 def window( 2948 self, 2949 *expressions: t.Optional[ExpOrStr], 2950 append: bool = True, 2951 dialect: DialectType = None, 2952 copy: bool = True, 2953 **opts, 2954 ) -> Select: 2955 return _apply_list_builder( 2956 *expressions, 2957 instance=self, 2958 arg="windows", 2959 append=append, 2960 into=Window, 2961 dialect=dialect, 2962 copy=copy, 2963 **opts, 2964 ) 2965 2966 def qualify( 2967 self, 2968 *expressions: t.Optional[ExpOrStr], 2969 append: bool = True, 2970 dialect: DialectType = None, 2971 copy: bool = True, 2972 **opts, 2973 ) -> Select: 2974 return _apply_conjunction_builder( 2975 *expressions, 2976 instance=self, 2977 arg="qualify", 2978 append=append, 2979 into=Qualify, 2980 dialect=dialect, 2981 copy=copy, 2982 **opts, 2983 ) 2984 2985 def distinct( 2986 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2987 ) -> Select: 2988 """ 2989 Set the OFFSET expression. 2990 2991 Example: 2992 >>> Select().from_("tbl").select("x").distinct().sql() 2993 'SELECT DISTINCT x FROM tbl' 2994 2995 Args: 2996 ons: the expressions to distinct on 2997 distinct: whether the Select should be distinct 2998 copy: if `False`, modify this expression instance in-place. 2999 3000 Returns: 3001 Select: the modified expression. 3002 """ 3003 instance = _maybe_copy(self, copy) 3004 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3005 instance.set("distinct", Distinct(on=on) if distinct else None) 3006 return instance 3007 3008 def ctas( 3009 self, 3010 table: ExpOrStr, 3011 properties: t.Optional[t.Dict] = None, 3012 dialect: DialectType = None, 3013 copy: bool = True, 3014 **opts, 3015 ) -> Create: 3016 """ 3017 Convert this expression to a CREATE TABLE AS statement. 3018 3019 Example: 3020 >>> Select().select("*").from_("tbl").ctas("x").sql() 3021 'CREATE TABLE x AS SELECT * FROM tbl' 3022 3023 Args: 3024 table: the SQL code string to parse as the table name. 3025 If another `Expression` instance is passed, it will be used as-is. 3026 properties: an optional mapping of table properties 3027 dialect: the dialect used to parse the input table. 3028 copy: if `False`, modify this expression instance in-place. 3029 opts: other options to use to parse the input table. 3030 3031 Returns: 3032 The new Create expression. 3033 """ 3034 instance = _maybe_copy(self, copy) 3035 table_expression = maybe_parse( 3036 table, 3037 into=Table, 3038 dialect=dialect, 3039 **opts, 3040 ) 3041 properties_expression = None 3042 if properties: 3043 properties_expression = Properties.from_dict(properties) 3044 3045 return Create( 3046 this=table_expression, 3047 kind="table", 3048 expression=instance, 3049 properties=properties_expression, 3050 ) 3051 3052 def lock(self, update: bool = True, copy: bool = True) -> Select: 3053 """ 3054 Set the locking read mode for this expression. 3055 3056 Examples: 3057 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3058 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3059 3060 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3061 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3062 3063 Args: 3064 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3065 copy: if `False`, modify this expression instance in-place. 3066 3067 Returns: 3068 The modified expression. 3069 """ 3070 3071 inst = _maybe_copy(self, copy) 3072 inst.set("locks", [Lock(update=update)]) 3073 3074 return inst 3075 3076 @property 3077 def named_selects(self) -> t.List[str]: 3078 return [e.output_name for e in self.expressions if e.alias_or_name] 3079 3080 @property 3081 def is_star(self) -> bool: 3082 return any(expression.is_star for expression in self.expressions) 3083 3084 @property 3085 def selects(self) -> t.List[Expression]: 3086 return self.expressions
2434 def from_( 2435 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2436 ) -> Select: 2437 """ 2438 Set the FROM expression. 2439 2440 Example: 2441 >>> Select().from_("tbl").select("x").sql() 2442 'SELECT x FROM tbl' 2443 2444 Args: 2445 expression : the SQL code strings to parse. 2446 If a `From` instance is passed, this is used as-is. 2447 If another `Expression` instance is passed, it will be wrapped in a `From`. 2448 dialect: the dialect used to parse the input expression. 2449 copy: if `False`, modify this expression instance in-place. 2450 opts: other options to use to parse the input expressions. 2451 2452 Returns: 2453 The modified Select expression. 2454 """ 2455 return _apply_builder( 2456 expression=expression, 2457 instance=self, 2458 arg="from", 2459 into=From, 2460 prefix="FROM", 2461 dialect=dialect, 2462 copy=copy, 2463 **opts, 2464 )
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.
2466 def group_by( 2467 self, 2468 *expressions: t.Optional[ExpOrStr], 2469 append: bool = True, 2470 dialect: DialectType = None, 2471 copy: bool = True, 2472 **opts, 2473 ) -> Select: 2474 """ 2475 Set the GROUP BY expression. 2476 2477 Example: 2478 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2479 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2480 2481 Args: 2482 *expressions: the SQL code strings to parse. 2483 If a `Group` instance is passed, this is used as-is. 2484 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2485 If nothing is passed in then a group by is not applied to the expression 2486 append: if `True`, add to any existing expressions. 2487 Otherwise, this flattens all the `Group` expression into a single expression. 2488 dialect: the dialect used to parse the input expression. 2489 copy: if `False`, modify this expression instance in-place. 2490 opts: other options to use to parse the input expressions. 2491 2492 Returns: 2493 The modified Select expression. 2494 """ 2495 if not expressions: 2496 return self if not copy else self.copy() 2497 2498 return _apply_child_list_builder( 2499 *expressions, 2500 instance=self, 2501 arg="group", 2502 append=append, 2503 copy=copy, 2504 prefix="GROUP BY", 2505 into=Group, 2506 dialect=dialect, 2507 **opts, 2508 )
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.
2510 def order_by( 2511 self, 2512 *expressions: t.Optional[ExpOrStr], 2513 append: bool = True, 2514 dialect: DialectType = None, 2515 copy: bool = True, 2516 **opts, 2517 ) -> Select: 2518 """ 2519 Set the ORDER BY expression. 2520 2521 Example: 2522 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2523 'SELECT x FROM tbl ORDER BY x DESC' 2524 2525 Args: 2526 *expressions: the SQL code strings to parse. 2527 If a `Group` instance is passed, this is used as-is. 2528 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2529 append: if `True`, add to any existing expressions. 2530 Otherwise, this flattens all the `Order` expression into a single expression. 2531 dialect: the dialect used to parse the input expression. 2532 copy: if `False`, modify this expression instance in-place. 2533 opts: other options to use to parse the input expressions. 2534 2535 Returns: 2536 The modified Select expression. 2537 """ 2538 return _apply_child_list_builder( 2539 *expressions, 2540 instance=self, 2541 arg="order", 2542 append=append, 2543 copy=copy, 2544 prefix="ORDER BY", 2545 into=Order, 2546 dialect=dialect, 2547 **opts, 2548 )
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.
2550 def sort_by( 2551 self, 2552 *expressions: t.Optional[ExpOrStr], 2553 append: bool = True, 2554 dialect: DialectType = None, 2555 copy: bool = True, 2556 **opts, 2557 ) -> Select: 2558 """ 2559 Set the SORT BY expression. 2560 2561 Example: 2562 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2563 'SELECT x FROM tbl SORT BY x DESC' 2564 2565 Args: 2566 *expressions: the SQL code strings to parse. 2567 If a `Group` instance is passed, this is used as-is. 2568 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2569 append: if `True`, add to any existing expressions. 2570 Otherwise, this flattens all the `Order` expression into a single expression. 2571 dialect: the dialect used to parse the input expression. 2572 copy: if `False`, modify this expression instance in-place. 2573 opts: other options to use to parse the input expressions. 2574 2575 Returns: 2576 The modified Select expression. 2577 """ 2578 return _apply_child_list_builder( 2579 *expressions, 2580 instance=self, 2581 arg="sort", 2582 append=append, 2583 copy=copy, 2584 prefix="SORT BY", 2585 into=Sort, 2586 dialect=dialect, 2587 **opts, 2588 )
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.
2590 def cluster_by( 2591 self, 2592 *expressions: t.Optional[ExpOrStr], 2593 append: bool = True, 2594 dialect: DialectType = None, 2595 copy: bool = True, 2596 **opts, 2597 ) -> Select: 2598 """ 2599 Set the CLUSTER BY expression. 2600 2601 Example: 2602 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2603 'SELECT x FROM tbl CLUSTER BY x DESC' 2604 2605 Args: 2606 *expressions: the SQL code strings to parse. 2607 If a `Group` instance is passed, this is used as-is. 2608 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2609 append: if `True`, add to any existing expressions. 2610 Otherwise, this flattens all the `Order` expression into a single expression. 2611 dialect: the dialect used to parse the input expression. 2612 copy: if `False`, modify this expression instance in-place. 2613 opts: other options to use to parse the input expressions. 2614 2615 Returns: 2616 The modified Select expression. 2617 """ 2618 return _apply_child_list_builder( 2619 *expressions, 2620 instance=self, 2621 arg="cluster", 2622 append=append, 2623 copy=copy, 2624 prefix="CLUSTER BY", 2625 into=Cluster, 2626 dialect=dialect, 2627 **opts, 2628 )
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.
2630 def limit( 2631 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2632 ) -> Select: 2633 """ 2634 Set the LIMIT expression. 2635 2636 Example: 2637 >>> Select().from_("tbl").select("x").limit(10).sql() 2638 'SELECT x FROM tbl LIMIT 10' 2639 2640 Args: 2641 expression: the SQL code string to parse. 2642 This can also be an integer. 2643 If a `Limit` instance is passed, this is used as-is. 2644 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2645 dialect: the dialect used to parse the input expression. 2646 copy: if `False`, modify this expression instance in-place. 2647 opts: other options to use to parse the input expressions. 2648 2649 Returns: 2650 Select: the modified expression. 2651 """ 2652 return _apply_builder( 2653 expression=expression, 2654 instance=self, 2655 arg="limit", 2656 into=Limit, 2657 prefix="LIMIT", 2658 dialect=dialect, 2659 copy=copy, 2660 **opts, 2661 )
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.
2663 def offset( 2664 self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts 2665 ) -> Select: 2666 """ 2667 Set the OFFSET expression. 2668 2669 Example: 2670 >>> Select().from_("tbl").select("x").offset(10).sql() 2671 'SELECT x FROM tbl OFFSET 10' 2672 2673 Args: 2674 expression: the SQL code string to parse. 2675 This can also be an integer. 2676 If a `Offset` instance is passed, this is used as-is. 2677 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2678 dialect: the dialect used to parse the input expression. 2679 copy: if `False`, modify this expression instance in-place. 2680 opts: other options to use to parse the input expressions. 2681 2682 Returns: 2683 The modified Select expression. 2684 """ 2685 return _apply_builder( 2686 expression=expression, 2687 instance=self, 2688 arg="offset", 2689 into=Offset, 2690 prefix="OFFSET", 2691 dialect=dialect, 2692 copy=copy, 2693 **opts, 2694 )
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.
2696 def select( 2697 self, 2698 *expressions: t.Optional[ExpOrStr], 2699 append: bool = True, 2700 dialect: DialectType = None, 2701 copy: bool = True, 2702 **opts, 2703 ) -> Select: 2704 """ 2705 Append to or set the SELECT expressions. 2706 2707 Example: 2708 >>> Select().select("x", "y").sql() 2709 'SELECT x, y' 2710 2711 Args: 2712 *expressions: the SQL code strings to parse. 2713 If an `Expression` instance is passed, it will be used as-is. 2714 append: if `True`, add to any existing expressions. 2715 Otherwise, this resets the expressions. 2716 dialect: the dialect used to parse the input expressions. 2717 copy: if `False`, modify this expression instance in-place. 2718 opts: other options to use to parse the input expressions. 2719 2720 Returns: 2721 The modified Select expression. 2722 """ 2723 return _apply_list_builder( 2724 *expressions, 2725 instance=self, 2726 arg="expressions", 2727 append=append, 2728 dialect=dialect, 2729 copy=copy, 2730 **opts, 2731 )
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.
2733 def lateral( 2734 self, 2735 *expressions: t.Optional[ExpOrStr], 2736 append: bool = True, 2737 dialect: DialectType = None, 2738 copy: bool = True, 2739 **opts, 2740 ) -> Select: 2741 """ 2742 Append to or set the LATERAL expressions. 2743 2744 Example: 2745 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2746 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2747 2748 Args: 2749 *expressions: the SQL code strings to parse. 2750 If an `Expression` instance is passed, it will be used as-is. 2751 append: if `True`, add to any existing expressions. 2752 Otherwise, this resets the expressions. 2753 dialect: the dialect used to parse the input expressions. 2754 copy: if `False`, modify this expression instance in-place. 2755 opts: other options to use to parse the input expressions. 2756 2757 Returns: 2758 The modified Select expression. 2759 """ 2760 return _apply_list_builder( 2761 *expressions, 2762 instance=self, 2763 arg="laterals", 2764 append=append, 2765 into=Lateral, 2766 prefix="LATERAL VIEW", 2767 dialect=dialect, 2768 copy=copy, 2769 **opts, 2770 )
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.
2772 def join( 2773 self, 2774 expression: ExpOrStr, 2775 on: t.Optional[ExpOrStr] = None, 2776 using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None, 2777 append: bool = True, 2778 join_type: t.Optional[str] = None, 2779 join_alias: t.Optional[Identifier | str] = None, 2780 dialect: DialectType = None, 2781 copy: bool = True, 2782 **opts, 2783 ) -> Select: 2784 """ 2785 Append to or set the JOIN expressions. 2786 2787 Example: 2788 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2789 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2790 2791 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2792 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2793 2794 Use `join_type` to change the type of join: 2795 2796 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2797 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2798 2799 Args: 2800 expression: the SQL code string to parse. 2801 If an `Expression` instance is passed, it will be used as-is. 2802 on: optionally specify the join "on" criteria as a SQL string. 2803 If an `Expression` instance is passed, it will be used as-is. 2804 using: optionally specify the join "using" criteria as a SQL string. 2805 If an `Expression` instance is passed, it will be used as-is. 2806 append: if `True`, add to any existing expressions. 2807 Otherwise, this resets the expressions. 2808 join_type: if set, alter the parsed join type. 2809 join_alias: an optional alias for the joined source. 2810 dialect: the dialect used to parse the input expressions. 2811 copy: if `False`, modify this expression instance in-place. 2812 opts: other options to use to parse the input expressions. 2813 2814 Returns: 2815 Select: the modified expression. 2816 """ 2817 parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts} 2818 2819 try: 2820 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2821 except ParseError: 2822 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2823 2824 join = expression if isinstance(expression, Join) else Join(this=expression) 2825 2826 if isinstance(join.this, Select): 2827 join.this.replace(join.this.subquery()) 2828 2829 if join_type: 2830 method: t.Optional[Token] 2831 side: t.Optional[Token] 2832 kind: t.Optional[Token] 2833 2834 method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2835 2836 if method: 2837 join.set("method", method.text) 2838 if side: 2839 join.set("side", side.text) 2840 if kind: 2841 join.set("kind", kind.text) 2842 2843 if on: 2844 on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts) 2845 join.set("on", on) 2846 2847 if using: 2848 join = _apply_list_builder( 2849 *ensure_list(using), 2850 instance=join, 2851 arg="using", 2852 append=append, 2853 copy=copy, 2854 **opts, 2855 ) 2856 2857 if join_alias: 2858 join.set("this", alias_(join.this, join_alias, table=True)) 2859 2860 return _apply_list_builder( 2861 join, 2862 instance=self, 2863 arg="joins", 2864 append=append, 2865 copy=copy, 2866 **opts, 2867 )
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.
2869 def where( 2870 self, 2871 *expressions: t.Optional[ExpOrStr], 2872 append: bool = True, 2873 dialect: DialectType = None, 2874 copy: bool = True, 2875 **opts, 2876 ) -> Select: 2877 """ 2878 Append to or set the WHERE expressions. 2879 2880 Example: 2881 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2882 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2883 2884 Args: 2885 *expressions: the SQL code strings to parse. 2886 If an `Expression` instance is passed, it will be used as-is. 2887 Multiple expressions are combined with an AND operator. 2888 append: if `True`, AND the new expressions to any existing expression. 2889 Otherwise, this resets the expression. 2890 dialect: the dialect used to parse the input expressions. 2891 copy: if `False`, modify this expression instance in-place. 2892 opts: other options to use to parse the input expressions. 2893 2894 Returns: 2895 Select: the modified expression. 2896 """ 2897 return _apply_conjunction_builder( 2898 *expressions, 2899 instance=self, 2900 arg="where", 2901 append=append, 2902 into=Where, 2903 dialect=dialect, 2904 copy=copy, 2905 **opts, 2906 )
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.
2908 def having( 2909 self, 2910 *expressions: t.Optional[ExpOrStr], 2911 append: bool = True, 2912 dialect: DialectType = None, 2913 copy: bool = True, 2914 **opts, 2915 ) -> Select: 2916 """ 2917 Append to or set the HAVING expressions. 2918 2919 Example: 2920 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2921 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2922 2923 Args: 2924 *expressions: the SQL code strings to parse. 2925 If an `Expression` instance is passed, it will be used as-is. 2926 Multiple expressions are combined with an AND operator. 2927 append: if `True`, AND the new expressions to any existing expression. 2928 Otherwise, this resets the expression. 2929 dialect: the dialect used to parse the input expressions. 2930 copy: if `False`, modify this expression instance in-place. 2931 opts: other options to use to parse the input expressions. 2932 2933 Returns: 2934 The modified Select expression. 2935 """ 2936 return _apply_conjunction_builder( 2937 *expressions, 2938 instance=self, 2939 arg="having", 2940 append=append, 2941 into=Having, 2942 dialect=dialect, 2943 copy=copy, 2944 **opts, 2945 )
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.
2947 def window( 2948 self, 2949 *expressions: t.Optional[ExpOrStr], 2950 append: bool = True, 2951 dialect: DialectType = None, 2952 copy: bool = True, 2953 **opts, 2954 ) -> Select: 2955 return _apply_list_builder( 2956 *expressions, 2957 instance=self, 2958 arg="windows", 2959 append=append, 2960 into=Window, 2961 dialect=dialect, 2962 copy=copy, 2963 **opts, 2964 )
2966 def qualify( 2967 self, 2968 *expressions: t.Optional[ExpOrStr], 2969 append: bool = True, 2970 dialect: DialectType = None, 2971 copy: bool = True, 2972 **opts, 2973 ) -> Select: 2974 return _apply_conjunction_builder( 2975 *expressions, 2976 instance=self, 2977 arg="qualify", 2978 append=append, 2979 into=Qualify, 2980 dialect=dialect, 2981 copy=copy, 2982 **opts, 2983 )
2985 def distinct( 2986 self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True 2987 ) -> Select: 2988 """ 2989 Set the OFFSET expression. 2990 2991 Example: 2992 >>> Select().from_("tbl").select("x").distinct().sql() 2993 'SELECT DISTINCT x FROM tbl' 2994 2995 Args: 2996 ons: the expressions to distinct on 2997 distinct: whether the Select should be distinct 2998 copy: if `False`, modify this expression instance in-place. 2999 3000 Returns: 3001 Select: the modified expression. 3002 """ 3003 instance = _maybe_copy(self, copy) 3004 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None 3005 instance.set("distinct", Distinct(on=on) if distinct else None) 3006 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.
3008 def ctas( 3009 self, 3010 table: ExpOrStr, 3011 properties: t.Optional[t.Dict] = None, 3012 dialect: DialectType = None, 3013 copy: bool = True, 3014 **opts, 3015 ) -> Create: 3016 """ 3017 Convert this expression to a CREATE TABLE AS statement. 3018 3019 Example: 3020 >>> Select().select("*").from_("tbl").ctas("x").sql() 3021 'CREATE TABLE x AS SELECT * FROM tbl' 3022 3023 Args: 3024 table: the SQL code string to parse as the table name. 3025 If another `Expression` instance is passed, it will be used as-is. 3026 properties: an optional mapping of table properties 3027 dialect: the dialect used to parse the input table. 3028 copy: if `False`, modify this expression instance in-place. 3029 opts: other options to use to parse the input table. 3030 3031 Returns: 3032 The new Create expression. 3033 """ 3034 instance = _maybe_copy(self, copy) 3035 table_expression = maybe_parse( 3036 table, 3037 into=Table, 3038 dialect=dialect, 3039 **opts, 3040 ) 3041 properties_expression = None 3042 if properties: 3043 properties_expression = Properties.from_dict(properties) 3044 3045 return Create( 3046 this=table_expression, 3047 kind="table", 3048 expression=instance, 3049 properties=properties_expression, 3050 )
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.
3052 def lock(self, update: bool = True, copy: bool = True) -> Select: 3053 """ 3054 Set the locking read mode for this expression. 3055 3056 Examples: 3057 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 3058 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 3059 3060 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 3061 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 3062 3063 Args: 3064 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 3065 copy: if `False`, modify this expression instance in-place. 3066 3067 Returns: 3068 The modified expression. 3069 """ 3070 3071 inst = _maybe_copy(self, copy) 3072 inst.set("locks", [Lock(update=update)]) 3073 3074 return inst
Set the locking read mode for this expression.
Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
- update: if
True
, the locking type will beFOR UPDATE
, else it will beFOR SHARE
. - copy: if
False
, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3089class Subquery(DerivedTable, Unionable): 3090 arg_types = { 3091 "this": True, 3092 "alias": False, 3093 "with": False, 3094 **QUERY_MODIFIERS, 3095 } 3096 3097 def unnest(self): 3098 """ 3099 Returns the first non subquery. 3100 """ 3101 expression = self 3102 while isinstance(expression, Subquery): 3103 expression = expression.this 3104 return expression 3105 3106 @property 3107 def is_star(self) -> bool: 3108 return self.this.is_star 3109 3110 @property 3111 def output_name(self) -> str: 3112 return self.alias
3097 def unnest(self): 3098 """ 3099 Returns the first non subquery. 3100 """ 3101 expression = self 3102 while isinstance(expression, Subquery): 3103 expression = expression.this 3104 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
3115class TableSample(Expression): 3116 arg_types = { 3117 "this": False, 3118 "method": False, 3119 "bucket_numerator": False, 3120 "bucket_denominator": False, 3121 "bucket_field": False, 3122 "percent": False, 3123 "rows": False, 3124 "size": False, 3125 "seed": False, 3126 "kind": False, 3127 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3130class Tag(Expression): 3131 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 3132 3133 arg_types = { 3134 "this": False, 3135 "prefix": False, 3136 "postfix": False, 3137 }
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
3142class Pivot(Expression): 3143 arg_types = { 3144 "this": False, 3145 "alias": False, 3146 "expressions": True, 3147 "field": False, 3148 "unpivot": False, 3149 "using": False, 3150 "group": False, 3151 "columns": False, 3152 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3155class Window(Expression): 3156 arg_types = { 3157 "this": True, 3158 "partition_by": False, 3159 "order": False, 3160 "spec": False, 3161 "alias": False, 3162 "over": False, 3163 "first": False, 3164 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3167class WindowSpec(Expression): 3168 arg_types = { 3169 "kind": False, 3170 "start": False, 3171 "start_side": False, 3172 "end": False, 3173 "end_side": False, 3174 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3181class Star(Expression): 3182 arg_types = {"except": False, "replace": False} 3183 3184 @property 3185 def name(self) -> str: 3186 return "*" 3187 3188 @property 3189 def output_name(self) -> str: 3190 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
3205class Null(Condition): 3206 arg_types: t.Dict[str, t.Any] = {} 3207 3208 @property 3209 def name(self) -> str: 3210 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
3221class DataType(Expression): 3222 arg_types = { 3223 "this": True, 3224 "expressions": False, 3225 "nested": False, 3226 "values": False, 3227 "prefix": False, 3228 } 3229 3230 class Type(AutoName): 3231 ARRAY = auto() 3232 BIGDECIMAL = auto() 3233 BIGINT = auto() 3234 BIGSERIAL = auto() 3235 BINARY = auto() 3236 BIT = auto() 3237 BOOLEAN = auto() 3238 CHAR = auto() 3239 DATE = auto() 3240 DATETIME = auto() 3241 DATETIME64 = auto() 3242 INT4RANGE = auto() 3243 INT4MULTIRANGE = auto() 3244 INT8RANGE = auto() 3245 INT8MULTIRANGE = auto() 3246 NUMRANGE = auto() 3247 NUMMULTIRANGE = auto() 3248 TSRANGE = auto() 3249 TSMULTIRANGE = auto() 3250 TSTZRANGE = auto() 3251 TSTZMULTIRANGE = auto() 3252 DATERANGE = auto() 3253 DATEMULTIRANGE = auto() 3254 DECIMAL = auto() 3255 DOUBLE = auto() 3256 FLOAT = auto() 3257 GEOGRAPHY = auto() 3258 GEOMETRY = auto() 3259 HLLSKETCH = auto() 3260 HSTORE = auto() 3261 IMAGE = auto() 3262 INET = auto() 3263 INT = auto() 3264 INT128 = auto() 3265 INT256 = auto() 3266 INTERVAL = auto() 3267 JSON = auto() 3268 JSONB = auto() 3269 LONGBLOB = auto() 3270 LONGTEXT = auto() 3271 MAP = auto() 3272 MEDIUMBLOB = auto() 3273 MEDIUMTEXT = auto() 3274 MONEY = auto() 3275 NCHAR = auto() 3276 NULL = auto() 3277 NULLABLE = auto() 3278 NVARCHAR = auto() 3279 OBJECT = auto() 3280 ROWVERSION = auto() 3281 SERIAL = auto() 3282 SMALLINT = auto() 3283 SMALLMONEY = auto() 3284 SMALLSERIAL = auto() 3285 STRUCT = auto() 3286 SUPER = auto() 3287 TEXT = auto() 3288 TIME = auto() 3289 TIMESTAMP = auto() 3290 TIMESTAMPTZ = auto() 3291 TIMESTAMPLTZ = auto() 3292 TINYINT = auto() 3293 UBIGINT = auto() 3294 UINT = auto() 3295 USMALLINT = auto() 3296 UTINYINT = auto() 3297 UNKNOWN = auto() # Sentinel value, useful for type annotation 3298 UINT128 = auto() 3299 UINT256 = auto() 3300 UNIQUEIDENTIFIER = auto() 3301 UUID = auto() 3302 VARBINARY = auto() 3303 VARCHAR = auto() 3304 VARIANT = auto() 3305 XML = auto() 3306 3307 TEXT_TYPES = { 3308 Type.CHAR, 3309 Type.NCHAR, 3310 Type.VARCHAR, 3311 Type.NVARCHAR, 3312 Type.TEXT, 3313 } 3314 3315 INTEGER_TYPES = { 3316 Type.INT, 3317 Type.TINYINT, 3318 Type.SMALLINT, 3319 Type.BIGINT, 3320 Type.INT128, 3321 Type.INT256, 3322 } 3323 3324 FLOAT_TYPES = { 3325 Type.FLOAT, 3326 Type.DOUBLE, 3327 } 3328 3329 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3330 3331 TEMPORAL_TYPES = { 3332 Type.TIMESTAMP, 3333 Type.TIMESTAMPTZ, 3334 Type.TIMESTAMPLTZ, 3335 Type.DATE, 3336 Type.DATETIME, 3337 Type.DATETIME64, 3338 } 3339 3340 @classmethod 3341 def build( 3342 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3343 ) -> DataType: 3344 from sqlglot import parse_one 3345 3346 if isinstance(dtype, str): 3347 if dtype.upper() in cls.Type.__members__: 3348 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3349 else: 3350 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3351 3352 if data_type_exp is None: 3353 raise ValueError(f"Unparsable data type value: {dtype}") 3354 elif isinstance(dtype, DataType.Type): 3355 data_type_exp = DataType(this=dtype) 3356 elif isinstance(dtype, DataType): 3357 return dtype 3358 else: 3359 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3360 3361 return DataType(**{**data_type_exp.args, **kwargs}) 3362 3363 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3364 return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3340 @classmethod 3341 def build( 3342 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3343 ) -> DataType: 3344 from sqlglot import parse_one 3345 3346 if isinstance(dtype, str): 3347 if dtype.upper() in cls.Type.__members__: 3348 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3349 else: 3350 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3351 3352 if data_type_exp is None: 3353 raise ValueError(f"Unparsable data type value: {dtype}") 3354 elif isinstance(dtype, DataType.Type): 3355 data_type_exp = DataType(this=dtype) 3356 elif isinstance(dtype, DataType): 3357 return dtype 3358 else: 3359 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3360 3361 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
3230 class Type(AutoName): 3231 ARRAY = auto() 3232 BIGDECIMAL = auto() 3233 BIGINT = auto() 3234 BIGSERIAL = auto() 3235 BINARY = auto() 3236 BIT = auto() 3237 BOOLEAN = auto() 3238 CHAR = auto() 3239 DATE = auto() 3240 DATETIME = auto() 3241 DATETIME64 = auto() 3242 INT4RANGE = auto() 3243 INT4MULTIRANGE = auto() 3244 INT8RANGE = auto() 3245 INT8MULTIRANGE = auto() 3246 NUMRANGE = auto() 3247 NUMMULTIRANGE = auto() 3248 TSRANGE = auto() 3249 TSMULTIRANGE = auto() 3250 TSTZRANGE = auto() 3251 TSTZMULTIRANGE = auto() 3252 DATERANGE = auto() 3253 DATEMULTIRANGE = auto() 3254 DECIMAL = auto() 3255 DOUBLE = auto() 3256 FLOAT = auto() 3257 GEOGRAPHY = auto() 3258 GEOMETRY = auto() 3259 HLLSKETCH = auto() 3260 HSTORE = auto() 3261 IMAGE = auto() 3262 INET = auto() 3263 INT = auto() 3264 INT128 = auto() 3265 INT256 = auto() 3266 INTERVAL = auto() 3267 JSON = auto() 3268 JSONB = auto() 3269 LONGBLOB = auto() 3270 LONGTEXT = auto() 3271 MAP = auto() 3272 MEDIUMBLOB = auto() 3273 MEDIUMTEXT = auto() 3274 MONEY = auto() 3275 NCHAR = auto() 3276 NULL = auto() 3277 NULLABLE = auto() 3278 NVARCHAR = auto() 3279 OBJECT = auto() 3280 ROWVERSION = auto() 3281 SERIAL = auto() 3282 SMALLINT = auto() 3283 SMALLMONEY = auto() 3284 SMALLSERIAL = auto() 3285 STRUCT = auto() 3286 SUPER = auto() 3287 TEXT = auto() 3288 TIME = auto() 3289 TIMESTAMP = auto() 3290 TIMESTAMPTZ = auto() 3291 TIMESTAMPLTZ = auto() 3292 TINYINT = auto() 3293 UBIGINT = auto() 3294 UINT = auto() 3295 USMALLINT = auto() 3296 UTINYINT = auto() 3297 UNKNOWN = auto() # Sentinel value, useful for type annotation 3298 UINT128 = auto() 3299 UINT256 = auto() 3300 UNIQUEIDENTIFIER = auto() 3301 UUID = auto() 3302 VARBINARY = auto() 3303 VARCHAR = auto() 3304 VARIANT = auto() 3305 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
3411class AddConstraint(Expression): 3412 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
3420class Binary(Condition): 3421 arg_types = {"this": True, "expression": True} 3422 3423 @property 3424 def left(self): 3425 return self.this 3426 3427 @property 3428 def right(self): 3429 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
3476class Dot(Binary): 3477 @property 3478 def name(self) -> str: 3479 return self.expression.name 3480 3481 @classmethod 3482 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3483 """Build a Dot object with a sequence of expressions.""" 3484 if len(expressions) < 2: 3485 raise ValueError(f"Dot requires >= 2 expressions.") 3486 3487 a, b, *expressions = expressions 3488 dot = Dot(this=a, expression=b) 3489 3490 for expression in expressions: 3491 dot = Dot(this=dot, expression=expression) 3492 3493 return dot
3481 @classmethod 3482 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3483 """Build a Dot object with a sequence of expressions.""" 3484 if len(expressions) < 2: 3485 raise ValueError(f"Dot requires >= 2 expressions.") 3486 3487 a, b, *expressions = expressions 3488 dot = Dot(this=a, expression=b) 3489 3490 for expression in expressions: 3491 dot = Dot(this=dot, expression=expression) 3492 3493 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3618class Alias(Expression): 3619 arg_types = {"this": True, "alias": False} 3620 3621 @property 3622 def output_name(self) -> str: 3623 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
3626class Aliases(Expression): 3627 arg_types = {"this": True, "expressions": True} 3628 3629 @property 3630 def aliases(self): 3631 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
3650class In(Predicate): 3651 arg_types = { 3652 "this": True, 3653 "expressions": False, 3654 "query": False, 3655 "unnest": False, 3656 "field": False, 3657 "is_global": False, 3658 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3661class TimeUnit(Expression): 3662 """Automatically converts unit arg into a var.""" 3663 3664 arg_types = {"unit": False} 3665 3666 def __init__(self, **args): 3667 unit = args.get("unit") 3668 if isinstance(unit, (Column, Literal)): 3669 args["unit"] = Var(this=unit.name) 3670 elif isinstance(unit, Week): 3671 unit.set("this", Var(this=unit.this.name)) 3672 3673 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
3676class Interval(TimeUnit): 3677 arg_types = {"this": False, "unit": False} 3678 3679 @property 3680 def unit(self) -> t.Optional[Var]: 3681 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
3693class Func(Condition): 3694 """ 3695 The base class for all function expressions. 3696 3697 Attributes: 3698 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3699 treated as a variable length argument and the argument's value will be stored as a list. 3700 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3701 for this function expression. These values are used to map this node to a name during parsing 3702 as well as to provide the function's name during SQL string generation. By default the SQL 3703 name is set to the expression's class name transformed to snake case. 3704 """ 3705 3706 is_var_len_args = False 3707 3708 @classmethod 3709 def from_arg_list(cls, args): 3710 if cls.is_var_len_args: 3711 all_arg_keys = list(cls.arg_types) 3712 # If this function supports variable length argument treat the last argument as such. 3713 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3714 num_non_var = len(non_var_len_arg_keys) 3715 3716 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3717 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3718 else: 3719 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3720 3721 return cls(**args_dict) 3722 3723 @classmethod 3724 def sql_names(cls): 3725 if cls is Func: 3726 raise NotImplementedError( 3727 "SQL name is only supported by concrete function implementations" 3728 ) 3729 if "_sql_names" not in cls.__dict__: 3730 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3731 return cls._sql_names 3732 3733 @classmethod 3734 def sql_name(cls): 3735 return cls.sql_names()[0] 3736 3737 @classmethod 3738 def default_parser_mappings(cls): 3739 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.
3708 @classmethod 3709 def from_arg_list(cls, args): 3710 if cls.is_var_len_args: 3711 all_arg_keys = list(cls.arg_types) 3712 # If this function supports variable length argument treat the last argument as such. 3713 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3714 num_non_var = len(non_var_len_arg_keys) 3715 3716 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3717 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3718 else: 3719 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3720 3721 return cls(**args_dict)
3723 @classmethod 3724 def sql_names(cls): 3725 if cls is Func: 3726 raise NotImplementedError( 3727 "SQL name is only supported by concrete function implementations" 3728 ) 3729 if "_sql_names" not in cls.__dict__: 3730 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3731 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
3746class ParameterizedAgg(AggFunc): 3747 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
3754class Anonymous(Func): 3755 arg_types = {"this": True, "expressions": False} 3756 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
3761class Hll(AggFunc): 3762 arg_types = {"this": True, "expressions": False} 3763 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
3766class ApproxDistinct(AggFunc): 3767 arg_types = {"this": True, "accuracy": False} 3768 _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
3797class ArrayConcat(Func): 3798 arg_types = {"this": True, "expressions": False} 3799 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
3810class ArrayFilter(Func): 3811 arg_types = {"this": True, "expression": True} 3812 _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
3843class Case(Func): 3844 arg_types = {"this": False, "ifs": True, "default": False} 3845 3846 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3847 instance = _maybe_copy(self, copy) 3848 instance.append( 3849 "ifs", 3850 If( 3851 this=maybe_parse(condition, copy=copy, **opts), 3852 true=maybe_parse(then, copy=copy, **opts), 3853 ), 3854 ) 3855 return instance 3856 3857 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3858 instance = _maybe_copy(self, copy) 3859 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3860 return instance
3846 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3847 instance = _maybe_copy(self, copy) 3848 instance.append( 3849 "ifs", 3850 If( 3851 this=maybe_parse(condition, copy=copy, **opts), 3852 true=maybe_parse(then, copy=copy, **opts), 3853 ), 3854 ) 3855 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
3863class Cast(Func): 3864 arg_types = {"this": True, "to": True} 3865 3866 @property 3867 def name(self) -> str: 3868 return self.this.name 3869 3870 @property 3871 def to(self) -> DataType: 3872 return self.args["to"] 3873 3874 @property 3875 def output_name(self) -> str: 3876 return self.name 3877 3878 def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool: 3879 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
3894class Ceil(Func): 3895 arg_types = {"this": True, "decimals": False} 3896 _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
3899class Coalesce(Func): 3900 arg_types = {"this": True, "expressions": False} 3901 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3941class DateAdd(Func, TimeUnit): 3942 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
3945class DateSub(Func, TimeUnit): 3946 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
3949class DateDiff(Func, TimeUnit): 3950 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3951 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
3958class DatetimeAdd(Func, TimeUnit): 3959 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
3962class DatetimeSub(Func, TimeUnit): 3963 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
3966class DatetimeDiff(Func, TimeUnit): 3967 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
3970class DatetimeTrunc(Func, TimeUnit): 3971 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
3998class TimestampAdd(Func, TimeUnit): 3999 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
4002class TimestampSub(Func, TimeUnit): 4003 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
4006class TimestampDiff(Func, TimeUnit): 4007 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
4010class TimestampTrunc(Func, TimeUnit): 4011 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
4014class TimeAdd(Func, TimeUnit): 4015 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
4018class TimeSub(Func, TimeUnit): 4019 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
4022class TimeDiff(Func, TimeUnit): 4023 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
4030class DateFromParts(Func): 4031 _sql_names = ["DATEFROMPARTS"] 4032 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
4083class Greatest(Func): 4084 arg_types = {"this": True, "expressions": False} 4085 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
4100class IfNull(Func): 4101 arg_types = {"this": True, "expression": False} 4102 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4113class JSONObject(Func): 4114 arg_types = { 4115 "expressions": False, 4116 "null_handling": False, 4117 "unique_keys": False, 4118 "return_type": False, 4119 "format_json": False, 4120 "encoding": False, 4121 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4124class OpenJSONColumnDef(Expression): 4125 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
4152class JSONFormat(Func): 4153 arg_types = {"this": False, "options": False} 4154 _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
4174class Levenshtein(Func): 4175 arg_types = { 4176 "this": True, 4177 "expression": False, 4178 "ins_cost": False, 4179 "del_cost": False, 4180 "sub_cost": False, 4181 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4220class VarMap(Func): 4221 arg_types = {"keys": True, "values": True} 4222 is_var_len_args = True 4223 4224 @property 4225 def keys(self) -> t.List[Expression]: 4226 return self.args["keys"].expressions 4227 4228 @property 4229 def values(self) -> t.List[Expression]: 4230 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
4234class MatchAgainst(Func): 4235 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
4238class Max(AggFunc): 4239 arg_types = {"this": True, "expressions": False} 4240 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
4247class Min(AggFunc): 4248 arg_types = {"this": True, "expressions": False} 4249 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
4280class ApproxQuantile(Quantile): 4281 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
4288class ReadCSV(Func): 4289 _sql_names = ["READ_CSV"] 4290 is_var_len_args = True 4291 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
4294class Reduce(Func): 4295 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
4298class RegexpExtract(Func): 4299 arg_types = { 4300 "this": True, 4301 "expression": True, 4302 "position": False, 4303 "occurrence": False, 4304 "group": False, 4305 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4369class StrPosition(Func): 4370 arg_types = { 4371 "this": True, 4372 "substr": True, 4373 "position": False, 4374 "instance": False, 4375 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4449class Trim(Func): 4450 arg_types = { 4451 "this": True, 4452 "expression": False, 4453 "position": False, 4454 "collation": False, 4455 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4458class TsOrDsAdd(Func, TimeUnit): 4459 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
4484class UnixToTime(Func): 4485 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4486 4487 SECONDS = Literal.string("seconds") 4488 MILLIS = Literal.string("millis") 4489 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
4512class XMLTable(Func): 4513 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
4524class Merge(Expression): 4525 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
4528class When(Func): 4529 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
4572def maybe_parse( 4573 sql_or_expression: ExpOrStr, 4574 *, 4575 into: t.Optional[IntoType] = None, 4576 dialect: DialectType = None, 4577 prefix: t.Optional[str] = None, 4578 copy: bool = False, 4579 **opts, 4580) -> Expression: 4581 """Gracefully handle a possible string or expression. 4582 4583 Example: 4584 >>> maybe_parse("1") 4585 (LITERAL this: 1, is_string: False) 4586 >>> maybe_parse(to_identifier("x")) 4587 (IDENTIFIER this: x, quoted: False) 4588 4589 Args: 4590 sql_or_expression: the SQL code string or an expression 4591 into: the SQLGlot Expression to parse into 4592 dialect: the dialect used to parse the input expressions (in the case that an 4593 input expression is a SQL string). 4594 prefix: a string to prefix the sql with before it gets parsed 4595 (automatically includes a space) 4596 copy: whether or not to copy the expression. 4597 **opts: other options to use to parse the input expressions (again, in the case 4598 that an input expression is a SQL string). 4599 4600 Returns: 4601 Expression: the parsed or given expression. 4602 """ 4603 if isinstance(sql_or_expression, Expression): 4604 if copy: 4605 return sql_or_expression.copy() 4606 return sql_or_expression 4607 4608 if sql_or_expression is None: 4609 raise ParseError(f"SQL cannot be None") 4610 4611 import sqlglot 4612 4613 sql = str(sql_or_expression) 4614 if prefix: 4615 sql = f"{prefix} {sql}" 4616 4617 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.
4801def union( 4802 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4803) -> Union: 4804 """ 4805 Initializes a syntax tree from one UNION expression. 4806 4807 Example: 4808 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4809 'SELECT * FROM foo UNION SELECT * FROM bla' 4810 4811 Args: 4812 left: the SQL code string corresponding to the left-hand side. 4813 If an `Expression` instance is passed, it will be used as-is. 4814 right: the SQL code string corresponding to the right-hand side. 4815 If an `Expression` instance is passed, it will be used as-is. 4816 distinct: set the DISTINCT flag if and only if this is true. 4817 dialect: the dialect used to parse the input expression. 4818 opts: other options to use to parse the input expressions. 4819 4820 Returns: 4821 The new Union instance. 4822 """ 4823 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4824 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4825 4826 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.
4829def intersect( 4830 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4831) -> Intersect: 4832 """ 4833 Initializes a syntax tree from one INTERSECT expression. 4834 4835 Example: 4836 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4837 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4838 4839 Args: 4840 left: the SQL code string corresponding to the left-hand side. 4841 If an `Expression` instance is passed, it will be used as-is. 4842 right: the SQL code string corresponding to the right-hand side. 4843 If an `Expression` instance is passed, it will be used as-is. 4844 distinct: set the DISTINCT flag if and only if this is true. 4845 dialect: the dialect used to parse the input expression. 4846 opts: other options to use to parse the input expressions. 4847 4848 Returns: 4849 The new Intersect instance. 4850 """ 4851 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4852 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4853 4854 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.
4857def except_( 4858 left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts 4859) -> Except: 4860 """ 4861 Initializes a syntax tree from one EXCEPT expression. 4862 4863 Example: 4864 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4865 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4866 4867 Args: 4868 left: the SQL code string corresponding to the left-hand side. 4869 If an `Expression` instance is passed, it will be used as-is. 4870 right: the SQL code string corresponding to the right-hand side. 4871 If an `Expression` instance is passed, it will be used as-is. 4872 distinct: set the DISTINCT flag if and only if this is true. 4873 dialect: the dialect used to parse the input expression. 4874 opts: other options to use to parse the input expressions. 4875 4876 Returns: 4877 The new Except instance. 4878 """ 4879 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4880 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4881 4882 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.
4885def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4886 """ 4887 Initializes a syntax tree from one or multiple SELECT expressions. 4888 4889 Example: 4890 >>> select("col1", "col2").from_("tbl").sql() 4891 'SELECT col1, col2 FROM tbl' 4892 4893 Args: 4894 *expressions: the SQL code string to parse as the expressions of a 4895 SELECT statement. If an Expression instance is passed, this is used as-is. 4896 dialect: the dialect used to parse the input expressions (in the case that an 4897 input expression is a SQL string). 4898 **opts: other options to use to parse the input expressions (again, in the case 4899 that an input expression is a SQL string). 4900 4901 Returns: 4902 Select: the syntax tree for the SELECT statement. 4903 """ 4904 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.
4907def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4908 """ 4909 Initializes a syntax tree from a FROM expression. 4910 4911 Example: 4912 >>> from_("tbl").select("col1", "col2").sql() 4913 'SELECT col1, col2 FROM tbl' 4914 4915 Args: 4916 *expression: the SQL code string to parse as the FROM expressions of a 4917 SELECT statement. If an Expression instance is passed, this is used as-is. 4918 dialect: the dialect used to parse the input expression (in the case that the 4919 input expression is a SQL string). 4920 **opts: other options to use to parse the input expressions (again, in the case 4921 that the input expression is a SQL string). 4922 4923 Returns: 4924 Select: the syntax tree for the SELECT statement. 4925 """ 4926 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.
4929def update( 4930 table: str | Table, 4931 properties: dict, 4932 where: t.Optional[ExpOrStr] = None, 4933 from_: t.Optional[ExpOrStr] = None, 4934 dialect: DialectType = None, 4935 **opts, 4936) -> Update: 4937 """ 4938 Creates an update statement. 4939 4940 Example: 4941 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4942 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4943 4944 Args: 4945 *properties: dictionary of properties to set which are 4946 auto converted to sql objects eg None -> NULL 4947 where: sql conditional parsed into a WHERE statement 4948 from_: sql statement parsed into a FROM statement 4949 dialect: the dialect used to parse the input expressions. 4950 **opts: other options to use to parse the input expressions. 4951 4952 Returns: 4953 Update: the syntax tree for the UPDATE statement. 4954 """ 4955 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4956 update_expr.set( 4957 "expressions", 4958 [ 4959 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4960 for k, v in properties.items() 4961 ], 4962 ) 4963 if from_: 4964 update_expr.set( 4965 "from", 4966 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4967 ) 4968 if isinstance(where, Condition): 4969 where = Where(this=where) 4970 if where: 4971 update_expr.set( 4972 "where", 4973 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4974 ) 4975 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.
4978def delete( 4979 table: ExpOrStr, 4980 where: t.Optional[ExpOrStr] = None, 4981 returning: t.Optional[ExpOrStr] = None, 4982 dialect: DialectType = None, 4983 **opts, 4984) -> Delete: 4985 """ 4986 Builds a delete statement. 4987 4988 Example: 4989 >>> delete("my_table", where="id > 1").sql() 4990 'DELETE FROM my_table WHERE id > 1' 4991 4992 Args: 4993 where: sql conditional parsed into a WHERE statement 4994 returning: sql conditional parsed into a RETURNING statement 4995 dialect: the dialect used to parse the input expressions. 4996 **opts: other options to use to parse the input expressions. 4997 4998 Returns: 4999 Delete: the syntax tree for the DELETE statement. 5000 """ 5001 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 5002 if where: 5003 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 5004 if returning: 5005 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 5006 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.
5009def insert( 5010 expression: ExpOrStr, 5011 into: ExpOrStr, 5012 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 5013 overwrite: t.Optional[bool] = None, 5014 dialect: DialectType = None, 5015 copy: bool = True, 5016 **opts, 5017) -> Insert: 5018 """ 5019 Builds an INSERT statement. 5020 5021 Example: 5022 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 5023 'INSERT INTO tbl VALUES (1, 2, 3)' 5024 5025 Args: 5026 expression: the sql string or expression of the INSERT statement 5027 into: the tbl to insert data to. 5028 columns: optionally the table's column names. 5029 overwrite: whether to INSERT OVERWRITE or not. 5030 dialect: the dialect used to parse the input expressions. 5031 copy: whether or not to copy the expression. 5032 **opts: other options to use to parse the input expressions. 5033 5034 Returns: 5035 Insert: the syntax tree for the INSERT statement. 5036 """ 5037 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5038 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 5039 5040 if columns: 5041 this = _apply_list_builder( 5042 *columns, 5043 instance=Schema(this=this), 5044 arg="expressions", 5045 into=Identifier, 5046 copy=False, 5047 dialect=dialect, 5048 **opts, 5049 ) 5050 5051 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.
5054def condition( 5055 expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 5056) -> Condition: 5057 """ 5058 Initialize a logical condition expression. 5059 5060 Example: 5061 >>> condition("x=1").sql() 5062 'x = 1' 5063 5064 This is helpful for composing larger logical syntax trees: 5065 >>> where = condition("x=1") 5066 >>> where = where.and_("y=1") 5067 >>> Select().from_("tbl").select("*").where(where).sql() 5068 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 5069 5070 Args: 5071 *expression: the SQL code string to parse. 5072 If an Expression instance is passed, this is used as-is. 5073 dialect: the dialect used to parse the input expression (in the case that the 5074 input expression is a SQL string). 5075 copy: Whether or not to copy `expression` (only applies to expressions). 5076 **opts: other options to use to parse the input expressions (again, in the case 5077 that the input expression is a SQL string). 5078 5079 Returns: 5080 The new Condition instance 5081 """ 5082 return maybe_parse( 5083 expression, 5084 into=Condition, 5085 dialect=dialect, 5086 copy=copy, 5087 **opts, 5088 )
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
5091def and_( 5092 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5093) -> Condition: 5094 """ 5095 Combine multiple conditions with an AND logical operator. 5096 5097 Example: 5098 >>> and_("x=1", and_("y=1", "z=1")).sql() 5099 'x = 1 AND (y = 1 AND z = 1)' 5100 5101 Args: 5102 *expressions: the SQL code strings to parse. 5103 If an Expression instance is passed, this is used as-is. 5104 dialect: the dialect used to parse the input expression. 5105 copy: whether or not to copy `expressions` (only applies to Expressions). 5106 **opts: other options to use to parse the input expressions. 5107 5108 Returns: 5109 And: the new condition 5110 """ 5111 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
5114def or_( 5115 *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts 5116) -> Condition: 5117 """ 5118 Combine multiple conditions with an OR logical operator. 5119 5120 Example: 5121 >>> or_("x=1", or_("y=1", "z=1")).sql() 5122 'x = 1 OR (y = 1 OR z = 1)' 5123 5124 Args: 5125 *expressions: the SQL code strings to parse. 5126 If an Expression instance is passed, this is used as-is. 5127 dialect: the dialect used to parse the input expression. 5128 copy: whether or not to copy `expressions` (only applies to Expressions). 5129 **opts: other options to use to parse the input expressions. 5130 5131 Returns: 5132 Or: the new condition 5133 """ 5134 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
5137def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not: 5138 """ 5139 Wrap a condition with a NOT operator. 5140 5141 Example: 5142 >>> not_("this_suit='black'").sql() 5143 "NOT this_suit = 'black'" 5144 5145 Args: 5146 expression: the SQL code string to parse. 5147 If an Expression instance is passed, this is used as-is. 5148 dialect: the dialect used to parse the input expression. 5149 copy: whether to copy the expression or not. 5150 **opts: other options to use to parse the input expressions. 5151 5152 Returns: 5153 The new condition. 5154 """ 5155 this = condition( 5156 expression, 5157 dialect=dialect, 5158 copy=copy, 5159 **opts, 5160 ) 5161 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.
5164def paren(expression: ExpOrStr, copy: bool = True) -> Paren: 5165 """ 5166 Wrap an expression in parentheses. 5167 5168 Example: 5169 >>> paren("5 + 3").sql() 5170 '(5 + 3)' 5171 5172 Args: 5173 expression: the SQL code string to parse. 5174 If an Expression instance is passed, this is used as-is. 5175 copy: whether to copy the expression or not. 5176 5177 Returns: 5178 The wrapped expression. 5179 """ 5180 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.
5198def to_identifier(name, quoted=None, copy=True): 5199 """Builds an identifier. 5200 5201 Args: 5202 name: The name to turn into an identifier. 5203 quoted: Whether or not force quote the identifier. 5204 copy: Whether or not to copy a passed in Identefier node. 5205 5206 Returns: 5207 The identifier ast node. 5208 """ 5209 5210 if name is None: 5211 return None 5212 5213 if isinstance(name, Identifier): 5214 identifier = _maybe_copy(name, copy) 5215 elif isinstance(name, str): 5216 identifier = Identifier( 5217 this=name, 5218 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 5219 ) 5220 else: 5221 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 5222 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.
5228def to_interval(interval: str | Literal) -> Interval: 5229 """Builds an interval expression from a string like '1 day' or '5 months'.""" 5230 if isinstance(interval, Literal): 5231 if not interval.is_string: 5232 raise ValueError("Invalid interval string.") 5233 5234 interval = interval.this 5235 5236 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5237 5238 if not interval_parts: 5239 raise ValueError("Invalid interval string.") 5240 5241 return Interval( 5242 this=Literal.string(interval_parts.group(1)), 5243 unit=Var(this=interval_parts.group(2)), 5244 )
Builds an interval expression from a string like '1 day' or '5 months'.
5257def to_table( 5258 sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs 5259) -> t.Optional[Table]: 5260 """ 5261 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5262 If a table is passed in then that table is returned. 5263 5264 Args: 5265 sql_path: a `[catalog].[schema].[table]` string. 5266 dialect: the source dialect according to which the table name will be parsed. 5267 kwargs: the kwargs to instantiate the resulting `Table` expression with. 5268 5269 Returns: 5270 A table expression. 5271 """ 5272 if sql_path is None or isinstance(sql_path, Table): 5273 return sql_path 5274 if not isinstance(sql_path, str): 5275 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5276 5277 table = maybe_parse(sql_path, into=Table, dialect=dialect) 5278 if table: 5279 for k, v in kwargs.items(): 5280 table.set(k, v) 5281 5282 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.
5285def to_column(sql_path: str | Column, **kwargs) -> Column: 5286 """ 5287 Create a column from a `[table].[column]` sql path. Schema is optional. 5288 5289 If a column is passed in then that column is returned. 5290 5291 Args: 5292 sql_path: `[table].[column]` string 5293 Returns: 5294 Table: A column expression 5295 """ 5296 if sql_path is None or isinstance(sql_path, Column): 5297 return sql_path 5298 if not isinstance(sql_path, str): 5299 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5300 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
5303def alias_( 5304 expression: ExpOrStr, 5305 alias: str | Identifier, 5306 table: bool | t.Sequence[str | Identifier] = False, 5307 quoted: t.Optional[bool] = None, 5308 dialect: DialectType = None, 5309 copy: bool = True, 5310 **opts, 5311): 5312 """Create an Alias expression. 5313 5314 Example: 5315 >>> alias_('foo', 'bar').sql() 5316 'foo AS bar' 5317 5318 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5319 '(SELECT 1, 2) AS bar(a, b)' 5320 5321 Args: 5322 expression: the SQL code strings to parse. 5323 If an Expression instance is passed, this is used as-is. 5324 alias: the alias name to use. If the name has 5325 special characters it is quoted. 5326 table: Whether or not to create a table alias, can also be a list of columns. 5327 quoted: whether or not to quote the alias 5328 dialect: the dialect used to parse the input expression. 5329 copy: Whether or not to copy the expression. 5330 **opts: other options to use to parse the input expressions. 5331 5332 Returns: 5333 Alias: the aliased expression 5334 """ 5335 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5336 alias = to_identifier(alias, quoted=quoted) 5337 5338 if table: 5339 table_alias = TableAlias(this=alias) 5340 exp.set("alias", table_alias) 5341 5342 if not isinstance(table, bool): 5343 for column in table: 5344 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5345 5346 return exp 5347 5348 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5349 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5350 # for the complete Window expression. 5351 # 5352 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5353 5354 if "alias" in exp.arg_types and not isinstance(exp, Window): 5355 exp.set("alias", alias) 5356 return exp 5357 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
5360def subquery( 5361 expression: ExpOrStr, 5362 alias: t.Optional[Identifier | str] = None, 5363 dialect: DialectType = None, 5364 **opts, 5365) -> Select: 5366 """ 5367 Build a subquery expression. 5368 5369 Example: 5370 >>> subquery('select x from tbl', 'bar').select('x').sql() 5371 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5372 5373 Args: 5374 expression: the SQL code strings to parse. 5375 If an Expression instance is passed, this is used as-is. 5376 alias: the alias name to use. 5377 dialect: the dialect used to parse the input expression. 5378 **opts: other options to use to parse the input expressions. 5379 5380 Returns: 5381 A new Select instance with the subquery expression included. 5382 """ 5383 5384 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5385 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.
5388def column( 5389 col: str | Identifier, 5390 table: t.Optional[str | Identifier] = None, 5391 db: t.Optional[str | Identifier] = None, 5392 catalog: t.Optional[str | Identifier] = None, 5393 quoted: t.Optional[bool] = None, 5394) -> Column: 5395 """ 5396 Build a Column. 5397 5398 Args: 5399 col: Column name. 5400 table: Table name. 5401 db: Database name. 5402 catalog: Catalog name. 5403 quoted: Whether to force quotes on the column's identifiers. 5404 5405 Returns: 5406 The new Column instance. 5407 """ 5408 return Column( 5409 this=to_identifier(col, quoted=quoted), 5410 table=to_identifier(table, quoted=quoted), 5411 db=to_identifier(db, quoted=quoted), 5412 catalog=to_identifier(catalog, quoted=quoted), 5413 )
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.
5416def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5417 """Cast an expression to a data type. 5418 5419 Example: 5420 >>> cast('x + 1', 'int').sql() 5421 'CAST(x + 1 AS INT)' 5422 5423 Args: 5424 expression: The expression to cast. 5425 to: The datatype to cast to. 5426 5427 Returns: 5428 The new Cast instance. 5429 """ 5430 expression = maybe_parse(expression, **opts) 5431 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.
5434def table_( 5435 table: Identifier | str, 5436 db: t.Optional[Identifier | str] = None, 5437 catalog: t.Optional[Identifier | str] = None, 5438 quoted: t.Optional[bool] = None, 5439 alias: t.Optional[Identifier | str] = None, 5440) -> Table: 5441 """Build a Table. 5442 5443 Args: 5444 table: Table name. 5445 db: Database name. 5446 catalog: Catalog name. 5447 quote: Whether to force quotes on the table's identifiers. 5448 alias: Table's alias. 5449 5450 Returns: 5451 The new Table instance. 5452 """ 5453 return Table( 5454 this=to_identifier(table, quoted=quoted), 5455 db=to_identifier(db, quoted=quoted), 5456 catalog=to_identifier(catalog, quoted=quoted), 5457 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5458 )
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.
5461def values( 5462 values: t.Iterable[t.Tuple[t.Any, ...]], 5463 alias: t.Optional[str] = None, 5464 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5465) -> Values: 5466 """Build VALUES statement. 5467 5468 Example: 5469 >>> values([(1, '2')]).sql() 5470 "VALUES (1, '2')" 5471 5472 Args: 5473 values: values statements that will be converted to SQL 5474 alias: optional alias 5475 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5476 If either are provided then an alias is also required. 5477 5478 Returns: 5479 Values: the Values expression object 5480 """ 5481 if columns and not alias: 5482 raise ValueError("Alias is required when providing columns") 5483 5484 return Values( 5485 expressions=[convert(tup) for tup in values], 5486 alias=( 5487 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5488 if columns 5489 else (TableAlias(this=to_identifier(alias)) if alias else None) 5490 ), 5491 )
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
5494def var(name: t.Optional[ExpOrStr]) -> Var: 5495 """Build a SQL variable. 5496 5497 Example: 5498 >>> repr(var('x')) 5499 '(VAR this: x)' 5500 5501 >>> repr(var(column('x', table='y'))) 5502 '(VAR this: x)' 5503 5504 Args: 5505 name: The name of the var or an expression who's name will become the var. 5506 5507 Returns: 5508 The new variable node. 5509 """ 5510 if not name: 5511 raise ValueError("Cannot convert empty name into var.") 5512 5513 if isinstance(name, Expression): 5514 name = name.name 5515 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.
5518def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5519 """Build ALTER TABLE... RENAME... expression 5520 5521 Args: 5522 old_name: The old name of the table 5523 new_name: The new name of the table 5524 5525 Returns: 5526 Alter table expression 5527 """ 5528 old_table = to_table(old_name) 5529 new_table = to_table(new_name) 5530 return AlterTable( 5531 this=old_table, 5532 actions=[ 5533 RenameTable(this=new_table), 5534 ], 5535 )
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
5538def convert(value: t.Any, copy: bool = False) -> Expression: 5539 """Convert a python value into an expression object. 5540 5541 Raises an error if a conversion is not possible. 5542 5543 Args: 5544 value: A python object. 5545 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5546 5547 Returns: 5548 Expression: the equivalent expression object. 5549 """ 5550 if isinstance(value, Expression): 5551 return _maybe_copy(value, copy) 5552 if isinstance(value, str): 5553 return Literal.string(value) 5554 if isinstance(value, bool): 5555 return Boolean(this=value) 5556 if value is None or (isinstance(value, float) and math.isnan(value)): 5557 return NULL 5558 if isinstance(value, numbers.Number): 5559 return Literal.number(value) 5560 if isinstance(value, datetime.datetime): 5561 datetime_literal = Literal.string( 5562 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5563 ) 5564 return TimeStrToTime(this=datetime_literal) 5565 if isinstance(value, datetime.date): 5566 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5567 return DateStrToDate(this=date_literal) 5568 if isinstance(value, tuple): 5569 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5570 if isinstance(value, list): 5571 return Array(expressions=[convert(v, copy=copy) for v in value]) 5572 if isinstance(value, dict): 5573 return Map( 5574 keys=[convert(k, copy=copy) for k in value], 5575 values=[convert(v, copy=copy) for v in value.values()], 5576 ) 5577 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.
5580def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None: 5581 """ 5582 Replace children of an expression with the result of a lambda fun(child) -> exp. 5583 """ 5584 for k, v in expression.args.items(): 5585 is_list_arg = type(v) is list 5586 5587 child_nodes = v if is_list_arg else [v] 5588 new_child_nodes = [] 5589 5590 for cn in child_nodes: 5591 if isinstance(cn, Expression): 5592 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5593 new_child_nodes.append(child_node) 5594 child_node.parent = expression 5595 child_node.arg_key = k 5596 else: 5597 new_child_nodes.append(cn) 5598 5599 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.
5602def column_table_names(expression: Expression) -> t.List[str]: 5603 """ 5604 Return all table names referenced through columns in an expression. 5605 5606 Example: 5607 >>> import sqlglot 5608 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5609 ['c', 'a'] 5610 5611 Args: 5612 expression: expression to find table names. 5613 5614 Returns: 5615 A list of unique names. 5616 """ 5617 return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) ['c', 'a']
Arguments:
- expression: expression to find table names.
Returns:
A list of unique names.
5620def table_name(table: Table | str) -> str: 5621 """Get the full name of a table as a string. 5622 5623 Args: 5624 table: table expression node or string. 5625 5626 Examples: 5627 >>> from sqlglot import exp, parse_one 5628 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5629 'a.b.c' 5630 5631 Returns: 5632 The table name. 5633 """ 5634 5635 table = maybe_parse(table, into=Table) 5636 5637 if not table: 5638 raise ValueError(f"Cannot parse {table}") 5639 5640 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.
5643def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E: 5644 """Replace all tables in expression according to the mapping. 5645 5646 Args: 5647 expression: expression node to be transformed and replaced. 5648 mapping: mapping of table names. 5649 5650 Examples: 5651 >>> from sqlglot import exp, parse_one 5652 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5653 'SELECT * FROM c' 5654 5655 Returns: 5656 The mapped expression. 5657 """ 5658 5659 def _replace_tables(node: Expression) -> Expression: 5660 if isinstance(node, Table): 5661 new_name = mapping.get(table_name(node)) 5662 if new_name: 5663 return to_table( 5664 new_name, 5665 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5666 ) 5667 return node 5668 5669 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression: expression node to be transformed and replaced.
- mapping: mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
5672def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression: 5673 """Replace placeholders in an expression. 5674 5675 Args: 5676 expression: expression node to be transformed and replaced. 5677 args: positional names that will substitute unnamed placeholders in the given order. 5678 kwargs: keyword arguments that will substitute named placeholders. 5679 5680 Examples: 5681 >>> from sqlglot import exp, parse_one 5682 >>> replace_placeholders( 5683 ... parse_one("select * from :tbl where ? = ?"), 5684 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5685 ... ).sql() 5686 "SELECT * FROM foo WHERE str_col = 'b'" 5687 5688 Returns: 5689 The mapped expression. 5690 """ 5691 5692 def _replace_placeholders(node: Expression, args, **kwargs) -> Expression: 5693 if isinstance(node, Placeholder): 5694 if node.name: 5695 new_name = kwargs.get(node.name) 5696 if new_name: 5697 return convert(new_name) 5698 else: 5699 try: 5700 return convert(next(args)) 5701 except StopIteration: 5702 pass 5703 return node 5704 5705 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.
5708def expand( 5709 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5710) -> Expression: 5711 """Transforms an expression by expanding all referenced sources into subqueries. 5712 5713 Examples: 5714 >>> from sqlglot import parse_one 5715 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5716 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5717 5718 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5719 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5720 5721 Args: 5722 expression: The expression to expand. 5723 sources: A dictionary of name to Subqueryables. 5724 copy: Whether or not to copy the expression during transformation. Defaults to True. 5725 5726 Returns: 5727 The transformed expression. 5728 """ 5729 5730 def _expand(node: Expression): 5731 if isinstance(node, Table): 5732 name = table_name(node) 5733 source = sources.get(name) 5734 if source: 5735 subquery = source.subquery(node.alias or name) 5736 subquery.comments = [f"source: {name}"] 5737 return subquery.transform(_expand, copy=False) 5738 return node 5739 5740 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.
5743def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5744 """ 5745 Returns a Func expression. 5746 5747 Examples: 5748 >>> func("abs", 5).sql() 5749 'ABS(5)' 5750 5751 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5752 'CAST(5 AS DOUBLE)' 5753 5754 Args: 5755 name: the name of the function to build. 5756 args: the args used to instantiate the function of interest. 5757 dialect: the source dialect. 5758 kwargs: the kwargs used to instantiate the function of interest. 5759 5760 Note: 5761 The arguments `args` and `kwargs` are mutually exclusive. 5762 5763 Returns: 5764 An instance of the function of interest, or an anonymous function, if `name` doesn't 5765 correspond to an existing `sqlglot.expressions.Func` class. 5766 """ 5767 if args and kwargs: 5768 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5769 5770 from sqlglot.dialects.dialect import Dialect 5771 5772 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5773 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5774 5775 parser = Dialect.get_or_raise(dialect)().parser() 5776 from_args_list = parser.FUNCTIONS.get(name.upper()) 5777 5778 if from_args_list: 5779 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5780 else: 5781 kwargs = kwargs or {"expressions": converted} 5782 function = Anonymous(this=name, **kwargs) 5783 5784 for error_message in function.error_messages(converted): 5785 raise ValueError(error_message) 5786 5787 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.
5790def true() -> Boolean: 5791 """ 5792 Returns a true Boolean expression. 5793 """ 5794 return Boolean(this=True)
Returns a true Boolean expression.
5797def false() -> Boolean: 5798 """ 5799 Returns a false Boolean expression. 5800 """ 5801 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.