Expressions
Every AST node in SQLGlot is represented by a subclass of Expression
.
This module contains the implementation of all supported Expression
types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select
.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot.errors import ParseError 25from sqlglot.helper import ( 26 AutoName, 27 camel_to_snake_case, 28 ensure_collection, 29 ensure_list, 30 seq_get, 31 split_num_words, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39E = t.TypeVar("E", bound="Expression") 40 41 42class _Expression(type): 43 def __new__(cls, clsname, bases, attrs): 44 klass = super().__new__(cls, clsname, bases, attrs) 45 46 # When an Expression class is created, its key is automatically set to be 47 # the lowercase version of the class' name. 48 klass.key = clsname.lower() 49 50 # This is so that docstrings are not inherited in pdoc 51 klass.__doc__ = klass.__doc__ or "" 52 53 return klass 54 55 56class Expression(metaclass=_Expression): 57 """ 58 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 59 context, such as its child expressions, their names (arg keys), and whether a given child expression 60 is optional or not. 61 62 Attributes: 63 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 64 and representing expressions as strings. 65 arg_types: determines what arguments (child nodes) are supported by an expression. It 66 maps arg keys to booleans that indicate whether the corresponding args are optional. 67 68 Example: 69 >>> class Foo(Expression): 70 ... arg_types = {"this": True, "expression": False} 71 72 The above definition informs us that Foo is an Expression that requires an argument called 73 "this" and may also optionally receive an argument called "expression". 74 75 Args: 76 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 77 parent: a reference to the parent expression (or None, in case of root expressions). 78 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 79 uses to refer to it. 80 comments: a list of comments that are associated with a given expression. This is used in 81 order to preserve comments when transpiling SQL code. 82 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 83 optimizer, in order to enable some transformations that require type information. 84 """ 85 86 key = "expression" 87 arg_types = {"this": True} 88 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 89 90 def __init__(self, **args: t.Any): 91 self.args: t.Dict[str, t.Any] = args 92 self.parent: t.Optional[Expression] = None 93 self.arg_key: t.Optional[str] = None 94 self.comments: t.Optional[t.List[str]] = None 95 self._type: t.Optional[DataType] = None 96 self._meta: t.Optional[t.Dict[str, t.Any]] = None 97 self._hash: t.Optional[int] = None 98 99 for arg_key, value in self.args.items(): 100 self._set_parent(arg_key, value) 101 102 def __eq__(self, other) -> bool: 103 return type(self) is type(other) and hash(self) == hash(other) 104 105 @property 106 def hashable_args(self) -> t.Any: 107 args = (self.args.get(k) for k in self.arg_types) 108 109 return tuple( 110 (tuple(_norm_arg(a) for a in arg) if arg else None) 111 if type(arg) is list 112 else (_norm_arg(arg) if arg is not None and arg is not False else None) 113 for arg in args 114 ) 115 116 def __hash__(self) -> int: 117 if self._hash is not None: 118 return self._hash 119 120 return hash((self.__class__, self.hashable_args)) 121 122 @property 123 def this(self): 124 """ 125 Retrieves the argument with key "this". 126 """ 127 return self.args.get("this") 128 129 @property 130 def expression(self): 131 """ 132 Retrieves the argument with key "expression". 133 """ 134 return self.args.get("expression") 135 136 @property 137 def expressions(self): 138 """ 139 Retrieves the argument with key "expressions". 140 """ 141 return self.args.get("expressions") or [] 142 143 def text(self, key) -> str: 144 """ 145 Returns a textual representation of the argument corresponding to "key". This can only be used 146 for args that are strings or leaf Expression instances, such as identifiers and literals. 147 """ 148 field = self.args.get(key) 149 if isinstance(field, str): 150 return field 151 if isinstance(field, (Identifier, Literal, Var)): 152 return field.this 153 if isinstance(field, (Star, Null)): 154 return field.name 155 return "" 156 157 @property 158 def is_string(self) -> bool: 159 """ 160 Checks whether a Literal expression is a string. 161 """ 162 return isinstance(self, Literal) and self.args["is_string"] 163 164 @property 165 def is_number(self) -> bool: 166 """ 167 Checks whether a Literal expression is a number. 168 """ 169 return isinstance(self, Literal) and not self.args["is_string"] 170 171 @property 172 def is_int(self) -> bool: 173 """ 174 Checks whether a Literal expression is an integer. 175 """ 176 if self.is_number: 177 try: 178 int(self.name) 179 return True 180 except ValueError: 181 pass 182 return False 183 184 @property 185 def is_star(self) -> bool: 186 """Checks whether an expression is a star.""" 187 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 188 189 @property 190 def alias(self) -> str: 191 """ 192 Returns the alias of the expression, or an empty string if it's not aliased. 193 """ 194 if isinstance(self.args.get("alias"), TableAlias): 195 return self.args["alias"].name 196 return self.text("alias") 197 198 @property 199 def name(self) -> str: 200 return self.text("this") 201 202 @property 203 def alias_or_name(self): 204 return self.alias or self.name 205 206 @property 207 def output_name(self): 208 """ 209 Name of the output column if this expression is a selection. 210 211 If the Expression has no output name, an empty string is returned. 212 213 Example: 214 >>> from sqlglot import parse_one 215 >>> parse_one("SELECT a").expressions[0].output_name 216 'a' 217 >>> parse_one("SELECT b AS c").expressions[0].output_name 218 'c' 219 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 220 '' 221 """ 222 return "" 223 224 @property 225 def type(self) -> t.Optional[DataType]: 226 return self._type 227 228 @type.setter 229 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 230 if dtype and not isinstance(dtype, DataType): 231 dtype = DataType.build(dtype) 232 self._type = dtype # type: ignore 233 234 @property 235 def meta(self) -> t.Dict[str, t.Any]: 236 if self._meta is None: 237 self._meta = {} 238 return self._meta 239 240 def __deepcopy__(self, memo): 241 copy = self.__class__(**deepcopy(self.args)) 242 if self.comments is not None: 243 copy.comments = deepcopy(self.comments) 244 245 if self._type is not None: 246 copy._type = self._type.copy() 247 248 if self._meta is not None: 249 copy._meta = deepcopy(self._meta) 250 251 return copy 252 253 def copy(self): 254 """ 255 Returns a deep copy of the expression. 256 """ 257 new = deepcopy(self) 258 new.parent = self.parent 259 return new 260 261 def append(self, arg_key, value): 262 """ 263 Appends value to arg_key if it's a list or sets it as a new list. 264 265 Args: 266 arg_key (str): name of the list expression arg 267 value (Any): value to append to the list 268 """ 269 if not isinstance(self.args.get(arg_key), list): 270 self.args[arg_key] = [] 271 self.args[arg_key].append(value) 272 self._set_parent(arg_key, value) 273 274 def set(self, arg_key, value): 275 """ 276 Sets `arg_key` to `value`. 277 278 Args: 279 arg_key (str): name of the expression arg. 280 value: value to set the arg to. 281 """ 282 self.args[arg_key] = value 283 self._set_parent(arg_key, value) 284 285 def _set_parent(self, arg_key, value): 286 if hasattr(value, "parent"): 287 value.parent = self 288 value.arg_key = arg_key 289 elif type(value) is list: 290 for v in value: 291 if hasattr(v, "parent"): 292 v.parent = self 293 v.arg_key = arg_key 294 295 @property 296 def depth(self): 297 """ 298 Returns the depth of this tree. 299 """ 300 if self.parent: 301 return self.parent.depth + 1 302 return 0 303 304 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 305 """Yields the key and expression for all arguments, exploding list args.""" 306 for k, vs in self.args.items(): 307 if type(vs) is list: 308 for v in vs: 309 if hasattr(v, "parent"): 310 yield k, v 311 else: 312 if hasattr(vs, "parent"): 313 yield k, vs 314 315 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 316 """ 317 Returns the first node in this tree which matches at least one of 318 the specified types. 319 320 Args: 321 expression_types: the expression type(s) to match. 322 323 Returns: 324 The node which matches the criteria or None if no such node was found. 325 """ 326 return next(self.find_all(*expression_types, bfs=bfs), None) 327 328 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 329 """ 330 Returns a generator object which visits all nodes in this tree and only 331 yields those that match at least one of the specified expression types. 332 333 Args: 334 expression_types: the expression type(s) to match. 335 336 Returns: 337 The generator object. 338 """ 339 for expression, *_ in self.walk(bfs=bfs): 340 if isinstance(expression, expression_types): 341 yield expression 342 343 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 344 """ 345 Returns a nearest parent matching expression_types. 346 347 Args: 348 expression_types: the expression type(s) to match. 349 350 Returns: 351 The parent node. 352 """ 353 ancestor = self.parent 354 while ancestor and not isinstance(ancestor, expression_types): 355 ancestor = ancestor.parent 356 return t.cast(E, ancestor) 357 358 @property 359 def parent_select(self): 360 """ 361 Returns the parent select statement. 362 """ 363 return self.find_ancestor(Select) 364 365 @property 366 def same_parent(self): 367 """Returns if the parent is the same class as itself.""" 368 return type(self.parent) is self.__class__ 369 370 def root(self) -> Expression: 371 """ 372 Returns the root expression of this tree. 373 """ 374 expression = self 375 while expression.parent: 376 expression = expression.parent 377 return expression 378 379 def walk(self, bfs=True, prune=None): 380 """ 381 Returns a generator object which visits all nodes in this tree. 382 383 Args: 384 bfs (bool): if set to True the BFS traversal order will be applied, 385 otherwise the DFS traversal will be used instead. 386 prune ((node, parent, arg_key) -> bool): callable that returns True if 387 the generator should stop traversing this branch of the tree. 388 389 Returns: 390 the generator object. 391 """ 392 if bfs: 393 yield from self.bfs(prune=prune) 394 else: 395 yield from self.dfs(prune=prune) 396 397 def dfs(self, parent=None, key=None, prune=None): 398 """ 399 Returns a generator object which visits all nodes in this tree in 400 the DFS (Depth-first) order. 401 402 Returns: 403 The generator object. 404 """ 405 parent = parent or self.parent 406 yield self, parent, key 407 if prune and prune(self, parent, key): 408 return 409 410 for k, v in self.iter_expressions(): 411 yield from v.dfs(self, k, prune) 412 413 def bfs(self, prune=None): 414 """ 415 Returns a generator object which visits all nodes in this tree in 416 the BFS (Breadth-first) order. 417 418 Returns: 419 The generator object. 420 """ 421 queue = deque([(self, self.parent, None)]) 422 423 while queue: 424 item, parent, key = queue.popleft() 425 426 yield item, parent, key 427 if prune and prune(item, parent, key): 428 continue 429 430 for k, v in item.iter_expressions(): 431 queue.append((v, item, k)) 432 433 def unnest(self): 434 """ 435 Returns the first non parenthesis child or self. 436 """ 437 expression = self 438 while type(expression) is Paren: 439 expression = expression.this 440 return expression 441 442 def unalias(self): 443 """ 444 Returns the inner expression if this is an Alias. 445 """ 446 if isinstance(self, Alias): 447 return self.this 448 return self 449 450 def unnest_operands(self): 451 """ 452 Returns unnested operands as a tuple. 453 """ 454 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 455 456 def flatten(self, unnest=True): 457 """ 458 Returns a generator which yields child nodes who's parents are the same class. 459 460 A AND B AND C -> [A, B, C] 461 """ 462 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 463 if not type(node) is self.__class__: 464 yield node.unnest() if unnest else node 465 466 def __str__(self): 467 return self.sql() 468 469 def __repr__(self): 470 return self._to_s() 471 472 def sql(self, dialect: DialectType = None, **opts) -> str: 473 """ 474 Returns SQL string representation of this tree. 475 476 Args: 477 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 478 opts: other `sqlglot.generator.Generator` options. 479 480 Returns: 481 The SQL string. 482 """ 483 from sqlglot.dialects import Dialect 484 485 return Dialect.get_or_raise(dialect)().generate(self, **opts) 486 487 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 488 indent = "" if not level else "\n" 489 indent += "".join([" "] * level) 490 left = f"({self.key.upper()} " 491 492 args: t.Dict[str, t.Any] = { 493 k: ", ".join( 494 v._to_s(hide_missing=hide_missing, level=level + 1) 495 if hasattr(v, "_to_s") 496 else str(v) 497 for v in ensure_list(vs) 498 if v is not None 499 ) 500 for k, vs in self.args.items() 501 } 502 args["comments"] = self.comments 503 args["type"] = self.type 504 args = {k: v for k, v in args.items() if v or not hide_missing} 505 506 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 507 right += ")" 508 509 return indent + left + right 510 511 def transform(self, fun, *args, copy=True, **kwargs): 512 """ 513 Recursively visits all tree nodes (excluding already transformed ones) 514 and applies the given transformation function to each node. 515 516 Args: 517 fun (function): a function which takes a node as an argument and returns a 518 new transformed node or the same node without modifications. If the function 519 returns None, then the corresponding node will be removed from the syntax tree. 520 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 521 modified in place. 522 523 Returns: 524 The transformed tree. 525 """ 526 node = self.copy() if copy else self 527 new_node = fun(node, *args, **kwargs) 528 529 if new_node is None or not isinstance(new_node, Expression): 530 return new_node 531 if new_node is not node: 532 new_node.parent = node.parent 533 return new_node 534 535 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 536 return new_node 537 538 def replace(self, expression): 539 """ 540 Swap out this expression with a new expression. 541 542 For example:: 543 544 >>> tree = Select().select("x").from_("tbl") 545 >>> tree.find(Column).replace(Column(this="y")) 546 (COLUMN this: y) 547 >>> tree.sql() 548 'SELECT y FROM tbl' 549 550 Args: 551 expression (Expression|None): new node 552 553 Returns: 554 The new expression or expressions. 555 """ 556 if not self.parent: 557 return expression 558 559 parent = self.parent 560 self.parent = None 561 562 replace_children(parent, lambda child: expression if child is self else child) 563 return expression 564 565 def pop(self): 566 """ 567 Remove this expression from its AST. 568 569 Returns: 570 The popped expression. 571 """ 572 self.replace(None) 573 return self 574 575 def assert_is(self, type_): 576 """ 577 Assert that this `Expression` is an instance of `type_`. 578 579 If it is NOT an instance of `type_`, this raises an assertion error. 580 Otherwise, this returns this expression. 581 582 Examples: 583 This is useful for type security in chained expressions: 584 585 >>> import sqlglot 586 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 587 'SELECT x, z FROM y' 588 """ 589 assert isinstance(self, type_) 590 return self 591 592 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 593 """ 594 Checks if this expression is valid (e.g. all mandatory args are set). 595 596 Args: 597 args: a sequence of values that were used to instantiate a Func expression. This is used 598 to check that the provided arguments don't exceed the function argument limit. 599 600 Returns: 601 A list of error messages for all possible errors that were found. 602 """ 603 errors: t.List[str] = [] 604 605 for k in self.args: 606 if k not in self.arg_types: 607 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 608 for k, mandatory in self.arg_types.items(): 609 v = self.args.get(k) 610 if mandatory and (v is None or (isinstance(v, list) and not v)): 611 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 612 613 if ( 614 args 615 and isinstance(self, Func) 616 and len(args) > len(self.arg_types) 617 and not self.is_var_len_args 618 ): 619 errors.append( 620 f"The number of provided arguments ({len(args)}) is greater than " 621 f"the maximum number of supported arguments ({len(self.arg_types)})" 622 ) 623 624 return errors 625 626 def dump(self): 627 """ 628 Dump this Expression to a JSON-serializable dict. 629 """ 630 from sqlglot.serde import dump 631 632 return dump(self) 633 634 @classmethod 635 def load(cls, obj): 636 """ 637 Load a dict (as returned by `Expression.dump`) into an Expression instance. 638 """ 639 from sqlglot.serde import load 640 641 return load(obj) 642 643 644IntoType = t.Union[ 645 str, 646 t.Type[Expression], 647 t.Collection[t.Union[str, t.Type[Expression]]], 648] 649ExpOrStr = t.Union[str, Expression] 650 651 652class Condition(Expression): 653 def and_(self, *expressions, dialect=None, **opts): 654 """ 655 AND this condition with one or multiple expressions. 656 657 Example: 658 >>> condition("x=1").and_("y=1").sql() 659 'x = 1 AND y = 1' 660 661 Args: 662 *expressions (str | Expression): the SQL code strings to parse. 663 If an `Expression` instance is passed, it will be used as-is. 664 dialect (str): the dialect used to parse the input expression. 665 opts (kwargs): other options to use to parse the input expressions. 666 667 Returns: 668 And: the new condition. 669 """ 670 return and_(self, *expressions, dialect=dialect, **opts) 671 672 def or_(self, *expressions, dialect=None, **opts): 673 """ 674 OR this condition with one or multiple expressions. 675 676 Example: 677 >>> condition("x=1").or_("y=1").sql() 678 'x = 1 OR y = 1' 679 680 Args: 681 *expressions (str | Expression): the SQL code strings to parse. 682 If an `Expression` instance is passed, it will be used as-is. 683 dialect (str): the dialect used to parse the input expression. 684 opts (kwargs): other options to use to parse the input expressions. 685 686 Returns: 687 Or: the new condition. 688 """ 689 return or_(self, *expressions, dialect=dialect, **opts) 690 691 def not_(self): 692 """ 693 Wrap this condition with NOT. 694 695 Example: 696 >>> condition("x=1").not_().sql() 697 'NOT x = 1' 698 699 Returns: 700 Not: the new condition. 701 """ 702 return not_(self) 703 704 705class Predicate(Condition): 706 """Relationships like x = y, x > 1, x >= y.""" 707 708 709class DerivedTable(Expression): 710 @property 711 def alias_column_names(self): 712 table_alias = self.args.get("alias") 713 if not table_alias: 714 return [] 715 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 716 return [c.name for c in column_list] 717 718 @property 719 def selects(self): 720 alias = self.args.get("alias") 721 722 if alias: 723 return alias.columns 724 return [] 725 726 @property 727 def named_selects(self): 728 return [select.output_name for select in self.selects] 729 730 731class Unionable(Expression): 732 def union(self, expression, distinct=True, dialect=None, **opts): 733 """ 734 Builds a UNION expression. 735 736 Example: 737 >>> import sqlglot 738 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 739 'SELECT * FROM foo UNION SELECT * FROM bla' 740 741 Args: 742 expression (str | Expression): the SQL code string. 743 If an `Expression` instance is passed, it will be used as-is. 744 distinct (bool): set the DISTINCT flag if and only if this is true. 745 dialect (str): the dialect used to parse the input expression. 746 opts (kwargs): other options to use to parse the input expressions. 747 Returns: 748 Union: the Union expression. 749 """ 750 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 751 752 def intersect(self, expression, distinct=True, dialect=None, **opts): 753 """ 754 Builds an INTERSECT expression. 755 756 Example: 757 >>> import sqlglot 758 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 759 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 760 761 Args: 762 expression (str | Expression): the SQL code string. 763 If an `Expression` instance is passed, it will be used as-is. 764 distinct (bool): set the DISTINCT flag if and only if this is true. 765 dialect (str): the dialect used to parse the input expression. 766 opts (kwargs): other options to use to parse the input expressions. 767 Returns: 768 Intersect: the Intersect expression 769 """ 770 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 771 772 def except_(self, expression, distinct=True, dialect=None, **opts): 773 """ 774 Builds an EXCEPT expression. 775 776 Example: 777 >>> import sqlglot 778 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 779 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 780 781 Args: 782 expression (str | Expression): the SQL code string. 783 If an `Expression` instance is passed, it will be used as-is. 784 distinct (bool): set the DISTINCT flag if and only if this is true. 785 dialect (str): the dialect used to parse the input expression. 786 opts (kwargs): other options to use to parse the input expressions. 787 Returns: 788 Except: the Except expression 789 """ 790 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 791 792 793class UDTF(DerivedTable, Unionable): 794 pass 795 796 797class Cache(Expression): 798 arg_types = { 799 "with": False, 800 "this": True, 801 "lazy": False, 802 "options": False, 803 "expression": False, 804 } 805 806 807class Uncache(Expression): 808 arg_types = {"this": True, "exists": False} 809 810 811class Create(Expression): 812 arg_types = { 813 "with": False, 814 "this": True, 815 "kind": True, 816 "expression": False, 817 "exists": False, 818 "properties": False, 819 "replace": False, 820 "unique": False, 821 "volatile": False, 822 "indexes": False, 823 "no_schema_binding": False, 824 "begin": False, 825 } 826 827 828class Describe(Expression): 829 arg_types = {"this": True, "kind": False} 830 831 832class Pragma(Expression): 833 pass 834 835 836class Set(Expression): 837 arg_types = {"expressions": False} 838 839 840class SetItem(Expression): 841 arg_types = { 842 "this": False, 843 "expressions": False, 844 "kind": False, 845 "collate": False, # MySQL SET NAMES statement 846 "global": False, 847 } 848 849 850class Show(Expression): 851 arg_types = { 852 "this": True, 853 "target": False, 854 "offset": False, 855 "limit": False, 856 "like": False, 857 "where": False, 858 "db": False, 859 "full": False, 860 "mutex": False, 861 "query": False, 862 "channel": False, 863 "global": False, 864 "log": False, 865 "position": False, 866 "types": False, 867 } 868 869 870class UserDefinedFunction(Expression): 871 arg_types = {"this": True, "expressions": False, "wrapped": False} 872 873 874class CharacterSet(Expression): 875 arg_types = {"this": True, "default": False} 876 877 878class With(Expression): 879 arg_types = {"expressions": True, "recursive": False} 880 881 @property 882 def recursive(self) -> bool: 883 return bool(self.args.get("recursive")) 884 885 886class WithinGroup(Expression): 887 arg_types = {"this": True, "expression": False} 888 889 890class CTE(DerivedTable): 891 arg_types = {"this": True, "alias": True} 892 893 894class TableAlias(Expression): 895 arg_types = {"this": False, "columns": False} 896 897 @property 898 def columns(self): 899 return self.args.get("columns") or [] 900 901 902class BitString(Condition): 903 pass 904 905 906class HexString(Condition): 907 pass 908 909 910class ByteString(Condition): 911 pass 912 913 914class Column(Condition): 915 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 916 917 @property 918 def table(self) -> str: 919 return self.text("table") 920 921 @property 922 def db(self) -> str: 923 return self.text("db") 924 925 @property 926 def catalog(self) -> str: 927 return self.text("catalog") 928 929 @property 930 def output_name(self) -> str: 931 return self.name 932 933 @property 934 def parts(self) -> t.List[Identifier]: 935 """Return the parts of a column in order catalog, db, table, name.""" 936 return [part for part in reversed(list(self.args.values())) if part] 937 938 def to_dot(self) -> Dot: 939 """Converts the column into a dot expression.""" 940 parts = self.parts 941 parent = self.parent 942 943 while parent: 944 if isinstance(parent, Dot): 945 parts.append(parent.expression) 946 parent = parent.parent 947 948 return Dot.build(parts) 949 950 951class ColumnDef(Expression): 952 arg_types = { 953 "this": True, 954 "kind": False, 955 "constraints": False, 956 "exists": False, 957 } 958 959 960class AlterColumn(Expression): 961 arg_types = { 962 "this": True, 963 "dtype": False, 964 "collate": False, 965 "using": False, 966 "default": False, 967 "drop": False, 968 } 969 970 971class RenameTable(Expression): 972 pass 973 974 975class SetTag(Expression): 976 arg_types = {"expressions": True, "unset": False} 977 978 979class Comment(Expression): 980 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 981 982 983class ColumnConstraint(Expression): 984 arg_types = {"this": False, "kind": True} 985 986 987class ColumnConstraintKind(Expression): 988 pass 989 990 991class AutoIncrementColumnConstraint(ColumnConstraintKind): 992 pass 993 994 995class CaseSpecificColumnConstraint(ColumnConstraintKind): 996 arg_types = {"not_": True} 997 998 999class CharacterSetColumnConstraint(ColumnConstraintKind): 1000 arg_types = {"this": True} 1001 1002 1003class CheckColumnConstraint(ColumnConstraintKind): 1004 pass 1005 1006 1007class CollateColumnConstraint(ColumnConstraintKind): 1008 pass 1009 1010 1011class CommentColumnConstraint(ColumnConstraintKind): 1012 pass 1013 1014 1015class CompressColumnConstraint(ColumnConstraintKind): 1016 pass 1017 1018 1019class DateFormatColumnConstraint(ColumnConstraintKind): 1020 arg_types = {"this": True} 1021 1022 1023class DefaultColumnConstraint(ColumnConstraintKind): 1024 pass 1025 1026 1027class EncodeColumnConstraint(ColumnConstraintKind): 1028 pass 1029 1030 1031class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1032 # this: True -> ALWAYS, this: False -> BY DEFAULT 1033 arg_types = { 1034 "this": False, 1035 "start": False, 1036 "increment": False, 1037 "minvalue": False, 1038 "maxvalue": False, 1039 "cycle": False, 1040 } 1041 1042 1043class InlineLengthColumnConstraint(ColumnConstraintKind): 1044 pass 1045 1046 1047class NotNullColumnConstraint(ColumnConstraintKind): 1048 arg_types = {"allow_null": False} 1049 1050 1051class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1052 arg_types = {"desc": False} 1053 1054 1055class TitleColumnConstraint(ColumnConstraintKind): 1056 pass 1057 1058 1059class UniqueColumnConstraint(ColumnConstraintKind): 1060 arg_types: t.Dict[str, t.Any] = {} 1061 1062 1063class UppercaseColumnConstraint(ColumnConstraintKind): 1064 arg_types: t.Dict[str, t.Any] = {} 1065 1066 1067class PathColumnConstraint(ColumnConstraintKind): 1068 pass 1069 1070 1071class Constraint(Expression): 1072 arg_types = {"this": True, "expressions": True} 1073 1074 1075class Delete(Expression): 1076 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1077 1078 def delete( 1079 self, 1080 table: ExpOrStr, 1081 dialect: DialectType = None, 1082 copy: bool = True, 1083 **opts, 1084 ) -> Delete: 1085 """ 1086 Create a DELETE expression or replace the table on an existing DELETE expression. 1087 1088 Example: 1089 >>> delete("tbl").sql() 1090 'DELETE FROM tbl' 1091 1092 Args: 1093 table: the table from which to delete. 1094 dialect: the dialect used to parse the input expression. 1095 copy: if `False`, modify this expression instance in-place. 1096 opts: other options to use to parse the input expressions. 1097 1098 Returns: 1099 Delete: the modified expression. 1100 """ 1101 return _apply_builder( 1102 expression=table, 1103 instance=self, 1104 arg="this", 1105 dialect=dialect, 1106 into=Table, 1107 copy=copy, 1108 **opts, 1109 ) 1110 1111 def where( 1112 self, 1113 *expressions: ExpOrStr, 1114 append: bool = True, 1115 dialect: DialectType = None, 1116 copy: bool = True, 1117 **opts, 1118 ) -> Delete: 1119 """ 1120 Append to or set the WHERE expressions. 1121 1122 Example: 1123 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1124 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1125 1126 Args: 1127 *expressions: the SQL code strings to parse. 1128 If an `Expression` instance is passed, it will be used as-is. 1129 Multiple expressions are combined with an AND operator. 1130 append: if `True`, AND the new expressions to any existing expression. 1131 Otherwise, this resets the expression. 1132 dialect: the dialect used to parse the input expressions. 1133 copy: if `False`, modify this expression instance in-place. 1134 opts: other options to use to parse the input expressions. 1135 1136 Returns: 1137 Delete: the modified expression. 1138 """ 1139 return _apply_conjunction_builder( 1140 *expressions, 1141 instance=self, 1142 arg="where", 1143 append=append, 1144 into=Where, 1145 dialect=dialect, 1146 copy=copy, 1147 **opts, 1148 ) 1149 1150 def returning( 1151 self, 1152 expression: ExpOrStr, 1153 dialect: DialectType = None, 1154 copy: bool = True, 1155 **opts, 1156 ) -> Delete: 1157 """ 1158 Set the RETURNING expression. Not supported by all dialects. 1159 1160 Example: 1161 >>> delete("tbl").returning("*", dialect="postgres").sql() 1162 'DELETE FROM tbl RETURNING *' 1163 1164 Args: 1165 expression: the SQL code strings to parse. 1166 If an `Expression` instance is passed, it will be used as-is. 1167 dialect: the dialect used to parse the input expressions. 1168 copy: if `False`, modify this expression instance in-place. 1169 opts: other options to use to parse the input expressions. 1170 1171 Returns: 1172 Delete: the modified expression. 1173 """ 1174 return _apply_builder( 1175 expression=expression, 1176 instance=self, 1177 arg="returning", 1178 prefix="RETURNING", 1179 dialect=dialect, 1180 copy=copy, 1181 into=Returning, 1182 **opts, 1183 ) 1184 1185 1186class Drop(Expression): 1187 arg_types = { 1188 "this": False, 1189 "kind": False, 1190 "exists": False, 1191 "temporary": False, 1192 "materialized": False, 1193 "cascade": False, 1194 } 1195 1196 1197class Filter(Expression): 1198 arg_types = {"this": True, "expression": True} 1199 1200 1201class Check(Expression): 1202 pass 1203 1204 1205class Directory(Expression): 1206 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1207 arg_types = {"this": True, "local": False, "row_format": False} 1208 1209 1210class ForeignKey(Expression): 1211 arg_types = { 1212 "expressions": True, 1213 "reference": False, 1214 "delete": False, 1215 "update": False, 1216 } 1217 1218 1219class PrimaryKey(Expression): 1220 arg_types = {"expressions": True, "options": False} 1221 1222 1223class Unique(Expression): 1224 arg_types = {"expressions": True} 1225 1226 1227# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1228# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1229class Into(Expression): 1230 arg_types = {"this": True, "temporary": False, "unlogged": False} 1231 1232 1233class From(Expression): 1234 arg_types = {"expressions": True} 1235 1236 1237class Having(Expression): 1238 pass 1239 1240 1241class Hint(Expression): 1242 arg_types = {"expressions": True} 1243 1244 1245class JoinHint(Expression): 1246 arg_types = {"this": True, "expressions": True} 1247 1248 1249class Identifier(Expression): 1250 arg_types = {"this": True, "quoted": False} 1251 1252 @property 1253 def quoted(self): 1254 return bool(self.args.get("quoted")) 1255 1256 @property 1257 def hashable_args(self) -> t.Any: 1258 if self.quoted and any(char.isupper() for char in self.this): 1259 return (self.this, self.quoted) 1260 return self.this.lower() 1261 1262 @property 1263 def output_name(self): 1264 return self.name 1265 1266 1267class Index(Expression): 1268 arg_types = { 1269 "this": False, 1270 "table": False, 1271 "where": False, 1272 "columns": False, 1273 "unique": False, 1274 "primary": False, 1275 "amp": False, # teradata 1276 } 1277 1278 1279class Insert(Expression): 1280 arg_types = { 1281 "with": False, 1282 "this": True, 1283 "expression": False, 1284 "returning": False, 1285 "overwrite": False, 1286 "exists": False, 1287 "partition": False, 1288 "alternative": False, 1289 } 1290 1291 1292class Returning(Expression): 1293 arg_types = {"expressions": True} 1294 1295 1296# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1297class Introducer(Expression): 1298 arg_types = {"this": True, "expression": True} 1299 1300 1301# national char, like n'utf8' 1302class National(Expression): 1303 pass 1304 1305 1306class LoadData(Expression): 1307 arg_types = { 1308 "this": True, 1309 "local": False, 1310 "overwrite": False, 1311 "inpath": True, 1312 "partition": False, 1313 "input_format": False, 1314 "serde": False, 1315 } 1316 1317 1318class Partition(Expression): 1319 arg_types = {"expressions": True} 1320 1321 1322class Fetch(Expression): 1323 arg_types = {"direction": False, "count": False} 1324 1325 1326class Group(Expression): 1327 arg_types = { 1328 "expressions": False, 1329 "grouping_sets": False, 1330 "cube": False, 1331 "rollup": False, 1332 } 1333 1334 1335class Lambda(Expression): 1336 arg_types = {"this": True, "expressions": True} 1337 1338 1339class Limit(Expression): 1340 arg_types = {"this": False, "expression": True} 1341 1342 1343class Literal(Condition): 1344 arg_types = {"this": True, "is_string": True} 1345 1346 @property 1347 def hashable_args(self) -> t.Any: 1348 return (self.this, self.args.get("is_string")) 1349 1350 @classmethod 1351 def number(cls, number) -> Literal: 1352 return cls(this=str(number), is_string=False) 1353 1354 @classmethod 1355 def string(cls, string) -> Literal: 1356 return cls(this=str(string), is_string=True) 1357 1358 @property 1359 def output_name(self): 1360 return self.name 1361 1362 1363class Join(Expression): 1364 arg_types = { 1365 "this": True, 1366 "on": False, 1367 "side": False, 1368 "kind": False, 1369 "using": False, 1370 "natural": False, 1371 } 1372 1373 @property 1374 def kind(self): 1375 return self.text("kind").upper() 1376 1377 @property 1378 def side(self): 1379 return self.text("side").upper() 1380 1381 @property 1382 def alias_or_name(self): 1383 return self.this.alias_or_name 1384 1385 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1386 """ 1387 Append to or set the ON expressions. 1388 1389 Example: 1390 >>> import sqlglot 1391 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1392 'JOIN x ON y = 1' 1393 1394 Args: 1395 *expressions (str | Expression): the SQL code strings to parse. 1396 If an `Expression` instance is passed, it will be used as-is. 1397 Multiple expressions are combined with an AND operator. 1398 append (bool): if `True`, AND the new expressions to any existing expression. 1399 Otherwise, this resets the expression. 1400 dialect (str): the dialect used to parse the input expressions. 1401 copy (bool): if `False`, modify this expression instance in-place. 1402 opts (kwargs): other options to use to parse the input expressions. 1403 1404 Returns: 1405 Join: the modified join expression. 1406 """ 1407 join = _apply_conjunction_builder( 1408 *expressions, 1409 instance=self, 1410 arg="on", 1411 append=append, 1412 dialect=dialect, 1413 copy=copy, 1414 **opts, 1415 ) 1416 1417 if join.kind == "CROSS": 1418 join.set("kind", None) 1419 1420 return join 1421 1422 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1423 """ 1424 Append to or set the USING expressions. 1425 1426 Example: 1427 >>> import sqlglot 1428 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1429 'JOIN x USING (foo, bla)' 1430 1431 Args: 1432 *expressions (str | Expression): the SQL code strings to parse. 1433 If an `Expression` instance is passed, it will be used as-is. 1434 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1435 Otherwise, this resets the expression. 1436 dialect (str): the dialect used to parse the input expressions. 1437 copy (bool): if `False`, modify this expression instance in-place. 1438 opts (kwargs): other options to use to parse the input expressions. 1439 1440 Returns: 1441 Join: the modified join expression. 1442 """ 1443 join = _apply_list_builder( 1444 *expressions, 1445 instance=self, 1446 arg="using", 1447 append=append, 1448 dialect=dialect, 1449 copy=copy, 1450 **opts, 1451 ) 1452 1453 if join.kind == "CROSS": 1454 join.set("kind", None) 1455 1456 return join 1457 1458 1459class Lateral(UDTF): 1460 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1461 1462 1463class MatchRecognize(Expression): 1464 arg_types = { 1465 "partition_by": False, 1466 "order": False, 1467 "measures": False, 1468 "rows": False, 1469 "after": False, 1470 "pattern": False, 1471 "define": False, 1472 } 1473 1474 1475# Clickhouse FROM FINAL modifier 1476# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1477class Final(Expression): 1478 pass 1479 1480 1481class Offset(Expression): 1482 arg_types = {"this": False, "expression": True} 1483 1484 1485class Order(Expression): 1486 arg_types = {"this": False, "expressions": True} 1487 1488 1489# hive specific sorts 1490# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1491class Cluster(Order): 1492 pass 1493 1494 1495class Distribute(Order): 1496 pass 1497 1498 1499class Sort(Order): 1500 pass 1501 1502 1503class Ordered(Expression): 1504 arg_types = {"this": True, "desc": True, "nulls_first": True} 1505 1506 1507class Property(Expression): 1508 arg_types = {"this": True, "value": True} 1509 1510 1511class AfterJournalProperty(Property): 1512 arg_types = {"no": True, "dual": False, "local": False} 1513 1514 1515class AlgorithmProperty(Property): 1516 arg_types = {"this": True} 1517 1518 1519class AutoIncrementProperty(Property): 1520 arg_types = {"this": True} 1521 1522 1523class BlockCompressionProperty(Property): 1524 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1525 1526 1527class CharacterSetProperty(Property): 1528 arg_types = {"this": True, "default": True} 1529 1530 1531class ChecksumProperty(Property): 1532 arg_types = {"on": False, "default": False} 1533 1534 1535class CollateProperty(Property): 1536 arg_types = {"this": True} 1537 1538 1539class DataBlocksizeProperty(Property): 1540 arg_types = {"size": False, "units": False, "min": False, "default": False} 1541 1542 1543class DefinerProperty(Property): 1544 arg_types = {"this": True} 1545 1546 1547class DistKeyProperty(Property): 1548 arg_types = {"this": True} 1549 1550 1551class DistStyleProperty(Property): 1552 arg_types = {"this": True} 1553 1554 1555class EngineProperty(Property): 1556 arg_types = {"this": True} 1557 1558 1559class ExecuteAsProperty(Property): 1560 arg_types = {"this": True} 1561 1562 1563class ExternalProperty(Property): 1564 arg_types = {"this": False} 1565 1566 1567class FallbackProperty(Property): 1568 arg_types = {"no": True, "protection": False} 1569 1570 1571class FileFormatProperty(Property): 1572 arg_types = {"this": True} 1573 1574 1575class FreespaceProperty(Property): 1576 arg_types = {"this": True, "percent": False} 1577 1578 1579class IsolatedLoadingProperty(Property): 1580 arg_types = { 1581 "no": True, 1582 "concurrent": True, 1583 "for_all": True, 1584 "for_insert": True, 1585 "for_none": True, 1586 } 1587 1588 1589class JournalProperty(Property): 1590 arg_types = {"no": True, "dual": False, "before": False} 1591 1592 1593class LanguageProperty(Property): 1594 arg_types = {"this": True} 1595 1596 1597class LikeProperty(Property): 1598 arg_types = {"this": True, "expressions": False} 1599 1600 1601class LocationProperty(Property): 1602 arg_types = {"this": True} 1603 1604 1605class LockingProperty(Property): 1606 arg_types = { 1607 "this": False, 1608 "kind": True, 1609 "for_or_in": True, 1610 "lock_type": True, 1611 "override": False, 1612 } 1613 1614 1615class LogProperty(Property): 1616 arg_types = {"no": True} 1617 1618 1619class MaterializedProperty(Property): 1620 arg_types = {"this": False} 1621 1622 1623class MergeBlockRatioProperty(Property): 1624 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1625 1626 1627class NoPrimaryIndexProperty(Property): 1628 arg_types = {"this": False} 1629 1630 1631class OnCommitProperty(Property): 1632 arg_type = {"this": False} 1633 1634 1635class PartitionedByProperty(Property): 1636 arg_types = {"this": True} 1637 1638 1639class ReturnsProperty(Property): 1640 arg_types = {"this": True, "is_table": False, "table": False} 1641 1642 1643class RowFormatDelimitedProperty(Property): 1644 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1645 arg_types = { 1646 "fields": False, 1647 "escaped": False, 1648 "collection_items": False, 1649 "map_keys": False, 1650 "lines": False, 1651 "null": False, 1652 "serde": False, 1653 } 1654 1655 1656class RowFormatSerdeProperty(Property): 1657 arg_types = {"this": True} 1658 1659 1660class SchemaCommentProperty(Property): 1661 arg_types = {"this": True} 1662 1663 1664class SerdeProperties(Property): 1665 arg_types = {"expressions": True} 1666 1667 1668class SetProperty(Property): 1669 arg_types = {"multi": True} 1670 1671 1672class SortKeyProperty(Property): 1673 arg_types = {"this": True, "compound": False} 1674 1675 1676class SqlSecurityProperty(Property): 1677 arg_types = {"definer": True} 1678 1679 1680class TableFormatProperty(Property): 1681 arg_types = {"this": True} 1682 1683 1684class TemporaryProperty(Property): 1685 arg_types = {"global_": True} 1686 1687 1688class TransientProperty(Property): 1689 arg_types = {"this": False} 1690 1691 1692class VolatilityProperty(Property): 1693 arg_types = {"this": True} 1694 1695 1696class WithDataProperty(Property): 1697 arg_types = {"no": True, "statistics": False} 1698 1699 1700class WithJournalTableProperty(Property): 1701 arg_types = {"this": True} 1702 1703 1704class Properties(Expression): 1705 arg_types = {"expressions": True} 1706 1707 NAME_TO_PROPERTY = { 1708 "ALGORITHM": AlgorithmProperty, 1709 "AUTO_INCREMENT": AutoIncrementProperty, 1710 "CHARACTER SET": CharacterSetProperty, 1711 "COLLATE": CollateProperty, 1712 "COMMENT": SchemaCommentProperty, 1713 "DEFINER": DefinerProperty, 1714 "DISTKEY": DistKeyProperty, 1715 "DISTSTYLE": DistStyleProperty, 1716 "ENGINE": EngineProperty, 1717 "EXECUTE AS": ExecuteAsProperty, 1718 "FORMAT": FileFormatProperty, 1719 "LANGUAGE": LanguageProperty, 1720 "LOCATION": LocationProperty, 1721 "PARTITIONED_BY": PartitionedByProperty, 1722 "RETURNS": ReturnsProperty, 1723 "SORTKEY": SortKeyProperty, 1724 "TABLE_FORMAT": TableFormatProperty, 1725 } 1726 1727 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1728 1729 # CREATE property locations 1730 # Form: schema specified 1731 # create [POST_CREATE] 1732 # table a [POST_NAME] 1733 # (b int) [POST_SCHEMA] 1734 # with ([POST_WITH]) 1735 # index (b) [POST_INDEX] 1736 # 1737 # Form: alias selection 1738 # create [POST_CREATE] 1739 # table a [POST_NAME] 1740 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1741 # index (c) [POST_INDEX] 1742 class Location(AutoName): 1743 POST_CREATE = auto() 1744 POST_NAME = auto() 1745 POST_SCHEMA = auto() 1746 POST_WITH = auto() 1747 POST_ALIAS = auto() 1748 POST_EXPRESSION = auto() 1749 POST_INDEX = auto() 1750 UNSUPPORTED = auto() 1751 1752 @classmethod 1753 def from_dict(cls, properties_dict) -> Properties: 1754 expressions = [] 1755 for key, value in properties_dict.items(): 1756 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1757 if property_cls: 1758 expressions.append(property_cls(this=convert(value))) 1759 else: 1760 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1761 1762 return cls(expressions=expressions) 1763 1764 1765class Qualify(Expression): 1766 pass 1767 1768 1769# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 1770class Return(Expression): 1771 pass 1772 1773 1774class Reference(Expression): 1775 arg_types = {"this": True, "expressions": False, "options": False} 1776 1777 1778class Tuple(Expression): 1779 arg_types = {"expressions": False} 1780 1781 1782class Subqueryable(Unionable): 1783 def subquery(self, alias=None, copy=True) -> Subquery: 1784 """ 1785 Convert this expression to an aliased expression that can be used as a Subquery. 1786 1787 Example: 1788 >>> subquery = Select().select("x").from_("tbl").subquery() 1789 >>> Select().select("x").from_(subquery).sql() 1790 'SELECT x FROM (SELECT x FROM tbl)' 1791 1792 Args: 1793 alias (str | Identifier): an optional alias for the subquery 1794 copy (bool): if `False`, modify this expression instance in-place. 1795 1796 Returns: 1797 Alias: the subquery 1798 """ 1799 instance = _maybe_copy(self, copy) 1800 return Subquery( 1801 this=instance, 1802 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1803 ) 1804 1805 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1806 raise NotImplementedError 1807 1808 @property 1809 def ctes(self): 1810 with_ = self.args.get("with") 1811 if not with_: 1812 return [] 1813 return with_.expressions 1814 1815 @property 1816 def selects(self): 1817 raise NotImplementedError("Subqueryable objects must implement `selects`") 1818 1819 @property 1820 def named_selects(self): 1821 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1822 1823 def with_( 1824 self, 1825 alias, 1826 as_, 1827 recursive=None, 1828 append=True, 1829 dialect=None, 1830 copy=True, 1831 **opts, 1832 ): 1833 """ 1834 Append to or set the common table expressions. 1835 1836 Example: 1837 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1838 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1839 1840 Args: 1841 alias (str | Expression): the SQL code string to parse as the table name. 1842 If an `Expression` instance is passed, this is used as-is. 1843 as_ (str | Expression): the SQL code string to parse as the table expression. 1844 If an `Expression` instance is passed, it will be used as-is. 1845 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1846 append (bool): if `True`, add to any existing expressions. 1847 Otherwise, this resets the expressions. 1848 dialect (str): the dialect used to parse the input expression. 1849 copy (bool): if `False`, modify this expression instance in-place. 1850 opts (kwargs): other options to use to parse the input expressions. 1851 1852 Returns: 1853 Select: the modified expression. 1854 """ 1855 alias_expression = maybe_parse( 1856 alias, 1857 dialect=dialect, 1858 into=TableAlias, 1859 **opts, 1860 ) 1861 as_expression = maybe_parse( 1862 as_, 1863 dialect=dialect, 1864 **opts, 1865 ) 1866 cte = CTE( 1867 this=as_expression, 1868 alias=alias_expression, 1869 ) 1870 return _apply_child_list_builder( 1871 cte, 1872 instance=self, 1873 arg="with", 1874 append=append, 1875 copy=copy, 1876 into=With, 1877 properties={"recursive": recursive or False}, 1878 ) 1879 1880 1881QUERY_MODIFIERS = { 1882 "match": False, 1883 "laterals": False, 1884 "joins": False, 1885 "pivots": False, 1886 "where": False, 1887 "group": False, 1888 "having": False, 1889 "qualify": False, 1890 "windows": False, 1891 "distribute": False, 1892 "sort": False, 1893 "cluster": False, 1894 "order": False, 1895 "limit": False, 1896 "offset": False, 1897 "lock": False, 1898 "sample": False, 1899} 1900 1901 1902class Table(Expression): 1903 arg_types = { 1904 "this": True, 1905 "alias": False, 1906 "db": False, 1907 "catalog": False, 1908 "laterals": False, 1909 "joins": False, 1910 "pivots": False, 1911 "hints": False, 1912 "system_time": False, 1913 } 1914 1915 @property 1916 def db(self) -> str: 1917 return self.text("db") 1918 1919 @property 1920 def catalog(self) -> str: 1921 return self.text("catalog") 1922 1923 1924# See the TSQL "Querying data in a system-versioned temporal table" page 1925class SystemTime(Expression): 1926 arg_types = { 1927 "this": False, 1928 "expression": False, 1929 "kind": True, 1930 } 1931 1932 1933class Union(Subqueryable): 1934 arg_types = { 1935 "with": False, 1936 "this": True, 1937 "expression": True, 1938 "distinct": False, 1939 **QUERY_MODIFIERS, 1940 } 1941 1942 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1943 """ 1944 Set the LIMIT expression. 1945 1946 Example: 1947 >>> select("1").union(select("1")).limit(1).sql() 1948 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1949 1950 Args: 1951 expression (str | int | Expression): the SQL code string to parse. 1952 This can also be an integer. 1953 If a `Limit` instance is passed, this is used as-is. 1954 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1955 dialect (str): the dialect used to parse the input expression. 1956 copy (bool): if `False`, modify this expression instance in-place. 1957 opts (kwargs): other options to use to parse the input expressions. 1958 1959 Returns: 1960 Select: The limited subqueryable. 1961 """ 1962 return ( 1963 select("*") 1964 .from_(self.subquery(alias="_l_0", copy=copy)) 1965 .limit(expression, dialect=dialect, copy=False, **opts) 1966 ) 1967 1968 def select( 1969 self, 1970 *expressions: ExpOrStr, 1971 append: bool = True, 1972 dialect: DialectType = None, 1973 copy: bool = True, 1974 **opts, 1975 ) -> Union: 1976 """Append to or set the SELECT of the union recursively. 1977 1978 Example: 1979 >>> from sqlglot import parse_one 1980 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1981 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1982 1983 Args: 1984 *expressions: the SQL code strings to parse. 1985 If an `Expression` instance is passed, it will be used as-is. 1986 append: if `True`, add to any existing expressions. 1987 Otherwise, this resets the expressions. 1988 dialect: the dialect used to parse the input expressions. 1989 copy: if `False`, modify this expression instance in-place. 1990 opts: other options to use to parse the input expressions. 1991 1992 Returns: 1993 Union: the modified expression. 1994 """ 1995 this = self.copy() if copy else self 1996 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1997 this.expression.unnest().select( 1998 *expressions, append=append, dialect=dialect, copy=False, **opts 1999 ) 2000 return this 2001 2002 @property 2003 def named_selects(self): 2004 return self.this.unnest().named_selects 2005 2006 @property 2007 def is_star(self) -> bool: 2008 return self.this.is_star or self.expression.is_star 2009 2010 @property 2011 def selects(self): 2012 return self.this.unnest().selects 2013 2014 @property 2015 def left(self): 2016 return self.this 2017 2018 @property 2019 def right(self): 2020 return self.expression 2021 2022 2023class Except(Union): 2024 pass 2025 2026 2027class Intersect(Union): 2028 pass 2029 2030 2031class Unnest(UDTF): 2032 arg_types = { 2033 "expressions": True, 2034 "ordinality": False, 2035 "alias": False, 2036 "offset": False, 2037 } 2038 2039 2040class Update(Expression): 2041 arg_types = { 2042 "with": False, 2043 "this": False, 2044 "expressions": True, 2045 "from": False, 2046 "where": False, 2047 "returning": False, 2048 } 2049 2050 2051class Values(UDTF): 2052 arg_types = { 2053 "expressions": True, 2054 "ordinality": False, 2055 "alias": False, 2056 } 2057 2058 2059class Var(Expression): 2060 pass 2061 2062 2063class Schema(Expression): 2064 arg_types = {"this": False, "expressions": False} 2065 2066 2067# Used to represent the FOR UPDATE and FOR SHARE locking read types. 2068# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html 2069class Lock(Expression): 2070 arg_types = {"update": True} 2071 2072 2073class Select(Subqueryable): 2074 arg_types = { 2075 "with": False, 2076 "kind": False, 2077 "expressions": False, 2078 "hint": False, 2079 "distinct": False, 2080 "into": False, 2081 "from": False, 2082 **QUERY_MODIFIERS, 2083 } 2084 2085 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2086 """ 2087 Set the FROM expression. 2088 2089 Example: 2090 >>> Select().from_("tbl").select("x").sql() 2091 'SELECT x FROM tbl' 2092 2093 Args: 2094 *expressions (str | Expression): the SQL code strings to parse. 2095 If a `From` instance is passed, this is used as-is. 2096 If another `Expression` instance is passed, it will be wrapped in a `From`. 2097 append (bool): if `True`, add to any existing expressions. 2098 Otherwise, this flattens all the `From` expression into a single expression. 2099 dialect (str): the dialect used to parse the input expression. 2100 copy (bool): if `False`, modify this expression instance in-place. 2101 opts (kwargs): other options to use to parse the input expressions. 2102 2103 Returns: 2104 Select: the modified expression. 2105 """ 2106 return _apply_child_list_builder( 2107 *expressions, 2108 instance=self, 2109 arg="from", 2110 append=append, 2111 copy=copy, 2112 prefix="FROM", 2113 into=From, 2114 dialect=dialect, 2115 **opts, 2116 ) 2117 2118 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2119 """ 2120 Set the GROUP BY expression. 2121 2122 Example: 2123 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2124 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2125 2126 Args: 2127 *expressions (str | Expression): the SQL code strings to parse. 2128 If a `Group` instance is passed, this is used as-is. 2129 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2130 If nothing is passed in then a group by is not applied to the expression 2131 append (bool): if `True`, add to any existing expressions. 2132 Otherwise, this flattens all the `Group` expression into a single expression. 2133 dialect (str): the dialect used to parse the input expression. 2134 copy (bool): if `False`, modify this expression instance in-place. 2135 opts (kwargs): other options to use to parse the input expressions. 2136 2137 Returns: 2138 Select: the modified expression. 2139 """ 2140 if not expressions: 2141 return self if not copy else self.copy() 2142 return _apply_child_list_builder( 2143 *expressions, 2144 instance=self, 2145 arg="group", 2146 append=append, 2147 copy=copy, 2148 prefix="GROUP BY", 2149 into=Group, 2150 dialect=dialect, 2151 **opts, 2152 ) 2153 2154 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2155 """ 2156 Set the ORDER BY expression. 2157 2158 Example: 2159 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2160 'SELECT x FROM tbl ORDER BY x DESC' 2161 2162 Args: 2163 *expressions (str | Expression): the SQL code strings to parse. 2164 If a `Group` instance is passed, this is used as-is. 2165 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2166 append (bool): if `True`, add to any existing expressions. 2167 Otherwise, this flattens all the `Order` expression into a single expression. 2168 dialect (str): the dialect used to parse the input expression. 2169 copy (bool): if `False`, modify this expression instance in-place. 2170 opts (kwargs): other options to use to parse the input expressions. 2171 2172 Returns: 2173 Select: the modified expression. 2174 """ 2175 return _apply_child_list_builder( 2176 *expressions, 2177 instance=self, 2178 arg="order", 2179 append=append, 2180 copy=copy, 2181 prefix="ORDER BY", 2182 into=Order, 2183 dialect=dialect, 2184 **opts, 2185 ) 2186 2187 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2188 """ 2189 Set the SORT BY expression. 2190 2191 Example: 2192 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2193 'SELECT x FROM tbl SORT BY x DESC' 2194 2195 Args: 2196 *expressions (str | Expression): the SQL code strings to parse. 2197 If a `Group` instance is passed, this is used as-is. 2198 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2199 append (bool): if `True`, add to any existing expressions. 2200 Otherwise, this flattens all the `Order` expression into a single expression. 2201 dialect (str): the dialect used to parse the input expression. 2202 copy (bool): if `False`, modify this expression instance in-place. 2203 opts (kwargs): other options to use to parse the input expressions. 2204 2205 Returns: 2206 Select: the modified expression. 2207 """ 2208 return _apply_child_list_builder( 2209 *expressions, 2210 instance=self, 2211 arg="sort", 2212 append=append, 2213 copy=copy, 2214 prefix="SORT BY", 2215 into=Sort, 2216 dialect=dialect, 2217 **opts, 2218 ) 2219 2220 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2221 """ 2222 Set the CLUSTER BY expression. 2223 2224 Example: 2225 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2226 'SELECT x FROM tbl CLUSTER BY x DESC' 2227 2228 Args: 2229 *expressions (str | Expression): the SQL code strings to parse. 2230 If a `Group` instance is passed, this is used as-is. 2231 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2232 append (bool): if `True`, add to any existing expressions. 2233 Otherwise, this flattens all the `Order` expression into a single expression. 2234 dialect (str): the dialect used to parse the input expression. 2235 copy (bool): if `False`, modify this expression instance in-place. 2236 opts (kwargs): other options to use to parse the input expressions. 2237 2238 Returns: 2239 Select: the modified expression. 2240 """ 2241 return _apply_child_list_builder( 2242 *expressions, 2243 instance=self, 2244 arg="cluster", 2245 append=append, 2246 copy=copy, 2247 prefix="CLUSTER BY", 2248 into=Cluster, 2249 dialect=dialect, 2250 **opts, 2251 ) 2252 2253 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2254 """ 2255 Set the LIMIT expression. 2256 2257 Example: 2258 >>> Select().from_("tbl").select("x").limit(10).sql() 2259 'SELECT x FROM tbl LIMIT 10' 2260 2261 Args: 2262 expression (str | int | Expression): the SQL code string to parse. 2263 This can also be an integer. 2264 If a `Limit` instance is passed, this is used as-is. 2265 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2266 dialect (str): the dialect used to parse the input expression. 2267 copy (bool): if `False`, modify this expression instance in-place. 2268 opts (kwargs): other options to use to parse the input expressions. 2269 2270 Returns: 2271 Select: the modified expression. 2272 """ 2273 return _apply_builder( 2274 expression=expression, 2275 instance=self, 2276 arg="limit", 2277 into=Limit, 2278 prefix="LIMIT", 2279 dialect=dialect, 2280 copy=copy, 2281 **opts, 2282 ) 2283 2284 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2285 """ 2286 Set the OFFSET expression. 2287 2288 Example: 2289 >>> Select().from_("tbl").select("x").offset(10).sql() 2290 'SELECT x FROM tbl OFFSET 10' 2291 2292 Args: 2293 expression (str | int | Expression): the SQL code string to parse. 2294 This can also be an integer. 2295 If a `Offset` instance is passed, this is used as-is. 2296 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2297 dialect (str): the dialect used to parse the input expression. 2298 copy (bool): if `False`, modify this expression instance in-place. 2299 opts (kwargs): other options to use to parse the input expressions. 2300 2301 Returns: 2302 Select: the modified expression. 2303 """ 2304 return _apply_builder( 2305 expression=expression, 2306 instance=self, 2307 arg="offset", 2308 into=Offset, 2309 prefix="OFFSET", 2310 dialect=dialect, 2311 copy=copy, 2312 **opts, 2313 ) 2314 2315 def select( 2316 self, 2317 *expressions: ExpOrStr, 2318 append: bool = True, 2319 dialect: DialectType = None, 2320 copy: bool = True, 2321 **opts, 2322 ) -> Select: 2323 """ 2324 Append to or set the SELECT expressions. 2325 2326 Example: 2327 >>> Select().select("x", "y").sql() 2328 'SELECT x, y' 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 Select: the modified expression. 2341 """ 2342 return _apply_list_builder( 2343 *expressions, 2344 instance=self, 2345 arg="expressions", 2346 append=append, 2347 dialect=dialect, 2348 copy=copy, 2349 **opts, 2350 ) 2351 2352 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2353 """ 2354 Append to or set the LATERAL expressions. 2355 2356 Example: 2357 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2358 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2359 2360 Args: 2361 *expressions (str | Expression): the SQL code strings to parse. 2362 If an `Expression` instance is passed, it will be used as-is. 2363 append (bool): if `True`, add to any existing expressions. 2364 Otherwise, this resets the expressions. 2365 dialect (str): the dialect used to parse the input expressions. 2366 copy (bool): if `False`, modify this expression instance in-place. 2367 opts (kwargs): other options to use to parse the input expressions. 2368 2369 Returns: 2370 Select: the modified expression. 2371 """ 2372 return _apply_list_builder( 2373 *expressions, 2374 instance=self, 2375 arg="laterals", 2376 append=append, 2377 into=Lateral, 2378 prefix="LATERAL VIEW", 2379 dialect=dialect, 2380 copy=copy, 2381 **opts, 2382 ) 2383 2384 def join( 2385 self, 2386 expression, 2387 on=None, 2388 using=None, 2389 append=True, 2390 join_type=None, 2391 join_alias=None, 2392 dialect=None, 2393 copy=True, 2394 **opts, 2395 ) -> Select: 2396 """ 2397 Append to or set the JOIN expressions. 2398 2399 Example: 2400 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2401 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2402 2403 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2404 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2405 2406 Use `join_type` to change the type of join: 2407 2408 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2409 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2410 2411 Args: 2412 expression (str | Expression): the SQL code string to parse. 2413 If an `Expression` instance is passed, it will be used as-is. 2414 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2415 If an `Expression` instance is passed, it will be used as-is. 2416 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2417 If an `Expression` instance is passed, it will be used as-is. 2418 append (bool): if `True`, add to any existing expressions. 2419 Otherwise, this resets the expressions. 2420 join_type (str): If set, alter the parsed join type 2421 dialect (str): the dialect used to parse the input expressions. 2422 copy (bool): if `False`, modify this expression instance in-place. 2423 opts (kwargs): other options to use to parse the input expressions. 2424 2425 Returns: 2426 Select: the modified expression. 2427 """ 2428 parse_args = {"dialect": dialect, **opts} 2429 2430 try: 2431 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2432 except ParseError: 2433 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2434 2435 join = expression if isinstance(expression, Join) else Join(this=expression) 2436 2437 if isinstance(join.this, Select): 2438 join.this.replace(join.this.subquery()) 2439 2440 if join_type: 2441 natural: t.Optional[Token] 2442 side: t.Optional[Token] 2443 kind: t.Optional[Token] 2444 2445 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2446 2447 if natural: 2448 join.set("natural", True) 2449 if side: 2450 join.set("side", side.text) 2451 if kind: 2452 join.set("kind", kind.text) 2453 2454 if on: 2455 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2456 join.set("on", on) 2457 2458 if using: 2459 join = _apply_list_builder( 2460 *ensure_collection(using), 2461 instance=join, 2462 arg="using", 2463 append=append, 2464 copy=copy, 2465 **opts, 2466 ) 2467 2468 if join_alias: 2469 join.set("this", alias_(join.this, join_alias, table=True)) 2470 return _apply_list_builder( 2471 join, 2472 instance=self, 2473 arg="joins", 2474 append=append, 2475 copy=copy, 2476 **opts, 2477 ) 2478 2479 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2480 """ 2481 Append to or set the WHERE expressions. 2482 2483 Example: 2484 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2485 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2486 2487 Args: 2488 *expressions (str | Expression): the SQL code strings to parse. 2489 If an `Expression` instance is passed, it will be used as-is. 2490 Multiple expressions are combined with an AND operator. 2491 append (bool): if `True`, AND the new expressions to any existing expression. 2492 Otherwise, this resets the expression. 2493 dialect (str): the dialect used to parse the input expressions. 2494 copy (bool): if `False`, modify this expression instance in-place. 2495 opts (kwargs): other options to use to parse the input expressions. 2496 2497 Returns: 2498 Select: the modified expression. 2499 """ 2500 return _apply_conjunction_builder( 2501 *expressions, 2502 instance=self, 2503 arg="where", 2504 append=append, 2505 into=Where, 2506 dialect=dialect, 2507 copy=copy, 2508 **opts, 2509 ) 2510 2511 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2512 """ 2513 Append to or set the HAVING expressions. 2514 2515 Example: 2516 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2517 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2518 2519 Args: 2520 *expressions (str | Expression): the SQL code strings to parse. 2521 If an `Expression` instance is passed, it will be used as-is. 2522 Multiple expressions are combined with an AND operator. 2523 append (bool): if `True`, AND the new expressions to any existing expression. 2524 Otherwise, this resets the expression. 2525 dialect (str): the dialect used to parse the input expressions. 2526 copy (bool): if `False`, modify this expression instance in-place. 2527 opts (kwargs): other options to use to parse the input expressions. 2528 2529 Returns: 2530 Select: the modified expression. 2531 """ 2532 return _apply_conjunction_builder( 2533 *expressions, 2534 instance=self, 2535 arg="having", 2536 append=append, 2537 into=Having, 2538 dialect=dialect, 2539 copy=copy, 2540 **opts, 2541 ) 2542 2543 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2544 return _apply_list_builder( 2545 *expressions, 2546 instance=self, 2547 arg="windows", 2548 append=append, 2549 into=Window, 2550 dialect=dialect, 2551 copy=copy, 2552 **opts, 2553 ) 2554 2555 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2556 return _apply_conjunction_builder( 2557 *expressions, 2558 instance=self, 2559 arg="qualify", 2560 append=append, 2561 into=Qualify, 2562 dialect=dialect, 2563 copy=copy, 2564 **opts, 2565 ) 2566 2567 def distinct(self, distinct=True, copy=True) -> Select: 2568 """ 2569 Set the OFFSET expression. 2570 2571 Example: 2572 >>> Select().from_("tbl").select("x").distinct().sql() 2573 'SELECT DISTINCT x FROM tbl' 2574 2575 Args: 2576 distinct (bool): whether the Select should be distinct 2577 copy (bool): if `False`, modify this expression instance in-place. 2578 2579 Returns: 2580 Select: the modified expression. 2581 """ 2582 instance = _maybe_copy(self, copy) 2583 instance.set("distinct", Distinct() if distinct else None) 2584 return instance 2585 2586 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2587 """ 2588 Convert this expression to a CREATE TABLE AS statement. 2589 2590 Example: 2591 >>> Select().select("*").from_("tbl").ctas("x").sql() 2592 'CREATE TABLE x AS SELECT * FROM tbl' 2593 2594 Args: 2595 table (str | Expression): the SQL code string to parse as the table name. 2596 If another `Expression` instance is passed, it will be used as-is. 2597 properties (dict): an optional mapping of table properties 2598 dialect (str): the dialect used to parse the input table. 2599 copy (bool): if `False`, modify this expression instance in-place. 2600 opts (kwargs): other options to use to parse the input table. 2601 2602 Returns: 2603 Create: the CREATE TABLE AS expression 2604 """ 2605 instance = _maybe_copy(self, copy) 2606 table_expression = maybe_parse( 2607 table, 2608 into=Table, 2609 dialect=dialect, 2610 **opts, 2611 ) 2612 properties_expression = None 2613 if properties: 2614 properties_expression = Properties.from_dict(properties) 2615 2616 return Create( 2617 this=table_expression, 2618 kind="table", 2619 expression=instance, 2620 properties=properties_expression, 2621 ) 2622 2623 def lock(self, update: bool = True, copy: bool = True) -> Select: 2624 """ 2625 Set the locking read mode for this expression. 2626 2627 Examples: 2628 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2629 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2630 2631 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2632 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2633 2634 Args: 2635 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2636 copy: if `False`, modify this expression instance in-place. 2637 2638 Returns: 2639 The modified expression. 2640 """ 2641 2642 inst = _maybe_copy(self, copy) 2643 inst.set("lock", Lock(update=update)) 2644 2645 return inst 2646 2647 @property 2648 def named_selects(self) -> t.List[str]: 2649 return [e.output_name for e in self.expressions if e.alias_or_name] 2650 2651 @property 2652 def is_star(self) -> bool: 2653 return any(expression.is_star for expression in self.expressions) 2654 2655 @property 2656 def selects(self) -> t.List[Expression]: 2657 return self.expressions 2658 2659 2660class Subquery(DerivedTable, Unionable): 2661 arg_types = { 2662 "this": True, 2663 "alias": False, 2664 "with": False, 2665 **QUERY_MODIFIERS, 2666 } 2667 2668 def unnest(self): 2669 """ 2670 Returns the first non subquery. 2671 """ 2672 expression = self 2673 while isinstance(expression, Subquery): 2674 expression = expression.this 2675 return expression 2676 2677 @property 2678 def is_star(self) -> bool: 2679 return self.this.is_star 2680 2681 @property 2682 def output_name(self): 2683 return self.alias 2684 2685 2686class TableSample(Expression): 2687 arg_types = { 2688 "this": False, 2689 "method": False, 2690 "bucket_numerator": False, 2691 "bucket_denominator": False, 2692 "bucket_field": False, 2693 "percent": False, 2694 "rows": False, 2695 "size": False, 2696 "seed": False, 2697 "kind": False, 2698 } 2699 2700 2701class Tag(Expression): 2702 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2703 2704 arg_types = { 2705 "this": False, 2706 "prefix": False, 2707 "postfix": False, 2708 } 2709 2710 2711class Pivot(Expression): 2712 arg_types = { 2713 "this": False, 2714 "alias": False, 2715 "expressions": True, 2716 "field": True, 2717 "unpivot": True, 2718 } 2719 2720 2721class Window(Expression): 2722 arg_types = { 2723 "this": True, 2724 "partition_by": False, 2725 "order": False, 2726 "spec": False, 2727 "alias": False, 2728 } 2729 2730 2731class WindowSpec(Expression): 2732 arg_types = { 2733 "kind": False, 2734 "start": False, 2735 "start_side": False, 2736 "end": False, 2737 "end_side": False, 2738 } 2739 2740 2741class Where(Expression): 2742 pass 2743 2744 2745class Star(Expression): 2746 arg_types = {"except": False, "replace": False} 2747 2748 @property 2749 def name(self) -> str: 2750 return "*" 2751 2752 @property 2753 def output_name(self): 2754 return self.name 2755 2756 2757class Parameter(Expression): 2758 arg_types = {"this": True, "wrapped": False} 2759 2760 2761class SessionParameter(Expression): 2762 arg_types = {"this": True, "kind": False} 2763 2764 2765class Placeholder(Expression): 2766 arg_types = {"this": False} 2767 2768 2769class Null(Condition): 2770 arg_types: t.Dict[str, t.Any] = {} 2771 2772 @property 2773 def name(self) -> str: 2774 return "NULL" 2775 2776 2777class Boolean(Condition): 2778 pass 2779 2780 2781class DataType(Expression): 2782 arg_types = { 2783 "this": True, 2784 "expressions": False, 2785 "nested": False, 2786 "values": False, 2787 "prefix": False, 2788 } 2789 2790 class Type(AutoName): 2791 CHAR = auto() 2792 NCHAR = auto() 2793 VARCHAR = auto() 2794 NVARCHAR = auto() 2795 TEXT = auto() 2796 MEDIUMTEXT = auto() 2797 LONGTEXT = auto() 2798 MEDIUMBLOB = auto() 2799 LONGBLOB = auto() 2800 BINARY = auto() 2801 VARBINARY = auto() 2802 INT = auto() 2803 UINT = auto() 2804 TINYINT = auto() 2805 UTINYINT = auto() 2806 SMALLINT = auto() 2807 USMALLINT = auto() 2808 BIGINT = auto() 2809 UBIGINT = auto() 2810 FLOAT = auto() 2811 DOUBLE = auto() 2812 DECIMAL = auto() 2813 BIT = auto() 2814 BOOLEAN = auto() 2815 JSON = auto() 2816 JSONB = auto() 2817 INTERVAL = auto() 2818 TIME = auto() 2819 TIMESTAMP = auto() 2820 TIMESTAMPTZ = auto() 2821 TIMESTAMPLTZ = auto() 2822 DATE = auto() 2823 DATETIME = auto() 2824 ARRAY = auto() 2825 MAP = auto() 2826 UUID = auto() 2827 GEOGRAPHY = auto() 2828 GEOMETRY = auto() 2829 STRUCT = auto() 2830 NULLABLE = auto() 2831 HLLSKETCH = auto() 2832 HSTORE = auto() 2833 SUPER = auto() 2834 SERIAL = auto() 2835 SMALLSERIAL = auto() 2836 BIGSERIAL = auto() 2837 XML = auto() 2838 UNIQUEIDENTIFIER = auto() 2839 MONEY = auto() 2840 SMALLMONEY = auto() 2841 ROWVERSION = auto() 2842 IMAGE = auto() 2843 VARIANT = auto() 2844 OBJECT = auto() 2845 INET = auto() 2846 NULL = auto() 2847 UNKNOWN = auto() # Sentinel value, useful for type annotation 2848 2849 TEXT_TYPES = { 2850 Type.CHAR, 2851 Type.NCHAR, 2852 Type.VARCHAR, 2853 Type.NVARCHAR, 2854 Type.TEXT, 2855 } 2856 2857 INTEGER_TYPES = { 2858 Type.INT, 2859 Type.TINYINT, 2860 Type.SMALLINT, 2861 Type.BIGINT, 2862 } 2863 2864 FLOAT_TYPES = { 2865 Type.FLOAT, 2866 Type.DOUBLE, 2867 } 2868 2869 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2870 2871 TEMPORAL_TYPES = { 2872 Type.TIMESTAMP, 2873 Type.TIMESTAMPTZ, 2874 Type.TIMESTAMPLTZ, 2875 Type.DATE, 2876 Type.DATETIME, 2877 } 2878 2879 @classmethod 2880 def build( 2881 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2882 ) -> DataType: 2883 from sqlglot import parse_one 2884 2885 if isinstance(dtype, str): 2886 if dtype.upper() in cls.Type.__members__: 2887 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2888 else: 2889 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2890 if data_type_exp is None: 2891 raise ValueError(f"Unparsable data type value: {dtype}") 2892 elif isinstance(dtype, DataType.Type): 2893 data_type_exp = DataType(this=dtype) 2894 elif isinstance(dtype, DataType): 2895 return dtype 2896 else: 2897 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2898 return DataType(**{**data_type_exp.args, **kwargs}) 2899 2900 def is_type(self, dtype: DataType.Type) -> bool: 2901 return self.this == dtype 2902 2903 2904# https://www.postgresql.org/docs/15/datatype-pseudo.html 2905class PseudoType(Expression): 2906 pass 2907 2908 2909class StructKwarg(Expression): 2910 arg_types = {"this": True, "expression": True} 2911 2912 2913# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 2914class SubqueryPredicate(Predicate): 2915 pass 2916 2917 2918class All(SubqueryPredicate): 2919 pass 2920 2921 2922class Any(SubqueryPredicate): 2923 pass 2924 2925 2926class Exists(SubqueryPredicate): 2927 pass 2928 2929 2930# Commands to interact with the databases or engines. For most of the command 2931# expressions we parse whatever comes after the command's name as a string. 2932class Command(Expression): 2933 arg_types = {"this": True, "expression": False} 2934 2935 2936class Transaction(Expression): 2937 arg_types = {"this": False, "modes": False} 2938 2939 2940class Commit(Expression): 2941 arg_types = {"chain": False} 2942 2943 2944class Rollback(Expression): 2945 arg_types = {"savepoint": False} 2946 2947 2948class AlterTable(Expression): 2949 arg_types = {"this": True, "actions": True, "exists": False} 2950 2951 2952class AddConstraint(Expression): 2953 arg_types = {"this": False, "expression": False, "enforced": False} 2954 2955 2956class DropPartition(Expression): 2957 arg_types = {"expressions": True, "exists": False} 2958 2959 2960# Binary expressions like (ADD a b) 2961class Binary(Expression): 2962 arg_types = {"this": True, "expression": True} 2963 2964 @property 2965 def left(self): 2966 return self.this 2967 2968 @property 2969 def right(self): 2970 return self.expression 2971 2972 2973class Add(Binary): 2974 pass 2975 2976 2977class Connector(Binary, Condition): 2978 pass 2979 2980 2981class And(Connector): 2982 pass 2983 2984 2985class Or(Connector): 2986 pass 2987 2988 2989class BitwiseAnd(Binary): 2990 pass 2991 2992 2993class BitwiseLeftShift(Binary): 2994 pass 2995 2996 2997class BitwiseOr(Binary): 2998 pass 2999 3000 3001class BitwiseRightShift(Binary): 3002 pass 3003 3004 3005class BitwiseXor(Binary): 3006 pass 3007 3008 3009class Div(Binary): 3010 pass 3011 3012 3013class Overlaps(Binary): 3014 pass 3015 3016 3017class Dot(Binary): 3018 @property 3019 def name(self) -> str: 3020 return self.expression.name 3021 3022 @classmethod 3023 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3024 """Build a Dot object with a sequence of expressions.""" 3025 if len(expressions) < 2: 3026 raise ValueError(f"Dot requires >= 2 expressions.") 3027 3028 a, b, *expressions = expressions 3029 dot = Dot(this=a, expression=b) 3030 3031 for expression in expressions: 3032 dot = Dot(this=dot, expression=expression) 3033 3034 return dot 3035 3036 3037class DPipe(Binary): 3038 pass 3039 3040 3041class EQ(Binary, Predicate): 3042 pass 3043 3044 3045class NullSafeEQ(Binary, Predicate): 3046 pass 3047 3048 3049class NullSafeNEQ(Binary, Predicate): 3050 pass 3051 3052 3053class Distance(Binary): 3054 pass 3055 3056 3057class Escape(Binary): 3058 pass 3059 3060 3061class Glob(Binary, Predicate): 3062 pass 3063 3064 3065class GT(Binary, Predicate): 3066 pass 3067 3068 3069class GTE(Binary, Predicate): 3070 pass 3071 3072 3073class ILike(Binary, Predicate): 3074 pass 3075 3076 3077class ILikeAny(Binary, Predicate): 3078 pass 3079 3080 3081class IntDiv(Binary): 3082 pass 3083 3084 3085class Is(Binary, Predicate): 3086 pass 3087 3088 3089class Kwarg(Binary): 3090 """Kwarg in special functions like func(kwarg => y).""" 3091 3092 3093class Like(Binary, Predicate): 3094 pass 3095 3096 3097class LikeAny(Binary, Predicate): 3098 pass 3099 3100 3101class LT(Binary, Predicate): 3102 pass 3103 3104 3105class LTE(Binary, Predicate): 3106 pass 3107 3108 3109class Mod(Binary): 3110 pass 3111 3112 3113class Mul(Binary): 3114 pass 3115 3116 3117class NEQ(Binary, Predicate): 3118 pass 3119 3120 3121class SimilarTo(Binary, Predicate): 3122 pass 3123 3124 3125class Slice(Binary): 3126 arg_types = {"this": False, "expression": False} 3127 3128 3129class Sub(Binary): 3130 pass 3131 3132 3133class ArrayOverlaps(Binary): 3134 pass 3135 3136 3137# Unary Expressions 3138# (NOT a) 3139class Unary(Expression): 3140 pass 3141 3142 3143class BitwiseNot(Unary): 3144 pass 3145 3146 3147class Not(Unary, Condition): 3148 pass 3149 3150 3151class Paren(Unary, Condition): 3152 arg_types = {"this": True, "with": False} 3153 3154 3155class Neg(Unary): 3156 pass 3157 3158 3159# Special Functions 3160class Alias(Expression): 3161 arg_types = {"this": True, "alias": False} 3162 3163 @property 3164 def output_name(self): 3165 return self.alias 3166 3167 3168class Aliases(Expression): 3169 arg_types = {"this": True, "expressions": True} 3170 3171 @property 3172 def aliases(self): 3173 return self.expressions 3174 3175 3176class AtTimeZone(Expression): 3177 arg_types = {"this": True, "zone": True} 3178 3179 3180class Between(Predicate): 3181 arg_types = {"this": True, "low": True, "high": True} 3182 3183 3184class Bracket(Condition): 3185 arg_types = {"this": True, "expressions": True} 3186 3187 3188class Distinct(Expression): 3189 arg_types = {"expressions": False, "on": False} 3190 3191 3192class In(Predicate): 3193 arg_types = { 3194 "this": True, 3195 "expressions": False, 3196 "query": False, 3197 "unnest": False, 3198 "field": False, 3199 "is_global": False, 3200 } 3201 3202 3203class TimeUnit(Expression): 3204 """Automatically converts unit arg into a var.""" 3205 3206 arg_types = {"unit": False} 3207 3208 def __init__(self, **args): 3209 unit = args.get("unit") 3210 if isinstance(unit, (Column, Literal)): 3211 args["unit"] = Var(this=unit.name) 3212 elif isinstance(unit, Week): 3213 unit.set("this", Var(this=unit.this.name)) 3214 super().__init__(**args) 3215 3216 3217class Interval(TimeUnit): 3218 arg_types = {"this": False, "unit": False} 3219 3220 3221class IgnoreNulls(Expression): 3222 pass 3223 3224 3225class RespectNulls(Expression): 3226 pass 3227 3228 3229# Functions 3230class Func(Condition): 3231 """ 3232 The base class for all function expressions. 3233 3234 Attributes: 3235 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3236 treated as a variable length argument and the argument's value will be stored as a list. 3237 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3238 for this function expression. These values are used to map this node to a name during parsing 3239 as well as to provide the function's name during SQL string generation. By default the SQL 3240 name is set to the expression's class name transformed to snake case. 3241 """ 3242 3243 is_var_len_args = False 3244 3245 @classmethod 3246 def from_arg_list(cls, args): 3247 if cls.is_var_len_args: 3248 all_arg_keys = list(cls.arg_types) 3249 # If this function supports variable length argument treat the last argument as such. 3250 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3251 num_non_var = len(non_var_len_arg_keys) 3252 3253 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3254 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3255 else: 3256 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3257 3258 return cls(**args_dict) 3259 3260 @classmethod 3261 def sql_names(cls): 3262 if cls is Func: 3263 raise NotImplementedError( 3264 "SQL name is only supported by concrete function implementations" 3265 ) 3266 if "_sql_names" not in cls.__dict__: 3267 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3268 return cls._sql_names 3269 3270 @classmethod 3271 def sql_name(cls): 3272 return cls.sql_names()[0] 3273 3274 @classmethod 3275 def default_parser_mappings(cls): 3276 return {name: cls.from_arg_list for name in cls.sql_names()} 3277 3278 3279class AggFunc(Func): 3280 pass 3281 3282 3283class Abs(Func): 3284 pass 3285 3286 3287class Anonymous(Func): 3288 arg_types = {"this": True, "expressions": False} 3289 is_var_len_args = True 3290 3291 3292class ApproxDistinct(AggFunc): 3293 arg_types = {"this": True, "accuracy": False} 3294 3295 3296class Array(Func): 3297 arg_types = {"expressions": False} 3298 is_var_len_args = True 3299 3300 3301# https://docs.snowflake.com/en/sql-reference/functions/to_char 3302class ToChar(Func): 3303 arg_types = {"this": True, "format": False} 3304 3305 3306class GenerateSeries(Func): 3307 arg_types = {"start": True, "end": True, "step": False} 3308 3309 3310class ArrayAgg(AggFunc): 3311 pass 3312 3313 3314class ArrayAll(Func): 3315 arg_types = {"this": True, "expression": True} 3316 3317 3318class ArrayAny(Func): 3319 arg_types = {"this": True, "expression": True} 3320 3321 3322class ArrayConcat(Func): 3323 arg_types = {"this": True, "expressions": False} 3324 is_var_len_args = True 3325 3326 3327class ArrayContains(Binary, Func): 3328 pass 3329 3330 3331class ArrayContained(Binary): 3332 pass 3333 3334 3335class ArrayFilter(Func): 3336 arg_types = {"this": True, "expression": True} 3337 _sql_names = ["FILTER", "ARRAY_FILTER"] 3338 3339 3340class ArrayJoin(Func): 3341 arg_types = {"this": True, "expression": True, "null": False} 3342 3343 3344class ArraySize(Func): 3345 arg_types = {"this": True, "expression": False} 3346 3347 3348class ArraySort(Func): 3349 arg_types = {"this": True, "expression": False} 3350 3351 3352class ArraySum(Func): 3353 pass 3354 3355 3356class ArrayUnionAgg(AggFunc): 3357 pass 3358 3359 3360class Avg(AggFunc): 3361 pass 3362 3363 3364class AnyValue(AggFunc): 3365 pass 3366 3367 3368class Case(Func): 3369 arg_types = {"this": False, "ifs": True, "default": False} 3370 3371 3372class Cast(Func): 3373 arg_types = {"this": True, "to": True} 3374 3375 @property 3376 def name(self) -> str: 3377 return self.this.name 3378 3379 @property 3380 def to(self): 3381 return self.args["to"] 3382 3383 @property 3384 def output_name(self): 3385 return self.name 3386 3387 def is_type(self, dtype: DataType.Type) -> bool: 3388 return self.to.is_type(dtype) 3389 3390 3391class Collate(Binary): 3392 pass 3393 3394 3395class TryCast(Cast): 3396 pass 3397 3398 3399class Ceil(Func): 3400 arg_types = {"this": True, "decimals": False} 3401 _sql_names = ["CEIL", "CEILING"] 3402 3403 3404class Coalesce(Func): 3405 arg_types = {"this": True, "expressions": False} 3406 is_var_len_args = True 3407 3408 3409class Concat(Func): 3410 arg_types = {"expressions": True} 3411 is_var_len_args = True 3412 3413 3414class ConcatWs(Concat): 3415 _sql_names = ["CONCAT_WS"] 3416 3417 3418class Count(AggFunc): 3419 arg_types = {"this": False} 3420 3421 3422class CountIf(AggFunc): 3423 pass 3424 3425 3426class CurrentDate(Func): 3427 arg_types = {"this": False} 3428 3429 3430class CurrentDatetime(Func): 3431 arg_types = {"this": False} 3432 3433 3434class CurrentTime(Func): 3435 arg_types = {"this": False} 3436 3437 3438class CurrentTimestamp(Func): 3439 arg_types = {"this": False} 3440 3441 3442class DateAdd(Func, TimeUnit): 3443 arg_types = {"this": True, "expression": True, "unit": False} 3444 3445 3446class DateSub(Func, TimeUnit): 3447 arg_types = {"this": True, "expression": True, "unit": False} 3448 3449 3450class DateDiff(Func, TimeUnit): 3451 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3452 arg_types = {"this": True, "expression": True, "unit": False} 3453 3454 3455class DateTrunc(Func): 3456 arg_types = {"unit": True, "this": True, "zone": False} 3457 3458 3459class DatetimeAdd(Func, TimeUnit): 3460 arg_types = {"this": True, "expression": True, "unit": False} 3461 3462 3463class DatetimeSub(Func, TimeUnit): 3464 arg_types = {"this": True, "expression": True, "unit": False} 3465 3466 3467class DatetimeDiff(Func, TimeUnit): 3468 arg_types = {"this": True, "expression": True, "unit": False} 3469 3470 3471class DatetimeTrunc(Func, TimeUnit): 3472 arg_types = {"this": True, "unit": True, "zone": False} 3473 3474 3475class DayOfWeek(Func): 3476 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3477 3478 3479class DayOfMonth(Func): 3480 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3481 3482 3483class DayOfYear(Func): 3484 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3485 3486 3487class WeekOfYear(Func): 3488 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3489 3490 3491class LastDateOfMonth(Func): 3492 pass 3493 3494 3495class Extract(Func): 3496 arg_types = {"this": True, "expression": True} 3497 3498 3499class TimestampAdd(Func, TimeUnit): 3500 arg_types = {"this": True, "expression": True, "unit": False} 3501 3502 3503class TimestampSub(Func, TimeUnit): 3504 arg_types = {"this": True, "expression": True, "unit": False} 3505 3506 3507class TimestampDiff(Func, TimeUnit): 3508 arg_types = {"this": True, "expression": True, "unit": False} 3509 3510 3511class TimestampTrunc(Func, TimeUnit): 3512 arg_types = {"this": True, "unit": True, "zone": False} 3513 3514 3515class TimeAdd(Func, TimeUnit): 3516 arg_types = {"this": True, "expression": True, "unit": False} 3517 3518 3519class TimeSub(Func, TimeUnit): 3520 arg_types = {"this": True, "expression": True, "unit": False} 3521 3522 3523class TimeDiff(Func, TimeUnit): 3524 arg_types = {"this": True, "expression": True, "unit": False} 3525 3526 3527class TimeTrunc(Func, TimeUnit): 3528 arg_types = {"this": True, "unit": True, "zone": False} 3529 3530 3531class DateFromParts(Func): 3532 _sql_names = ["DATEFROMPARTS"] 3533 arg_types = {"year": True, "month": True, "day": True} 3534 3535 3536class DateStrToDate(Func): 3537 pass 3538 3539 3540class DateToDateStr(Func): 3541 pass 3542 3543 3544class DateToDi(Func): 3545 pass 3546 3547 3548class Day(Func): 3549 pass 3550 3551 3552class Decode(Func): 3553 arg_types = {"this": True, "charset": True, "replace": False} 3554 3555 3556class DiToDate(Func): 3557 pass 3558 3559 3560class Encode(Func): 3561 arg_types = {"this": True, "charset": True} 3562 3563 3564class Exp(Func): 3565 pass 3566 3567 3568class Explode(Func): 3569 pass 3570 3571 3572class ExponentialTimeDecayedAvg(AggFunc): 3573 arg_types = {"this": True, "time": False, "decay": False} 3574 3575 3576class Floor(Func): 3577 arg_types = {"this": True, "decimals": False} 3578 3579 3580class Greatest(Func): 3581 arg_types = {"this": True, "expressions": False} 3582 is_var_len_args = True 3583 3584 3585class GroupConcat(Func): 3586 arg_types = {"this": True, "separator": False} 3587 3588 3589class GroupUniqArray(AggFunc): 3590 arg_types = {"this": True, "size": False} 3591 3592 3593class Hex(Func): 3594 pass 3595 3596 3597class Histogram(AggFunc): 3598 arg_types = {"this": True, "bins": False} 3599 3600 3601class If(Func): 3602 arg_types = {"this": True, "true": True, "false": False} 3603 3604 3605class IfNull(Func): 3606 arg_types = {"this": True, "expression": False} 3607 _sql_names = ["IFNULL", "NVL"] 3608 3609 3610class Initcap(Func): 3611 pass 3612 3613 3614class JSONKeyValue(Expression): 3615 arg_types = {"this": True, "expression": True} 3616 3617 3618class JSONObject(Func): 3619 arg_types = { 3620 "expressions": False, 3621 "null_handling": False, 3622 "unique_keys": False, 3623 "return_type": False, 3624 "format_json": False, 3625 "encoding": False, 3626 } 3627 3628 3629class JSONBContains(Binary): 3630 _sql_names = ["JSONB_CONTAINS"] 3631 3632 3633class JSONExtract(Binary, Func): 3634 _sql_names = ["JSON_EXTRACT"] 3635 3636 3637class JSONExtractScalar(JSONExtract): 3638 _sql_names = ["JSON_EXTRACT_SCALAR"] 3639 3640 3641class JSONBExtract(JSONExtract): 3642 _sql_names = ["JSONB_EXTRACT"] 3643 3644 3645class JSONBExtractScalar(JSONExtract): 3646 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3647 3648 3649class Least(Func): 3650 arg_types = {"expressions": False} 3651 is_var_len_args = True 3652 3653 3654class Length(Func): 3655 pass 3656 3657 3658class Levenshtein(Func): 3659 arg_types = { 3660 "this": True, 3661 "expression": False, 3662 "ins_cost": False, 3663 "del_cost": False, 3664 "sub_cost": False, 3665 } 3666 3667 3668class Ln(Func): 3669 pass 3670 3671 3672class Log(Func): 3673 arg_types = {"this": True, "expression": False} 3674 3675 3676class Log2(Func): 3677 pass 3678 3679 3680class Log10(Func): 3681 pass 3682 3683 3684class LogicalOr(AggFunc): 3685 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 3686 3687 3688class LogicalAnd(AggFunc): 3689 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 3690 3691 3692class Lower(Func): 3693 _sql_names = ["LOWER", "LCASE"] 3694 3695 3696class Map(Func): 3697 arg_types = {"keys": False, "values": False} 3698 3699 3700class VarMap(Func): 3701 arg_types = {"keys": True, "values": True} 3702 is_var_len_args = True 3703 3704 3705class Matches(Func): 3706 """Oracle/Snowflake decode. 3707 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3708 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3709 """ 3710 3711 arg_types = {"this": True, "expressions": True} 3712 is_var_len_args = True 3713 3714 3715class Max(AggFunc): 3716 arg_types = {"this": True, "expressions": False} 3717 is_var_len_args = True 3718 3719 3720class Min(AggFunc): 3721 arg_types = {"this": True, "expressions": False} 3722 is_var_len_args = True 3723 3724 3725class Month(Func): 3726 pass 3727 3728 3729class Nvl2(Func): 3730 arg_types = {"this": True, "true": True, "false": False} 3731 3732 3733class Posexplode(Func): 3734 pass 3735 3736 3737class Pow(Binary, Func): 3738 _sql_names = ["POWER", "POW"] 3739 3740 3741class PercentileCont(AggFunc): 3742 pass 3743 3744 3745class PercentileDisc(AggFunc): 3746 pass 3747 3748 3749class Quantile(AggFunc): 3750 arg_types = {"this": True, "quantile": True} 3751 3752 3753# Clickhouse-specific: 3754# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles 3755class Quantiles(AggFunc): 3756 arg_types = {"parameters": True, "expressions": True} 3757 is_var_len_args = True 3758 3759 3760class QuantileIf(AggFunc): 3761 arg_types = {"parameters": True, "expressions": True} 3762 3763 3764class ApproxQuantile(Quantile): 3765 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 3766 3767 3768class RangeN(Func): 3769 arg_types = {"this": True, "expressions": True, "each": False} 3770 3771 3772class ReadCSV(Func): 3773 _sql_names = ["READ_CSV"] 3774 is_var_len_args = True 3775 arg_types = {"this": True, "expressions": False} 3776 3777 3778class Reduce(Func): 3779 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 3780 3781 3782class RegexpExtract(Func): 3783 arg_types = { 3784 "this": True, 3785 "expression": True, 3786 "position": False, 3787 "occurrence": False, 3788 "group": False, 3789 } 3790 3791 3792class RegexpLike(Func): 3793 arg_types = {"this": True, "expression": True, "flag": False} 3794 3795 3796class RegexpILike(Func): 3797 arg_types = {"this": True, "expression": True, "flag": False} 3798 3799 3800class RegexpSplit(Func): 3801 arg_types = {"this": True, "expression": True} 3802 3803 3804class Repeat(Func): 3805 arg_types = {"this": True, "times": True} 3806 3807 3808class Round(Func): 3809 arg_types = {"this": True, "decimals": False} 3810 3811 3812class RowNumber(Func): 3813 arg_types: t.Dict[str, t.Any] = {} 3814 3815 3816class SafeDivide(Func): 3817 arg_types = {"this": True, "expression": True} 3818 3819 3820class SetAgg(AggFunc): 3821 pass 3822 3823 3824class SortArray(Func): 3825 arg_types = {"this": True, "asc": False} 3826 3827 3828class Split(Func): 3829 arg_types = {"this": True, "expression": True, "limit": False} 3830 3831 3832# Start may be omitted in the case of postgres 3833# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 3834class Substring(Func): 3835 arg_types = {"this": True, "start": False, "length": False} 3836 3837 3838class StrPosition(Func): 3839 arg_types = { 3840 "this": True, 3841 "substr": True, 3842 "position": False, 3843 "instance": False, 3844 } 3845 3846 3847class StrToDate(Func): 3848 arg_types = {"this": True, "format": True} 3849 3850 3851class StrToTime(Func): 3852 arg_types = {"this": True, "format": True} 3853 3854 3855# Spark allows unix_timestamp() 3856# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 3857class StrToUnix(Func): 3858 arg_types = {"this": False, "format": False} 3859 3860 3861class NumberToStr(Func): 3862 arg_types = {"this": True, "format": True} 3863 3864 3865class Struct(Func): 3866 arg_types = {"expressions": True} 3867 is_var_len_args = True 3868 3869 3870class StructExtract(Func): 3871 arg_types = {"this": True, "expression": True} 3872 3873 3874class Sum(AggFunc): 3875 pass 3876 3877 3878class Sqrt(Func): 3879 pass 3880 3881 3882class Stddev(AggFunc): 3883 pass 3884 3885 3886class StddevPop(AggFunc): 3887 pass 3888 3889 3890class StddevSamp(AggFunc): 3891 pass 3892 3893 3894class TimeToStr(Func): 3895 arg_types = {"this": True, "format": True} 3896 3897 3898class TimeToTimeStr(Func): 3899 pass 3900 3901 3902class TimeToUnix(Func): 3903 pass 3904 3905 3906class TimeStrToDate(Func): 3907 pass 3908 3909 3910class TimeStrToTime(Func): 3911 pass 3912 3913 3914class TimeStrToUnix(Func): 3915 pass 3916 3917 3918class Trim(Func): 3919 arg_types = { 3920 "this": True, 3921 "expression": False, 3922 "position": False, 3923 "collation": False, 3924 } 3925 3926 3927class TsOrDsAdd(Func, TimeUnit): 3928 arg_types = {"this": True, "expression": True, "unit": False} 3929 3930 3931class TsOrDsToDateStr(Func): 3932 pass 3933 3934 3935class TsOrDsToDate(Func): 3936 arg_types = {"this": True, "format": False} 3937 3938 3939class TsOrDiToDi(Func): 3940 pass 3941 3942 3943class Unhex(Func): 3944 pass 3945 3946 3947class UnixToStr(Func): 3948 arg_types = {"this": True, "format": False} 3949 3950 3951# https://prestodb.io/docs/current/functions/datetime.html 3952# presto has weird zone/hours/minutes 3953class UnixToTime(Func): 3954 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3955 3956 SECONDS = Literal.string("seconds") 3957 MILLIS = Literal.string("millis") 3958 MICROS = Literal.string("micros") 3959 3960 3961class UnixToTimeStr(Func): 3962 pass 3963 3964 3965class Upper(Func): 3966 _sql_names = ["UPPER", "UCASE"] 3967 3968 3969class Variance(AggFunc): 3970 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 3971 3972 3973class VariancePop(AggFunc): 3974 _sql_names = ["VARIANCE_POP", "VAR_POP"] 3975 3976 3977class Week(Func): 3978 arg_types = {"this": True, "mode": False} 3979 3980 3981class XMLTable(Func): 3982 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 3983 3984 3985class Year(Func): 3986 pass 3987 3988 3989class Use(Expression): 3990 arg_types = {"this": True, "kind": False} 3991 3992 3993class Merge(Expression): 3994 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 3995 3996 3997class When(Func): 3998 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 3999 4000 4001def _norm_arg(arg): 4002 return arg.lower() if type(arg) is str else arg 4003 4004 4005ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4006 4007 4008# Helpers 4009def maybe_parse( 4010 sql_or_expression: ExpOrStr, 4011 *, 4012 into: t.Optional[IntoType] = None, 4013 dialect: DialectType = None, 4014 prefix: t.Optional[str] = None, 4015 copy: bool = False, 4016 **opts, 4017) -> Expression: 4018 """Gracefully handle a possible string or expression. 4019 4020 Example: 4021 >>> maybe_parse("1") 4022 (LITERAL this: 1, is_string: False) 4023 >>> maybe_parse(to_identifier("x")) 4024 (IDENTIFIER this: x, quoted: False) 4025 4026 Args: 4027 sql_or_expression: the SQL code string or an expression 4028 into: the SQLGlot Expression to parse into 4029 dialect: the dialect used to parse the input expressions (in the case that an 4030 input expression is a SQL string). 4031 prefix: a string to prefix the sql with before it gets parsed 4032 (automatically includes a space) 4033 copy: whether or not to copy the expression. 4034 **opts: other options to use to parse the input expressions (again, in the case 4035 that an input expression is a SQL string). 4036 4037 Returns: 4038 Expression: the parsed or given expression. 4039 """ 4040 if isinstance(sql_or_expression, Expression): 4041 if copy: 4042 return sql_or_expression.copy() 4043 return sql_or_expression 4044 4045 import sqlglot 4046 4047 sql = str(sql_or_expression) 4048 if prefix: 4049 sql = f"{prefix} {sql}" 4050 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4051 4052 4053def _maybe_copy(instance, copy=True): 4054 return instance.copy() if copy else instance 4055 4056 4057def _is_wrong_expression(expression, into): 4058 return isinstance(expression, Expression) and not isinstance(expression, into) 4059 4060 4061def _apply_builder( 4062 expression, 4063 instance, 4064 arg, 4065 copy=True, 4066 prefix=None, 4067 into=None, 4068 dialect=None, 4069 **opts, 4070): 4071 if _is_wrong_expression(expression, into): 4072 expression = into(this=expression) 4073 instance = _maybe_copy(instance, copy) 4074 expression = maybe_parse( 4075 sql_or_expression=expression, 4076 prefix=prefix, 4077 into=into, 4078 dialect=dialect, 4079 **opts, 4080 ) 4081 instance.set(arg, expression) 4082 return instance 4083 4084 4085def _apply_child_list_builder( 4086 *expressions, 4087 instance, 4088 arg, 4089 append=True, 4090 copy=True, 4091 prefix=None, 4092 into=None, 4093 dialect=None, 4094 properties=None, 4095 **opts, 4096): 4097 instance = _maybe_copy(instance, copy) 4098 parsed = [] 4099 for expression in expressions: 4100 if _is_wrong_expression(expression, into): 4101 expression = into(expressions=[expression]) 4102 expression = maybe_parse( 4103 expression, 4104 into=into, 4105 dialect=dialect, 4106 prefix=prefix, 4107 **opts, 4108 ) 4109 parsed.extend(expression.expressions) 4110 4111 existing = instance.args.get(arg) 4112 if append and existing: 4113 parsed = existing.expressions + parsed 4114 4115 child = into(expressions=parsed) 4116 for k, v in (properties or {}).items(): 4117 child.set(k, v) 4118 instance.set(arg, child) 4119 return instance 4120 4121 4122def _apply_list_builder( 4123 *expressions, 4124 instance, 4125 arg, 4126 append=True, 4127 copy=True, 4128 prefix=None, 4129 into=None, 4130 dialect=None, 4131 **opts, 4132): 4133 inst = _maybe_copy(instance, copy) 4134 4135 expressions = [ 4136 maybe_parse( 4137 sql_or_expression=expression, 4138 into=into, 4139 prefix=prefix, 4140 dialect=dialect, 4141 **opts, 4142 ) 4143 for expression in expressions 4144 ] 4145 4146 existing_expressions = inst.args.get(arg) 4147 if append and existing_expressions: 4148 expressions = existing_expressions + expressions 4149 4150 inst.set(arg, expressions) 4151 return inst 4152 4153 4154def _apply_conjunction_builder( 4155 *expressions, 4156 instance, 4157 arg, 4158 into=None, 4159 append=True, 4160 copy=True, 4161 dialect=None, 4162 **opts, 4163): 4164 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4165 if not expressions: 4166 return instance 4167 4168 inst = _maybe_copy(instance, copy) 4169 4170 existing = inst.args.get(arg) 4171 if append and existing is not None: 4172 expressions = [existing.this if into else existing] + list(expressions) 4173 4174 node = and_(*expressions, dialect=dialect, **opts) 4175 4176 inst.set(arg, into(this=node) if into else node) 4177 return inst 4178 4179 4180def _combine(expressions, operator, dialect=None, **opts): 4181 expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions] 4182 this = expressions[0] 4183 if expressions[1:]: 4184 this = _wrap_operator(this) 4185 for expression in expressions[1:]: 4186 this = operator(this=this, expression=_wrap_operator(expression)) 4187 return this 4188 4189 4190def _wrap_operator(expression): 4191 if isinstance(expression, (And, Or, Not)): 4192 expression = Paren(this=expression) 4193 return expression 4194 4195 4196def union(left, right, distinct=True, dialect=None, **opts): 4197 """ 4198 Initializes a syntax tree from one UNION expression. 4199 4200 Example: 4201 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4202 'SELECT * FROM foo UNION SELECT * FROM bla' 4203 4204 Args: 4205 left (str | Expression): the SQL code string corresponding to the left-hand side. 4206 If an `Expression` instance is passed, it will be used as-is. 4207 right (str | Expression): the SQL code string corresponding to the right-hand side. 4208 If an `Expression` instance is passed, it will be used as-is. 4209 distinct (bool): set the DISTINCT flag if and only if this is true. 4210 dialect (str): the dialect used to parse the input expression. 4211 opts (kwargs): other options to use to parse the input expressions. 4212 Returns: 4213 Union: the syntax tree for the UNION expression. 4214 """ 4215 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4216 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4217 4218 return Union(this=left, expression=right, distinct=distinct) 4219 4220 4221def intersect(left, right, distinct=True, dialect=None, **opts): 4222 """ 4223 Initializes a syntax tree from one INTERSECT expression. 4224 4225 Example: 4226 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4227 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4228 4229 Args: 4230 left (str | Expression): the SQL code string corresponding to the left-hand side. 4231 If an `Expression` instance is passed, it will be used as-is. 4232 right (str | Expression): the SQL code string corresponding to the right-hand side. 4233 If an `Expression` instance is passed, it will be used as-is. 4234 distinct (bool): set the DISTINCT flag if and only if this is true. 4235 dialect (str): the dialect used to parse the input expression. 4236 opts (kwargs): other options to use to parse the input expressions. 4237 Returns: 4238 Intersect: the syntax tree for the INTERSECT expression. 4239 """ 4240 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4241 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4242 4243 return Intersect(this=left, expression=right, distinct=distinct) 4244 4245 4246def except_(left, right, distinct=True, dialect=None, **opts): 4247 """ 4248 Initializes a syntax tree from one EXCEPT expression. 4249 4250 Example: 4251 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4252 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4253 4254 Args: 4255 left (str | Expression): the SQL code string corresponding to the left-hand side. 4256 If an `Expression` instance is passed, it will be used as-is. 4257 right (str | Expression): the SQL code string corresponding to the right-hand side. 4258 If an `Expression` instance is passed, it will be used as-is. 4259 distinct (bool): set the DISTINCT flag if and only if this is true. 4260 dialect (str): the dialect used to parse the input expression. 4261 opts (kwargs): other options to use to parse the input expressions. 4262 Returns: 4263 Except: the syntax tree for the EXCEPT statement. 4264 """ 4265 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4266 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4267 4268 return Except(this=left, expression=right, distinct=distinct) 4269 4270 4271def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4272 """ 4273 Initializes a syntax tree from one or multiple SELECT expressions. 4274 4275 Example: 4276 >>> select("col1", "col2").from_("tbl").sql() 4277 'SELECT col1, col2 FROM tbl' 4278 4279 Args: 4280 *expressions: the SQL code string to parse as the expressions of a 4281 SELECT statement. If an Expression instance is passed, this is used as-is. 4282 dialect: the dialect used to parse the input expressions (in the case that an 4283 input expression is a SQL string). 4284 **opts: other options to use to parse the input expressions (again, in the case 4285 that an input expression is a SQL string). 4286 4287 Returns: 4288 Select: the syntax tree for the SELECT statement. 4289 """ 4290 return Select().select(*expressions, dialect=dialect, **opts) 4291 4292 4293def from_(*expressions, dialect=None, **opts) -> Select: 4294 """ 4295 Initializes a syntax tree from a FROM expression. 4296 4297 Example: 4298 >>> from_("tbl").select("col1", "col2").sql() 4299 'SELECT col1, col2 FROM tbl' 4300 4301 Args: 4302 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4303 SELECT statement. If an Expression instance is passed, this is used as-is. 4304 dialect (str): the dialect used to parse the input expression (in the case that the 4305 input expression is a SQL string). 4306 **opts: other options to use to parse the input expressions (again, in the case 4307 that the input expression is a SQL string). 4308 4309 Returns: 4310 Select: the syntax tree for the SELECT statement. 4311 """ 4312 return Select().from_(*expressions, dialect=dialect, **opts) 4313 4314 4315def update( 4316 table: str | Table, 4317 properties: dict, 4318 where: t.Optional[ExpOrStr] = None, 4319 from_: t.Optional[ExpOrStr] = None, 4320 dialect: DialectType = None, 4321 **opts, 4322) -> Update: 4323 """ 4324 Creates an update statement. 4325 4326 Example: 4327 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4328 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4329 4330 Args: 4331 *properties: dictionary of properties to set which are 4332 auto converted to sql objects eg None -> NULL 4333 where: sql conditional parsed into a WHERE statement 4334 from_: sql statement parsed into a FROM statement 4335 dialect: the dialect used to parse the input expressions. 4336 **opts: other options to use to parse the input expressions. 4337 4338 Returns: 4339 Update: the syntax tree for the UPDATE statement. 4340 """ 4341 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4342 update_expr.set( 4343 "expressions", 4344 [ 4345 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4346 for k, v in properties.items() 4347 ], 4348 ) 4349 if from_: 4350 update_expr.set( 4351 "from", 4352 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4353 ) 4354 if isinstance(where, Condition): 4355 where = Where(this=where) 4356 if where: 4357 update_expr.set( 4358 "where", 4359 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4360 ) 4361 return update_expr 4362 4363 4364def delete( 4365 table: ExpOrStr, 4366 where: t.Optional[ExpOrStr] = None, 4367 returning: t.Optional[ExpOrStr] = None, 4368 dialect: DialectType = None, 4369 **opts, 4370) -> Delete: 4371 """ 4372 Builds a delete statement. 4373 4374 Example: 4375 >>> delete("my_table", where="id > 1").sql() 4376 'DELETE FROM my_table WHERE id > 1' 4377 4378 Args: 4379 where: sql conditional parsed into a WHERE statement 4380 returning: sql conditional parsed into a RETURNING statement 4381 dialect: the dialect used to parse the input expressions. 4382 **opts: other options to use to parse the input expressions. 4383 4384 Returns: 4385 Delete: the syntax tree for the DELETE statement. 4386 """ 4387 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4388 if where: 4389 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4390 if returning: 4391 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4392 return delete_expr 4393 4394 4395def condition(expression, dialect=None, **opts) -> Condition: 4396 """ 4397 Initialize a logical condition expression. 4398 4399 Example: 4400 >>> condition("x=1").sql() 4401 'x = 1' 4402 4403 This is helpful for composing larger logical syntax trees: 4404 >>> where = condition("x=1") 4405 >>> where = where.and_("y=1") 4406 >>> Select().from_("tbl").select("*").where(where).sql() 4407 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4408 4409 Args: 4410 *expression (str | Expression): the SQL code string to parse. 4411 If an Expression instance is passed, this is used as-is. 4412 dialect (str): the dialect used to parse the input expression (in the case that the 4413 input expression is a SQL string). 4414 **opts: other options to use to parse the input expressions (again, in the case 4415 that the input expression is a SQL string). 4416 4417 Returns: 4418 Condition: the expression 4419 """ 4420 return maybe_parse( # type: ignore 4421 expression, 4422 into=Condition, 4423 dialect=dialect, 4424 **opts, 4425 ) 4426 4427 4428def and_(*expressions, dialect=None, **opts) -> And: 4429 """ 4430 Combine multiple conditions with an AND logical operator. 4431 4432 Example: 4433 >>> and_("x=1", and_("y=1", "z=1")).sql() 4434 'x = 1 AND (y = 1 AND z = 1)' 4435 4436 Args: 4437 *expressions (str | Expression): the SQL code strings to parse. 4438 If an Expression instance is passed, this is used as-is. 4439 dialect (str): the dialect used to parse the input expression. 4440 **opts: other options to use to parse the input expressions. 4441 4442 Returns: 4443 And: the new condition 4444 """ 4445 return _combine(expressions, And, dialect, **opts) 4446 4447 4448def or_(*expressions, dialect=None, **opts) -> Or: 4449 """ 4450 Combine multiple conditions with an OR logical operator. 4451 4452 Example: 4453 >>> or_("x=1", or_("y=1", "z=1")).sql() 4454 'x = 1 OR (y = 1 OR z = 1)' 4455 4456 Args: 4457 *expressions (str | Expression): the SQL code strings to parse. 4458 If an Expression instance is passed, this is used as-is. 4459 dialect (str): the dialect used to parse the input expression. 4460 **opts: other options to use to parse the input expressions. 4461 4462 Returns: 4463 Or: the new condition 4464 """ 4465 return _combine(expressions, Or, dialect, **opts) 4466 4467 4468def not_(expression, dialect=None, **opts) -> Not: 4469 """ 4470 Wrap a condition with a NOT operator. 4471 4472 Example: 4473 >>> not_("this_suit='black'").sql() 4474 "NOT this_suit = 'black'" 4475 4476 Args: 4477 expression (str | Expression): the SQL code strings to parse. 4478 If an Expression instance is passed, this is used as-is. 4479 dialect (str): the dialect used to parse the input expression. 4480 **opts: other options to use to parse the input expressions. 4481 4482 Returns: 4483 Not: the new condition 4484 """ 4485 this = condition( 4486 expression, 4487 dialect=dialect, 4488 **opts, 4489 ) 4490 return Not(this=_wrap_operator(this)) 4491 4492 4493def paren(expression) -> Paren: 4494 return Paren(this=expression) 4495 4496 4497SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4498 4499 4500@t.overload 4501def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None: 4502 ... 4503 4504 4505@t.overload 4506def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier: 4507 ... 4508 4509 4510def to_identifier(name, quoted=None): 4511 """Builds an identifier. 4512 4513 Args: 4514 name: The name to turn into an identifier. 4515 quoted: Whether or not force quote the identifier. 4516 4517 Returns: 4518 The identifier ast node. 4519 """ 4520 4521 if name is None: 4522 return None 4523 4524 if isinstance(name, Identifier): 4525 identifier = name 4526 elif isinstance(name, str): 4527 identifier = Identifier( 4528 this=name, 4529 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4530 ) 4531 else: 4532 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4533 return identifier 4534 4535 4536INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4537 4538 4539def to_interval(interval: str | Literal) -> Interval: 4540 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4541 if isinstance(interval, Literal): 4542 if not interval.is_string: 4543 raise ValueError("Invalid interval string.") 4544 4545 interval = interval.this 4546 4547 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4548 4549 if not interval_parts: 4550 raise ValueError("Invalid interval string.") 4551 4552 return Interval( 4553 this=Literal.string(interval_parts.group(1)), 4554 unit=Var(this=interval_parts.group(2)), 4555 ) 4556 4557 4558@t.overload 4559def to_table(sql_path: str | Table, **kwargs) -> Table: 4560 ... 4561 4562 4563@t.overload 4564def to_table(sql_path: None, **kwargs) -> None: 4565 ... 4566 4567 4568def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4569 """ 4570 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4571 If a table is passed in then that table is returned. 4572 4573 Args: 4574 sql_path: a `[catalog].[schema].[table]` string. 4575 4576 Returns: 4577 A table expression. 4578 """ 4579 if sql_path is None or isinstance(sql_path, Table): 4580 return sql_path 4581 if not isinstance(sql_path, str): 4582 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4583 4584 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4585 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 4586 4587 4588def to_column(sql_path: str | Column, **kwargs) -> Column: 4589 """ 4590 Create a column from a `[table].[column]` sql path. Schema is optional. 4591 4592 If a column is passed in then that column is returned. 4593 4594 Args: 4595 sql_path: `[table].[column]` string 4596 Returns: 4597 Table: A column expression 4598 """ 4599 if sql_path is None or isinstance(sql_path, Column): 4600 return sql_path 4601 if not isinstance(sql_path, str): 4602 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4603 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 4604 4605 4606def alias_( 4607 expression: ExpOrStr, 4608 alias: str | Identifier, 4609 table: bool | t.Sequence[str | Identifier] = False, 4610 quoted: t.Optional[bool] = None, 4611 dialect: DialectType = None, 4612 **opts, 4613): 4614 """Create an Alias expression. 4615 4616 Example: 4617 >>> alias_('foo', 'bar').sql() 4618 'foo AS bar' 4619 4620 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4621 '(SELECT 1, 2) AS bar(a, b)' 4622 4623 Args: 4624 expression: the SQL code strings to parse. 4625 If an Expression instance is passed, this is used as-is. 4626 alias: the alias name to use. If the name has 4627 special characters it is quoted. 4628 table: Whether or not to create a table alias, can also be a list of columns. 4629 quoted: whether or not to quote the alias 4630 dialect: the dialect used to parse the input expression. 4631 **opts: other options to use to parse the input expressions. 4632 4633 Returns: 4634 Alias: the aliased expression 4635 """ 4636 exp = maybe_parse(expression, dialect=dialect, **opts) 4637 alias = to_identifier(alias, quoted=quoted) 4638 4639 if table: 4640 table_alias = TableAlias(this=alias) 4641 exp.set("alias", table_alias) 4642 4643 if not isinstance(table, bool): 4644 for column in table: 4645 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4646 4647 return exp 4648 4649 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4650 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4651 # for the complete Window expression. 4652 # 4653 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4654 4655 if "alias" in exp.arg_types and not isinstance(exp, Window): 4656 exp = exp.copy() 4657 exp.set("alias", alias) 4658 return exp 4659 return Alias(this=exp, alias=alias) 4660 4661 4662def subquery(expression, alias=None, dialect=None, **opts): 4663 """ 4664 Build a subquery expression. 4665 4666 Example: 4667 >>> subquery('select x from tbl', 'bar').select('x').sql() 4668 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4669 4670 Args: 4671 expression (str | Expression): the SQL code strings to parse. 4672 If an Expression instance is passed, this is used as-is. 4673 alias (str | Expression): the alias name to use. 4674 dialect (str): the dialect used to parse the input expression. 4675 **opts: other options to use to parse the input expressions. 4676 4677 Returns: 4678 Select: a new select with the subquery expression included 4679 """ 4680 4681 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4682 return Select().from_(expression, dialect=dialect, **opts) 4683 4684 4685def column( 4686 col: str | Identifier, 4687 table: t.Optional[str | Identifier] = None, 4688 db: t.Optional[str | Identifier] = None, 4689 catalog: t.Optional[str | Identifier] = None, 4690 quoted: t.Optional[bool] = None, 4691) -> Column: 4692 """ 4693 Build a Column. 4694 4695 Args: 4696 col: column name 4697 table: table name 4698 db: db name 4699 catalog: catalog name 4700 quoted: whether or not to force quote each part 4701 Returns: 4702 Column: column instance 4703 """ 4704 return Column( 4705 this=to_identifier(col, quoted=quoted), 4706 table=to_identifier(table, quoted=quoted), 4707 db=to_identifier(db, quoted=quoted), 4708 catalog=to_identifier(catalog, quoted=quoted), 4709 ) 4710 4711 4712def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4713 """Cast an expression to a data type. 4714 4715 Example: 4716 >>> cast('x + 1', 'int').sql() 4717 'CAST(x + 1 AS INT)' 4718 4719 Args: 4720 expression: The expression to cast. 4721 to: The datatype to cast to. 4722 4723 Returns: 4724 A cast node. 4725 """ 4726 expression = maybe_parse(expression, **opts) 4727 return Cast(this=expression, to=DataType.build(to, **opts)) 4728 4729 4730def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4731 """Build a Table. 4732 4733 Args: 4734 table (str | Expression): column name 4735 db (str | Expression): db name 4736 catalog (str | Expression): catalog name 4737 4738 Returns: 4739 Table: table instance 4740 """ 4741 return Table( 4742 this=to_identifier(table, quoted=quoted), 4743 db=to_identifier(db, quoted=quoted), 4744 catalog=to_identifier(catalog, quoted=quoted), 4745 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4746 ) 4747 4748 4749def values( 4750 values: t.Iterable[t.Tuple[t.Any, ...]], 4751 alias: t.Optional[str] = None, 4752 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4753) -> Values: 4754 """Build VALUES statement. 4755 4756 Example: 4757 >>> values([(1, '2')]).sql() 4758 "VALUES (1, '2')" 4759 4760 Args: 4761 values: values statements that will be converted to SQL 4762 alias: optional alias 4763 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4764 If either are provided then an alias is also required. 4765 If a dictionary is provided then the first column of the values will be casted to the expected type 4766 in order to help with type inference. 4767 4768 Returns: 4769 Values: the Values expression object 4770 """ 4771 if columns and not alias: 4772 raise ValueError("Alias is required when providing columns") 4773 table_alias = ( 4774 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4775 if columns 4776 else TableAlias(this=to_identifier(alias) if alias else None) 4777 ) 4778 expressions = [convert(tup) for tup in values] 4779 if columns and isinstance(columns, dict): 4780 types = list(columns.values()) 4781 expressions[0].set( 4782 "expressions", 4783 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4784 ) 4785 return Values( 4786 expressions=expressions, 4787 alias=table_alias, 4788 ) 4789 4790 4791def var(name: t.Optional[ExpOrStr]) -> Var: 4792 """Build a SQL variable. 4793 4794 Example: 4795 >>> repr(var('x')) 4796 '(VAR this: x)' 4797 4798 >>> repr(var(column('x', table='y'))) 4799 '(VAR this: x)' 4800 4801 Args: 4802 name: The name of the var or an expression who's name will become the var. 4803 4804 Returns: 4805 The new variable node. 4806 """ 4807 if not name: 4808 raise ValueError("Cannot convert empty name into var.") 4809 4810 if isinstance(name, Expression): 4811 name = name.name 4812 return Var(this=name) 4813 4814 4815def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4816 """Build ALTER TABLE... RENAME... expression 4817 4818 Args: 4819 old_name: The old name of the table 4820 new_name: The new name of the table 4821 4822 Returns: 4823 Alter table expression 4824 """ 4825 old_table = to_table(old_name) 4826 new_table = to_table(new_name) 4827 return AlterTable( 4828 this=old_table, 4829 actions=[ 4830 RenameTable(this=new_table), 4831 ], 4832 ) 4833 4834 4835def convert(value) -> Expression: 4836 """Convert a python value into an expression object. 4837 4838 Raises an error if a conversion is not possible. 4839 4840 Args: 4841 value (Any): a python object 4842 4843 Returns: 4844 Expression: the equivalent expression object 4845 """ 4846 if isinstance(value, Expression): 4847 return value 4848 if value is None: 4849 return NULL 4850 if isinstance(value, bool): 4851 return Boolean(this=value) 4852 if isinstance(value, str): 4853 return Literal.string(value) 4854 if isinstance(value, float) and math.isnan(value): 4855 return NULL 4856 if isinstance(value, numbers.Number): 4857 return Literal.number(value) 4858 if isinstance(value, tuple): 4859 return Tuple(expressions=[convert(v) for v in value]) 4860 if isinstance(value, list): 4861 return Array(expressions=[convert(v) for v in value]) 4862 if isinstance(value, dict): 4863 return Map( 4864 keys=[convert(k) for k in value], 4865 values=[convert(v) for v in value.values()], 4866 ) 4867 if isinstance(value, datetime.datetime): 4868 datetime_literal = Literal.string( 4869 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4870 ) 4871 return TimeStrToTime(this=datetime_literal) 4872 if isinstance(value, datetime.date): 4873 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4874 return DateStrToDate(this=date_literal) 4875 raise ValueError(f"Cannot convert {value}") 4876 4877 4878def replace_children(expression, fun, *args, **kwargs): 4879 """ 4880 Replace children of an expression with the result of a lambda fun(child) -> exp. 4881 """ 4882 for k, v in expression.args.items(): 4883 is_list_arg = type(v) is list 4884 4885 child_nodes = v if is_list_arg else [v] 4886 new_child_nodes = [] 4887 4888 for cn in child_nodes: 4889 if isinstance(cn, Expression): 4890 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4891 new_child_nodes.append(child_node) 4892 child_node.parent = expression 4893 child_node.arg_key = k 4894 else: 4895 new_child_nodes.append(cn) 4896 4897 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 4898 4899 4900def column_table_names(expression): 4901 """ 4902 Return all table names referenced through columns in an expression. 4903 4904 Example: 4905 >>> import sqlglot 4906 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4907 ['c', 'a'] 4908 4909 Args: 4910 expression (sqlglot.Expression): expression to find table names 4911 4912 Returns: 4913 list: A list of unique names 4914 """ 4915 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 4916 4917 4918def table_name(table) -> str: 4919 """Get the full name of a table as a string. 4920 4921 Args: 4922 table (exp.Table | str): table expression node or string. 4923 4924 Examples: 4925 >>> from sqlglot import exp, parse_one 4926 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4927 'a.b.c' 4928 4929 Returns: 4930 The table name. 4931 """ 4932 4933 table = maybe_parse(table, into=Table) 4934 4935 if not table: 4936 raise ValueError(f"Cannot parse {table}") 4937 4938 return ".".join( 4939 part 4940 for part in ( 4941 table.text("catalog"), 4942 table.text("db"), 4943 table.name, 4944 ) 4945 if part 4946 ) 4947 4948 4949def replace_tables(expression, mapping): 4950 """Replace all tables in expression according to the mapping. 4951 4952 Args: 4953 expression (sqlglot.Expression): expression node to be transformed and replaced. 4954 mapping (Dict[str, str]): mapping of table names. 4955 4956 Examples: 4957 >>> from sqlglot import exp, parse_one 4958 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4959 'SELECT * FROM c' 4960 4961 Returns: 4962 The mapped expression. 4963 """ 4964 4965 def _replace_tables(node): 4966 if isinstance(node, Table): 4967 new_name = mapping.get(table_name(node)) 4968 if new_name: 4969 return to_table( 4970 new_name, 4971 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4972 ) 4973 return node 4974 4975 return expression.transform(_replace_tables) 4976 4977 4978def replace_placeholders(expression, *args, **kwargs): 4979 """Replace placeholders in an expression. 4980 4981 Args: 4982 expression (sqlglot.Expression): expression node to be transformed and replaced. 4983 args: positional names that will substitute unnamed placeholders in the given order. 4984 kwargs: keyword arguments that will substitute named placeholders. 4985 4986 Examples: 4987 >>> from sqlglot import exp, parse_one 4988 >>> replace_placeholders( 4989 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4990 ... ).sql() 4991 'SELECT * FROM foo WHERE a = b' 4992 4993 Returns: 4994 The mapped expression. 4995 """ 4996 4997 def _replace_placeholders(node, args, **kwargs): 4998 if isinstance(node, Placeholder): 4999 if node.name: 5000 new_name = kwargs.get(node.name) 5001 if new_name: 5002 return to_identifier(new_name) 5003 else: 5004 try: 5005 return to_identifier(next(args)) 5006 except StopIteration: 5007 pass 5008 return node 5009 5010 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5011 5012 5013def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 5014 """Transforms an expression by expanding all referenced sources into subqueries. 5015 5016 Examples: 5017 >>> from sqlglot import parse_one 5018 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5019 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5020 5021 Args: 5022 expression: The expression to expand. 5023 sources: A dictionary of name to Subqueryables. 5024 copy: Whether or not to copy the expression during transformation. Defaults to True. 5025 5026 Returns: 5027 The transformed expression. 5028 """ 5029 5030 def _expand(node: Expression): 5031 if isinstance(node, Table): 5032 name = table_name(node) 5033 source = sources.get(name) 5034 if source: 5035 subquery = source.subquery(node.alias or name) 5036 subquery.comments = [f"source: {name}"] 5037 return subquery 5038 return node 5039 5040 return expression.transform(_expand, copy=copy) 5041 5042 5043def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5044 """ 5045 Returns a Func expression. 5046 5047 Examples: 5048 >>> func("abs", 5).sql() 5049 'ABS(5)' 5050 5051 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5052 'CAST(5 AS DOUBLE)' 5053 5054 Args: 5055 name: the name of the function to build. 5056 args: the args used to instantiate the function of interest. 5057 dialect: the source dialect. 5058 kwargs: the kwargs used to instantiate the function of interest. 5059 5060 Note: 5061 The arguments `args` and `kwargs` are mutually exclusive. 5062 5063 Returns: 5064 An instance of the function of interest, or an anonymous function, if `name` doesn't 5065 correspond to an existing `sqlglot.expressions.Func` class. 5066 """ 5067 if args and kwargs: 5068 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5069 5070 from sqlglot.dialects.dialect import Dialect 5071 5072 converted = [convert(arg) for arg in args] 5073 kwargs = {key: convert(value) for key, value in kwargs.items()} 5074 5075 parser = Dialect.get_or_raise(dialect)().parser() 5076 from_args_list = parser.FUNCTIONS.get(name.upper()) 5077 5078 if from_args_list: 5079 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5080 else: 5081 kwargs = kwargs or {"expressions": converted} 5082 function = Anonymous(this=name, **kwargs) 5083 5084 for error_message in function.error_messages(converted): 5085 raise ValueError(error_message) 5086 5087 return function 5088 5089 5090def true(): 5091 """ 5092 Returns a true Boolean expression. 5093 """ 5094 return Boolean(this=True) 5095 5096 5097def false(): 5098 """ 5099 Returns a false Boolean expression. 5100 """ 5101 return Boolean(this=False) 5102 5103 5104def null(): 5105 """ 5106 Returns a Null expression. 5107 """ 5108 return Null() 5109 5110 5111# TODO: deprecate this 5112TRUE = Boolean(this=True) 5113FALSE = Boolean(this=False) 5114NULL = Null()
57class Expression(metaclass=_Expression): 58 """ 59 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 60 context, such as its child expressions, their names (arg keys), and whether a given child expression 61 is optional or not. 62 63 Attributes: 64 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 65 and representing expressions as strings. 66 arg_types: determines what arguments (child nodes) are supported by an expression. It 67 maps arg keys to booleans that indicate whether the corresponding args are optional. 68 69 Example: 70 >>> class Foo(Expression): 71 ... arg_types = {"this": True, "expression": False} 72 73 The above definition informs us that Foo is an Expression that requires an argument called 74 "this" and may also optionally receive an argument called "expression". 75 76 Args: 77 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 78 parent: a reference to the parent expression (or None, in case of root expressions). 79 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 80 uses to refer to it. 81 comments: a list of comments that are associated with a given expression. This is used in 82 order to preserve comments when transpiling SQL code. 83 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 84 optimizer, in order to enable some transformations that require type information. 85 """ 86 87 key = "expression" 88 arg_types = {"this": True} 89 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 90 91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value) 102 103 def __eq__(self, other) -> bool: 104 return type(self) is type(other) and hash(self) == hash(other) 105 106 @property 107 def hashable_args(self) -> t.Any: 108 args = (self.args.get(k) for k in self.arg_types) 109 110 return tuple( 111 (tuple(_norm_arg(a) for a in arg) if arg else None) 112 if type(arg) is list 113 else (_norm_arg(arg) if arg is not None and arg is not False else None) 114 for arg in args 115 ) 116 117 def __hash__(self) -> int: 118 if self._hash is not None: 119 return self._hash 120 121 return hash((self.__class__, self.hashable_args)) 122 123 @property 124 def this(self): 125 """ 126 Retrieves the argument with key "this". 127 """ 128 return self.args.get("this") 129 130 @property 131 def expression(self): 132 """ 133 Retrieves the argument with key "expression". 134 """ 135 return self.args.get("expression") 136 137 @property 138 def expressions(self): 139 """ 140 Retrieves the argument with key "expressions". 141 """ 142 return self.args.get("expressions") or [] 143 144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return "" 157 158 @property 159 def is_string(self) -> bool: 160 """ 161 Checks whether a Literal expression is a string. 162 """ 163 return isinstance(self, Literal) and self.args["is_string"] 164 165 @property 166 def is_number(self) -> bool: 167 """ 168 Checks whether a Literal expression is a number. 169 """ 170 return isinstance(self, Literal) and not self.args["is_string"] 171 172 @property 173 def is_int(self) -> bool: 174 """ 175 Checks whether a Literal expression is an integer. 176 """ 177 if self.is_number: 178 try: 179 int(self.name) 180 return True 181 except ValueError: 182 pass 183 return False 184 185 @property 186 def is_star(self) -> bool: 187 """Checks whether an expression is a star.""" 188 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 189 190 @property 191 def alias(self) -> str: 192 """ 193 Returns the alias of the expression, or an empty string if it's not aliased. 194 """ 195 if isinstance(self.args.get("alias"), TableAlias): 196 return self.args["alias"].name 197 return self.text("alias") 198 199 @property 200 def name(self) -> str: 201 return self.text("this") 202 203 @property 204 def alias_or_name(self): 205 return self.alias or self.name 206 207 @property 208 def output_name(self): 209 """ 210 Name of the output column if this expression is a selection. 211 212 If the Expression has no output name, an empty string is returned. 213 214 Example: 215 >>> from sqlglot import parse_one 216 >>> parse_one("SELECT a").expressions[0].output_name 217 'a' 218 >>> parse_one("SELECT b AS c").expressions[0].output_name 219 'c' 220 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 221 '' 222 """ 223 return "" 224 225 @property 226 def type(self) -> t.Optional[DataType]: 227 return self._type 228 229 @type.setter 230 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 231 if dtype and not isinstance(dtype, DataType): 232 dtype = DataType.build(dtype) 233 self._type = dtype # type: ignore 234 235 @property 236 def meta(self) -> t.Dict[str, t.Any]: 237 if self._meta is None: 238 self._meta = {} 239 return self._meta 240 241 def __deepcopy__(self, memo): 242 copy = self.__class__(**deepcopy(self.args)) 243 if self.comments is not None: 244 copy.comments = deepcopy(self.comments) 245 246 if self._type is not None: 247 copy._type = self._type.copy() 248 249 if self._meta is not None: 250 copy._meta = deepcopy(self._meta) 251 252 return copy 253 254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new 261 262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value) 274 275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value) 285 286 def _set_parent(self, arg_key, value): 287 if hasattr(value, "parent"): 288 value.parent = self 289 value.arg_key = arg_key 290 elif type(value) is list: 291 for v in value: 292 if hasattr(v, "parent"): 293 v.parent = self 294 v.arg_key = arg_key 295 296 @property 297 def depth(self): 298 """ 299 Returns the depth of this tree. 300 """ 301 if self.parent: 302 return self.parent.depth + 1 303 return 0 304 305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs 315 316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None) 328 329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression 343 344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor) 358 359 @property 360 def parent_select(self): 361 """ 362 Returns the parent select statement. 363 """ 364 return self.find_ancestor(Select) 365 366 @property 367 def same_parent(self): 368 """Returns if the parent is the same class as itself.""" 369 return type(self.parent) is self.__class__ 370 371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression 379 380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune) 397 398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune) 413 414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k)) 433 434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression 442 443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self 450 451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 456 457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node 466 467 def __str__(self): 468 return self.sql() 469 470 def __repr__(self): 471 return self._to_s() 472 473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts) 487 488 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 489 indent = "" if not level else "\n" 490 indent += "".join([" "] * level) 491 left = f"({self.key.upper()} " 492 493 args: t.Dict[str, t.Any] = { 494 k: ", ".join( 495 v._to_s(hide_missing=hide_missing, level=level + 1) 496 if hasattr(v, "_to_s") 497 else str(v) 498 for v in ensure_list(vs) 499 if v is not None 500 ) 501 for k, vs in self.args.items() 502 } 503 args["comments"] = self.comments 504 args["type"] = self.type 505 args = {k: v for k, v in args.items() if v or not hide_missing} 506 507 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 508 right += ")" 509 510 return indent + left + right 511 512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node 538 539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression 565 566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self 575 576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self 592 593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors 626 627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self) 634 635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataType
type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value)
144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
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 ''
254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new
Returns a deep copy of the expression.
262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value)
Sets arg_key
to value
.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs
Yields the key and expression for all arguments, exploding list args.
316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The node which matches the criteria or None if no such node was found.
329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The generator object.
344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression
Returns the root expression of this tree.
380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression
Returns the first non parenthesis child or self.
443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self
Returns the inner expression if this is an Alias.
451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generator
options.
Returns:
The SQL string.
512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression (Expression|None): new node
Returns:
The new expression or expressions.
566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self
Remove this expression from its AST.
Returns:
The popped expression.
576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self
Assert that this Expression
is an instance of type_
.
If it is NOT an instance of type_
, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self)
Dump this Expression to a JSON-serializable dict.
635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
Load a dict (as returned by Expression.dump
) into an Expression instance.
653class Condition(Expression): 654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts) 672 673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts) 691 692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Returns:
Not: the new condition.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
710class DerivedTable(Expression): 711 @property 712 def alias_column_names(self): 713 table_alias = self.args.get("alias") 714 if not table_alias: 715 return [] 716 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 717 return [c.name for c in column_list] 718 719 @property 720 def selects(self): 721 alias = self.args.get("alias") 722 723 if alias: 724 return alias.columns 725 return [] 726 727 @property 728 def named_selects(self): 729 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
732class Unionable(Expression): 733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 752 753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 772 773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the Union expression.
753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the Intersect expression
773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the Except expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
798class Cache(Expression): 799 arg_types = { 800 "with": False, 801 "this": True, 802 "lazy": False, 803 "options": False, 804 "expression": False, 805 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
812class Create(Expression): 813 arg_types = { 814 "with": False, 815 "this": True, 816 "kind": True, 817 "expression": False, 818 "exists": False, 819 "properties": False, 820 "replace": False, 821 "unique": False, 822 "volatile": False, 823 "indexes": False, 824 "no_schema_binding": False, 825 "begin": False, 826 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
841class SetItem(Expression): 842 arg_types = { 843 "this": False, 844 "expressions": False, 845 "kind": False, 846 "collate": False, # MySQL SET NAMES statement 847 "global": False, 848 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
851class Show(Expression): 852 arg_types = { 853 "this": True, 854 "target": False, 855 "offset": False, 856 "limit": False, 857 "like": False, 858 "where": False, 859 "db": False, 860 "full": False, 861 "mutex": False, 862 "query": False, 863 "channel": False, 864 "global": False, 865 "log": False, 866 "position": False, 867 "types": False, 868 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
871class UserDefinedFunction(Expression): 872 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
879class With(Expression): 880 arg_types = {"expressions": True, "recursive": False} 881 882 @property 883 def recursive(self) -> bool: 884 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
895class TableAlias(Expression): 896 arg_types = {"this": False, "columns": False} 897 898 @property 899 def columns(self): 900 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
915class Column(Condition): 916 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 917 918 @property 919 def table(self) -> str: 920 return self.text("table") 921 922 @property 923 def db(self) -> str: 924 return self.text("db") 925 926 @property 927 def catalog(self) -> str: 928 return self.text("catalog") 929 930 @property 931 def output_name(self) -> str: 932 return self.name 933 934 @property 935 def parts(self) -> t.List[Identifier]: 936 """Return the parts of a column in order catalog, db, table, name.""" 937 return [part for part in reversed(list(self.args.values())) if part] 938 939 def to_dot(self) -> Dot: 940 """Converts the column into a dot expression.""" 941 parts = self.parts 942 parent = self.parent 943 944 while parent: 945 if isinstance(parent, Dot): 946 parts.append(parent.expression) 947 parent = parent.parent 948 949 return Dot.build(parts)
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.
939 def to_dot(self) -> Dot: 940 """Converts the column into a dot expression.""" 941 parts = self.parts 942 parent = self.parent 943 944 while parent: 945 if isinstance(parent, Dot): 946 parts.append(parent.expression) 947 parent = parent.parent 948 949 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
952class ColumnDef(Expression): 953 arg_types = { 954 "this": True, 955 "kind": False, 956 "constraints": False, 957 "exists": False, 958 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
961class AlterColumn(Expression): 962 arg_types = { 963 "this": True, 964 "dtype": False, 965 "collate": False, 966 "using": False, 967 "default": False, 968 "drop": False, 969 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
980class Comment(Expression): 981 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1032class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1033 # this: True -> ALWAYS, this: False -> BY DEFAULT 1034 arg_types = { 1035 "this": False, 1036 "start": False, 1037 "increment": False, 1038 "minvalue": False, 1039 "maxvalue": False, 1040 "cycle": False, 1041 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1076class Delete(Expression): 1077 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1078 1079 def delete( 1080 self, 1081 table: ExpOrStr, 1082 dialect: DialectType = None, 1083 copy: bool = True, 1084 **opts, 1085 ) -> Delete: 1086 """ 1087 Create a DELETE expression or replace the table on an existing DELETE expression. 1088 1089 Example: 1090 >>> delete("tbl").sql() 1091 'DELETE FROM tbl' 1092 1093 Args: 1094 table: the table from which to delete. 1095 dialect: the dialect used to parse the input expression. 1096 copy: if `False`, modify this expression instance in-place. 1097 opts: other options to use to parse the input expressions. 1098 1099 Returns: 1100 Delete: the modified expression. 1101 """ 1102 return _apply_builder( 1103 expression=table, 1104 instance=self, 1105 arg="this", 1106 dialect=dialect, 1107 into=Table, 1108 copy=copy, 1109 **opts, 1110 ) 1111 1112 def where( 1113 self, 1114 *expressions: ExpOrStr, 1115 append: bool = True, 1116 dialect: DialectType = None, 1117 copy: bool = True, 1118 **opts, 1119 ) -> Delete: 1120 """ 1121 Append to or set the WHERE expressions. 1122 1123 Example: 1124 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1125 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1126 1127 Args: 1128 *expressions: the SQL code strings to parse. 1129 If an `Expression` instance is passed, it will be used as-is. 1130 Multiple expressions are combined with an AND operator. 1131 append: if `True`, AND the new expressions to any existing expression. 1132 Otherwise, this resets the expression. 1133 dialect: the dialect used to parse the input expressions. 1134 copy: if `False`, modify this expression instance in-place. 1135 opts: other options to use to parse the input expressions. 1136 1137 Returns: 1138 Delete: the modified expression. 1139 """ 1140 return _apply_conjunction_builder( 1141 *expressions, 1142 instance=self, 1143 arg="where", 1144 append=append, 1145 into=Where, 1146 dialect=dialect, 1147 copy=copy, 1148 **opts, 1149 ) 1150 1151 def returning( 1152 self, 1153 expression: ExpOrStr, 1154 dialect: DialectType = None, 1155 copy: bool = True, 1156 **opts, 1157 ) -> Delete: 1158 """ 1159 Set the RETURNING expression. Not supported by all dialects. 1160 1161 Example: 1162 >>> delete("tbl").returning("*", dialect="postgres").sql() 1163 'DELETE FROM tbl RETURNING *' 1164 1165 Args: 1166 expression: the SQL code strings to parse. 1167 If an `Expression` instance is passed, it will be used as-is. 1168 dialect: the dialect used to parse the input expressions. 1169 copy: if `False`, modify this expression instance in-place. 1170 opts: other options to use to parse the input expressions. 1171 1172 Returns: 1173 Delete: the modified expression. 1174 """ 1175 return _apply_builder( 1176 expression=expression, 1177 instance=self, 1178 arg="returning", 1179 prefix="RETURNING", 1180 dialect=dialect, 1181 copy=copy, 1182 into=Returning, 1183 **opts, 1184 )
1079 def delete( 1080 self, 1081 table: ExpOrStr, 1082 dialect: DialectType = None, 1083 copy: bool = True, 1084 **opts, 1085 ) -> Delete: 1086 """ 1087 Create a DELETE expression or replace the table on an existing DELETE expression. 1088 1089 Example: 1090 >>> delete("tbl").sql() 1091 'DELETE FROM tbl' 1092 1093 Args: 1094 table: the table from which to delete. 1095 dialect: the dialect used to parse the input expression. 1096 copy: if `False`, modify this expression instance in-place. 1097 opts: other options to use to parse the input expressions. 1098 1099 Returns: 1100 Delete: the modified expression. 1101 """ 1102 return _apply_builder( 1103 expression=table, 1104 instance=self, 1105 arg="this", 1106 dialect=dialect, 1107 into=Table, 1108 copy=copy, 1109 **opts, 1110 )
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.
1112 def where( 1113 self, 1114 *expressions: ExpOrStr, 1115 append: bool = True, 1116 dialect: DialectType = None, 1117 copy: bool = True, 1118 **opts, 1119 ) -> Delete: 1120 """ 1121 Append to or set the WHERE expressions. 1122 1123 Example: 1124 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1125 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1126 1127 Args: 1128 *expressions: the SQL code strings to parse. 1129 If an `Expression` instance is passed, it will be used as-is. 1130 Multiple expressions are combined with an AND operator. 1131 append: if `True`, AND the new expressions to any existing expression. 1132 Otherwise, this resets the expression. 1133 dialect: the dialect used to parse the input expressions. 1134 copy: if `False`, modify this expression instance in-place. 1135 opts: other options to use to parse the input expressions. 1136 1137 Returns: 1138 Delete: the modified expression. 1139 """ 1140 return _apply_conjunction_builder( 1141 *expressions, 1142 instance=self, 1143 arg="where", 1144 append=append, 1145 into=Where, 1146 dialect=dialect, 1147 copy=copy, 1148 **opts, 1149 )
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.
1151 def returning( 1152 self, 1153 expression: ExpOrStr, 1154 dialect: DialectType = None, 1155 copy: bool = True, 1156 **opts, 1157 ) -> Delete: 1158 """ 1159 Set the RETURNING expression. Not supported by all dialects. 1160 1161 Example: 1162 >>> delete("tbl").returning("*", dialect="postgres").sql() 1163 'DELETE FROM tbl RETURNING *' 1164 1165 Args: 1166 expression: the SQL code strings to parse. 1167 If an `Expression` instance is passed, it will be used as-is. 1168 dialect: the dialect used to parse the input expressions. 1169 copy: if `False`, modify this expression instance in-place. 1170 opts: other options to use to parse the input expressions. 1171 1172 Returns: 1173 Delete: the modified expression. 1174 """ 1175 return _apply_builder( 1176 expression=expression, 1177 instance=self, 1178 arg="returning", 1179 prefix="RETURNING", 1180 dialect=dialect, 1181 copy=copy, 1182 into=Returning, 1183 **opts, 1184 )
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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1187class Drop(Expression): 1188 arg_types = { 1189 "this": False, 1190 "kind": False, 1191 "exists": False, 1192 "temporary": False, 1193 "materialized": False, 1194 "cascade": False, 1195 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1206class Directory(Expression): 1207 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1208 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1211class ForeignKey(Expression): 1212 arg_types = { 1213 "expressions": True, 1214 "reference": False, 1215 "delete": False, 1216 "update": False, 1217 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1250class Identifier(Expression): 1251 arg_types = {"this": True, "quoted": False} 1252 1253 @property 1254 def quoted(self): 1255 return bool(self.args.get("quoted")) 1256 1257 @property 1258 def hashable_args(self) -> t.Any: 1259 if self.quoted and any(char.isupper() for char in self.this): 1260 return (self.this, self.quoted) 1261 return self.this.lower() 1262 1263 @property 1264 def output_name(self): 1265 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1268class Index(Expression): 1269 arg_types = { 1270 "this": False, 1271 "table": False, 1272 "where": False, 1273 "columns": False, 1274 "unique": False, 1275 "primary": False, 1276 "amp": False, # teradata 1277 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1280class Insert(Expression): 1281 arg_types = { 1282 "with": False, 1283 "this": True, 1284 "expression": False, 1285 "returning": False, 1286 "overwrite": False, 1287 "exists": False, 1288 "partition": False, 1289 "alternative": False, 1290 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1307class LoadData(Expression): 1308 arg_types = { 1309 "this": True, 1310 "local": False, 1311 "overwrite": False, 1312 "inpath": True, 1313 "partition": False, 1314 "input_format": False, 1315 "serde": False, 1316 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1327class Group(Expression): 1328 arg_types = { 1329 "expressions": False, 1330 "grouping_sets": False, 1331 "cube": False, 1332 "rollup": False, 1333 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1344class Literal(Condition): 1345 arg_types = {"this": True, "is_string": True} 1346 1347 @property 1348 def hashable_args(self) -> t.Any: 1349 return (self.this, self.args.get("is_string")) 1350 1351 @classmethod 1352 def number(cls, number) -> Literal: 1353 return cls(this=str(number), is_string=False) 1354 1355 @classmethod 1356 def string(cls, string) -> Literal: 1357 return cls(this=str(string), is_string=True) 1358 1359 @property 1360 def output_name(self): 1361 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1364class Join(Expression): 1365 arg_types = { 1366 "this": True, 1367 "on": False, 1368 "side": False, 1369 "kind": False, 1370 "using": False, 1371 "natural": False, 1372 } 1373 1374 @property 1375 def kind(self): 1376 return self.text("kind").upper() 1377 1378 @property 1379 def side(self): 1380 return self.text("side").upper() 1381 1382 @property 1383 def alias_or_name(self): 1384 return self.this.alias_or_name 1385 1386 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1387 """ 1388 Append to or set the ON expressions. 1389 1390 Example: 1391 >>> import sqlglot 1392 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1393 'JOIN x ON y = 1' 1394 1395 Args: 1396 *expressions (str | Expression): the SQL code strings to parse. 1397 If an `Expression` instance is passed, it will be used as-is. 1398 Multiple expressions are combined with an AND operator. 1399 append (bool): if `True`, AND the new expressions to any existing expression. 1400 Otherwise, this resets the expression. 1401 dialect (str): the dialect used to parse the input expressions. 1402 copy (bool): if `False`, modify this expression instance in-place. 1403 opts (kwargs): other options to use to parse the input expressions. 1404 1405 Returns: 1406 Join: the modified join expression. 1407 """ 1408 join = _apply_conjunction_builder( 1409 *expressions, 1410 instance=self, 1411 arg="on", 1412 append=append, 1413 dialect=dialect, 1414 copy=copy, 1415 **opts, 1416 ) 1417 1418 if join.kind == "CROSS": 1419 join.set("kind", None) 1420 1421 return join 1422 1423 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1424 """ 1425 Append to or set the USING expressions. 1426 1427 Example: 1428 >>> import sqlglot 1429 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1430 'JOIN x USING (foo, bla)' 1431 1432 Args: 1433 *expressions (str | Expression): the SQL code strings to parse. 1434 If an `Expression` instance is passed, it will be used as-is. 1435 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1436 Otherwise, this resets the expression. 1437 dialect (str): the dialect used to parse the input expressions. 1438 copy (bool): if `False`, modify this expression instance in-place. 1439 opts (kwargs): other options to use to parse the input expressions. 1440 1441 Returns: 1442 Join: the modified join expression. 1443 """ 1444 join = _apply_list_builder( 1445 *expressions, 1446 instance=self, 1447 arg="using", 1448 append=append, 1449 dialect=dialect, 1450 copy=copy, 1451 **opts, 1452 ) 1453 1454 if join.kind == "CROSS": 1455 join.set("kind", None) 1456 1457 return join
1386 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1387 """ 1388 Append to or set the ON expressions. 1389 1390 Example: 1391 >>> import sqlglot 1392 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1393 'JOIN x ON y = 1' 1394 1395 Args: 1396 *expressions (str | Expression): the SQL code strings to parse. 1397 If an `Expression` instance is passed, it will be used as-is. 1398 Multiple expressions are combined with an AND operator. 1399 append (bool): if `True`, AND the new expressions to any existing expression. 1400 Otherwise, this resets the expression. 1401 dialect (str): the dialect used to parse the input expressions. 1402 copy (bool): if `False`, modify this expression instance in-place. 1403 opts (kwargs): other options to use to parse the input expressions. 1404 1405 Returns: 1406 Join: the modified join expression. 1407 """ 1408 join = _apply_conjunction_builder( 1409 *expressions, 1410 instance=self, 1411 arg="on", 1412 append=append, 1413 dialect=dialect, 1414 copy=copy, 1415 **opts, 1416 ) 1417 1418 if join.kind == "CROSS": 1419 join.set("kind", None) 1420 1421 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
1423 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1424 """ 1425 Append to or set the USING expressions. 1426 1427 Example: 1428 >>> import sqlglot 1429 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1430 'JOIN x USING (foo, bla)' 1431 1432 Args: 1433 *expressions (str | Expression): the SQL code strings to parse. 1434 If an `Expression` instance is passed, it will be used as-is. 1435 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1436 Otherwise, this resets the expression. 1437 dialect (str): the dialect used to parse the input expressions. 1438 copy (bool): if `False`, modify this expression instance in-place. 1439 opts (kwargs): other options to use to parse the input expressions. 1440 1441 Returns: 1442 Join: the modified join expression. 1443 """ 1444 join = _apply_list_builder( 1445 *expressions, 1446 instance=self, 1447 arg="using", 1448 append=append, 1449 dialect=dialect, 1450 copy=copy, 1451 **opts, 1452 ) 1453 1454 if join.kind == "CROSS": 1455 join.set("kind", None) 1456 1457 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append (bool): if
True
, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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 Lateral(UDTF): 1461 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1464class MatchRecognize(Expression): 1465 arg_types = { 1466 "partition_by": False, 1467 "order": False, 1468 "measures": False, 1469 "rows": False, 1470 "after": False, 1471 "pattern": False, 1472 "define": False, 1473 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1512class AfterJournalProperty(Property): 1513 arg_types = {"no": True, "dual": False, "local": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1524class BlockCompressionProperty(Property): 1525 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1540class DataBlocksizeProperty(Property): 1541 arg_types = {"size": False, "units": False, "min": False, "default": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1580class IsolatedLoadingProperty(Property): 1581 arg_types = { 1582 "no": True, 1583 "concurrent": True, 1584 "for_all": True, 1585 "for_insert": True, 1586 "for_none": True, 1587 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1606class LockingProperty(Property): 1607 arg_types = { 1608 "this": False, 1609 "kind": True, 1610 "for_or_in": True, 1611 "lock_type": True, 1612 "override": False, 1613 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1624class MergeBlockRatioProperty(Property): 1625 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1640class ReturnsProperty(Property): 1641 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1644class RowFormatDelimitedProperty(Property): 1645 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1646 arg_types = { 1647 "fields": False, 1648 "escaped": False, 1649 "collection_items": False, 1650 "map_keys": False, 1651 "lines": False, 1652 "null": False, 1653 "serde": False, 1654 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1705class Properties(Expression): 1706 arg_types = {"expressions": True} 1707 1708 NAME_TO_PROPERTY = { 1709 "ALGORITHM": AlgorithmProperty, 1710 "AUTO_INCREMENT": AutoIncrementProperty, 1711 "CHARACTER SET": CharacterSetProperty, 1712 "COLLATE": CollateProperty, 1713 "COMMENT": SchemaCommentProperty, 1714 "DEFINER": DefinerProperty, 1715 "DISTKEY": DistKeyProperty, 1716 "DISTSTYLE": DistStyleProperty, 1717 "ENGINE": EngineProperty, 1718 "EXECUTE AS": ExecuteAsProperty, 1719 "FORMAT": FileFormatProperty, 1720 "LANGUAGE": LanguageProperty, 1721 "LOCATION": LocationProperty, 1722 "PARTITIONED_BY": PartitionedByProperty, 1723 "RETURNS": ReturnsProperty, 1724 "SORTKEY": SortKeyProperty, 1725 "TABLE_FORMAT": TableFormatProperty, 1726 } 1727 1728 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1729 1730 # CREATE property locations 1731 # Form: schema specified 1732 # create [POST_CREATE] 1733 # table a [POST_NAME] 1734 # (b int) [POST_SCHEMA] 1735 # with ([POST_WITH]) 1736 # index (b) [POST_INDEX] 1737 # 1738 # Form: alias selection 1739 # create [POST_CREATE] 1740 # table a [POST_NAME] 1741 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1742 # index (c) [POST_INDEX] 1743 class Location(AutoName): 1744 POST_CREATE = auto() 1745 POST_NAME = auto() 1746 POST_SCHEMA = auto() 1747 POST_WITH = auto() 1748 POST_ALIAS = auto() 1749 POST_EXPRESSION = auto() 1750 POST_INDEX = auto() 1751 UNSUPPORTED = auto() 1752 1753 @classmethod 1754 def from_dict(cls, properties_dict) -> Properties: 1755 expressions = [] 1756 for key, value in properties_dict.items(): 1757 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1758 if property_cls: 1759 expressions.append(property_cls(this=convert(value))) 1760 else: 1761 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1762 1763 return cls(expressions=expressions)
1753 @classmethod 1754 def from_dict(cls, properties_dict) -> Properties: 1755 expressions = [] 1756 for key, value in properties_dict.items(): 1757 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1758 if property_cls: 1759 expressions.append(property_cls(this=convert(value))) 1760 else: 1761 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1762 1763 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1743 class Location(AutoName): 1744 POST_CREATE = auto() 1745 POST_NAME = auto() 1746 POST_SCHEMA = auto() 1747 POST_WITH = auto() 1748 POST_ALIAS = auto() 1749 POST_EXPRESSION = auto() 1750 POST_INDEX = auto() 1751 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1775class Reference(Expression): 1776 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1783class Subqueryable(Unionable): 1784 def subquery(self, alias=None, copy=True) -> Subquery: 1785 """ 1786 Convert this expression to an aliased expression that can be used as a Subquery. 1787 1788 Example: 1789 >>> subquery = Select().select("x").from_("tbl").subquery() 1790 >>> Select().select("x").from_(subquery).sql() 1791 'SELECT x FROM (SELECT x FROM tbl)' 1792 1793 Args: 1794 alias (str | Identifier): an optional alias for the subquery 1795 copy (bool): if `False`, modify this expression instance in-place. 1796 1797 Returns: 1798 Alias: the subquery 1799 """ 1800 instance = _maybe_copy(self, copy) 1801 return Subquery( 1802 this=instance, 1803 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1804 ) 1805 1806 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1807 raise NotImplementedError 1808 1809 @property 1810 def ctes(self): 1811 with_ = self.args.get("with") 1812 if not with_: 1813 return [] 1814 return with_.expressions 1815 1816 @property 1817 def selects(self): 1818 raise NotImplementedError("Subqueryable objects must implement `selects`") 1819 1820 @property 1821 def named_selects(self): 1822 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1823 1824 def with_( 1825 self, 1826 alias, 1827 as_, 1828 recursive=None, 1829 append=True, 1830 dialect=None, 1831 copy=True, 1832 **opts, 1833 ): 1834 """ 1835 Append to or set the common table expressions. 1836 1837 Example: 1838 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1839 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1840 1841 Args: 1842 alias (str | Expression): the SQL code string to parse as the table name. 1843 If an `Expression` instance is passed, this is used as-is. 1844 as_ (str | Expression): the SQL code string to parse as the table expression. 1845 If an `Expression` instance is passed, it will be used as-is. 1846 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1847 append (bool): if `True`, add to any existing expressions. 1848 Otherwise, this resets the expressions. 1849 dialect (str): the dialect used to parse the input expression. 1850 copy (bool): if `False`, modify this expression instance in-place. 1851 opts (kwargs): other options to use to parse the input expressions. 1852 1853 Returns: 1854 Select: the modified expression. 1855 """ 1856 alias_expression = maybe_parse( 1857 alias, 1858 dialect=dialect, 1859 into=TableAlias, 1860 **opts, 1861 ) 1862 as_expression = maybe_parse( 1863 as_, 1864 dialect=dialect, 1865 **opts, 1866 ) 1867 cte = CTE( 1868 this=as_expression, 1869 alias=alias_expression, 1870 ) 1871 return _apply_child_list_builder( 1872 cte, 1873 instance=self, 1874 arg="with", 1875 append=append, 1876 copy=copy, 1877 into=With, 1878 properties={"recursive": recursive or False}, 1879 )
1784 def subquery(self, alias=None, copy=True) -> Subquery: 1785 """ 1786 Convert this expression to an aliased expression that can be used as a Subquery. 1787 1788 Example: 1789 >>> subquery = Select().select("x").from_("tbl").subquery() 1790 >>> Select().select("x").from_(subquery).sql() 1791 'SELECT x FROM (SELECT x FROM tbl)' 1792 1793 Args: 1794 alias (str | Identifier): an optional alias for the subquery 1795 copy (bool): if `False`, modify this expression instance in-place. 1796 1797 Returns: 1798 Alias: the subquery 1799 """ 1800 instance = _maybe_copy(self, copy) 1801 return Subquery( 1802 this=instance, 1803 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1804 )
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
1824 def with_( 1825 self, 1826 alias, 1827 as_, 1828 recursive=None, 1829 append=True, 1830 dialect=None, 1831 copy=True, 1832 **opts, 1833 ): 1834 """ 1835 Append to or set the common table expressions. 1836 1837 Example: 1838 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1839 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1840 1841 Args: 1842 alias (str | Expression): the SQL code string to parse as the table name. 1843 If an `Expression` instance is passed, this is used as-is. 1844 as_ (str | Expression): the SQL code string to parse as the table expression. 1845 If an `Expression` instance is passed, it will be used as-is. 1846 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1847 append (bool): if `True`, add to any existing expressions. 1848 Otherwise, this resets the expressions. 1849 dialect (str): the dialect used to parse the input expression. 1850 copy (bool): if `False`, modify this expression instance in-place. 1851 opts (kwargs): other options to use to parse the input expressions. 1852 1853 Returns: 1854 Select: the modified expression. 1855 """ 1856 alias_expression = maybe_parse( 1857 alias, 1858 dialect=dialect, 1859 into=TableAlias, 1860 **opts, 1861 ) 1862 as_expression = maybe_parse( 1863 as_, 1864 dialect=dialect, 1865 **opts, 1866 ) 1867 cte = CTE( 1868 this=as_expression, 1869 alias=alias_expression, 1870 ) 1871 return _apply_child_list_builder( 1872 cte, 1873 instance=self, 1874 arg="with", 1875 append=append, 1876 copy=copy, 1877 into=With, 1878 properties={"recursive": recursive or False}, 1879 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias (str | Expression): the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_ (str | Expression): the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive (bool): set the RECURSIVE part of the expression. Defaults to
False
. - append (bool): if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1903class Table(Expression): 1904 arg_types = { 1905 "this": True, 1906 "alias": False, 1907 "db": False, 1908 "catalog": False, 1909 "laterals": False, 1910 "joins": False, 1911 "pivots": False, 1912 "hints": False, 1913 "system_time": False, 1914 } 1915 1916 @property 1917 def db(self) -> str: 1918 return self.text("db") 1919 1920 @property 1921 def catalog(self) -> str: 1922 return self.text("catalog")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1926class SystemTime(Expression): 1927 arg_types = { 1928 "this": False, 1929 "expression": False, 1930 "kind": True, 1931 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1934class Union(Subqueryable): 1935 arg_types = { 1936 "with": False, 1937 "this": True, 1938 "expression": True, 1939 "distinct": False, 1940 **QUERY_MODIFIERS, 1941 } 1942 1943 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1944 """ 1945 Set the LIMIT expression. 1946 1947 Example: 1948 >>> select("1").union(select("1")).limit(1).sql() 1949 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1950 1951 Args: 1952 expression (str | int | Expression): the SQL code string to parse. 1953 This can also be an integer. 1954 If a `Limit` instance is passed, this is used as-is. 1955 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1956 dialect (str): the dialect used to parse the input expression. 1957 copy (bool): if `False`, modify this expression instance in-place. 1958 opts (kwargs): other options to use to parse the input expressions. 1959 1960 Returns: 1961 Select: The limited subqueryable. 1962 """ 1963 return ( 1964 select("*") 1965 .from_(self.subquery(alias="_l_0", copy=copy)) 1966 .limit(expression, dialect=dialect, copy=False, **opts) 1967 ) 1968 1969 def select( 1970 self, 1971 *expressions: ExpOrStr, 1972 append: bool = True, 1973 dialect: DialectType = None, 1974 copy: bool = True, 1975 **opts, 1976 ) -> Union: 1977 """Append to or set the SELECT of the union recursively. 1978 1979 Example: 1980 >>> from sqlglot import parse_one 1981 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1982 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1983 1984 Args: 1985 *expressions: the SQL code strings to parse. 1986 If an `Expression` instance is passed, it will be used as-is. 1987 append: if `True`, add to any existing expressions. 1988 Otherwise, this resets the expressions. 1989 dialect: the dialect used to parse the input expressions. 1990 copy: if `False`, modify this expression instance in-place. 1991 opts: other options to use to parse the input expressions. 1992 1993 Returns: 1994 Union: the modified expression. 1995 """ 1996 this = self.copy() if copy else self 1997 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1998 this.expression.unnest().select( 1999 *expressions, append=append, dialect=dialect, copy=False, **opts 2000 ) 2001 return this 2002 2003 @property 2004 def named_selects(self): 2005 return self.this.unnest().named_selects 2006 2007 @property 2008 def is_star(self) -> bool: 2009 return self.this.is_star or self.expression.is_star 2010 2011 @property 2012 def selects(self): 2013 return self.this.unnest().selects 2014 2015 @property 2016 def left(self): 2017 return self.this 2018 2019 @property 2020 def right(self): 2021 return self.expression
1943 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1944 """ 1945 Set the LIMIT expression. 1946 1947 Example: 1948 >>> select("1").union(select("1")).limit(1).sql() 1949 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1950 1951 Args: 1952 expression (str | int | Expression): the SQL code string to parse. 1953 This can also be an integer. 1954 If a `Limit` instance is passed, this is used as-is. 1955 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1956 dialect (str): the dialect used to parse the input expression. 1957 copy (bool): if `False`, modify this expression instance in-place. 1958 opts (kwargs): other options to use to parse the input expressions. 1959 1960 Returns: 1961 Select: The limited subqueryable. 1962 """ 1963 return ( 1964 select("*") 1965 .from_(self.subquery(alias="_l_0", copy=copy)) 1966 .limit(expression, dialect=dialect, copy=False, **opts) 1967 )
Set the LIMIT expression.
Example:
>>> select("1").union(select("1")).limit(1).sql() 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limit
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aLimit
. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: The limited subqueryable.
1969 def select( 1970 self, 1971 *expressions: ExpOrStr, 1972 append: bool = True, 1973 dialect: DialectType = None, 1974 copy: bool = True, 1975 **opts, 1976 ) -> Union: 1977 """Append to or set the SELECT of the union recursively. 1978 1979 Example: 1980 >>> from sqlglot import parse_one 1981 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1982 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1983 1984 Args: 1985 *expressions: the SQL code strings to parse. 1986 If an `Expression` instance is passed, it will be used as-is. 1987 append: if `True`, add to any existing expressions. 1988 Otherwise, this resets the expressions. 1989 dialect: the dialect used to parse the input expressions. 1990 copy: if `False`, modify this expression instance in-place. 1991 opts: other options to use to parse the input expressions. 1992 1993 Returns: 1994 Union: the modified expression. 1995 """ 1996 this = self.copy() if copy else self 1997 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1998 this.expression.unnest().select( 1999 *expressions, append=append, dialect=dialect, copy=False, **opts 2000 ) 2001 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2032class Unnest(UDTF): 2033 arg_types = { 2034 "expressions": True, 2035 "ordinality": False, 2036 "alias": False, 2037 "offset": False, 2038 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2041class Update(Expression): 2042 arg_types = { 2043 "with": False, 2044 "this": False, 2045 "expressions": True, 2046 "from": False, 2047 "where": False, 2048 "returning": False, 2049 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2052class Values(UDTF): 2053 arg_types = { 2054 "expressions": True, 2055 "ordinality": False, 2056 "alias": False, 2057 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2074class Select(Subqueryable): 2075 arg_types = { 2076 "with": False, 2077 "kind": False, 2078 "expressions": False, 2079 "hint": False, 2080 "distinct": False, 2081 "into": False, 2082 "from": False, 2083 **QUERY_MODIFIERS, 2084 } 2085 2086 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2087 """ 2088 Set the FROM expression. 2089 2090 Example: 2091 >>> Select().from_("tbl").select("x").sql() 2092 'SELECT x FROM tbl' 2093 2094 Args: 2095 *expressions (str | Expression): the SQL code strings to parse. 2096 If a `From` instance is passed, this is used as-is. 2097 If another `Expression` instance is passed, it will be wrapped in a `From`. 2098 append (bool): if `True`, add to any existing expressions. 2099 Otherwise, this flattens all the `From` expression into a single expression. 2100 dialect (str): the dialect used to parse the input expression. 2101 copy (bool): if `False`, modify this expression instance in-place. 2102 opts (kwargs): other options to use to parse the input expressions. 2103 2104 Returns: 2105 Select: the modified expression. 2106 """ 2107 return _apply_child_list_builder( 2108 *expressions, 2109 instance=self, 2110 arg="from", 2111 append=append, 2112 copy=copy, 2113 prefix="FROM", 2114 into=From, 2115 dialect=dialect, 2116 **opts, 2117 ) 2118 2119 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2120 """ 2121 Set the GROUP BY expression. 2122 2123 Example: 2124 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2125 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2126 2127 Args: 2128 *expressions (str | Expression): the SQL code strings to parse. 2129 If a `Group` instance is passed, this is used as-is. 2130 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2131 If nothing is passed in then a group by is not applied to the expression 2132 append (bool): if `True`, add to any existing expressions. 2133 Otherwise, this flattens all the `Group` expression into a single expression. 2134 dialect (str): the dialect used to parse the input expression. 2135 copy (bool): if `False`, modify this expression instance in-place. 2136 opts (kwargs): other options to use to parse the input expressions. 2137 2138 Returns: 2139 Select: the modified expression. 2140 """ 2141 if not expressions: 2142 return self if not copy else self.copy() 2143 return _apply_child_list_builder( 2144 *expressions, 2145 instance=self, 2146 arg="group", 2147 append=append, 2148 copy=copy, 2149 prefix="GROUP BY", 2150 into=Group, 2151 dialect=dialect, 2152 **opts, 2153 ) 2154 2155 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2156 """ 2157 Set the ORDER BY expression. 2158 2159 Example: 2160 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2161 'SELECT x FROM tbl ORDER BY x DESC' 2162 2163 Args: 2164 *expressions (str | Expression): the SQL code strings to parse. 2165 If a `Group` instance is passed, this is used as-is. 2166 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2167 append (bool): if `True`, add to any existing expressions. 2168 Otherwise, this flattens all the `Order` expression into a single expression. 2169 dialect (str): the dialect used to parse the input expression. 2170 copy (bool): if `False`, modify this expression instance in-place. 2171 opts (kwargs): other options to use to parse the input expressions. 2172 2173 Returns: 2174 Select: the modified expression. 2175 """ 2176 return _apply_child_list_builder( 2177 *expressions, 2178 instance=self, 2179 arg="order", 2180 append=append, 2181 copy=copy, 2182 prefix="ORDER BY", 2183 into=Order, 2184 dialect=dialect, 2185 **opts, 2186 ) 2187 2188 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2189 """ 2190 Set the SORT BY expression. 2191 2192 Example: 2193 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2194 'SELECT x FROM tbl SORT BY x DESC' 2195 2196 Args: 2197 *expressions (str | Expression): the SQL code strings to parse. 2198 If a `Group` instance is passed, this is used as-is. 2199 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2200 append (bool): if `True`, add to any existing expressions. 2201 Otherwise, this flattens all the `Order` expression into a single expression. 2202 dialect (str): the dialect used to parse the input expression. 2203 copy (bool): if `False`, modify this expression instance in-place. 2204 opts (kwargs): other options to use to parse the input expressions. 2205 2206 Returns: 2207 Select: the modified expression. 2208 """ 2209 return _apply_child_list_builder( 2210 *expressions, 2211 instance=self, 2212 arg="sort", 2213 append=append, 2214 copy=copy, 2215 prefix="SORT BY", 2216 into=Sort, 2217 dialect=dialect, 2218 **opts, 2219 ) 2220 2221 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2222 """ 2223 Set the CLUSTER BY expression. 2224 2225 Example: 2226 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2227 'SELECT x FROM tbl CLUSTER BY x DESC' 2228 2229 Args: 2230 *expressions (str | Expression): the SQL code strings to parse. 2231 If a `Group` instance is passed, this is used as-is. 2232 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2233 append (bool): if `True`, add to any existing expressions. 2234 Otherwise, this flattens all the `Order` expression into a single expression. 2235 dialect (str): the dialect used to parse the input expression. 2236 copy (bool): if `False`, modify this expression instance in-place. 2237 opts (kwargs): other options to use to parse the input expressions. 2238 2239 Returns: 2240 Select: the modified expression. 2241 """ 2242 return _apply_child_list_builder( 2243 *expressions, 2244 instance=self, 2245 arg="cluster", 2246 append=append, 2247 copy=copy, 2248 prefix="CLUSTER BY", 2249 into=Cluster, 2250 dialect=dialect, 2251 **opts, 2252 ) 2253 2254 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2255 """ 2256 Set the LIMIT expression. 2257 2258 Example: 2259 >>> Select().from_("tbl").select("x").limit(10).sql() 2260 'SELECT x FROM tbl LIMIT 10' 2261 2262 Args: 2263 expression (str | int | Expression): the SQL code string to parse. 2264 This can also be an integer. 2265 If a `Limit` instance is passed, this is used as-is. 2266 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2267 dialect (str): the dialect used to parse the input expression. 2268 copy (bool): if `False`, modify this expression instance in-place. 2269 opts (kwargs): other options to use to parse the input expressions. 2270 2271 Returns: 2272 Select: the modified expression. 2273 """ 2274 return _apply_builder( 2275 expression=expression, 2276 instance=self, 2277 arg="limit", 2278 into=Limit, 2279 prefix="LIMIT", 2280 dialect=dialect, 2281 copy=copy, 2282 **opts, 2283 ) 2284 2285 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2286 """ 2287 Set the OFFSET expression. 2288 2289 Example: 2290 >>> Select().from_("tbl").select("x").offset(10).sql() 2291 'SELECT x FROM tbl OFFSET 10' 2292 2293 Args: 2294 expression (str | int | Expression): the SQL code string to parse. 2295 This can also be an integer. 2296 If a `Offset` instance is passed, this is used as-is. 2297 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2298 dialect (str): the dialect used to parse the input expression. 2299 copy (bool): if `False`, modify this expression instance in-place. 2300 opts (kwargs): other options to use to parse the input expressions. 2301 2302 Returns: 2303 Select: the modified expression. 2304 """ 2305 return _apply_builder( 2306 expression=expression, 2307 instance=self, 2308 arg="offset", 2309 into=Offset, 2310 prefix="OFFSET", 2311 dialect=dialect, 2312 copy=copy, 2313 **opts, 2314 ) 2315 2316 def select( 2317 self, 2318 *expressions: ExpOrStr, 2319 append: bool = True, 2320 dialect: DialectType = None, 2321 copy: bool = True, 2322 **opts, 2323 ) -> Select: 2324 """ 2325 Append to or set the SELECT expressions. 2326 2327 Example: 2328 >>> Select().select("x", "y").sql() 2329 'SELECT x, y' 2330 2331 Args: 2332 *expressions: the SQL code strings to parse. 2333 If an `Expression` instance is passed, it will be used as-is. 2334 append: if `True`, add to any existing expressions. 2335 Otherwise, this resets the expressions. 2336 dialect: the dialect used to parse the input expressions. 2337 copy: if `False`, modify this expression instance in-place. 2338 opts: other options to use to parse the input expressions. 2339 2340 Returns: 2341 Select: the modified expression. 2342 """ 2343 return _apply_list_builder( 2344 *expressions, 2345 instance=self, 2346 arg="expressions", 2347 append=append, 2348 dialect=dialect, 2349 copy=copy, 2350 **opts, 2351 ) 2352 2353 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2354 """ 2355 Append to or set the LATERAL expressions. 2356 2357 Example: 2358 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2359 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2360 2361 Args: 2362 *expressions (str | Expression): the SQL code strings to parse. 2363 If an `Expression` instance is passed, it will be used as-is. 2364 append (bool): if `True`, add to any existing expressions. 2365 Otherwise, this resets the expressions. 2366 dialect (str): the dialect used to parse the input expressions. 2367 copy (bool): if `False`, modify this expression instance in-place. 2368 opts (kwargs): other options to use to parse the input expressions. 2369 2370 Returns: 2371 Select: the modified expression. 2372 """ 2373 return _apply_list_builder( 2374 *expressions, 2375 instance=self, 2376 arg="laterals", 2377 append=append, 2378 into=Lateral, 2379 prefix="LATERAL VIEW", 2380 dialect=dialect, 2381 copy=copy, 2382 **opts, 2383 ) 2384 2385 def join( 2386 self, 2387 expression, 2388 on=None, 2389 using=None, 2390 append=True, 2391 join_type=None, 2392 join_alias=None, 2393 dialect=None, 2394 copy=True, 2395 **opts, 2396 ) -> Select: 2397 """ 2398 Append to or set the JOIN expressions. 2399 2400 Example: 2401 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2402 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2403 2404 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2405 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2406 2407 Use `join_type` to change the type of join: 2408 2409 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2410 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2411 2412 Args: 2413 expression (str | Expression): the SQL code string to parse. 2414 If an `Expression` instance is passed, it will be used as-is. 2415 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2416 If an `Expression` instance is passed, it will be used as-is. 2417 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2418 If an `Expression` instance is passed, it will be used as-is. 2419 append (bool): if `True`, add to any existing expressions. 2420 Otherwise, this resets the expressions. 2421 join_type (str): If set, alter the parsed join type 2422 dialect (str): the dialect used to parse the input expressions. 2423 copy (bool): if `False`, modify this expression instance in-place. 2424 opts (kwargs): other options to use to parse the input expressions. 2425 2426 Returns: 2427 Select: the modified expression. 2428 """ 2429 parse_args = {"dialect": dialect, **opts} 2430 2431 try: 2432 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2433 except ParseError: 2434 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2435 2436 join = expression if isinstance(expression, Join) else Join(this=expression) 2437 2438 if isinstance(join.this, Select): 2439 join.this.replace(join.this.subquery()) 2440 2441 if join_type: 2442 natural: t.Optional[Token] 2443 side: t.Optional[Token] 2444 kind: t.Optional[Token] 2445 2446 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2447 2448 if natural: 2449 join.set("natural", True) 2450 if side: 2451 join.set("side", side.text) 2452 if kind: 2453 join.set("kind", kind.text) 2454 2455 if on: 2456 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2457 join.set("on", on) 2458 2459 if using: 2460 join = _apply_list_builder( 2461 *ensure_collection(using), 2462 instance=join, 2463 arg="using", 2464 append=append, 2465 copy=copy, 2466 **opts, 2467 ) 2468 2469 if join_alias: 2470 join.set("this", alias_(join.this, join_alias, table=True)) 2471 return _apply_list_builder( 2472 join, 2473 instance=self, 2474 arg="joins", 2475 append=append, 2476 copy=copy, 2477 **opts, 2478 ) 2479 2480 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2481 """ 2482 Append to or set the WHERE expressions. 2483 2484 Example: 2485 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2486 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2487 2488 Args: 2489 *expressions (str | Expression): the SQL code strings to parse. 2490 If an `Expression` instance is passed, it will be used as-is. 2491 Multiple expressions are combined with an AND operator. 2492 append (bool): if `True`, AND the new expressions to any existing expression. 2493 Otherwise, this resets the expression. 2494 dialect (str): the dialect used to parse the input expressions. 2495 copy (bool): if `False`, modify this expression instance in-place. 2496 opts (kwargs): other options to use to parse the input expressions. 2497 2498 Returns: 2499 Select: the modified expression. 2500 """ 2501 return _apply_conjunction_builder( 2502 *expressions, 2503 instance=self, 2504 arg="where", 2505 append=append, 2506 into=Where, 2507 dialect=dialect, 2508 copy=copy, 2509 **opts, 2510 ) 2511 2512 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2513 """ 2514 Append to or set the HAVING expressions. 2515 2516 Example: 2517 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2518 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2519 2520 Args: 2521 *expressions (str | Expression): the SQL code strings to parse. 2522 If an `Expression` instance is passed, it will be used as-is. 2523 Multiple expressions are combined with an AND operator. 2524 append (bool): if `True`, AND the new expressions to any existing expression. 2525 Otherwise, this resets the expression. 2526 dialect (str): the dialect used to parse the input expressions. 2527 copy (bool): if `False`, modify this expression instance in-place. 2528 opts (kwargs): other options to use to parse the input expressions. 2529 2530 Returns: 2531 Select: the modified expression. 2532 """ 2533 return _apply_conjunction_builder( 2534 *expressions, 2535 instance=self, 2536 arg="having", 2537 append=append, 2538 into=Having, 2539 dialect=dialect, 2540 copy=copy, 2541 **opts, 2542 ) 2543 2544 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2545 return _apply_list_builder( 2546 *expressions, 2547 instance=self, 2548 arg="windows", 2549 append=append, 2550 into=Window, 2551 dialect=dialect, 2552 copy=copy, 2553 **opts, 2554 ) 2555 2556 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2557 return _apply_conjunction_builder( 2558 *expressions, 2559 instance=self, 2560 arg="qualify", 2561 append=append, 2562 into=Qualify, 2563 dialect=dialect, 2564 copy=copy, 2565 **opts, 2566 ) 2567 2568 def distinct(self, distinct=True, copy=True) -> Select: 2569 """ 2570 Set the OFFSET expression. 2571 2572 Example: 2573 >>> Select().from_("tbl").select("x").distinct().sql() 2574 'SELECT DISTINCT x FROM tbl' 2575 2576 Args: 2577 distinct (bool): whether the Select should be distinct 2578 copy (bool): if `False`, modify this expression instance in-place. 2579 2580 Returns: 2581 Select: the modified expression. 2582 """ 2583 instance = _maybe_copy(self, copy) 2584 instance.set("distinct", Distinct() if distinct else None) 2585 return instance 2586 2587 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2588 """ 2589 Convert this expression to a CREATE TABLE AS statement. 2590 2591 Example: 2592 >>> Select().select("*").from_("tbl").ctas("x").sql() 2593 'CREATE TABLE x AS SELECT * FROM tbl' 2594 2595 Args: 2596 table (str | Expression): the SQL code string to parse as the table name. 2597 If another `Expression` instance is passed, it will be used as-is. 2598 properties (dict): an optional mapping of table properties 2599 dialect (str): the dialect used to parse the input table. 2600 copy (bool): if `False`, modify this expression instance in-place. 2601 opts (kwargs): other options to use to parse the input table. 2602 2603 Returns: 2604 Create: the CREATE TABLE AS expression 2605 """ 2606 instance = _maybe_copy(self, copy) 2607 table_expression = maybe_parse( 2608 table, 2609 into=Table, 2610 dialect=dialect, 2611 **opts, 2612 ) 2613 properties_expression = None 2614 if properties: 2615 properties_expression = Properties.from_dict(properties) 2616 2617 return Create( 2618 this=table_expression, 2619 kind="table", 2620 expression=instance, 2621 properties=properties_expression, 2622 ) 2623 2624 def lock(self, update: bool = True, copy: bool = True) -> Select: 2625 """ 2626 Set the locking read mode for this expression. 2627 2628 Examples: 2629 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2630 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2631 2632 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2633 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2634 2635 Args: 2636 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2637 copy: if `False`, modify this expression instance in-place. 2638 2639 Returns: 2640 The modified expression. 2641 """ 2642 2643 inst = _maybe_copy(self, copy) 2644 inst.set("lock", Lock(update=update)) 2645 2646 return inst 2647 2648 @property 2649 def named_selects(self) -> t.List[str]: 2650 return [e.output_name for e in self.expressions if e.alias_or_name] 2651 2652 @property 2653 def is_star(self) -> bool: 2654 return any(expression.is_star for expression in self.expressions) 2655 2656 @property 2657 def selects(self) -> t.List[Expression]: 2658 return self.expressions
2086 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2087 """ 2088 Set the FROM expression. 2089 2090 Example: 2091 >>> Select().from_("tbl").select("x").sql() 2092 'SELECT x FROM tbl' 2093 2094 Args: 2095 *expressions (str | Expression): the SQL code strings to parse. 2096 If a `From` instance is passed, this is used as-is. 2097 If another `Expression` instance is passed, it will be wrapped in a `From`. 2098 append (bool): if `True`, add to any existing expressions. 2099 Otherwise, this flattens all the `From` expression into a single expression. 2100 dialect (str): the dialect used to parse the input expression. 2101 copy (bool): if `False`, modify this expression instance in-place. 2102 opts (kwargs): other options to use to parse the input expressions. 2103 2104 Returns: 2105 Select: the modified expression. 2106 """ 2107 return _apply_child_list_builder( 2108 *expressions, 2109 instance=self, 2110 arg="from", 2111 append=append, 2112 copy=copy, 2113 prefix="FROM", 2114 into=From, 2115 dialect=dialect, 2116 **opts, 2117 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
From
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aFrom
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theFrom
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2119 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2120 """ 2121 Set the GROUP BY expression. 2122 2123 Example: 2124 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2125 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2126 2127 Args: 2128 *expressions (str | Expression): the SQL code strings to parse. 2129 If a `Group` instance is passed, this is used as-is. 2130 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2131 If nothing is passed in then a group by is not applied to the expression 2132 append (bool): if `True`, add to any existing expressions. 2133 Otherwise, this flattens all the `Group` expression into a single expression. 2134 dialect (str): the dialect used to parse the input expression. 2135 copy (bool): if `False`, modify this expression instance in-place. 2136 opts (kwargs): other options to use to parse the input expressions. 2137 2138 Returns: 2139 Select: the modified expression. 2140 """ 2141 if not expressions: 2142 return self if not copy else self.copy() 2143 return _apply_child_list_builder( 2144 *expressions, 2145 instance=self, 2146 arg="group", 2147 append=append, 2148 copy=copy, 2149 prefix="GROUP BY", 2150 into=Group, 2151 dialect=dialect, 2152 **opts, 2153 )
Set the GROUP BY expression.
Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If 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 (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theGroup
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2155 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2156 """ 2157 Set the ORDER BY expression. 2158 2159 Example: 2160 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2161 'SELECT x FROM tbl ORDER BY x DESC' 2162 2163 Args: 2164 *expressions (str | Expression): the SQL code strings to parse. 2165 If a `Group` instance is passed, this is used as-is. 2166 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2167 append (bool): if `True`, add to any existing expressions. 2168 Otherwise, this flattens all the `Order` expression into a single expression. 2169 dialect (str): the dialect used to parse the input expression. 2170 copy (bool): if `False`, modify this expression instance in-place. 2171 opts (kwargs): other options to use to parse the input expressions. 2172 2173 Returns: 2174 Select: the modified expression. 2175 """ 2176 return _apply_child_list_builder( 2177 *expressions, 2178 instance=self, 2179 arg="order", 2180 append=append, 2181 copy=copy, 2182 prefix="ORDER BY", 2183 into=Order, 2184 dialect=dialect, 2185 **opts, 2186 )
Set the ORDER BY expression.
Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aOrder
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2188 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2189 """ 2190 Set the SORT BY expression. 2191 2192 Example: 2193 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2194 'SELECT x FROM tbl SORT BY x DESC' 2195 2196 Args: 2197 *expressions (str | Expression): the SQL code strings to parse. 2198 If a `Group` instance is passed, this is used as-is. 2199 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2200 append (bool): if `True`, add to any existing expressions. 2201 Otherwise, this flattens all the `Order` expression into a single expression. 2202 dialect (str): the dialect used to parse the input expression. 2203 copy (bool): if `False`, modify this expression instance in-place. 2204 opts (kwargs): other options to use to parse the input expressions. 2205 2206 Returns: 2207 Select: the modified expression. 2208 """ 2209 return _apply_child_list_builder( 2210 *expressions, 2211 instance=self, 2212 arg="sort", 2213 append=append, 2214 copy=copy, 2215 prefix="SORT BY", 2216 into=Sort, 2217 dialect=dialect, 2218 **opts, 2219 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aSORT
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2221 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2222 """ 2223 Set the CLUSTER BY expression. 2224 2225 Example: 2226 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2227 'SELECT x FROM tbl CLUSTER BY x DESC' 2228 2229 Args: 2230 *expressions (str | Expression): the SQL code strings to parse. 2231 If a `Group` instance is passed, this is used as-is. 2232 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2233 append (bool): if `True`, add to any existing expressions. 2234 Otherwise, this flattens all the `Order` expression into a single expression. 2235 dialect (str): the dialect used to parse the input expression. 2236 copy (bool): if `False`, modify this expression instance in-place. 2237 opts (kwargs): other options to use to parse the input expressions. 2238 2239 Returns: 2240 Select: the modified expression. 2241 """ 2242 return _apply_child_list_builder( 2243 *expressions, 2244 instance=self, 2245 arg="cluster", 2246 append=append, 2247 copy=copy, 2248 prefix="CLUSTER BY", 2249 into=Cluster, 2250 dialect=dialect, 2251 **opts, 2252 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aCluster
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2254 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2255 """ 2256 Set the LIMIT expression. 2257 2258 Example: 2259 >>> Select().from_("tbl").select("x").limit(10).sql() 2260 'SELECT x FROM tbl LIMIT 10' 2261 2262 Args: 2263 expression (str | int | Expression): the SQL code string to parse. 2264 This can also be an integer. 2265 If a `Limit` instance is passed, this is used as-is. 2266 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2267 dialect (str): the dialect used to parse the input expression. 2268 copy (bool): if `False`, modify this expression instance in-place. 2269 opts (kwargs): other options to use to parse the input expressions. 2270 2271 Returns: 2272 Select: the modified expression. 2273 """ 2274 return _apply_builder( 2275 expression=expression, 2276 instance=self, 2277 arg="limit", 2278 into=Limit, 2279 prefix="LIMIT", 2280 dialect=dialect, 2281 copy=copy, 2282 **opts, 2283 )
Set the LIMIT expression.
Example:
>>> Select().from_("tbl").select("x").limit(10).sql() 'SELECT x FROM tbl LIMIT 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limit
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aLimit
. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2285 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2286 """ 2287 Set the OFFSET expression. 2288 2289 Example: 2290 >>> Select().from_("tbl").select("x").offset(10).sql() 2291 'SELECT x FROM tbl OFFSET 10' 2292 2293 Args: 2294 expression (str | int | Expression): the SQL code string to parse. 2295 This can also be an integer. 2296 If a `Offset` instance is passed, this is used as-is. 2297 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2298 dialect (str): the dialect used to parse the input expression. 2299 copy (bool): if `False`, modify this expression instance in-place. 2300 opts (kwargs): other options to use to parse the input expressions. 2301 2302 Returns: 2303 Select: the modified expression. 2304 """ 2305 return _apply_builder( 2306 expression=expression, 2307 instance=self, 2308 arg="offset", 2309 into=Offset, 2310 prefix="OFFSET", 2311 dialect=dialect, 2312 copy=copy, 2313 **opts, 2314 )
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Offset
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aOffset
. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2316 def select( 2317 self, 2318 *expressions: ExpOrStr, 2319 append: bool = True, 2320 dialect: DialectType = None, 2321 copy: bool = True, 2322 **opts, 2323 ) -> Select: 2324 """ 2325 Append to or set the SELECT expressions. 2326 2327 Example: 2328 >>> Select().select("x", "y").sql() 2329 'SELECT x, y' 2330 2331 Args: 2332 *expressions: the SQL code strings to parse. 2333 If an `Expression` instance is passed, it will be used as-is. 2334 append: if `True`, add to any existing expressions. 2335 Otherwise, this resets the expressions. 2336 dialect: the dialect used to parse the input expressions. 2337 copy: if `False`, modify this expression instance in-place. 2338 opts: other options to use to parse the input expressions. 2339 2340 Returns: 2341 Select: the modified expression. 2342 """ 2343 return _apply_list_builder( 2344 *expressions, 2345 instance=self, 2346 arg="expressions", 2347 append=append, 2348 dialect=dialect, 2349 copy=copy, 2350 **opts, 2351 )
Append to or set the SELECT expressions.
Example:
>>> Select().select("x", "y").sql() 'SELECT x, y'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2353 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2354 """ 2355 Append to or set the LATERAL expressions. 2356 2357 Example: 2358 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2359 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2360 2361 Args: 2362 *expressions (str | Expression): the SQL code strings to parse. 2363 If an `Expression` instance is passed, it will be used as-is. 2364 append (bool): if `True`, add to any existing expressions. 2365 Otherwise, this resets the expressions. 2366 dialect (str): the dialect used to parse the input expressions. 2367 copy (bool): if `False`, modify this expression instance in-place. 2368 opts (kwargs): other options to use to parse the input expressions. 2369 2370 Returns: 2371 Select: the modified expression. 2372 """ 2373 return _apply_list_builder( 2374 *expressions, 2375 instance=self, 2376 arg="laterals", 2377 append=append, 2378 into=Lateral, 2379 prefix="LATERAL VIEW", 2380 dialect=dialect, 2381 copy=copy, 2382 **opts, 2383 )
Append to or set the LATERAL expressions.
Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append (bool): if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2385 def join( 2386 self, 2387 expression, 2388 on=None, 2389 using=None, 2390 append=True, 2391 join_type=None, 2392 join_alias=None, 2393 dialect=None, 2394 copy=True, 2395 **opts, 2396 ) -> Select: 2397 """ 2398 Append to or set the JOIN expressions. 2399 2400 Example: 2401 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2402 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2403 2404 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2405 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2406 2407 Use `join_type` to change the type of join: 2408 2409 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2410 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2411 2412 Args: 2413 expression (str | Expression): the SQL code string to parse. 2414 If an `Expression` instance is passed, it will be used as-is. 2415 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2416 If an `Expression` instance is passed, it will be used as-is. 2417 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2418 If an `Expression` instance is passed, it will be used as-is. 2419 append (bool): if `True`, add to any existing expressions. 2420 Otherwise, this resets the expressions. 2421 join_type (str): If set, alter the parsed join type 2422 dialect (str): the dialect used to parse the input expressions. 2423 copy (bool): if `False`, modify this expression instance in-place. 2424 opts (kwargs): other options to use to parse the input expressions. 2425 2426 Returns: 2427 Select: the modified expression. 2428 """ 2429 parse_args = {"dialect": dialect, **opts} 2430 2431 try: 2432 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2433 except ParseError: 2434 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2435 2436 join = expression if isinstance(expression, Join) else Join(this=expression) 2437 2438 if isinstance(join.this, Select): 2439 join.this.replace(join.this.subquery()) 2440 2441 if join_type: 2442 natural: t.Optional[Token] 2443 side: t.Optional[Token] 2444 kind: t.Optional[Token] 2445 2446 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2447 2448 if natural: 2449 join.set("natural", True) 2450 if side: 2451 join.set("side", side.text) 2452 if kind: 2453 join.set("kind", kind.text) 2454 2455 if on: 2456 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2457 join.set("on", on) 2458 2459 if using: 2460 join = _apply_list_builder( 2461 *ensure_collection(using), 2462 instance=join, 2463 arg="using", 2464 append=append, 2465 copy=copy, 2466 **opts, 2467 ) 2468 2469 if join_alias: 2470 join.set("this", alias_(join.this, join_alias, table=True)) 2471 return _apply_list_builder( 2472 join, 2473 instance=self, 2474 arg="joins", 2475 append=append, 2476 copy=copy, 2477 **opts, 2478 )
Append to or set the JOIN expressions.
Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'
Use
join_type
to change the type of join:>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
- expression (str | Expression): the SQL code string to parse.
If an
Expression
instance is passed, it will be used as-is. - on (str | Expression): optionally specify the join "on" criteria as a SQL string.
If an
Expression
instance is passed, it will be used as-is. - using (str | Expression): optionally specify the join "using" criteria as a SQL string.
If an
Expression
instance is passed, it will be used as-is. - append (bool): if
True
, add to any existing expressions. Otherwise, this resets the expressions. - join_type (str): If set, alter the parsed join type
- dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2480 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2481 """ 2482 Append to or set the WHERE expressions. 2483 2484 Example: 2485 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2486 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2487 2488 Args: 2489 *expressions (str | Expression): the SQL code strings to parse. 2490 If an `Expression` instance is passed, it will be used as-is. 2491 Multiple expressions are combined with an AND operator. 2492 append (bool): if `True`, AND the new expressions to any existing expression. 2493 Otherwise, this resets the expression. 2494 dialect (str): the dialect used to parse the input expressions. 2495 copy (bool): if `False`, modify this expression instance in-place. 2496 opts (kwargs): other options to use to parse the input expressions. 2497 2498 Returns: 2499 Select: the modified expression. 2500 """ 2501 return _apply_conjunction_builder( 2502 *expressions, 2503 instance=self, 2504 arg="where", 2505 append=append, 2506 into=Where, 2507 dialect=dialect, 2508 copy=copy, 2509 **opts, 2510 )
Append to or set the WHERE expressions.
Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2512 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2513 """ 2514 Append to or set the HAVING expressions. 2515 2516 Example: 2517 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2518 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2519 2520 Args: 2521 *expressions (str | Expression): the SQL code strings to parse. 2522 If an `Expression` instance is passed, it will be used as-is. 2523 Multiple expressions are combined with an AND operator. 2524 append (bool): if `True`, AND the new expressions to any existing expression. 2525 Otherwise, this resets the expression. 2526 dialect (str): the dialect used to parse the input expressions. 2527 copy (bool): if `False`, modify this expression instance in-place. 2528 opts (kwargs): other options to use to parse the input expressions. 2529 2530 Returns: 2531 Select: the modified expression. 2532 """ 2533 return _apply_conjunction_builder( 2534 *expressions, 2535 instance=self, 2536 arg="having", 2537 append=append, 2538 into=Having, 2539 dialect=dialect, 2540 copy=copy, 2541 **opts, 2542 )
Append to or set the HAVING expressions.
Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True
, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2568 def distinct(self, distinct=True, copy=True) -> Select: 2569 """ 2570 Set the OFFSET expression. 2571 2572 Example: 2573 >>> Select().from_("tbl").select("x").distinct().sql() 2574 'SELECT DISTINCT x FROM tbl' 2575 2576 Args: 2577 distinct (bool): whether the Select should be distinct 2578 copy (bool): if `False`, modify this expression instance in-place. 2579 2580 Returns: 2581 Select: the modified expression. 2582 """ 2583 instance = _maybe_copy(self, copy) 2584 instance.set("distinct", Distinct() if distinct else None) 2585 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- distinct (bool): whether the Select should be distinct
- copy (bool): if
False
, modify this expression instance in-place.
Returns:
Select: the modified expression.
2587 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2588 """ 2589 Convert this expression to a CREATE TABLE AS statement. 2590 2591 Example: 2592 >>> Select().select("*").from_("tbl").ctas("x").sql() 2593 'CREATE TABLE x AS SELECT * FROM tbl' 2594 2595 Args: 2596 table (str | Expression): the SQL code string to parse as the table name. 2597 If another `Expression` instance is passed, it will be used as-is. 2598 properties (dict): an optional mapping of table properties 2599 dialect (str): the dialect used to parse the input table. 2600 copy (bool): if `False`, modify this expression instance in-place. 2601 opts (kwargs): other options to use to parse the input table. 2602 2603 Returns: 2604 Create: the CREATE TABLE AS expression 2605 """ 2606 instance = _maybe_copy(self, copy) 2607 table_expression = maybe_parse( 2608 table, 2609 into=Table, 2610 dialect=dialect, 2611 **opts, 2612 ) 2613 properties_expression = None 2614 if properties: 2615 properties_expression = Properties.from_dict(properties) 2616 2617 return Create( 2618 this=table_expression, 2619 kind="table", 2620 expression=instance, 2621 properties=properties_expression, 2622 )
Convert this expression to a CREATE TABLE AS statement.
Example:
>>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
- table (str | Expression): the SQL code string to parse as the table name.
If another
Expression
instance is passed, it will be used as-is. - properties (dict): an optional mapping of table properties
- dialect (str): the dialect used to parse the input table.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input table.
Returns:
Create: the CREATE TABLE AS expression
2624 def lock(self, update: bool = True, copy: bool = True) -> Select: 2625 """ 2626 Set the locking read mode for this expression. 2627 2628 Examples: 2629 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2630 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2631 2632 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2633 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2634 2635 Args: 2636 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2637 copy: if `False`, modify this expression instance in-place. 2638 2639 Returns: 2640 The modified expression. 2641 """ 2642 2643 inst = _maybe_copy(self, copy) 2644 inst.set("lock", Lock(update=update)) 2645 2646 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2661class Subquery(DerivedTable, Unionable): 2662 arg_types = { 2663 "this": True, 2664 "alias": False, 2665 "with": False, 2666 **QUERY_MODIFIERS, 2667 } 2668 2669 def unnest(self): 2670 """ 2671 Returns the first non subquery. 2672 """ 2673 expression = self 2674 while isinstance(expression, Subquery): 2675 expression = expression.this 2676 return expression 2677 2678 @property 2679 def is_star(self) -> bool: 2680 return self.this.is_star 2681 2682 @property 2683 def output_name(self): 2684 return self.alias
2669 def unnest(self): 2670 """ 2671 Returns the first non subquery. 2672 """ 2673 expression = self 2674 while isinstance(expression, Subquery): 2675 expression = expression.this 2676 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
2687class TableSample(Expression): 2688 arg_types = { 2689 "this": False, 2690 "method": False, 2691 "bucket_numerator": False, 2692 "bucket_denominator": False, 2693 "bucket_field": False, 2694 "percent": False, 2695 "rows": False, 2696 "size": False, 2697 "seed": False, 2698 "kind": False, 2699 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2702class Tag(Expression): 2703 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2704 2705 arg_types = { 2706 "this": False, 2707 "prefix": False, 2708 "postfix": False, 2709 }
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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2712class Pivot(Expression): 2713 arg_types = { 2714 "this": False, 2715 "alias": False, 2716 "expressions": True, 2717 "field": True, 2718 "unpivot": True, 2719 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2722class Window(Expression): 2723 arg_types = { 2724 "this": True, 2725 "partition_by": False, 2726 "order": False, 2727 "spec": False, 2728 "alias": False, 2729 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2732class WindowSpec(Expression): 2733 arg_types = { 2734 "kind": False, 2735 "start": False, 2736 "start_side": False, 2737 "end": False, 2738 "end_side": False, 2739 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2746class Star(Expression): 2747 arg_types = {"except": False, "replace": False} 2748 2749 @property 2750 def name(self) -> str: 2751 return "*" 2752 2753 @property 2754 def output_name(self): 2755 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2770class Null(Condition): 2771 arg_types: t.Dict[str, t.Any] = {} 2772 2773 @property 2774 def name(self) -> str: 2775 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2782class DataType(Expression): 2783 arg_types = { 2784 "this": True, 2785 "expressions": False, 2786 "nested": False, 2787 "values": False, 2788 "prefix": False, 2789 } 2790 2791 class Type(AutoName): 2792 CHAR = auto() 2793 NCHAR = auto() 2794 VARCHAR = auto() 2795 NVARCHAR = auto() 2796 TEXT = auto() 2797 MEDIUMTEXT = auto() 2798 LONGTEXT = auto() 2799 MEDIUMBLOB = auto() 2800 LONGBLOB = auto() 2801 BINARY = auto() 2802 VARBINARY = auto() 2803 INT = auto() 2804 UINT = auto() 2805 TINYINT = auto() 2806 UTINYINT = auto() 2807 SMALLINT = auto() 2808 USMALLINT = auto() 2809 BIGINT = auto() 2810 UBIGINT = auto() 2811 FLOAT = auto() 2812 DOUBLE = auto() 2813 DECIMAL = auto() 2814 BIT = auto() 2815 BOOLEAN = auto() 2816 JSON = auto() 2817 JSONB = auto() 2818 INTERVAL = auto() 2819 TIME = auto() 2820 TIMESTAMP = auto() 2821 TIMESTAMPTZ = auto() 2822 TIMESTAMPLTZ = auto() 2823 DATE = auto() 2824 DATETIME = auto() 2825 ARRAY = auto() 2826 MAP = auto() 2827 UUID = auto() 2828 GEOGRAPHY = auto() 2829 GEOMETRY = auto() 2830 STRUCT = auto() 2831 NULLABLE = auto() 2832 HLLSKETCH = auto() 2833 HSTORE = auto() 2834 SUPER = auto() 2835 SERIAL = auto() 2836 SMALLSERIAL = auto() 2837 BIGSERIAL = auto() 2838 XML = auto() 2839 UNIQUEIDENTIFIER = auto() 2840 MONEY = auto() 2841 SMALLMONEY = auto() 2842 ROWVERSION = auto() 2843 IMAGE = auto() 2844 VARIANT = auto() 2845 OBJECT = auto() 2846 INET = auto() 2847 NULL = auto() 2848 UNKNOWN = auto() # Sentinel value, useful for type annotation 2849 2850 TEXT_TYPES = { 2851 Type.CHAR, 2852 Type.NCHAR, 2853 Type.VARCHAR, 2854 Type.NVARCHAR, 2855 Type.TEXT, 2856 } 2857 2858 INTEGER_TYPES = { 2859 Type.INT, 2860 Type.TINYINT, 2861 Type.SMALLINT, 2862 Type.BIGINT, 2863 } 2864 2865 FLOAT_TYPES = { 2866 Type.FLOAT, 2867 Type.DOUBLE, 2868 } 2869 2870 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2871 2872 TEMPORAL_TYPES = { 2873 Type.TIMESTAMP, 2874 Type.TIMESTAMPTZ, 2875 Type.TIMESTAMPLTZ, 2876 Type.DATE, 2877 Type.DATETIME, 2878 } 2879 2880 @classmethod 2881 def build( 2882 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2883 ) -> DataType: 2884 from sqlglot import parse_one 2885 2886 if isinstance(dtype, str): 2887 if dtype.upper() in cls.Type.__members__: 2888 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2889 else: 2890 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2891 if data_type_exp is None: 2892 raise ValueError(f"Unparsable data type value: {dtype}") 2893 elif isinstance(dtype, DataType.Type): 2894 data_type_exp = DataType(this=dtype) 2895 elif isinstance(dtype, DataType): 2896 return dtype 2897 else: 2898 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2899 return DataType(**{**data_type_exp.args, **kwargs}) 2900 2901 def is_type(self, dtype: DataType.Type) -> bool: 2902 return self.this == dtype
2880 @classmethod 2881 def build( 2882 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2883 ) -> DataType: 2884 from sqlglot import parse_one 2885 2886 if isinstance(dtype, str): 2887 if dtype.upper() in cls.Type.__members__: 2888 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2889 else: 2890 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2891 if data_type_exp is None: 2892 raise ValueError(f"Unparsable data type value: {dtype}") 2893 elif isinstance(dtype, DataType.Type): 2894 data_type_exp = DataType(this=dtype) 2895 elif isinstance(dtype, DataType): 2896 return dtype 2897 else: 2898 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2899 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2791 class Type(AutoName): 2792 CHAR = auto() 2793 NCHAR = auto() 2794 VARCHAR = auto() 2795 NVARCHAR = auto() 2796 TEXT = auto() 2797 MEDIUMTEXT = auto() 2798 LONGTEXT = auto() 2799 MEDIUMBLOB = auto() 2800 LONGBLOB = auto() 2801 BINARY = auto() 2802 VARBINARY = auto() 2803 INT = auto() 2804 UINT = auto() 2805 TINYINT = auto() 2806 UTINYINT = auto() 2807 SMALLINT = auto() 2808 USMALLINT = auto() 2809 BIGINT = auto() 2810 UBIGINT = auto() 2811 FLOAT = auto() 2812 DOUBLE = auto() 2813 DECIMAL = auto() 2814 BIT = auto() 2815 BOOLEAN = auto() 2816 JSON = auto() 2817 JSONB = auto() 2818 INTERVAL = auto() 2819 TIME = auto() 2820 TIMESTAMP = auto() 2821 TIMESTAMPTZ = auto() 2822 TIMESTAMPLTZ = auto() 2823 DATE = auto() 2824 DATETIME = auto() 2825 ARRAY = auto() 2826 MAP = auto() 2827 UUID = auto() 2828 GEOGRAPHY = auto() 2829 GEOMETRY = auto() 2830 STRUCT = auto() 2831 NULLABLE = auto() 2832 HLLSKETCH = auto() 2833 HSTORE = auto() 2834 SUPER = auto() 2835 SERIAL = auto() 2836 SMALLSERIAL = auto() 2837 BIGSERIAL = auto() 2838 XML = auto() 2839 UNIQUEIDENTIFIER = auto() 2840 MONEY = auto() 2841 SMALLMONEY = auto() 2842 ROWVERSION = auto() 2843 IMAGE = auto() 2844 VARIANT = auto() 2845 OBJECT = auto() 2846 INET = auto() 2847 NULL = auto() 2848 UNKNOWN = auto() # Sentinel value, useful for type annotation
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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2953class AddConstraint(Expression): 2954 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2962class Binary(Expression): 2963 arg_types = {"this": True, "expression": True} 2964 2965 @property 2966 def left(self): 2967 return self.this 2968 2969 @property 2970 def right(self): 2971 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3018class Dot(Binary): 3019 @property 3020 def name(self) -> str: 3021 return self.expression.name 3022 3023 @classmethod 3024 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3025 """Build a Dot object with a sequence of expressions.""" 3026 if len(expressions) < 2: 3027 raise ValueError(f"Dot requires >= 2 expressions.") 3028 3029 a, b, *expressions = expressions 3030 dot = Dot(this=a, expression=b) 3031 3032 for expression in expressions: 3033 dot = Dot(this=dot, expression=expression) 3034 3035 return dot
3023 @classmethod 3024 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3025 """Build a Dot object with a sequence of expressions.""" 3026 if len(expressions) < 2: 3027 raise ValueError(f"Dot requires >= 2 expressions.") 3028 3029 a, b, *expressions = expressions 3030 dot = Dot(this=a, expression=b) 3031 3032 for expression in expressions: 3033 dot = Dot(this=dot, expression=expression) 3034 3035 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3161class Alias(Expression): 3162 arg_types = {"this": True, "alias": False} 3163 3164 @property 3165 def output_name(self): 3166 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3169class Aliases(Expression): 3170 arg_types = {"this": True, "expressions": True} 3171 3172 @property 3173 def aliases(self): 3174 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3193class In(Predicate): 3194 arg_types = { 3195 "this": True, 3196 "expressions": False, 3197 "query": False, 3198 "unnest": False, 3199 "field": False, 3200 "is_global": False, 3201 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3204class TimeUnit(Expression): 3205 """Automatically converts unit arg into a var.""" 3206 3207 arg_types = {"unit": False} 3208 3209 def __init__(self, **args): 3210 unit = args.get("unit") 3211 if isinstance(unit, (Column, Literal)): 3212 args["unit"] = Var(this=unit.name) 3213 elif isinstance(unit, Week): 3214 unit.set("this", Var(this=unit.this.name)) 3215 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3231class Func(Condition): 3232 """ 3233 The base class for all function expressions. 3234 3235 Attributes: 3236 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3237 treated as a variable length argument and the argument's value will be stored as a list. 3238 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3239 for this function expression. These values are used to map this node to a name during parsing 3240 as well as to provide the function's name during SQL string generation. By default the SQL 3241 name is set to the expression's class name transformed to snake case. 3242 """ 3243 3244 is_var_len_args = False 3245 3246 @classmethod 3247 def from_arg_list(cls, args): 3248 if cls.is_var_len_args: 3249 all_arg_keys = list(cls.arg_types) 3250 # If this function supports variable length argument treat the last argument as such. 3251 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3252 num_non_var = len(non_var_len_arg_keys) 3253 3254 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3255 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3256 else: 3257 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3258 3259 return cls(**args_dict) 3260 3261 @classmethod 3262 def sql_names(cls): 3263 if cls is Func: 3264 raise NotImplementedError( 3265 "SQL name is only supported by concrete function implementations" 3266 ) 3267 if "_sql_names" not in cls.__dict__: 3268 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3269 return cls._sql_names 3270 3271 @classmethod 3272 def sql_name(cls): 3273 return cls.sql_names()[0] 3274 3275 @classmethod 3276 def default_parser_mappings(cls): 3277 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.
3246 @classmethod 3247 def from_arg_list(cls, args): 3248 if cls.is_var_len_args: 3249 all_arg_keys = list(cls.arg_types) 3250 # If this function supports variable length argument treat the last argument as such. 3251 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3252 num_non_var = len(non_var_len_arg_keys) 3253 3254 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3255 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3256 else: 3257 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3258 3259 return cls(**args_dict)
3261 @classmethod 3262 def sql_names(cls): 3263 if cls is Func: 3264 raise NotImplementedError( 3265 "SQL name is only supported by concrete function implementations" 3266 ) 3267 if "_sql_names" not in cls.__dict__: 3268 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3269 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3288class Anonymous(Func): 3289 arg_types = {"this": True, "expressions": False} 3290 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3323class ArrayConcat(Func): 3324 arg_types = {"this": True, "expressions": False} 3325 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3336class ArrayFilter(Func): 3337 arg_types = {"this": True, "expression": True} 3338 _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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3373class Cast(Func): 3374 arg_types = {"this": True, "to": True} 3375 3376 @property 3377 def name(self) -> str: 3378 return self.this.name 3379 3380 @property 3381 def to(self): 3382 return self.args["to"] 3383 3384 @property 3385 def output_name(self): 3386 return self.name 3387 3388 def is_type(self, dtype: DataType.Type) -> bool: 3389 return self.to.is_type(dtype)
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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3400class Ceil(Func): 3401 arg_types = {"this": True, "decimals": False} 3402 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3405class Coalesce(Func): 3406 arg_types = {"this": True, "expressions": False} 3407 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3443class DateAdd(Func, TimeUnit): 3444 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3447class DateSub(Func, TimeUnit): 3448 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3451class DateDiff(Func, TimeUnit): 3452 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3453 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3460class DatetimeAdd(Func, TimeUnit): 3461 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3464class DatetimeSub(Func, TimeUnit): 3465 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3468class DatetimeDiff(Func, TimeUnit): 3469 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3472class DatetimeTrunc(Func, TimeUnit): 3473 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3500class TimestampAdd(Func, TimeUnit): 3501 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3504class TimestampSub(Func, TimeUnit): 3505 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3508class TimestampDiff(Func, TimeUnit): 3509 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3512class TimestampTrunc(Func, TimeUnit): 3513 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3516class TimeAdd(Func, TimeUnit): 3517 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3520class TimeSub(Func, TimeUnit): 3521 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3524class TimeDiff(Func, TimeUnit): 3525 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3532class DateFromParts(Func): 3533 _sql_names = ["DATEFROMPARTS"] 3534 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3573class ExponentialTimeDecayedAvg(AggFunc): 3574 arg_types = {"this": True, "time": False, "decay": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3581class Greatest(Func): 3582 arg_types = {"this": True, "expressions": False} 3583 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3606class IfNull(Func): 3607 arg_types = {"this": True, "expression": False} 3608 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3619class JSONObject(Func): 3620 arg_types = { 3621 "expressions": False, 3622 "null_handling": False, 3623 "unique_keys": False, 3624 "return_type": False, 3625 "format_json": False, 3626 "encoding": False, 3627 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3659class Levenshtein(Func): 3660 arg_types = { 3661 "this": True, 3662 "expression": False, 3663 "ins_cost": False, 3664 "del_cost": False, 3665 "sub_cost": False, 3666 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3706class Matches(Func): 3707 """Oracle/Snowflake decode. 3708 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3709 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3710 """ 3711 3712 arg_types = {"this": True, "expressions": True} 3713 is_var_len_args = True
Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3716class Max(AggFunc): 3717 arg_types = {"this": True, "expressions": False} 3718 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3721class Min(AggFunc): 3722 arg_types = {"this": True, "expressions": False} 3723 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3756class Quantiles(AggFunc): 3757 arg_types = {"parameters": True, "expressions": True} 3758 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3765class ApproxQuantile(Quantile): 3766 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3773class ReadCSV(Func): 3774 _sql_names = ["READ_CSV"] 3775 is_var_len_args = True 3776 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3779class Reduce(Func): 3780 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3783class RegexpExtract(Func): 3784 arg_types = { 3785 "this": True, 3786 "expression": True, 3787 "position": False, 3788 "occurrence": False, 3789 "group": False, 3790 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3839class StrPosition(Func): 3840 arg_types = { 3841 "this": True, 3842 "substr": True, 3843 "position": False, 3844 "instance": False, 3845 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3919class Trim(Func): 3920 arg_types = { 3921 "this": True, 3922 "expression": False, 3923 "position": False, 3924 "collation": False, 3925 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3928class TsOrDsAdd(Func, TimeUnit): 3929 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3954class UnixToTime(Func): 3955 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3956 3957 SECONDS = Literal.string("seconds") 3958 MILLIS = Literal.string("millis") 3959 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3982class XMLTable(Func): 3983 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3994class Merge(Expression): 3995 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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 When(Func): 3999 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
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4010def maybe_parse( 4011 sql_or_expression: ExpOrStr, 4012 *, 4013 into: t.Optional[IntoType] = None, 4014 dialect: DialectType = None, 4015 prefix: t.Optional[str] = None, 4016 copy: bool = False, 4017 **opts, 4018) -> Expression: 4019 """Gracefully handle a possible string or expression. 4020 4021 Example: 4022 >>> maybe_parse("1") 4023 (LITERAL this: 1, is_string: False) 4024 >>> maybe_parse(to_identifier("x")) 4025 (IDENTIFIER this: x, quoted: False) 4026 4027 Args: 4028 sql_or_expression: the SQL code string or an expression 4029 into: the SQLGlot Expression to parse into 4030 dialect: the dialect used to parse the input expressions (in the case that an 4031 input expression is a SQL string). 4032 prefix: a string to prefix the sql with before it gets parsed 4033 (automatically includes a space) 4034 copy: whether or not to copy the expression. 4035 **opts: other options to use to parse the input expressions (again, in the case 4036 that an input expression is a SQL string). 4037 4038 Returns: 4039 Expression: the parsed or given expression. 4040 """ 4041 if isinstance(sql_or_expression, Expression): 4042 if copy: 4043 return sql_or_expression.copy() 4044 return sql_or_expression 4045 4046 import sqlglot 4047 4048 sql = str(sql_or_expression) 4049 if prefix: 4050 sql = f"{prefix} {sql}" 4051 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.
4197def union(left, right, distinct=True, dialect=None, **opts): 4198 """ 4199 Initializes a syntax tree from one UNION expression. 4200 4201 Example: 4202 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4203 'SELECT * FROM foo UNION SELECT * FROM bla' 4204 4205 Args: 4206 left (str | Expression): the SQL code string corresponding to the left-hand side. 4207 If an `Expression` instance is passed, it will be used as-is. 4208 right (str | Expression): the SQL code string corresponding to the right-hand side. 4209 If an `Expression` instance is passed, it will be used as-is. 4210 distinct (bool): set the DISTINCT flag if and only if this is true. 4211 dialect (str): the dialect used to parse the input expression. 4212 opts (kwargs): other options to use to parse the input expressions. 4213 Returns: 4214 Union: the syntax tree for the UNION expression. 4215 """ 4216 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4217 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4218 4219 return Union(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one UNION expression.
Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the syntax tree for the UNION expression.
4222def intersect(left, right, distinct=True, dialect=None, **opts): 4223 """ 4224 Initializes a syntax tree from one INTERSECT expression. 4225 4226 Example: 4227 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4228 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4229 4230 Args: 4231 left (str | Expression): the SQL code string corresponding to the left-hand side. 4232 If an `Expression` instance is passed, it will be used as-is. 4233 right (str | Expression): the SQL code string corresponding to the right-hand side. 4234 If an `Expression` instance is passed, it will be used as-is. 4235 distinct (bool): set the DISTINCT flag if and only if this is true. 4236 dialect (str): the dialect used to parse the input expression. 4237 opts (kwargs): other options to use to parse the input expressions. 4238 Returns: 4239 Intersect: the syntax tree for the INTERSECT expression. 4240 """ 4241 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4242 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4243 4244 return Intersect(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one INTERSECT expression.
Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the syntax tree for the INTERSECT expression.
4247def except_(left, right, distinct=True, dialect=None, **opts): 4248 """ 4249 Initializes a syntax tree from one EXCEPT expression. 4250 4251 Example: 4252 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4253 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4254 4255 Args: 4256 left (str | Expression): the SQL code string corresponding to the left-hand side. 4257 If an `Expression` instance is passed, it will be used as-is. 4258 right (str | Expression): the SQL code string corresponding to the right-hand side. 4259 If an `Expression` instance is passed, it will be used as-is. 4260 distinct (bool): set the DISTINCT flag if and only if this is true. 4261 dialect (str): the dialect used to parse the input expression. 4262 opts (kwargs): other options to use to parse the input expressions. 4263 Returns: 4264 Except: the syntax tree for the EXCEPT statement. 4265 """ 4266 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4267 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4268 4269 return Except(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one EXCEPT expression.
Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expression
instance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expression
instance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the syntax tree for the EXCEPT statement.
4272def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4273 """ 4274 Initializes a syntax tree from one or multiple SELECT expressions. 4275 4276 Example: 4277 >>> select("col1", "col2").from_("tbl").sql() 4278 'SELECT col1, col2 FROM tbl' 4279 4280 Args: 4281 *expressions: the SQL code string to parse as the expressions of a 4282 SELECT statement. If an Expression instance is passed, this is used as-is. 4283 dialect: the dialect used to parse the input expressions (in the case that an 4284 input expression is a SQL string). 4285 **opts: other options to use to parse the input expressions (again, in the case 4286 that an input expression is a SQL string). 4287 4288 Returns: 4289 Select: the syntax tree for the SELECT statement. 4290 """ 4291 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.
4294def from_(*expressions, dialect=None, **opts) -> Select: 4295 """ 4296 Initializes a syntax tree from a FROM expression. 4297 4298 Example: 4299 >>> from_("tbl").select("col1", "col2").sql() 4300 'SELECT col1, col2 FROM tbl' 4301 4302 Args: 4303 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4304 SELECT statement. If an Expression instance is passed, this is used as-is. 4305 dialect (str): the dialect used to parse the input expression (in the case that the 4306 input expression is a SQL string). 4307 **opts: other options to use to parse the input expressions (again, in the case 4308 that the input expression is a SQL string). 4309 4310 Returns: 4311 Select: the syntax tree for the SELECT statement. 4312 """ 4313 return Select().from_(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4316def update( 4317 table: str | Table, 4318 properties: dict, 4319 where: t.Optional[ExpOrStr] = None, 4320 from_: t.Optional[ExpOrStr] = None, 4321 dialect: DialectType = None, 4322 **opts, 4323) -> Update: 4324 """ 4325 Creates an update statement. 4326 4327 Example: 4328 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4329 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4330 4331 Args: 4332 *properties: dictionary of properties to set which are 4333 auto converted to sql objects eg None -> NULL 4334 where: sql conditional parsed into a WHERE statement 4335 from_: sql statement parsed into a FROM statement 4336 dialect: the dialect used to parse the input expressions. 4337 **opts: other options to use to parse the input expressions. 4338 4339 Returns: 4340 Update: the syntax tree for the UPDATE statement. 4341 """ 4342 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4343 update_expr.set( 4344 "expressions", 4345 [ 4346 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4347 for k, v in properties.items() 4348 ], 4349 ) 4350 if from_: 4351 update_expr.set( 4352 "from", 4353 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4354 ) 4355 if isinstance(where, Condition): 4356 where = Where(this=where) 4357 if where: 4358 update_expr.set( 4359 "where", 4360 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4361 ) 4362 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.
4365def delete( 4366 table: ExpOrStr, 4367 where: t.Optional[ExpOrStr] = None, 4368 returning: t.Optional[ExpOrStr] = None, 4369 dialect: DialectType = None, 4370 **opts, 4371) -> Delete: 4372 """ 4373 Builds a delete statement. 4374 4375 Example: 4376 >>> delete("my_table", where="id > 1").sql() 4377 'DELETE FROM my_table WHERE id > 1' 4378 4379 Args: 4380 where: sql conditional parsed into a WHERE statement 4381 returning: sql conditional parsed into a RETURNING statement 4382 dialect: the dialect used to parse the input expressions. 4383 **opts: other options to use to parse the input expressions. 4384 4385 Returns: 4386 Delete: the syntax tree for the DELETE statement. 4387 """ 4388 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4389 if where: 4390 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4391 if returning: 4392 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4393 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.
4396def condition(expression, dialect=None, **opts) -> Condition: 4397 """ 4398 Initialize a logical condition expression. 4399 4400 Example: 4401 >>> condition("x=1").sql() 4402 'x = 1' 4403 4404 This is helpful for composing larger logical syntax trees: 4405 >>> where = condition("x=1") 4406 >>> where = where.and_("y=1") 4407 >>> Select().from_("tbl").select("*").where(where).sql() 4408 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4409 4410 Args: 4411 *expression (str | Expression): the SQL code string to parse. 4412 If an Expression instance is passed, this is used as-is. 4413 dialect (str): the dialect used to parse the input expression (in the case that the 4414 input expression is a SQL string). 4415 **opts: other options to use to parse the input expressions (again, in the case 4416 that the input expression is a SQL string). 4417 4418 Returns: 4419 Condition: the expression 4420 """ 4421 return maybe_parse( # type: ignore 4422 expression, 4423 into=Condition, 4424 dialect=dialect, 4425 **opts, 4426 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'
This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4429def and_(*expressions, dialect=None, **opts) -> And: 4430 """ 4431 Combine multiple conditions with an AND logical operator. 4432 4433 Example: 4434 >>> and_("x=1", and_("y=1", "z=1")).sql() 4435 'x = 1 AND (y = 1 AND z = 1)' 4436 4437 Args: 4438 *expressions (str | Expression): the SQL code strings to parse. 4439 If an Expression instance is passed, this is used as-is. 4440 dialect (str): the dialect used to parse the input expression. 4441 **opts: other options to use to parse the input expressions. 4442 4443 Returns: 4444 And: the new condition 4445 """ 4446 return _combine(expressions, And, dialect, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4449def or_(*expressions, dialect=None, **opts) -> Or: 4450 """ 4451 Combine multiple conditions with an OR logical operator. 4452 4453 Example: 4454 >>> or_("x=1", or_("y=1", "z=1")).sql() 4455 'x = 1 OR (y = 1 OR z = 1)' 4456 4457 Args: 4458 *expressions (str | Expression): the SQL code strings to parse. 4459 If an Expression instance is passed, this is used as-is. 4460 dialect (str): the dialect used to parse the input expression. 4461 **opts: other options to use to parse the input expressions. 4462 4463 Returns: 4464 Or: the new condition 4465 """ 4466 return _combine(expressions, Or, dialect, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4469def not_(expression, dialect=None, **opts) -> Not: 4470 """ 4471 Wrap a condition with a NOT operator. 4472 4473 Example: 4474 >>> not_("this_suit='black'").sql() 4475 "NOT this_suit = 'black'" 4476 4477 Args: 4478 expression (str | Expression): the SQL code strings to parse. 4479 If an Expression instance is passed, this is used as-is. 4480 dialect (str): the dialect used to parse the input expression. 4481 **opts: other options to use to parse the input expressions. 4482 4483 Returns: 4484 Not: the new condition 4485 """ 4486 this = condition( 4487 expression, 4488 dialect=dialect, 4489 **opts, 4490 ) 4491 return Not(this=_wrap_operator(this))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Not: the new condition
4511def to_identifier(name, quoted=None): 4512 """Builds an identifier. 4513 4514 Args: 4515 name: The name to turn into an identifier. 4516 quoted: Whether or not force quote the identifier. 4517 4518 Returns: 4519 The identifier ast node. 4520 """ 4521 4522 if name is None: 4523 return None 4524 4525 if isinstance(name, Identifier): 4526 identifier = name 4527 elif isinstance(name, str): 4528 identifier = Identifier( 4529 this=name, 4530 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4531 ) 4532 else: 4533 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4534 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
Returns:
The identifier ast node.
4540def to_interval(interval: str | Literal) -> Interval: 4541 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4542 if isinstance(interval, Literal): 4543 if not interval.is_string: 4544 raise ValueError("Invalid interval string.") 4545 4546 interval = interval.this 4547 4548 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4549 4550 if not interval_parts: 4551 raise ValueError("Invalid interval string.") 4552 4553 return Interval( 4554 this=Literal.string(interval_parts.group(1)), 4555 unit=Var(this=interval_parts.group(2)), 4556 )
Builds an interval expression from a string like '1 day' or '5 months'.
4569def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4570 """ 4571 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4572 If a table is passed in then that table is returned. 4573 4574 Args: 4575 sql_path: a `[catalog].[schema].[table]` string. 4576 4577 Returns: 4578 A table expression. 4579 """ 4580 if sql_path is None or isinstance(sql_path, Table): 4581 return sql_path 4582 if not isinstance(sql_path, str): 4583 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4584 4585 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4586 return Table(this=table_name, db=db, catalog=catalog, **kwargs)
Create a table expression from a [catalog].[schema].[table]
sql path. Catalog and schema are optional.
If a table is passed in then that table is returned.
Arguments:
- sql_path: a
[catalog].[schema].[table]
string.
Returns:
A table expression.
4589def to_column(sql_path: str | Column, **kwargs) -> Column: 4590 """ 4591 Create a column from a `[table].[column]` sql path. Schema is optional. 4592 4593 If a column is passed in then that column is returned. 4594 4595 Args: 4596 sql_path: `[table].[column]` string 4597 Returns: 4598 Table: A column expression 4599 """ 4600 if sql_path is None or isinstance(sql_path, Column): 4601 return sql_path 4602 if not isinstance(sql_path, str): 4603 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4604 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
4607def alias_( 4608 expression: ExpOrStr, 4609 alias: str | Identifier, 4610 table: bool | t.Sequence[str | Identifier] = False, 4611 quoted: t.Optional[bool] = None, 4612 dialect: DialectType = None, 4613 **opts, 4614): 4615 """Create an Alias expression. 4616 4617 Example: 4618 >>> alias_('foo', 'bar').sql() 4619 'foo AS bar' 4620 4621 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4622 '(SELECT 1, 2) AS bar(a, b)' 4623 4624 Args: 4625 expression: the SQL code strings to parse. 4626 If an Expression instance is passed, this is used as-is. 4627 alias: the alias name to use. If the name has 4628 special characters it is quoted. 4629 table: Whether or not to create a table alias, can also be a list of columns. 4630 quoted: whether or not to quote the alias 4631 dialect: the dialect used to parse the input expression. 4632 **opts: other options to use to parse the input expressions. 4633 4634 Returns: 4635 Alias: the aliased expression 4636 """ 4637 exp = maybe_parse(expression, dialect=dialect, **opts) 4638 alias = to_identifier(alias, quoted=quoted) 4639 4640 if table: 4641 table_alias = TableAlias(this=alias) 4642 exp.set("alias", table_alias) 4643 4644 if not isinstance(table, bool): 4645 for column in table: 4646 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4647 4648 return exp 4649 4650 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4651 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4652 # for the complete Window expression. 4653 # 4654 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4655 4656 if "alias" in exp.arg_types and not isinstance(exp, Window): 4657 exp = exp.copy() 4658 exp.set("alias", alias) 4659 return exp 4660 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
4663def subquery(expression, alias=None, dialect=None, **opts): 4664 """ 4665 Build a subquery expression. 4666 4667 Example: 4668 >>> subquery('select x from tbl', 'bar').select('x').sql() 4669 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4670 4671 Args: 4672 expression (str | Expression): the SQL code strings to parse. 4673 If an Expression instance is passed, this is used as-is. 4674 alias (str | Expression): the alias name to use. 4675 dialect (str): the dialect used to parse the input expression. 4676 **opts: other options to use to parse the input expressions. 4677 4678 Returns: 4679 Select: a new select with the subquery expression included 4680 """ 4681 4682 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4683 return Select().from_(expression, dialect=dialect, **opts)
Build a subquery expression.
Example:
>>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias (str | Expression): the alias name to use.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Select: a new select with the subquery expression included
4686def column( 4687 col: str | Identifier, 4688 table: t.Optional[str | Identifier] = None, 4689 db: t.Optional[str | Identifier] = None, 4690 catalog: t.Optional[str | Identifier] = None, 4691 quoted: t.Optional[bool] = None, 4692) -> Column: 4693 """ 4694 Build a Column. 4695 4696 Args: 4697 col: column name 4698 table: table name 4699 db: db name 4700 catalog: catalog name 4701 quoted: whether or not to force quote each part 4702 Returns: 4703 Column: column instance 4704 """ 4705 return Column( 4706 this=to_identifier(col, quoted=quoted), 4707 table=to_identifier(table, quoted=quoted), 4708 db=to_identifier(db, quoted=quoted), 4709 catalog=to_identifier(catalog, quoted=quoted), 4710 )
Build a Column.
Arguments:
- col: column name
- table: table name
- db: db name
- catalog: catalog name
- quoted: whether or not to force quote each part
Returns:
Column: column instance
4713def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4714 """Cast an expression to a data type. 4715 4716 Example: 4717 >>> cast('x + 1', 'int').sql() 4718 'CAST(x + 1 AS INT)' 4719 4720 Args: 4721 expression: The expression to cast. 4722 to: The datatype to cast to. 4723 4724 Returns: 4725 A cast node. 4726 """ 4727 expression = maybe_parse(expression, **opts) 4728 return Cast(this=expression, to=DataType.build(to, **opts))
Cast an expression to a data type.
Example:
>>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Arguments:
- expression: The expression to cast.
- to: The datatype to cast to.
Returns:
A cast node.
4731def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4732 """Build a Table. 4733 4734 Args: 4735 table (str | Expression): column name 4736 db (str | Expression): db name 4737 catalog (str | Expression): catalog name 4738 4739 Returns: 4740 Table: table instance 4741 """ 4742 return Table( 4743 this=to_identifier(table, quoted=quoted), 4744 db=to_identifier(db, quoted=quoted), 4745 catalog=to_identifier(catalog, quoted=quoted), 4746 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4747 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
4750def values( 4751 values: t.Iterable[t.Tuple[t.Any, ...]], 4752 alias: t.Optional[str] = None, 4753 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4754) -> Values: 4755 """Build VALUES statement. 4756 4757 Example: 4758 >>> values([(1, '2')]).sql() 4759 "VALUES (1, '2')" 4760 4761 Args: 4762 values: values statements that will be converted to SQL 4763 alias: optional alias 4764 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4765 If either are provided then an alias is also required. 4766 If a dictionary is provided then the first column of the values will be casted to the expected type 4767 in order to help with type inference. 4768 4769 Returns: 4770 Values: the Values expression object 4771 """ 4772 if columns and not alias: 4773 raise ValueError("Alias is required when providing columns") 4774 table_alias = ( 4775 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4776 if columns 4777 else TableAlias(this=to_identifier(alias) if alias else None) 4778 ) 4779 expressions = [convert(tup) for tup in values] 4780 if columns and isinstance(columns, dict): 4781 types = list(columns.values()) 4782 expressions[0].set( 4783 "expressions", 4784 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4785 ) 4786 return Values( 4787 expressions=expressions, 4788 alias=table_alias, 4789 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:
Values: the Values expression object
4792def var(name: t.Optional[ExpOrStr]) -> Var: 4793 """Build a SQL variable. 4794 4795 Example: 4796 >>> repr(var('x')) 4797 '(VAR this: x)' 4798 4799 >>> repr(var(column('x', table='y'))) 4800 '(VAR this: x)' 4801 4802 Args: 4803 name: The name of the var or an expression who's name will become the var. 4804 4805 Returns: 4806 The new variable node. 4807 """ 4808 if not name: 4809 raise ValueError("Cannot convert empty name into var.") 4810 4811 if isinstance(name, Expression): 4812 name = name.name 4813 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.
4816def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4817 """Build ALTER TABLE... RENAME... expression 4818 4819 Args: 4820 old_name: The old name of the table 4821 new_name: The new name of the table 4822 4823 Returns: 4824 Alter table expression 4825 """ 4826 old_table = to_table(old_name) 4827 new_table = to_table(new_name) 4828 return AlterTable( 4829 this=old_table, 4830 actions=[ 4831 RenameTable(this=new_table), 4832 ], 4833 )
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
4836def convert(value) -> Expression: 4837 """Convert a python value into an expression object. 4838 4839 Raises an error if a conversion is not possible. 4840 4841 Args: 4842 value (Any): a python object 4843 4844 Returns: 4845 Expression: the equivalent expression object 4846 """ 4847 if isinstance(value, Expression): 4848 return value 4849 if value is None: 4850 return NULL 4851 if isinstance(value, bool): 4852 return Boolean(this=value) 4853 if isinstance(value, str): 4854 return Literal.string(value) 4855 if isinstance(value, float) and math.isnan(value): 4856 return NULL 4857 if isinstance(value, numbers.Number): 4858 return Literal.number(value) 4859 if isinstance(value, tuple): 4860 return Tuple(expressions=[convert(v) for v in value]) 4861 if isinstance(value, list): 4862 return Array(expressions=[convert(v) for v in value]) 4863 if isinstance(value, dict): 4864 return Map( 4865 keys=[convert(k) for k in value], 4866 values=[convert(v) for v in value.values()], 4867 ) 4868 if isinstance(value, datetime.datetime): 4869 datetime_literal = Literal.string( 4870 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4871 ) 4872 return TimeStrToTime(this=datetime_literal) 4873 if isinstance(value, datetime.date): 4874 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4875 return DateStrToDate(this=date_literal) 4876 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value (Any): a python object
Returns:
Expression: the equivalent expression object
4879def replace_children(expression, fun, *args, **kwargs): 4880 """ 4881 Replace children of an expression with the result of a lambda fun(child) -> exp. 4882 """ 4883 for k, v in expression.args.items(): 4884 is_list_arg = type(v) is list 4885 4886 child_nodes = v if is_list_arg else [v] 4887 new_child_nodes = [] 4888 4889 for cn in child_nodes: 4890 if isinstance(cn, Expression): 4891 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4892 new_child_nodes.append(child_node) 4893 child_node.parent = expression 4894 child_node.arg_key = k 4895 else: 4896 new_child_nodes.append(cn) 4897 4898 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.
4901def column_table_names(expression): 4902 """ 4903 Return all table names referenced through columns in an expression. 4904 4905 Example: 4906 >>> import sqlglot 4907 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4908 ['c', 'a'] 4909 4910 Args: 4911 expression (sqlglot.Expression): expression to find table names 4912 4913 Returns: 4914 list: A list of unique names 4915 """ 4916 return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) ['c', 'a']
Arguments:
- expression (sqlglot.Expression): expression to find table names
Returns:
list: A list of unique names
4919def table_name(table) -> str: 4920 """Get the full name of a table as a string. 4921 4922 Args: 4923 table (exp.Table | str): table expression node or string. 4924 4925 Examples: 4926 >>> from sqlglot import exp, parse_one 4927 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4928 'a.b.c' 4929 4930 Returns: 4931 The table name. 4932 """ 4933 4934 table = maybe_parse(table, into=Table) 4935 4936 if not table: 4937 raise ValueError(f"Cannot parse {table}") 4938 4939 return ".".join( 4940 part 4941 for part in ( 4942 table.text("catalog"), 4943 table.text("db"), 4944 table.name, 4945 ) 4946 if part 4947 )
Get the full name of a table as a string.
Arguments:
- table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns:
The table name.
4950def replace_tables(expression, mapping): 4951 """Replace all tables in expression according to the mapping. 4952 4953 Args: 4954 expression (sqlglot.Expression): expression node to be transformed and replaced. 4955 mapping (Dict[str, str]): mapping of table names. 4956 4957 Examples: 4958 >>> from sqlglot import exp, parse_one 4959 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4960 'SELECT * FROM c' 4961 4962 Returns: 4963 The mapped expression. 4964 """ 4965 4966 def _replace_tables(node): 4967 if isinstance(node, Table): 4968 new_name = mapping.get(table_name(node)) 4969 if new_name: 4970 return to_table( 4971 new_name, 4972 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4973 ) 4974 return node 4975 4976 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
4979def replace_placeholders(expression, *args, **kwargs): 4980 """Replace placeholders in an expression. 4981 4982 Args: 4983 expression (sqlglot.Expression): expression node to be transformed and replaced. 4984 args: positional names that will substitute unnamed placeholders in the given order. 4985 kwargs: keyword arguments that will substitute named placeholders. 4986 4987 Examples: 4988 >>> from sqlglot import exp, parse_one 4989 >>> replace_placeholders( 4990 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4991 ... ).sql() 4992 'SELECT * FROM foo WHERE a = b' 4993 4994 Returns: 4995 The mapped expression. 4996 """ 4997 4998 def _replace_placeholders(node, args, **kwargs): 4999 if isinstance(node, Placeholder): 5000 if node.name: 5001 new_name = kwargs.get(node.name) 5002 if new_name: 5003 return to_identifier(new_name) 5004 else: 5005 try: 5006 return to_identifier(next(args)) 5007 except StopIteration: 5008 pass 5009 return node 5010 5011 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" ... ).sql() 'SELECT * FROM foo WHERE a = b'
Returns:
The mapped expression.
5014def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 5015 """Transforms an expression by expanding all referenced sources into subqueries. 5016 5017 Examples: 5018 >>> from sqlglot import parse_one 5019 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5020 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5021 5022 Args: 5023 expression: The expression to expand. 5024 sources: A dictionary of name to Subqueryables. 5025 copy: Whether or not to copy the expression during transformation. Defaults to True. 5026 5027 Returns: 5028 The transformed expression. 5029 """ 5030 5031 def _expand(node: Expression): 5032 if isinstance(node, Table): 5033 name = table_name(node) 5034 source = sources.get(name) 5035 if source: 5036 subquery = source.subquery(node.alias or name) 5037 subquery.comments = [f"source: {name}"] 5038 return subquery 5039 return node 5040 5041 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5044def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5045 """ 5046 Returns a Func expression. 5047 5048 Examples: 5049 >>> func("abs", 5).sql() 5050 'ABS(5)' 5051 5052 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5053 'CAST(5 AS DOUBLE)' 5054 5055 Args: 5056 name: the name of the function to build. 5057 args: the args used to instantiate the function of interest. 5058 dialect: the source dialect. 5059 kwargs: the kwargs used to instantiate the function of interest. 5060 5061 Note: 5062 The arguments `args` and `kwargs` are mutually exclusive. 5063 5064 Returns: 5065 An instance of the function of interest, or an anonymous function, if `name` doesn't 5066 correspond to an existing `sqlglot.expressions.Func` class. 5067 """ 5068 if args and kwargs: 5069 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5070 5071 from sqlglot.dialects.dialect import Dialect 5072 5073 converted = [convert(arg) for arg in args] 5074 kwargs = {key: convert(value) for key, value in kwargs.items()} 5075 5076 parser = Dialect.get_or_raise(dialect)().parser() 5077 from_args_list = parser.FUNCTIONS.get(name.upper()) 5078 5079 if from_args_list: 5080 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5081 else: 5082 kwargs = kwargs or {"expressions": converted} 5083 function = Anonymous(this=name, **kwargs) 5084 5085 for error_message in function.error_messages(converted): 5086 raise ValueError(error_message) 5087 5088 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.
5091def true(): 5092 """ 5093 Returns a true Boolean expression. 5094 """ 5095 return Boolean(this=True)
Returns a true Boolean expression.
5098def false(): 5099 """ 5100 Returns a false Boolean expression. 5101 """ 5102 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.