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 parent: a reference to the parent expression (or None, in case of root expressions). 68 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 69 uses to refer to it. 70 comments: a list of comments that are associated with a given expression. This is used in 71 order to preserve comments when transpiling SQL code. 72 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 73 optimizer, in order to enable some transformations that require type information. 74 75 Example: 76 >>> class Foo(Expression): 77 ... arg_types = {"this": True, "expression": False} 78 79 The above definition informs us that Foo is an Expression that requires an argument called 80 "this" and may also optionally receive an argument called "expression". 81 82 Args: 83 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 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 add_comments(self, comments: t.Optional[t.List[str]]) -> None: 262 if self.comments is None: 263 self.comments = [] 264 if comments: 265 self.comments.extend(comments) 266 267 def append(self, arg_key, value): 268 """ 269 Appends value to arg_key if it's a list or sets it as a new list. 270 271 Args: 272 arg_key (str): name of the list expression arg 273 value (Any): value to append to the list 274 """ 275 if not isinstance(self.args.get(arg_key), list): 276 self.args[arg_key] = [] 277 self.args[arg_key].append(value) 278 self._set_parent(arg_key, value) 279 280 def set(self, arg_key, value): 281 """ 282 Sets `arg_key` to `value`. 283 284 Args: 285 arg_key (str): name of the expression arg. 286 value: value to set the arg to. 287 """ 288 self.args[arg_key] = value 289 self._set_parent(arg_key, value) 290 291 def _set_parent(self, arg_key, value): 292 if hasattr(value, "parent"): 293 value.parent = self 294 value.arg_key = arg_key 295 elif type(value) is list: 296 for v in value: 297 if hasattr(v, "parent"): 298 v.parent = self 299 v.arg_key = arg_key 300 301 @property 302 def depth(self): 303 """ 304 Returns the depth of this tree. 305 """ 306 if self.parent: 307 return self.parent.depth + 1 308 return 0 309 310 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 311 """Yields the key and expression for all arguments, exploding list args.""" 312 for k, vs in self.args.items(): 313 if type(vs) is list: 314 for v in vs: 315 if hasattr(v, "parent"): 316 yield k, v 317 else: 318 if hasattr(vs, "parent"): 319 yield k, vs 320 321 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 322 """ 323 Returns the first node in this tree which matches at least one of 324 the specified types. 325 326 Args: 327 expression_types: the expression type(s) to match. 328 329 Returns: 330 The node which matches the criteria or None if no such node was found. 331 """ 332 return next(self.find_all(*expression_types, bfs=bfs), None) 333 334 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 335 """ 336 Returns a generator object which visits all nodes in this tree and only 337 yields those that match at least one of the specified expression types. 338 339 Args: 340 expression_types: the expression type(s) to match. 341 342 Returns: 343 The generator object. 344 """ 345 for expression, *_ in self.walk(bfs=bfs): 346 if isinstance(expression, expression_types): 347 yield expression 348 349 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 350 """ 351 Returns a nearest parent matching expression_types. 352 353 Args: 354 expression_types: the expression type(s) to match. 355 356 Returns: 357 The parent node. 358 """ 359 ancestor = self.parent 360 while ancestor and not isinstance(ancestor, expression_types): 361 ancestor = ancestor.parent 362 return t.cast(E, ancestor) 363 364 @property 365 def parent_select(self): 366 """ 367 Returns the parent select statement. 368 """ 369 return self.find_ancestor(Select) 370 371 @property 372 def same_parent(self): 373 """Returns if the parent is the same class as itself.""" 374 return type(self.parent) is self.__class__ 375 376 def root(self) -> Expression: 377 """ 378 Returns the root expression of this tree. 379 """ 380 expression = self 381 while expression.parent: 382 expression = expression.parent 383 return expression 384 385 def walk(self, bfs=True, prune=None): 386 """ 387 Returns a generator object which visits all nodes in this tree. 388 389 Args: 390 bfs (bool): if set to True the BFS traversal order will be applied, 391 otherwise the DFS traversal will be used instead. 392 prune ((node, parent, arg_key) -> bool): callable that returns True if 393 the generator should stop traversing this branch of the tree. 394 395 Returns: 396 the generator object. 397 """ 398 if bfs: 399 yield from self.bfs(prune=prune) 400 else: 401 yield from self.dfs(prune=prune) 402 403 def dfs(self, parent=None, key=None, prune=None): 404 """ 405 Returns a generator object which visits all nodes in this tree in 406 the DFS (Depth-first) order. 407 408 Returns: 409 The generator object. 410 """ 411 parent = parent or self.parent 412 yield self, parent, key 413 if prune and prune(self, parent, key): 414 return 415 416 for k, v in self.iter_expressions(): 417 yield from v.dfs(self, k, prune) 418 419 def bfs(self, prune=None): 420 """ 421 Returns a generator object which visits all nodes in this tree in 422 the BFS (Breadth-first) order. 423 424 Returns: 425 The generator object. 426 """ 427 queue = deque([(self, self.parent, None)]) 428 429 while queue: 430 item, parent, key = queue.popleft() 431 432 yield item, parent, key 433 if prune and prune(item, parent, key): 434 continue 435 436 for k, v in item.iter_expressions(): 437 queue.append((v, item, k)) 438 439 def unnest(self): 440 """ 441 Returns the first non parenthesis child or self. 442 """ 443 expression = self 444 while type(expression) is Paren: 445 expression = expression.this 446 return expression 447 448 def unalias(self): 449 """ 450 Returns the inner expression if this is an Alias. 451 """ 452 if isinstance(self, Alias): 453 return self.this 454 return self 455 456 def unnest_operands(self): 457 """ 458 Returns unnested operands as a tuple. 459 """ 460 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 461 462 def flatten(self, unnest=True): 463 """ 464 Returns a generator which yields child nodes who's parents are the same class. 465 466 A AND B AND C -> [A, B, C] 467 """ 468 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 469 if not type(node) is self.__class__: 470 yield node.unnest() if unnest else node 471 472 def __str__(self): 473 return self.sql() 474 475 def __repr__(self): 476 return self._to_s() 477 478 def sql(self, dialect: DialectType = None, **opts) -> str: 479 """ 480 Returns SQL string representation of this tree. 481 482 Args: 483 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 484 opts: other `sqlglot.generator.Generator` options. 485 486 Returns: 487 The SQL string. 488 """ 489 from sqlglot.dialects import Dialect 490 491 return Dialect.get_or_raise(dialect)().generate(self, **opts) 492 493 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 494 indent = "" if not level else "\n" 495 indent += "".join([" "] * level) 496 left = f"({self.key.upper()} " 497 498 args: t.Dict[str, t.Any] = { 499 k: ", ".join( 500 v._to_s(hide_missing=hide_missing, level=level + 1) 501 if hasattr(v, "_to_s") 502 else str(v) 503 for v in ensure_list(vs) 504 if v is not None 505 ) 506 for k, vs in self.args.items() 507 } 508 args["comments"] = self.comments 509 args["type"] = self.type 510 args = {k: v for k, v in args.items() if v or not hide_missing} 511 512 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 513 right += ")" 514 515 return indent + left + right 516 517 def transform(self, fun, *args, copy=True, **kwargs): 518 """ 519 Recursively visits all tree nodes (excluding already transformed ones) 520 and applies the given transformation function to each node. 521 522 Args: 523 fun (function): a function which takes a node as an argument and returns a 524 new transformed node or the same node without modifications. If the function 525 returns None, then the corresponding node will be removed from the syntax tree. 526 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 527 modified in place. 528 529 Returns: 530 The transformed tree. 531 """ 532 node = self.copy() if copy else self 533 new_node = fun(node, *args, **kwargs) 534 535 if new_node is None or not isinstance(new_node, Expression): 536 return new_node 537 if new_node is not node: 538 new_node.parent = node.parent 539 return new_node 540 541 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 542 return new_node 543 544 def replace(self, expression): 545 """ 546 Swap out this expression with a new expression. 547 548 For example:: 549 550 >>> tree = Select().select("x").from_("tbl") 551 >>> tree.find(Column).replace(Column(this="y")) 552 (COLUMN this: y) 553 >>> tree.sql() 554 'SELECT y FROM tbl' 555 556 Args: 557 expression (Expression|None): new node 558 559 Returns: 560 The new expression or expressions. 561 """ 562 if not self.parent: 563 return expression 564 565 parent = self.parent 566 self.parent = None 567 568 replace_children(parent, lambda child: expression if child is self else child) 569 return expression 570 571 def pop(self): 572 """ 573 Remove this expression from its AST. 574 575 Returns: 576 The popped expression. 577 """ 578 self.replace(None) 579 return self 580 581 def assert_is(self, type_): 582 """ 583 Assert that this `Expression` is an instance of `type_`. 584 585 If it is NOT an instance of `type_`, this raises an assertion error. 586 Otherwise, this returns this expression. 587 588 Examples: 589 This is useful for type security in chained expressions: 590 591 >>> import sqlglot 592 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 593 'SELECT x, z FROM y' 594 """ 595 assert isinstance(self, type_) 596 return self 597 598 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 599 """ 600 Checks if this expression is valid (e.g. all mandatory args are set). 601 602 Args: 603 args: a sequence of values that were used to instantiate a Func expression. This is used 604 to check that the provided arguments don't exceed the function argument limit. 605 606 Returns: 607 A list of error messages for all possible errors that were found. 608 """ 609 errors: t.List[str] = [] 610 611 for k in self.args: 612 if k not in self.arg_types: 613 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 614 for k, mandatory in self.arg_types.items(): 615 v = self.args.get(k) 616 if mandatory and (v is None or (isinstance(v, list) and not v)): 617 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 618 619 if ( 620 args 621 and isinstance(self, Func) 622 and len(args) > len(self.arg_types) 623 and not self.is_var_len_args 624 ): 625 errors.append( 626 f"The number of provided arguments ({len(args)}) is greater than " 627 f"the maximum number of supported arguments ({len(self.arg_types)})" 628 ) 629 630 return errors 631 632 def dump(self): 633 """ 634 Dump this Expression to a JSON-serializable dict. 635 """ 636 from sqlglot.serde import dump 637 638 return dump(self) 639 640 @classmethod 641 def load(cls, obj): 642 """ 643 Load a dict (as returned by `Expression.dump`) into an Expression instance. 644 """ 645 from sqlglot.serde import load 646 647 return load(obj) 648 649 650IntoType = t.Union[ 651 str, 652 t.Type[Expression], 653 t.Collection[t.Union[str, t.Type[Expression]]], 654] 655ExpOrStr = t.Union[str, Expression] 656 657 658class Condition(Expression): 659 def and_(self, *expressions, dialect=None, copy=True, **opts): 660 """ 661 AND this condition with one or multiple expressions. 662 663 Example: 664 >>> condition("x=1").and_("y=1").sql() 665 'x = 1 AND y = 1' 666 667 Args: 668 *expressions (str | Expression): the SQL code strings to parse. 669 If an `Expression` instance is passed, it will be used as-is. 670 dialect (str): the dialect used to parse the input expression. 671 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 672 opts (kwargs): other options to use to parse the input expressions. 673 674 Returns: 675 And: the new condition. 676 """ 677 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 678 679 def or_(self, *expressions, dialect=None, copy=True, **opts): 680 """ 681 OR this condition with one or multiple expressions. 682 683 Example: 684 >>> condition("x=1").or_("y=1").sql() 685 'x = 1 OR y = 1' 686 687 Args: 688 *expressions (str | Expression): the SQL code strings to parse. 689 If an `Expression` instance is passed, it will be used as-is. 690 dialect (str): the dialect used to parse the input expression. 691 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 692 opts (kwargs): other options to use to parse the input expressions. 693 694 Returns: 695 Or: the new condition. 696 """ 697 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 698 699 def not_(self, copy=True): 700 """ 701 Wrap this condition with NOT. 702 703 Example: 704 >>> condition("x=1").not_().sql() 705 'NOT x = 1' 706 707 Args: 708 copy (bool): whether or not to copy this object. 709 710 Returns: 711 Not: the new condition. 712 """ 713 return not_(self, copy=copy) 714 715 def as_( 716 self, 717 alias: str | Identifier, 718 quoted: t.Optional[bool] = None, 719 dialect: DialectType = None, 720 copy: bool = True, 721 **opts, 722 ) -> Alias: 723 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 724 725 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 726 this = self.copy() 727 other = convert(other, copy=True) 728 if not isinstance(this, klass) and not isinstance(other, klass): 729 this = _wrap(this, Binary) 730 other = _wrap(other, Binary) 731 if reverse: 732 return klass(this=other, expression=this) 733 return klass(this=this, expression=other) 734 735 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 736 return Bracket( 737 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 738 ) 739 740 def isin( 741 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts 742 ) -> In: 743 return In( 744 this=_maybe_copy(self, copy), 745 expressions=[convert(e, copy=copy) for e in expressions], 746 query=maybe_parse(query, copy=copy, **opts) if query else None, 747 ) 748 749 def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between: 750 return Between( 751 this=_maybe_copy(self, copy), 752 low=convert(low, copy=copy, **opts), 753 high=convert(high, copy=copy, **opts), 754 ) 755 756 def is_(self, other: ExpOrStr) -> Is: 757 return self._binop(Is, other) 758 759 def like(self, other: ExpOrStr) -> Like: 760 return self._binop(Like, other) 761 762 def ilike(self, other: ExpOrStr) -> ILike: 763 return self._binop(ILike, other) 764 765 def eq(self, other: t.Any) -> EQ: 766 return self._binop(EQ, other) 767 768 def neq(self, other: t.Any) -> NEQ: 769 return self._binop(NEQ, other) 770 771 def rlike(self, other: ExpOrStr) -> RegexpLike: 772 return self._binop(RegexpLike, other) 773 774 def __lt__(self, other: t.Any) -> LT: 775 return self._binop(LT, other) 776 777 def __le__(self, other: t.Any) -> LTE: 778 return self._binop(LTE, other) 779 780 def __gt__(self, other: t.Any) -> GT: 781 return self._binop(GT, other) 782 783 def __ge__(self, other: t.Any) -> GTE: 784 return self._binop(GTE, other) 785 786 def __add__(self, other: t.Any) -> Add: 787 return self._binop(Add, other) 788 789 def __radd__(self, other: t.Any) -> Add: 790 return self._binop(Add, other, reverse=True) 791 792 def __sub__(self, other: t.Any) -> Sub: 793 return self._binop(Sub, other) 794 795 def __rsub__(self, other: t.Any) -> Sub: 796 return self._binop(Sub, other, reverse=True) 797 798 def __mul__(self, other: t.Any) -> Mul: 799 return self._binop(Mul, other) 800 801 def __rmul__(self, other: t.Any) -> Mul: 802 return self._binop(Mul, other, reverse=True) 803 804 def __truediv__(self, other: t.Any) -> Div: 805 return self._binop(Div, other) 806 807 def __rtruediv__(self, other: t.Any) -> Div: 808 return self._binop(Div, other, reverse=True) 809 810 def __floordiv__(self, other: t.Any) -> IntDiv: 811 return self._binop(IntDiv, other) 812 813 def __rfloordiv__(self, other: t.Any) -> IntDiv: 814 return self._binop(IntDiv, other, reverse=True) 815 816 def __mod__(self, other: t.Any) -> Mod: 817 return self._binop(Mod, other) 818 819 def __rmod__(self, other: t.Any) -> Mod: 820 return self._binop(Mod, other, reverse=True) 821 822 def __pow__(self, other: t.Any) -> Pow: 823 return self._binop(Pow, other) 824 825 def __rpow__(self, other: t.Any) -> Pow: 826 return self._binop(Pow, other, reverse=True) 827 828 def __and__(self, other: t.Any) -> And: 829 return self._binop(And, other) 830 831 def __rand__(self, other: t.Any) -> And: 832 return self._binop(And, other, reverse=True) 833 834 def __or__(self, other: t.Any) -> Or: 835 return self._binop(Or, other) 836 837 def __ror__(self, other: t.Any) -> Or: 838 return self._binop(Or, other, reverse=True) 839 840 def __neg__(self) -> Neg: 841 return Neg(this=_wrap(self.copy(), Binary)) 842 843 def __invert__(self) -> Not: 844 return not_(self.copy()) 845 846 847class Predicate(Condition): 848 """Relationships like x = y, x > 1, x >= y.""" 849 850 851class DerivedTable(Expression): 852 @property 853 def alias_column_names(self): 854 table_alias = self.args.get("alias") 855 if not table_alias: 856 return [] 857 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 858 return [c.name for c in column_list] 859 860 @property 861 def selects(self): 862 return self.this.selects if isinstance(self.this, Subqueryable) else [] 863 864 @property 865 def named_selects(self): 866 return [select.output_name for select in self.selects] 867 868 869class Unionable(Expression): 870 def union(self, expression, distinct=True, dialect=None, **opts): 871 """ 872 Builds a UNION expression. 873 874 Example: 875 >>> import sqlglot 876 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 877 'SELECT * FROM foo UNION SELECT * FROM bla' 878 879 Args: 880 expression (str | Expression): the SQL code string. 881 If an `Expression` instance is passed, it will be used as-is. 882 distinct (bool): set the DISTINCT flag if and only if this is true. 883 dialect (str): the dialect used to parse the input expression. 884 opts (kwargs): other options to use to parse the input expressions. 885 Returns: 886 Union: the Union expression. 887 """ 888 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 889 890 def intersect(self, expression, distinct=True, dialect=None, **opts): 891 """ 892 Builds an INTERSECT expression. 893 894 Example: 895 >>> import sqlglot 896 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 897 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 898 899 Args: 900 expression (str | Expression): the SQL code string. 901 If an `Expression` instance is passed, it will be used as-is. 902 distinct (bool): set the DISTINCT flag if and only if this is true. 903 dialect (str): the dialect used to parse the input expression. 904 opts (kwargs): other options to use to parse the input expressions. 905 Returns: 906 Intersect: the Intersect expression 907 """ 908 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 909 910 def except_(self, expression, distinct=True, dialect=None, **opts): 911 """ 912 Builds an EXCEPT expression. 913 914 Example: 915 >>> import sqlglot 916 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 917 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 918 919 Args: 920 expression (str | Expression): the SQL code string. 921 If an `Expression` instance is passed, it will be used as-is. 922 distinct (bool): set the DISTINCT flag if and only if this is true. 923 dialect (str): the dialect used to parse the input expression. 924 opts (kwargs): other options to use to parse the input expressions. 925 Returns: 926 Except: the Except expression 927 """ 928 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 929 930 931class UDTF(DerivedTable, Unionable): 932 @property 933 def selects(self): 934 alias = self.args.get("alias") 935 return alias.columns if alias else [] 936 937 938class Cache(Expression): 939 arg_types = { 940 "with": False, 941 "this": True, 942 "lazy": False, 943 "options": False, 944 "expression": False, 945 } 946 947 948class Uncache(Expression): 949 arg_types = {"this": True, "exists": False} 950 951 952class Create(Expression): 953 arg_types = { 954 "with": False, 955 "this": True, 956 "kind": True, 957 "expression": False, 958 "exists": False, 959 "properties": False, 960 "replace": False, 961 "unique": False, 962 "indexes": False, 963 "no_schema_binding": False, 964 "begin": False, 965 "clone": False, 966 } 967 968 969# https://docs.snowflake.com/en/sql-reference/sql/create-clone 970class Clone(Expression): 971 arg_types = { 972 "this": True, 973 "when": False, 974 "kind": False, 975 "expression": False, 976 } 977 978 979class Describe(Expression): 980 arg_types = {"this": True, "kind": False} 981 982 983class Pragma(Expression): 984 pass 985 986 987class Set(Expression): 988 arg_types = {"expressions": False} 989 990 991class SetItem(Expression): 992 arg_types = { 993 "this": False, 994 "expressions": False, 995 "kind": False, 996 "collate": False, # MySQL SET NAMES statement 997 "global": False, 998 } 999 1000 1001class Show(Expression): 1002 arg_types = { 1003 "this": True, 1004 "target": False, 1005 "offset": False, 1006 "limit": False, 1007 "like": False, 1008 "where": False, 1009 "db": False, 1010 "full": False, 1011 "mutex": False, 1012 "query": False, 1013 "channel": False, 1014 "global": False, 1015 "log": False, 1016 "position": False, 1017 "types": False, 1018 } 1019 1020 1021class UserDefinedFunction(Expression): 1022 arg_types = {"this": True, "expressions": False, "wrapped": False} 1023 1024 1025class CharacterSet(Expression): 1026 arg_types = {"this": True, "default": False} 1027 1028 1029class With(Expression): 1030 arg_types = {"expressions": True, "recursive": False} 1031 1032 @property 1033 def recursive(self) -> bool: 1034 return bool(self.args.get("recursive")) 1035 1036 1037class WithinGroup(Expression): 1038 arg_types = {"this": True, "expression": False} 1039 1040 1041class CTE(DerivedTable): 1042 arg_types = {"this": True, "alias": True} 1043 1044 1045class TableAlias(Expression): 1046 arg_types = {"this": False, "columns": False} 1047 1048 @property 1049 def columns(self): 1050 return self.args.get("columns") or [] 1051 1052 1053class BitString(Condition): 1054 pass 1055 1056 1057class HexString(Condition): 1058 pass 1059 1060 1061class ByteString(Condition): 1062 pass 1063 1064 1065class Column(Condition): 1066 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1067 1068 @property 1069 def table(self) -> str: 1070 return self.text("table") 1071 1072 @property 1073 def db(self) -> str: 1074 return self.text("db") 1075 1076 @property 1077 def catalog(self) -> str: 1078 return self.text("catalog") 1079 1080 @property 1081 def output_name(self) -> str: 1082 return self.name 1083 1084 @property 1085 def parts(self) -> t.List[Identifier]: 1086 """Return the parts of a column in order catalog, db, table, name.""" 1087 return [ 1088 t.cast(Identifier, self.args[part]) 1089 for part in ("catalog", "db", "table", "this") 1090 if self.args.get(part) 1091 ] 1092 1093 def to_dot(self) -> Dot: 1094 """Converts the column into a dot expression.""" 1095 parts = self.parts 1096 parent = self.parent 1097 1098 while parent: 1099 if isinstance(parent, Dot): 1100 parts.append(parent.expression) 1101 parent = parent.parent 1102 1103 return Dot.build(parts) 1104 1105 1106class ColumnPosition(Expression): 1107 arg_types = {"this": False, "position": True} 1108 1109 1110class ColumnDef(Expression): 1111 arg_types = { 1112 "this": True, 1113 "kind": False, 1114 "constraints": False, 1115 "exists": False, 1116 "position": False, 1117 } 1118 1119 @property 1120 def constraints(self) -> t.List[ColumnConstraint]: 1121 return self.args.get("constraints") or [] 1122 1123 1124class AlterColumn(Expression): 1125 arg_types = { 1126 "this": True, 1127 "dtype": False, 1128 "collate": False, 1129 "using": False, 1130 "default": False, 1131 "drop": False, 1132 } 1133 1134 1135class RenameTable(Expression): 1136 pass 1137 1138 1139class SetTag(Expression): 1140 arg_types = {"expressions": True, "unset": False} 1141 1142 1143class Comment(Expression): 1144 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 1145 1146 1147# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1148class MergeTreeTTLAction(Expression): 1149 arg_types = { 1150 "this": True, 1151 "delete": False, 1152 "recompress": False, 1153 "to_disk": False, 1154 "to_volume": False, 1155 } 1156 1157 1158# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl 1159class MergeTreeTTL(Expression): 1160 arg_types = { 1161 "expressions": True, 1162 "where": False, 1163 "group": False, 1164 "aggregates": False, 1165 } 1166 1167 1168class ColumnConstraint(Expression): 1169 arg_types = {"this": False, "kind": True} 1170 1171 @property 1172 def kind(self) -> ColumnConstraintKind: 1173 return self.args["kind"] 1174 1175 1176class ColumnConstraintKind(Expression): 1177 pass 1178 1179 1180class AutoIncrementColumnConstraint(ColumnConstraintKind): 1181 pass 1182 1183 1184class CaseSpecificColumnConstraint(ColumnConstraintKind): 1185 arg_types = {"not_": True} 1186 1187 1188class CharacterSetColumnConstraint(ColumnConstraintKind): 1189 arg_types = {"this": True} 1190 1191 1192class CheckColumnConstraint(ColumnConstraintKind): 1193 pass 1194 1195 1196class CollateColumnConstraint(ColumnConstraintKind): 1197 pass 1198 1199 1200class CommentColumnConstraint(ColumnConstraintKind): 1201 pass 1202 1203 1204class CompressColumnConstraint(ColumnConstraintKind): 1205 pass 1206 1207 1208class DateFormatColumnConstraint(ColumnConstraintKind): 1209 arg_types = {"this": True} 1210 1211 1212class DefaultColumnConstraint(ColumnConstraintKind): 1213 pass 1214 1215 1216class EncodeColumnConstraint(ColumnConstraintKind): 1217 pass 1218 1219 1220class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1221 # this: True -> ALWAYS, this: False -> BY DEFAULT 1222 arg_types = { 1223 "this": False, 1224 "on_null": False, 1225 "start": False, 1226 "increment": False, 1227 "minvalue": False, 1228 "maxvalue": False, 1229 "cycle": False, 1230 } 1231 1232 1233class InlineLengthColumnConstraint(ColumnConstraintKind): 1234 pass 1235 1236 1237class NotNullColumnConstraint(ColumnConstraintKind): 1238 arg_types = {"allow_null": False} 1239 1240 1241# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 1242class OnUpdateColumnConstraint(ColumnConstraintKind): 1243 pass 1244 1245 1246class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1247 arg_types = {"desc": False} 1248 1249 1250class TitleColumnConstraint(ColumnConstraintKind): 1251 pass 1252 1253 1254class UniqueColumnConstraint(ColumnConstraintKind): 1255 arg_types: t.Dict[str, t.Any] = {} 1256 1257 1258class UppercaseColumnConstraint(ColumnConstraintKind): 1259 arg_types: t.Dict[str, t.Any] = {} 1260 1261 1262class PathColumnConstraint(ColumnConstraintKind): 1263 pass 1264 1265 1266class Constraint(Expression): 1267 arg_types = {"this": True, "expressions": True} 1268 1269 1270class Delete(Expression): 1271 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1272 1273 def delete( 1274 self, 1275 table: ExpOrStr, 1276 dialect: DialectType = None, 1277 copy: bool = True, 1278 **opts, 1279 ) -> Delete: 1280 """ 1281 Create a DELETE expression or replace the table on an existing DELETE expression. 1282 1283 Example: 1284 >>> delete("tbl").sql() 1285 'DELETE FROM tbl' 1286 1287 Args: 1288 table: the table from which to delete. 1289 dialect: the dialect used to parse the input expression. 1290 copy: if `False`, modify this expression instance in-place. 1291 opts: other options to use to parse the input expressions. 1292 1293 Returns: 1294 Delete: the modified expression. 1295 """ 1296 return _apply_builder( 1297 expression=table, 1298 instance=self, 1299 arg="this", 1300 dialect=dialect, 1301 into=Table, 1302 copy=copy, 1303 **opts, 1304 ) 1305 1306 def where( 1307 self, 1308 *expressions: ExpOrStr, 1309 append: bool = True, 1310 dialect: DialectType = None, 1311 copy: bool = True, 1312 **opts, 1313 ) -> Delete: 1314 """ 1315 Append to or set the WHERE expressions. 1316 1317 Example: 1318 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1319 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1320 1321 Args: 1322 *expressions: the SQL code strings to parse. 1323 If an `Expression` instance is passed, it will be used as-is. 1324 Multiple expressions are combined with an AND operator. 1325 append: if `True`, AND the new expressions to any existing expression. 1326 Otherwise, this resets the expression. 1327 dialect: the dialect used to parse the input expressions. 1328 copy: if `False`, modify this expression instance in-place. 1329 opts: other options to use to parse the input expressions. 1330 1331 Returns: 1332 Delete: the modified expression. 1333 """ 1334 return _apply_conjunction_builder( 1335 *expressions, 1336 instance=self, 1337 arg="where", 1338 append=append, 1339 into=Where, 1340 dialect=dialect, 1341 copy=copy, 1342 **opts, 1343 ) 1344 1345 def returning( 1346 self, 1347 expression: ExpOrStr, 1348 dialect: DialectType = None, 1349 copy: bool = True, 1350 **opts, 1351 ) -> Delete: 1352 """ 1353 Set the RETURNING expression. Not supported by all dialects. 1354 1355 Example: 1356 >>> delete("tbl").returning("*", dialect="postgres").sql() 1357 'DELETE FROM tbl RETURNING *' 1358 1359 Args: 1360 expression: the SQL code strings to parse. 1361 If an `Expression` instance is passed, it will be used as-is. 1362 dialect: the dialect used to parse the input expressions. 1363 copy: if `False`, modify this expression instance in-place. 1364 opts: other options to use to parse the input expressions. 1365 1366 Returns: 1367 Delete: the modified expression. 1368 """ 1369 return _apply_builder( 1370 expression=expression, 1371 instance=self, 1372 arg="returning", 1373 prefix="RETURNING", 1374 dialect=dialect, 1375 copy=copy, 1376 into=Returning, 1377 **opts, 1378 ) 1379 1380 1381class Drop(Expression): 1382 arg_types = { 1383 "this": False, 1384 "kind": False, 1385 "exists": False, 1386 "temporary": False, 1387 "materialized": False, 1388 "cascade": False, 1389 "constraints": False, 1390 "purge": False, 1391 } 1392 1393 1394class Filter(Expression): 1395 arg_types = {"this": True, "expression": True} 1396 1397 1398class Check(Expression): 1399 pass 1400 1401 1402class Directory(Expression): 1403 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1404 arg_types = {"this": True, "local": False, "row_format": False} 1405 1406 1407class ForeignKey(Expression): 1408 arg_types = { 1409 "expressions": True, 1410 "reference": False, 1411 "delete": False, 1412 "update": False, 1413 } 1414 1415 1416class PrimaryKey(Expression): 1417 arg_types = {"expressions": True, "options": False} 1418 1419 1420class Unique(Expression): 1421 arg_types = {"expressions": True} 1422 1423 1424# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1425# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1426class Into(Expression): 1427 arg_types = {"this": True, "temporary": False, "unlogged": False} 1428 1429 1430class From(Expression): 1431 @property 1432 def name(self) -> str: 1433 return self.this.name 1434 1435 @property 1436 def alias_or_name(self) -> str: 1437 return self.this.alias_or_name 1438 1439 1440class Having(Expression): 1441 pass 1442 1443 1444class Hint(Expression): 1445 arg_types = {"expressions": True} 1446 1447 1448class JoinHint(Expression): 1449 arg_types = {"this": True, "expressions": True} 1450 1451 1452class Identifier(Expression): 1453 arg_types = {"this": True, "quoted": False} 1454 1455 @property 1456 def quoted(self): 1457 return bool(self.args.get("quoted")) 1458 1459 @property 1460 def hashable_args(self) -> t.Any: 1461 if self.quoted and any(char.isupper() for char in self.this): 1462 return (self.this, self.quoted) 1463 return self.this.lower() 1464 1465 @property 1466 def output_name(self): 1467 return self.name 1468 1469 1470class Index(Expression): 1471 arg_types = { 1472 "this": False, 1473 "table": False, 1474 "where": False, 1475 "columns": False, 1476 "unique": False, 1477 "primary": False, 1478 "amp": False, # teradata 1479 } 1480 1481 1482class Insert(Expression): 1483 arg_types = { 1484 "with": False, 1485 "this": True, 1486 "expression": False, 1487 "conflict": False, 1488 "returning": False, 1489 "overwrite": False, 1490 "exists": False, 1491 "partition": False, 1492 "alternative": False, 1493 } 1494 1495 def with_( 1496 self, 1497 alias: ExpOrStr, 1498 as_: ExpOrStr, 1499 recursive: t.Optional[bool] = None, 1500 append: bool = True, 1501 dialect: DialectType = None, 1502 copy: bool = True, 1503 **opts, 1504 ) -> Insert: 1505 """ 1506 Append to or set the common table expressions. 1507 1508 Example: 1509 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1510 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1511 1512 Args: 1513 alias: the SQL code string to parse as the table name. 1514 If an `Expression` instance is passed, this is used as-is. 1515 as_: the SQL code string to parse as the table expression. 1516 If an `Expression` instance is passed, it will be used as-is. 1517 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1518 append: if `True`, add to any existing expressions. 1519 Otherwise, this resets the expressions. 1520 dialect: the dialect used to parse the input expression. 1521 copy: if `False`, modify this expression instance in-place. 1522 opts: other options to use to parse the input expressions. 1523 1524 Returns: 1525 The modified expression. 1526 """ 1527 return _apply_cte_builder( 1528 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1529 ) 1530 1531 1532class OnConflict(Expression): 1533 arg_types = { 1534 "duplicate": False, 1535 "expressions": False, 1536 "nothing": False, 1537 "key": False, 1538 "constraint": False, 1539 } 1540 1541 1542class Returning(Expression): 1543 arg_types = {"expressions": True} 1544 1545 1546# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1547class Introducer(Expression): 1548 arg_types = {"this": True, "expression": True} 1549 1550 1551# national char, like n'utf8' 1552class National(Expression): 1553 pass 1554 1555 1556class LoadData(Expression): 1557 arg_types = { 1558 "this": True, 1559 "local": False, 1560 "overwrite": False, 1561 "inpath": True, 1562 "partition": False, 1563 "input_format": False, 1564 "serde": False, 1565 } 1566 1567 1568class Partition(Expression): 1569 arg_types = {"expressions": True} 1570 1571 1572class Fetch(Expression): 1573 arg_types = { 1574 "direction": False, 1575 "count": False, 1576 "percent": False, 1577 "with_ties": False, 1578 } 1579 1580 1581class Group(Expression): 1582 arg_types = { 1583 "expressions": False, 1584 "grouping_sets": False, 1585 "cube": False, 1586 "rollup": False, 1587 "totals": False, 1588 } 1589 1590 1591class Lambda(Expression): 1592 arg_types = {"this": True, "expressions": True} 1593 1594 1595class Limit(Expression): 1596 arg_types = {"this": False, "expression": True} 1597 1598 1599class Literal(Condition): 1600 arg_types = {"this": True, "is_string": True} 1601 1602 @property 1603 def hashable_args(self) -> t.Any: 1604 return (self.this, self.args.get("is_string")) 1605 1606 @classmethod 1607 def number(cls, number) -> Literal: 1608 return cls(this=str(number), is_string=False) 1609 1610 @classmethod 1611 def string(cls, string) -> Literal: 1612 return cls(this=str(string), is_string=True) 1613 1614 @property 1615 def output_name(self): 1616 return self.name 1617 1618 1619class Join(Expression): 1620 arg_types = { 1621 "this": True, 1622 "on": False, 1623 "side": False, 1624 "kind": False, 1625 "using": False, 1626 "natural": False, 1627 "global": False, 1628 "hint": False, 1629 } 1630 1631 @property 1632 def kind(self): 1633 return self.text("kind").upper() 1634 1635 @property 1636 def side(self): 1637 return self.text("side").upper() 1638 1639 @property 1640 def hint(self): 1641 return self.text("hint").upper() 1642 1643 @property 1644 def alias_or_name(self): 1645 return self.this.alias_or_name 1646 1647 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1648 """ 1649 Append to or set the ON expressions. 1650 1651 Example: 1652 >>> import sqlglot 1653 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1654 'JOIN x ON y = 1' 1655 1656 Args: 1657 *expressions (str | Expression): the SQL code strings to parse. 1658 If an `Expression` instance is passed, it will be used as-is. 1659 Multiple expressions are combined with an AND operator. 1660 append (bool): if `True`, AND the new expressions to any existing expression. 1661 Otherwise, this resets the expression. 1662 dialect (str): the dialect used to parse the input expressions. 1663 copy (bool): if `False`, modify this expression instance in-place. 1664 opts (kwargs): other options to use to parse the input expressions. 1665 1666 Returns: 1667 Join: the modified join expression. 1668 """ 1669 join = _apply_conjunction_builder( 1670 *expressions, 1671 instance=self, 1672 arg="on", 1673 append=append, 1674 dialect=dialect, 1675 copy=copy, 1676 **opts, 1677 ) 1678 1679 if join.kind == "CROSS": 1680 join.set("kind", None) 1681 1682 return join 1683 1684 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1685 """ 1686 Append to or set the USING expressions. 1687 1688 Example: 1689 >>> import sqlglot 1690 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1691 'JOIN x USING (foo, bla)' 1692 1693 Args: 1694 *expressions (str | Expression): the SQL code strings to parse. 1695 If an `Expression` instance is passed, it will be used as-is. 1696 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1697 Otherwise, this resets the expression. 1698 dialect (str): the dialect used to parse the input expressions. 1699 copy (bool): if `False`, modify this expression instance in-place. 1700 opts (kwargs): other options to use to parse the input expressions. 1701 1702 Returns: 1703 Join: the modified join expression. 1704 """ 1705 join = _apply_list_builder( 1706 *expressions, 1707 instance=self, 1708 arg="using", 1709 append=append, 1710 dialect=dialect, 1711 copy=copy, 1712 **opts, 1713 ) 1714 1715 if join.kind == "CROSS": 1716 join.set("kind", None) 1717 1718 return join 1719 1720 1721class Lateral(UDTF): 1722 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1723 1724 1725class MatchRecognize(Expression): 1726 arg_types = { 1727 "partition_by": False, 1728 "order": False, 1729 "measures": False, 1730 "rows": False, 1731 "after": False, 1732 "pattern": False, 1733 "define": False, 1734 "alias": False, 1735 } 1736 1737 1738# Clickhouse FROM FINAL modifier 1739# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1740class Final(Expression): 1741 pass 1742 1743 1744class Offset(Expression): 1745 arg_types = {"this": False, "expression": True} 1746 1747 1748class Order(Expression): 1749 arg_types = {"this": False, "expressions": True} 1750 1751 1752# hive specific sorts 1753# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1754class Cluster(Order): 1755 pass 1756 1757 1758class Distribute(Order): 1759 pass 1760 1761 1762class Sort(Order): 1763 pass 1764 1765 1766class Ordered(Expression): 1767 arg_types = {"this": True, "desc": True, "nulls_first": True} 1768 1769 1770class Property(Expression): 1771 arg_types = {"this": True, "value": True} 1772 1773 1774class AfterJournalProperty(Property): 1775 arg_types = {"no": True, "dual": False, "local": False} 1776 1777 1778class AlgorithmProperty(Property): 1779 arg_types = {"this": True} 1780 1781 1782class AutoIncrementProperty(Property): 1783 arg_types = {"this": True} 1784 1785 1786class BlockCompressionProperty(Property): 1787 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1788 1789 1790class CharacterSetProperty(Property): 1791 arg_types = {"this": True, "default": True} 1792 1793 1794class ChecksumProperty(Property): 1795 arg_types = {"on": False, "default": False} 1796 1797 1798class CollateProperty(Property): 1799 arg_types = {"this": True} 1800 1801 1802class DataBlocksizeProperty(Property): 1803 arg_types = {"size": False, "units": False, "min": False, "default": False} 1804 1805 1806class DefinerProperty(Property): 1807 arg_types = {"this": True} 1808 1809 1810class DistKeyProperty(Property): 1811 arg_types = {"this": True} 1812 1813 1814class DistStyleProperty(Property): 1815 arg_types = {"this": True} 1816 1817 1818class EngineProperty(Property): 1819 arg_types = {"this": True} 1820 1821 1822class ExecuteAsProperty(Property): 1823 arg_types = {"this": True} 1824 1825 1826class ExternalProperty(Property): 1827 arg_types = {"this": False} 1828 1829 1830class FallbackProperty(Property): 1831 arg_types = {"no": True, "protection": False} 1832 1833 1834class FileFormatProperty(Property): 1835 arg_types = {"this": True} 1836 1837 1838class FreespaceProperty(Property): 1839 arg_types = {"this": True, "percent": False} 1840 1841 1842class InputOutputFormat(Expression): 1843 arg_types = {"input_format": False, "output_format": False} 1844 1845 1846class IsolatedLoadingProperty(Property): 1847 arg_types = { 1848 "no": True, 1849 "concurrent": True, 1850 "for_all": True, 1851 "for_insert": True, 1852 "for_none": True, 1853 } 1854 1855 1856class JournalProperty(Property): 1857 arg_types = {"no": True, "dual": False, "before": False} 1858 1859 1860class LanguageProperty(Property): 1861 arg_types = {"this": True} 1862 1863 1864class LikeProperty(Property): 1865 arg_types = {"this": True, "expressions": False} 1866 1867 1868class LocationProperty(Property): 1869 arg_types = {"this": True} 1870 1871 1872class LockingProperty(Property): 1873 arg_types = { 1874 "this": False, 1875 "kind": True, 1876 "for_or_in": True, 1877 "lock_type": True, 1878 "override": False, 1879 } 1880 1881 1882class LogProperty(Property): 1883 arg_types = {"no": True} 1884 1885 1886class MaterializedProperty(Property): 1887 arg_types = {"this": False} 1888 1889 1890class MergeBlockRatioProperty(Property): 1891 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1892 1893 1894class NoPrimaryIndexProperty(Property): 1895 arg_types = {"this": False} 1896 1897 1898class OnCommitProperty(Property): 1899 arg_type = {"delete": False} 1900 1901 1902class PartitionedByProperty(Property): 1903 arg_types = {"this": True} 1904 1905 1906class ReturnsProperty(Property): 1907 arg_types = {"this": True, "is_table": False, "table": False} 1908 1909 1910class RowFormatProperty(Property): 1911 arg_types = {"this": True} 1912 1913 1914class RowFormatDelimitedProperty(Property): 1915 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1916 arg_types = { 1917 "fields": False, 1918 "escaped": False, 1919 "collection_items": False, 1920 "map_keys": False, 1921 "lines": False, 1922 "null": False, 1923 "serde": False, 1924 } 1925 1926 1927class RowFormatSerdeProperty(Property): 1928 arg_types = {"this": True} 1929 1930 1931class SchemaCommentProperty(Property): 1932 arg_types = {"this": True} 1933 1934 1935class SerdeProperties(Property): 1936 arg_types = {"expressions": True} 1937 1938 1939class SetProperty(Property): 1940 arg_types = {"multi": True} 1941 1942 1943class SettingsProperty(Property): 1944 arg_types = {"expressions": True} 1945 1946 1947class SortKeyProperty(Property): 1948 arg_types = {"this": True, "compound": False} 1949 1950 1951class SqlSecurityProperty(Property): 1952 arg_types = {"definer": True} 1953 1954 1955class StabilityProperty(Property): 1956 arg_types = {"this": True} 1957 1958 1959class TemporaryProperty(Property): 1960 arg_types = {"global_": True} 1961 1962 1963class TransientProperty(Property): 1964 arg_types = {"this": False} 1965 1966 1967class VolatileProperty(Property): 1968 arg_types = {"this": False} 1969 1970 1971class WithDataProperty(Property): 1972 arg_types = {"no": True, "statistics": False} 1973 1974 1975class WithJournalTableProperty(Property): 1976 arg_types = {"this": True} 1977 1978 1979class Properties(Expression): 1980 arg_types = {"expressions": True} 1981 1982 NAME_TO_PROPERTY = { 1983 "ALGORITHM": AlgorithmProperty, 1984 "AUTO_INCREMENT": AutoIncrementProperty, 1985 "CHARACTER SET": CharacterSetProperty, 1986 "COLLATE": CollateProperty, 1987 "COMMENT": SchemaCommentProperty, 1988 "DEFINER": DefinerProperty, 1989 "DISTKEY": DistKeyProperty, 1990 "DISTSTYLE": DistStyleProperty, 1991 "ENGINE": EngineProperty, 1992 "EXECUTE AS": ExecuteAsProperty, 1993 "FORMAT": FileFormatProperty, 1994 "LANGUAGE": LanguageProperty, 1995 "LOCATION": LocationProperty, 1996 "PARTITIONED_BY": PartitionedByProperty, 1997 "RETURNS": ReturnsProperty, 1998 "ROW_FORMAT": RowFormatProperty, 1999 "SORTKEY": SortKeyProperty, 2000 } 2001 2002 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2003 2004 # CREATE property locations 2005 # Form: schema specified 2006 # create [POST_CREATE] 2007 # table a [POST_NAME] 2008 # (b int) [POST_SCHEMA] 2009 # with ([POST_WITH]) 2010 # index (b) [POST_INDEX] 2011 # 2012 # Form: alias selection 2013 # create [POST_CREATE] 2014 # table a [POST_NAME] 2015 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2016 # index (c) [POST_INDEX] 2017 class Location(AutoName): 2018 POST_CREATE = auto() 2019 POST_NAME = auto() 2020 POST_SCHEMA = auto() 2021 POST_WITH = auto() 2022 POST_ALIAS = auto() 2023 POST_EXPRESSION = auto() 2024 POST_INDEX = auto() 2025 UNSUPPORTED = auto() 2026 2027 @classmethod 2028 def from_dict(cls, properties_dict) -> Properties: 2029 expressions = [] 2030 for key, value in properties_dict.items(): 2031 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2032 if property_cls: 2033 expressions.append(property_cls(this=convert(value))) 2034 else: 2035 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2036 2037 return cls(expressions=expressions) 2038 2039 2040class Qualify(Expression): 2041 pass 2042 2043 2044# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 2045class Return(Expression): 2046 pass 2047 2048 2049class Reference(Expression): 2050 arg_types = {"this": True, "expressions": False, "options": False} 2051 2052 2053class Tuple(Expression): 2054 arg_types = {"expressions": False} 2055 2056 def isin( 2057 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts 2058 ) -> In: 2059 return In( 2060 this=_maybe_copy(self, copy), 2061 expressions=[convert(e, copy=copy) for e in expressions], 2062 query=maybe_parse(query, copy=copy, **opts) if query else None, 2063 ) 2064 2065 2066class Subqueryable(Unionable): 2067 def subquery(self, alias=None, copy=True) -> Subquery: 2068 """ 2069 Convert this expression to an aliased expression that can be used as a Subquery. 2070 2071 Example: 2072 >>> subquery = Select().select("x").from_("tbl").subquery() 2073 >>> Select().select("x").from_(subquery).sql() 2074 'SELECT x FROM (SELECT x FROM tbl)' 2075 2076 Args: 2077 alias (str | Identifier): an optional alias for the subquery 2078 copy (bool): if `False`, modify this expression instance in-place. 2079 2080 Returns: 2081 Alias: the subquery 2082 """ 2083 instance = _maybe_copy(self, copy) 2084 if not isinstance(alias, Expression): 2085 alias = TableAlias(this=to_identifier(alias)) if alias else None 2086 2087 return Subquery(this=instance, alias=alias) 2088 2089 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2090 raise NotImplementedError 2091 2092 @property 2093 def ctes(self): 2094 with_ = self.args.get("with") 2095 if not with_: 2096 return [] 2097 return with_.expressions 2098 2099 @property 2100 def selects(self): 2101 raise NotImplementedError("Subqueryable objects must implement `selects`") 2102 2103 @property 2104 def named_selects(self): 2105 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2106 2107 def with_( 2108 self, 2109 alias: ExpOrStr, 2110 as_: ExpOrStr, 2111 recursive: t.Optional[bool] = None, 2112 append: bool = True, 2113 dialect: DialectType = None, 2114 copy: bool = True, 2115 **opts, 2116 ) -> Subqueryable: 2117 """ 2118 Append to or set the common table expressions. 2119 2120 Example: 2121 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2122 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2123 2124 Args: 2125 alias: the SQL code string to parse as the table name. 2126 If an `Expression` instance is passed, this is used as-is. 2127 as_: the SQL code string to parse as the table expression. 2128 If an `Expression` instance is passed, it will be used as-is. 2129 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2130 append: if `True`, add to any existing expressions. 2131 Otherwise, this resets the expressions. 2132 dialect: the dialect used to parse the input expression. 2133 copy: if `False`, modify this expression instance in-place. 2134 opts: other options to use to parse the input expressions. 2135 2136 Returns: 2137 The modified expression. 2138 """ 2139 return _apply_cte_builder( 2140 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2141 ) 2142 2143 2144QUERY_MODIFIERS = { 2145 "match": False, 2146 "laterals": False, 2147 "joins": False, 2148 "pivots": False, 2149 "where": False, 2150 "group": False, 2151 "having": False, 2152 "qualify": False, 2153 "windows": False, 2154 "distribute": False, 2155 "sort": False, 2156 "cluster": False, 2157 "order": False, 2158 "limit": False, 2159 "offset": False, 2160 "locks": False, 2161 "sample": False, 2162 "settings": False, 2163 "format": False, 2164} 2165 2166 2167class Table(Expression): 2168 arg_types = { 2169 "this": True, 2170 "alias": False, 2171 "db": False, 2172 "catalog": False, 2173 "laterals": False, 2174 "joins": False, 2175 "pivots": False, 2176 "hints": False, 2177 "system_time": False, 2178 } 2179 2180 @property 2181 def db(self) -> str: 2182 return self.text("db") 2183 2184 @property 2185 def catalog(self) -> str: 2186 return self.text("catalog") 2187 2188 @property 2189 def parts(self) -> t.List[Identifier]: 2190 """Return the parts of a column in order catalog, db, table.""" 2191 return [ 2192 t.cast(Identifier, self.args[part]) 2193 for part in ("catalog", "db", "this") 2194 if self.args.get(part) 2195 ] 2196 2197 2198# See the TSQL "Querying data in a system-versioned temporal table" page 2199class SystemTime(Expression): 2200 arg_types = { 2201 "this": False, 2202 "expression": False, 2203 "kind": True, 2204 } 2205 2206 2207class Union(Subqueryable): 2208 arg_types = { 2209 "with": False, 2210 "this": True, 2211 "expression": True, 2212 "distinct": False, 2213 **QUERY_MODIFIERS, 2214 } 2215 2216 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2217 """ 2218 Set the LIMIT expression. 2219 2220 Example: 2221 >>> select("1").union(select("1")).limit(1).sql() 2222 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2223 2224 Args: 2225 expression (str | int | Expression): the SQL code string to parse. 2226 This can also be an integer. 2227 If a `Limit` instance is passed, this is used as-is. 2228 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2229 dialect (str): the dialect used to parse the input expression. 2230 copy (bool): if `False`, modify this expression instance in-place. 2231 opts (kwargs): other options to use to parse the input expressions. 2232 2233 Returns: 2234 Select: The limited subqueryable. 2235 """ 2236 return ( 2237 select("*") 2238 .from_(self.subquery(alias="_l_0", copy=copy)) 2239 .limit(expression, dialect=dialect, copy=False, **opts) 2240 ) 2241 2242 def select( 2243 self, 2244 *expressions: ExpOrStr, 2245 append: bool = True, 2246 dialect: DialectType = None, 2247 copy: bool = True, 2248 **opts, 2249 ) -> Union: 2250 """Append to or set the SELECT of the union recursively. 2251 2252 Example: 2253 >>> from sqlglot import parse_one 2254 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2255 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2256 2257 Args: 2258 *expressions: the SQL code strings to parse. 2259 If an `Expression` instance is passed, it will be used as-is. 2260 append: if `True`, add to any existing expressions. 2261 Otherwise, this resets the expressions. 2262 dialect: the dialect used to parse the input expressions. 2263 copy: if `False`, modify this expression instance in-place. 2264 opts: other options to use to parse the input expressions. 2265 2266 Returns: 2267 Union: the modified expression. 2268 """ 2269 this = self.copy() if copy else self 2270 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2271 this.expression.unnest().select( 2272 *expressions, append=append, dialect=dialect, copy=False, **opts 2273 ) 2274 return this 2275 2276 @property 2277 def named_selects(self): 2278 return self.this.unnest().named_selects 2279 2280 @property 2281 def is_star(self) -> bool: 2282 return self.this.is_star or self.expression.is_star 2283 2284 @property 2285 def selects(self): 2286 return self.this.unnest().selects 2287 2288 @property 2289 def left(self): 2290 return self.this 2291 2292 @property 2293 def right(self): 2294 return self.expression 2295 2296 2297class Except(Union): 2298 pass 2299 2300 2301class Intersect(Union): 2302 pass 2303 2304 2305class Unnest(UDTF): 2306 arg_types = { 2307 "expressions": True, 2308 "ordinality": False, 2309 "alias": False, 2310 "offset": False, 2311 } 2312 2313 2314class Update(Expression): 2315 arg_types = { 2316 "with": False, 2317 "this": False, 2318 "expressions": True, 2319 "from": False, 2320 "where": False, 2321 "returning": False, 2322 } 2323 2324 2325class Values(UDTF): 2326 arg_types = { 2327 "expressions": True, 2328 "ordinality": False, 2329 "alias": False, 2330 } 2331 2332 2333class Var(Expression): 2334 pass 2335 2336 2337class Schema(Expression): 2338 arg_types = {"this": False, "expressions": False} 2339 2340 2341# https://dev.mysql.com/doc/refman/8.0/en/select.html 2342# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html 2343class Lock(Expression): 2344 arg_types = {"update": True, "expressions": False, "wait": False} 2345 2346 2347class Select(Subqueryable): 2348 arg_types = { 2349 "with": False, 2350 "kind": False, 2351 "expressions": False, 2352 "hint": False, 2353 "distinct": False, 2354 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2355 "value": False, 2356 "into": False, 2357 "from": False, 2358 **QUERY_MODIFIERS, 2359 } 2360 2361 def from_( 2362 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2363 ) -> Select: 2364 """ 2365 Set the FROM expression. 2366 2367 Example: 2368 >>> Select().from_("tbl").select("x").sql() 2369 'SELECT x FROM tbl' 2370 2371 Args: 2372 expression : the SQL code strings to parse. 2373 If a `From` instance is passed, this is used as-is. 2374 If another `Expression` instance is passed, it will be wrapped in a `From`. 2375 dialect: the dialect used to parse the input expression. 2376 copy: if `False`, modify this expression instance in-place. 2377 opts: other options to use to parse the input expressions. 2378 2379 Returns: 2380 Select: the modified expression. 2381 """ 2382 return _apply_builder( 2383 expression=expression, 2384 instance=self, 2385 arg="from", 2386 into=From, 2387 prefix="FROM", 2388 dialect=dialect, 2389 copy=copy, 2390 **opts, 2391 ) 2392 2393 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2394 """ 2395 Set the GROUP BY expression. 2396 2397 Example: 2398 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2399 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2400 2401 Args: 2402 *expressions (str | Expression): the SQL code strings to parse. 2403 If a `Group` instance is passed, this is used as-is. 2404 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2405 If nothing is passed in then a group by is not applied to the expression 2406 append (bool): if `True`, add to any existing expressions. 2407 Otherwise, this flattens all the `Group` expression into a single expression. 2408 dialect (str): the dialect used to parse the input expression. 2409 copy (bool): if `False`, modify this expression instance in-place. 2410 opts (kwargs): other options to use to parse the input expressions. 2411 2412 Returns: 2413 Select: the modified expression. 2414 """ 2415 if not expressions: 2416 return self if not copy else self.copy() 2417 return _apply_child_list_builder( 2418 *expressions, 2419 instance=self, 2420 arg="group", 2421 append=append, 2422 copy=copy, 2423 prefix="GROUP BY", 2424 into=Group, 2425 dialect=dialect, 2426 **opts, 2427 ) 2428 2429 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2430 """ 2431 Set the ORDER BY expression. 2432 2433 Example: 2434 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2435 'SELECT x FROM tbl ORDER BY x DESC' 2436 2437 Args: 2438 *expressions (str | Expression): the SQL code strings to parse. 2439 If a `Group` instance is passed, this is used as-is. 2440 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2441 append (bool): if `True`, add to any existing expressions. 2442 Otherwise, this flattens all the `Order` expression into a single expression. 2443 dialect (str): the dialect used to parse the input expression. 2444 copy (bool): if `False`, modify this expression instance in-place. 2445 opts (kwargs): other options to use to parse the input expressions. 2446 2447 Returns: 2448 Select: the modified expression. 2449 """ 2450 return _apply_child_list_builder( 2451 *expressions, 2452 instance=self, 2453 arg="order", 2454 append=append, 2455 copy=copy, 2456 prefix="ORDER BY", 2457 into=Order, 2458 dialect=dialect, 2459 **opts, 2460 ) 2461 2462 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2463 """ 2464 Set the SORT BY expression. 2465 2466 Example: 2467 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2468 'SELECT x FROM tbl SORT BY x DESC' 2469 2470 Args: 2471 *expressions (str | Expression): the SQL code strings to parse. 2472 If a `Group` instance is passed, this is used as-is. 2473 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2474 append (bool): if `True`, add to any existing expressions. 2475 Otherwise, this flattens all the `Order` expression into a single expression. 2476 dialect (str): the dialect used to parse the input expression. 2477 copy (bool): if `False`, modify this expression instance in-place. 2478 opts (kwargs): other options to use to parse the input expressions. 2479 2480 Returns: 2481 Select: the modified expression. 2482 """ 2483 return _apply_child_list_builder( 2484 *expressions, 2485 instance=self, 2486 arg="sort", 2487 append=append, 2488 copy=copy, 2489 prefix="SORT BY", 2490 into=Sort, 2491 dialect=dialect, 2492 **opts, 2493 ) 2494 2495 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2496 """ 2497 Set the CLUSTER BY expression. 2498 2499 Example: 2500 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2501 'SELECT x FROM tbl CLUSTER BY x DESC' 2502 2503 Args: 2504 *expressions (str | Expression): the SQL code strings to parse. 2505 If a `Group` instance is passed, this is used as-is. 2506 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2507 append (bool): if `True`, add to any existing expressions. 2508 Otherwise, this flattens all the `Order` expression into a single expression. 2509 dialect (str): the dialect used to parse the input expression. 2510 copy (bool): if `False`, modify this expression instance in-place. 2511 opts (kwargs): other options to use to parse the input expressions. 2512 2513 Returns: 2514 Select: the modified expression. 2515 """ 2516 return _apply_child_list_builder( 2517 *expressions, 2518 instance=self, 2519 arg="cluster", 2520 append=append, 2521 copy=copy, 2522 prefix="CLUSTER BY", 2523 into=Cluster, 2524 dialect=dialect, 2525 **opts, 2526 ) 2527 2528 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2529 """ 2530 Set the LIMIT expression. 2531 2532 Example: 2533 >>> Select().from_("tbl").select("x").limit(10).sql() 2534 'SELECT x FROM tbl LIMIT 10' 2535 2536 Args: 2537 expression (str | int | Expression): the SQL code string to parse. 2538 This can also be an integer. 2539 If a `Limit` instance is passed, this is used as-is. 2540 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2541 dialect (str): the dialect used to parse the input expression. 2542 copy (bool): if `False`, modify this expression instance in-place. 2543 opts (kwargs): other options to use to parse the input expressions. 2544 2545 Returns: 2546 Select: the modified expression. 2547 """ 2548 return _apply_builder( 2549 expression=expression, 2550 instance=self, 2551 arg="limit", 2552 into=Limit, 2553 prefix="LIMIT", 2554 dialect=dialect, 2555 copy=copy, 2556 **opts, 2557 ) 2558 2559 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2560 """ 2561 Set the OFFSET expression. 2562 2563 Example: 2564 >>> Select().from_("tbl").select("x").offset(10).sql() 2565 'SELECT x FROM tbl OFFSET 10' 2566 2567 Args: 2568 expression (str | int | Expression): the SQL code string to parse. 2569 This can also be an integer. 2570 If a `Offset` instance is passed, this is used as-is. 2571 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2572 dialect (str): the dialect used to parse the input expression. 2573 copy (bool): if `False`, modify this expression instance in-place. 2574 opts (kwargs): other options to use to parse the input expressions. 2575 2576 Returns: 2577 Select: the modified expression. 2578 """ 2579 return _apply_builder( 2580 expression=expression, 2581 instance=self, 2582 arg="offset", 2583 into=Offset, 2584 prefix="OFFSET", 2585 dialect=dialect, 2586 copy=copy, 2587 **opts, 2588 ) 2589 2590 def select( 2591 self, 2592 *expressions: ExpOrStr, 2593 append: bool = True, 2594 dialect: DialectType = None, 2595 copy: bool = True, 2596 **opts, 2597 ) -> Select: 2598 """ 2599 Append to or set the SELECT expressions. 2600 2601 Example: 2602 >>> Select().select("x", "y").sql() 2603 'SELECT x, y' 2604 2605 Args: 2606 *expressions: the SQL code strings to parse. 2607 If an `Expression` instance is passed, it will be used as-is. 2608 append: if `True`, add to any existing expressions. 2609 Otherwise, this resets the expressions. 2610 dialect: the dialect used to parse the input expressions. 2611 copy: if `False`, modify this expression instance in-place. 2612 opts: other options to use to parse the input expressions. 2613 2614 Returns: 2615 Select: the modified expression. 2616 """ 2617 return _apply_list_builder( 2618 *expressions, 2619 instance=self, 2620 arg="expressions", 2621 append=append, 2622 dialect=dialect, 2623 copy=copy, 2624 **opts, 2625 ) 2626 2627 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2628 """ 2629 Append to or set the LATERAL expressions. 2630 2631 Example: 2632 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2633 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2634 2635 Args: 2636 *expressions (str | Expression): the SQL code strings to parse. 2637 If an `Expression` instance is passed, it will be used as-is. 2638 append (bool): if `True`, add to any existing expressions. 2639 Otherwise, this resets the expressions. 2640 dialect (str): the dialect used to parse the input expressions. 2641 copy (bool): if `False`, modify this expression instance in-place. 2642 opts (kwargs): other options to use to parse the input expressions. 2643 2644 Returns: 2645 Select: the modified expression. 2646 """ 2647 return _apply_list_builder( 2648 *expressions, 2649 instance=self, 2650 arg="laterals", 2651 append=append, 2652 into=Lateral, 2653 prefix="LATERAL VIEW", 2654 dialect=dialect, 2655 copy=copy, 2656 **opts, 2657 ) 2658 2659 def join( 2660 self, 2661 expression, 2662 on=None, 2663 using=None, 2664 append=True, 2665 join_type=None, 2666 join_alias=None, 2667 dialect=None, 2668 copy=True, 2669 **opts, 2670 ) -> Select: 2671 """ 2672 Append to or set the JOIN expressions. 2673 2674 Example: 2675 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2676 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2677 2678 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2679 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2680 2681 Use `join_type` to change the type of join: 2682 2683 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2684 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2685 2686 Args: 2687 expression (str | Expression): the SQL code string to parse. 2688 If an `Expression` instance is passed, it will be used as-is. 2689 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2690 If an `Expression` instance is passed, it will be used as-is. 2691 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2692 If an `Expression` instance is passed, it will be used as-is. 2693 append (bool): if `True`, add to any existing expressions. 2694 Otherwise, this resets the expressions. 2695 join_type (str): If set, alter the parsed join type 2696 dialect (str): the dialect used to parse the input expressions. 2697 copy (bool): if `False`, modify this expression instance in-place. 2698 opts (kwargs): other options to use to parse the input expressions. 2699 2700 Returns: 2701 Select: the modified expression. 2702 """ 2703 parse_args = {"dialect": dialect, **opts} 2704 2705 try: 2706 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2707 except ParseError: 2708 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2709 2710 join = expression if isinstance(expression, Join) else Join(this=expression) 2711 2712 if isinstance(join.this, Select): 2713 join.this.replace(join.this.subquery()) 2714 2715 if join_type: 2716 natural: t.Optional[Token] 2717 side: t.Optional[Token] 2718 kind: t.Optional[Token] 2719 2720 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2721 2722 if natural: 2723 join.set("natural", True) 2724 if side: 2725 join.set("side", side.text) 2726 if kind: 2727 join.set("kind", kind.text) 2728 2729 if on: 2730 on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts) 2731 join.set("on", on) 2732 2733 if using: 2734 join = _apply_list_builder( 2735 *ensure_collection(using), 2736 instance=join, 2737 arg="using", 2738 append=append, 2739 copy=copy, 2740 **opts, 2741 ) 2742 2743 if join_alias: 2744 join.set("this", alias_(join.this, join_alias, table=True)) 2745 return _apply_list_builder( 2746 join, 2747 instance=self, 2748 arg="joins", 2749 append=append, 2750 copy=copy, 2751 **opts, 2752 ) 2753 2754 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2755 """ 2756 Append to or set the WHERE expressions. 2757 2758 Example: 2759 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2760 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2761 2762 Args: 2763 *expressions (str | Expression): the SQL code strings to parse. 2764 If an `Expression` instance is passed, it will be used as-is. 2765 Multiple expressions are combined with an AND operator. 2766 append (bool): if `True`, AND the new expressions to any existing expression. 2767 Otherwise, this resets the expression. 2768 dialect (str): the dialect used to parse the input expressions. 2769 copy (bool): if `False`, modify this expression instance in-place. 2770 opts (kwargs): other options to use to parse the input expressions. 2771 2772 Returns: 2773 Select: the modified expression. 2774 """ 2775 return _apply_conjunction_builder( 2776 *expressions, 2777 instance=self, 2778 arg="where", 2779 append=append, 2780 into=Where, 2781 dialect=dialect, 2782 copy=copy, 2783 **opts, 2784 ) 2785 2786 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2787 """ 2788 Append to or set the HAVING expressions. 2789 2790 Example: 2791 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2792 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2793 2794 Args: 2795 *expressions (str | Expression): the SQL code strings to parse. 2796 If an `Expression` instance is passed, it will be used as-is. 2797 Multiple expressions are combined with an AND operator. 2798 append (bool): if `True`, AND the new expressions to any existing expression. 2799 Otherwise, this resets the expression. 2800 dialect (str): the dialect used to parse the input expressions. 2801 copy (bool): if `False`, modify this expression instance in-place. 2802 opts (kwargs): other options to use to parse the input expressions. 2803 2804 Returns: 2805 Select: the modified expression. 2806 """ 2807 return _apply_conjunction_builder( 2808 *expressions, 2809 instance=self, 2810 arg="having", 2811 append=append, 2812 into=Having, 2813 dialect=dialect, 2814 copy=copy, 2815 **opts, 2816 ) 2817 2818 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2819 return _apply_list_builder( 2820 *expressions, 2821 instance=self, 2822 arg="windows", 2823 append=append, 2824 into=Window, 2825 dialect=dialect, 2826 copy=copy, 2827 **opts, 2828 ) 2829 2830 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2831 return _apply_conjunction_builder( 2832 *expressions, 2833 instance=self, 2834 arg="qualify", 2835 append=append, 2836 into=Qualify, 2837 dialect=dialect, 2838 copy=copy, 2839 **opts, 2840 ) 2841 2842 def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select: 2843 """ 2844 Set the OFFSET expression. 2845 2846 Example: 2847 >>> Select().from_("tbl").select("x").distinct().sql() 2848 'SELECT DISTINCT x FROM tbl' 2849 2850 Args: 2851 ons: the expressions to distinct on 2852 distinct: whether the Select should be distinct 2853 copy: if `False`, modify this expression instance in-place. 2854 2855 Returns: 2856 Select: the modified expression. 2857 """ 2858 instance = _maybe_copy(self, copy) 2859 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None 2860 instance.set("distinct", Distinct(on=on) if distinct else None) 2861 return instance 2862 2863 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2864 """ 2865 Convert this expression to a CREATE TABLE AS statement. 2866 2867 Example: 2868 >>> Select().select("*").from_("tbl").ctas("x").sql() 2869 'CREATE TABLE x AS SELECT * FROM tbl' 2870 2871 Args: 2872 table (str | Expression): the SQL code string to parse as the table name. 2873 If another `Expression` instance is passed, it will be used as-is. 2874 properties (dict): an optional mapping of table properties 2875 dialect (str): the dialect used to parse the input table. 2876 copy (bool): if `False`, modify this expression instance in-place. 2877 opts (kwargs): other options to use to parse the input table. 2878 2879 Returns: 2880 Create: the CREATE TABLE AS expression 2881 """ 2882 instance = _maybe_copy(self, copy) 2883 table_expression = maybe_parse( 2884 table, 2885 into=Table, 2886 dialect=dialect, 2887 **opts, 2888 ) 2889 properties_expression = None 2890 if properties: 2891 properties_expression = Properties.from_dict(properties) 2892 2893 return Create( 2894 this=table_expression, 2895 kind="table", 2896 expression=instance, 2897 properties=properties_expression, 2898 ) 2899 2900 def lock(self, update: bool = True, copy: bool = True) -> Select: 2901 """ 2902 Set the locking read mode for this expression. 2903 2904 Examples: 2905 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2906 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2907 2908 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2909 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2910 2911 Args: 2912 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2913 copy: if `False`, modify this expression instance in-place. 2914 2915 Returns: 2916 The modified expression. 2917 """ 2918 2919 inst = _maybe_copy(self, copy) 2920 inst.set("locks", [Lock(update=update)]) 2921 2922 return inst 2923 2924 @property 2925 def named_selects(self) -> t.List[str]: 2926 return [e.output_name for e in self.expressions if e.alias_or_name] 2927 2928 @property 2929 def is_star(self) -> bool: 2930 return any(expression.is_star for expression in self.expressions) 2931 2932 @property 2933 def selects(self) -> t.List[Expression]: 2934 return self.expressions 2935 2936 2937class Subquery(DerivedTable, Unionable): 2938 arg_types = { 2939 "this": True, 2940 "alias": False, 2941 "with": False, 2942 **QUERY_MODIFIERS, 2943 } 2944 2945 def unnest(self): 2946 """ 2947 Returns the first non subquery. 2948 """ 2949 expression = self 2950 while isinstance(expression, Subquery): 2951 expression = expression.this 2952 return expression 2953 2954 @property 2955 def is_star(self) -> bool: 2956 return self.this.is_star 2957 2958 @property 2959 def output_name(self): 2960 return self.alias 2961 2962 2963class TableSample(Expression): 2964 arg_types = { 2965 "this": False, 2966 "method": False, 2967 "bucket_numerator": False, 2968 "bucket_denominator": False, 2969 "bucket_field": False, 2970 "percent": False, 2971 "rows": False, 2972 "size": False, 2973 "seed": False, 2974 "kind": False, 2975 } 2976 2977 2978class Tag(Expression): 2979 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2980 2981 arg_types = { 2982 "this": False, 2983 "prefix": False, 2984 "postfix": False, 2985 } 2986 2987 2988class Pivot(Expression): 2989 arg_types = { 2990 "alias": False, 2991 "expressions": True, 2992 "field": True, 2993 "unpivot": True, 2994 "columns": False, 2995 } 2996 2997 2998class Window(Expression): 2999 arg_types = { 3000 "this": True, 3001 "partition_by": False, 3002 "order": False, 3003 "spec": False, 3004 "alias": False, 3005 "over": False, 3006 "first": False, 3007 } 3008 3009 3010class WindowSpec(Expression): 3011 arg_types = { 3012 "kind": False, 3013 "start": False, 3014 "start_side": False, 3015 "end": False, 3016 "end_side": False, 3017 } 3018 3019 3020class Where(Expression): 3021 pass 3022 3023 3024class Star(Expression): 3025 arg_types = {"except": False, "replace": False} 3026 3027 @property 3028 def name(self) -> str: 3029 return "*" 3030 3031 @property 3032 def output_name(self): 3033 return self.name 3034 3035 3036class Parameter(Expression): 3037 arg_types = {"this": True, "wrapped": False} 3038 3039 3040class SessionParameter(Expression): 3041 arg_types = {"this": True, "kind": False} 3042 3043 3044class Placeholder(Expression): 3045 arg_types = {"this": False, "kind": False} 3046 3047 3048class Null(Condition): 3049 arg_types: t.Dict[str, t.Any] = {} 3050 3051 @property 3052 def name(self) -> str: 3053 return "NULL" 3054 3055 3056class Boolean(Condition): 3057 pass 3058 3059 3060class DataTypeSize(Expression): 3061 arg_types = {"this": True, "expression": False} 3062 3063 3064class DataType(Expression): 3065 arg_types = { 3066 "this": True, 3067 "expressions": False, 3068 "nested": False, 3069 "values": False, 3070 "prefix": False, 3071 } 3072 3073 class Type(AutoName): 3074 ARRAY = auto() 3075 BIGDECIMAL = auto() 3076 BIGINT = auto() 3077 BIGSERIAL = auto() 3078 BINARY = auto() 3079 BIT = auto() 3080 BOOLEAN = auto() 3081 CHAR = auto() 3082 DATE = auto() 3083 DATETIME = auto() 3084 DATETIME64 = auto() 3085 DECIMAL = auto() 3086 DOUBLE = auto() 3087 FLOAT = auto() 3088 GEOGRAPHY = auto() 3089 GEOMETRY = auto() 3090 HLLSKETCH = auto() 3091 HSTORE = auto() 3092 IMAGE = auto() 3093 INET = auto() 3094 INT = auto() 3095 INT128 = auto() 3096 INT256 = auto() 3097 INTERVAL = auto() 3098 JSON = auto() 3099 JSONB = auto() 3100 LONGBLOB = auto() 3101 LONGTEXT = auto() 3102 MAP = auto() 3103 MEDIUMBLOB = auto() 3104 MEDIUMTEXT = auto() 3105 MONEY = auto() 3106 NCHAR = auto() 3107 NULL = auto() 3108 NULLABLE = auto() 3109 NVARCHAR = auto() 3110 OBJECT = auto() 3111 ROWVERSION = auto() 3112 SERIAL = auto() 3113 SMALLINT = auto() 3114 SMALLMONEY = auto() 3115 SMALLSERIAL = auto() 3116 STRUCT = auto() 3117 SUPER = auto() 3118 TEXT = auto() 3119 TIME = auto() 3120 TIMESTAMP = auto() 3121 TIMESTAMPTZ = auto() 3122 TIMESTAMPLTZ = auto() 3123 TINYINT = auto() 3124 UBIGINT = auto() 3125 UINT = auto() 3126 USMALLINT = auto() 3127 UTINYINT = auto() 3128 UNKNOWN = auto() # Sentinel value, useful for type annotation 3129 UINT128 = auto() 3130 UINT256 = auto() 3131 UNIQUEIDENTIFIER = auto() 3132 UUID = auto() 3133 VARBINARY = auto() 3134 VARCHAR = auto() 3135 VARIANT = auto() 3136 XML = auto() 3137 3138 TEXT_TYPES = { 3139 Type.CHAR, 3140 Type.NCHAR, 3141 Type.VARCHAR, 3142 Type.NVARCHAR, 3143 Type.TEXT, 3144 } 3145 3146 INTEGER_TYPES = { 3147 Type.INT, 3148 Type.TINYINT, 3149 Type.SMALLINT, 3150 Type.BIGINT, 3151 Type.INT128, 3152 Type.INT256, 3153 } 3154 3155 FLOAT_TYPES = { 3156 Type.FLOAT, 3157 Type.DOUBLE, 3158 } 3159 3160 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3161 3162 TEMPORAL_TYPES = { 3163 Type.TIMESTAMP, 3164 Type.TIMESTAMPTZ, 3165 Type.TIMESTAMPLTZ, 3166 Type.DATE, 3167 Type.DATETIME, 3168 Type.DATETIME64, 3169 } 3170 3171 @classmethod 3172 def build( 3173 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3174 ) -> DataType: 3175 from sqlglot import parse_one 3176 3177 if isinstance(dtype, str): 3178 if dtype.upper() in cls.Type.__members__: 3179 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3180 else: 3181 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3182 3183 if data_type_exp is None: 3184 raise ValueError(f"Unparsable data type value: {dtype}") 3185 elif isinstance(dtype, DataType.Type): 3186 data_type_exp = DataType(this=dtype) 3187 elif isinstance(dtype, DataType): 3188 return dtype 3189 else: 3190 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3191 3192 return DataType(**{**data_type_exp.args, **kwargs}) 3193 3194 def is_type(self, dtype: DataType.Type) -> bool: 3195 return self.this == dtype 3196 3197 3198# https://www.postgresql.org/docs/15/datatype-pseudo.html 3199class PseudoType(Expression): 3200 pass 3201 3202 3203# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 3204class SubqueryPredicate(Predicate): 3205 pass 3206 3207 3208class All(SubqueryPredicate): 3209 pass 3210 3211 3212class Any(SubqueryPredicate): 3213 pass 3214 3215 3216class Exists(SubqueryPredicate): 3217 pass 3218 3219 3220# Commands to interact with the databases or engines. For most of the command 3221# expressions we parse whatever comes after the command's name as a string. 3222class Command(Expression): 3223 arg_types = {"this": True, "expression": False} 3224 3225 3226class Transaction(Expression): 3227 arg_types = {"this": False, "modes": False} 3228 3229 3230class Commit(Expression): 3231 arg_types = {"chain": False} 3232 3233 3234class Rollback(Expression): 3235 arg_types = {"savepoint": False} 3236 3237 3238class AlterTable(Expression): 3239 arg_types = {"this": True, "actions": True, "exists": False} 3240 3241 3242class AddConstraint(Expression): 3243 arg_types = {"this": False, "expression": False, "enforced": False} 3244 3245 3246class DropPartition(Expression): 3247 arg_types = {"expressions": True, "exists": False} 3248 3249 3250# Binary expressions like (ADD a b) 3251class Binary(Condition): 3252 arg_types = {"this": True, "expression": True} 3253 3254 @property 3255 def left(self): 3256 return self.this 3257 3258 @property 3259 def right(self): 3260 return self.expression 3261 3262 3263class Add(Binary): 3264 pass 3265 3266 3267class Connector(Binary): 3268 pass 3269 3270 3271class And(Connector): 3272 pass 3273 3274 3275class Or(Connector): 3276 pass 3277 3278 3279class BitwiseAnd(Binary): 3280 pass 3281 3282 3283class BitwiseLeftShift(Binary): 3284 pass 3285 3286 3287class BitwiseOr(Binary): 3288 pass 3289 3290 3291class BitwiseRightShift(Binary): 3292 pass 3293 3294 3295class BitwiseXor(Binary): 3296 pass 3297 3298 3299class Div(Binary): 3300 pass 3301 3302 3303class Overlaps(Binary): 3304 pass 3305 3306 3307class Dot(Binary): 3308 @property 3309 def name(self) -> str: 3310 return self.expression.name 3311 3312 @classmethod 3313 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3314 """Build a Dot object with a sequence of expressions.""" 3315 if len(expressions) < 2: 3316 raise ValueError(f"Dot requires >= 2 expressions.") 3317 3318 a, b, *expressions = expressions 3319 dot = Dot(this=a, expression=b) 3320 3321 for expression in expressions: 3322 dot = Dot(this=dot, expression=expression) 3323 3324 return dot 3325 3326 3327class DPipe(Binary): 3328 pass 3329 3330 3331class EQ(Binary, Predicate): 3332 pass 3333 3334 3335class NullSafeEQ(Binary, Predicate): 3336 pass 3337 3338 3339class NullSafeNEQ(Binary, Predicate): 3340 pass 3341 3342 3343class Distance(Binary): 3344 pass 3345 3346 3347class Escape(Binary): 3348 pass 3349 3350 3351class Glob(Binary, Predicate): 3352 pass 3353 3354 3355class GT(Binary, Predicate): 3356 pass 3357 3358 3359class GTE(Binary, Predicate): 3360 pass 3361 3362 3363class ILike(Binary, Predicate): 3364 pass 3365 3366 3367class ILikeAny(Binary, Predicate): 3368 pass 3369 3370 3371class IntDiv(Binary): 3372 pass 3373 3374 3375class Is(Binary, Predicate): 3376 pass 3377 3378 3379class Kwarg(Binary): 3380 """Kwarg in special functions like func(kwarg => y).""" 3381 3382 3383class Like(Binary, Predicate): 3384 pass 3385 3386 3387class LikeAny(Binary, Predicate): 3388 pass 3389 3390 3391class LT(Binary, Predicate): 3392 pass 3393 3394 3395class LTE(Binary, Predicate): 3396 pass 3397 3398 3399class Mod(Binary): 3400 pass 3401 3402 3403class Mul(Binary): 3404 pass 3405 3406 3407class NEQ(Binary, Predicate): 3408 pass 3409 3410 3411class SimilarTo(Binary, Predicate): 3412 pass 3413 3414 3415class Slice(Binary): 3416 arg_types = {"this": False, "expression": False} 3417 3418 3419class Sub(Binary): 3420 pass 3421 3422 3423class ArrayOverlaps(Binary): 3424 pass 3425 3426 3427# Unary Expressions 3428# (NOT a) 3429class Unary(Condition): 3430 pass 3431 3432 3433class BitwiseNot(Unary): 3434 pass 3435 3436 3437class Not(Unary): 3438 pass 3439 3440 3441class Paren(Unary): 3442 arg_types = {"this": True, "with": False} 3443 3444 3445class Neg(Unary): 3446 pass 3447 3448 3449class Alias(Expression): 3450 arg_types = {"this": True, "alias": False} 3451 3452 @property 3453 def output_name(self): 3454 return self.alias 3455 3456 3457class Aliases(Expression): 3458 arg_types = {"this": True, "expressions": True} 3459 3460 @property 3461 def aliases(self): 3462 return self.expressions 3463 3464 3465class AtTimeZone(Expression): 3466 arg_types = {"this": True, "zone": True} 3467 3468 3469class Between(Predicate): 3470 arg_types = {"this": True, "low": True, "high": True} 3471 3472 3473class Bracket(Condition): 3474 arg_types = {"this": True, "expressions": True} 3475 3476 3477class Distinct(Expression): 3478 arg_types = {"expressions": False, "on": False} 3479 3480 3481class In(Predicate): 3482 arg_types = { 3483 "this": True, 3484 "expressions": False, 3485 "query": False, 3486 "unnest": False, 3487 "field": False, 3488 "is_global": False, 3489 } 3490 3491 3492class TimeUnit(Expression): 3493 """Automatically converts unit arg into a var.""" 3494 3495 arg_types = {"unit": False} 3496 3497 def __init__(self, **args): 3498 unit = args.get("unit") 3499 if isinstance(unit, (Column, Literal)): 3500 args["unit"] = Var(this=unit.name) 3501 elif isinstance(unit, Week): 3502 unit.set("this", Var(this=unit.this.name)) 3503 super().__init__(**args) 3504 3505 3506class Interval(TimeUnit): 3507 arg_types = {"this": False, "unit": False} 3508 3509 @property 3510 def unit(self) -> t.Optional[Var]: 3511 return self.args.get("unit") 3512 3513 3514class IgnoreNulls(Expression): 3515 pass 3516 3517 3518class RespectNulls(Expression): 3519 pass 3520 3521 3522# Functions 3523class Func(Condition): 3524 """ 3525 The base class for all function expressions. 3526 3527 Attributes: 3528 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3529 treated as a variable length argument and the argument's value will be stored as a list. 3530 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3531 for this function expression. These values are used to map this node to a name during parsing 3532 as well as to provide the function's name during SQL string generation. By default the SQL 3533 name is set to the expression's class name transformed to snake case. 3534 """ 3535 3536 is_var_len_args = False 3537 3538 @classmethod 3539 def from_arg_list(cls, args): 3540 if cls.is_var_len_args: 3541 all_arg_keys = list(cls.arg_types) 3542 # If this function supports variable length argument treat the last argument as such. 3543 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3544 num_non_var = len(non_var_len_arg_keys) 3545 3546 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3547 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3548 else: 3549 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3550 3551 return cls(**args_dict) 3552 3553 @classmethod 3554 def sql_names(cls): 3555 if cls is Func: 3556 raise NotImplementedError( 3557 "SQL name is only supported by concrete function implementations" 3558 ) 3559 if "_sql_names" not in cls.__dict__: 3560 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3561 return cls._sql_names 3562 3563 @classmethod 3564 def sql_name(cls): 3565 return cls.sql_names()[0] 3566 3567 @classmethod 3568 def default_parser_mappings(cls): 3569 return {name: cls.from_arg_list for name in cls.sql_names()} 3570 3571 3572class AggFunc(Func): 3573 pass 3574 3575 3576class ParameterizedAgg(AggFunc): 3577 arg_types = {"this": True, "expressions": True, "params": True} 3578 3579 3580class Abs(Func): 3581 pass 3582 3583 3584class Anonymous(Func): 3585 arg_types = {"this": True, "expressions": False} 3586 is_var_len_args = True 3587 3588 3589# https://docs.snowflake.com/en/sql-reference/functions/hll 3590# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3591class Hll(AggFunc): 3592 arg_types = {"this": True, "expressions": False} 3593 is_var_len_args = True 3594 3595 3596class ApproxDistinct(AggFunc): 3597 arg_types = {"this": True, "accuracy": False} 3598 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"] 3599 3600 3601class Array(Func): 3602 arg_types = {"expressions": False} 3603 is_var_len_args = True 3604 3605 3606# https://docs.snowflake.com/en/sql-reference/functions/to_char 3607class ToChar(Func): 3608 arg_types = {"this": True, "format": False} 3609 3610 3611class GenerateSeries(Func): 3612 arg_types = {"start": True, "end": True, "step": False} 3613 3614 3615class ArrayAgg(AggFunc): 3616 pass 3617 3618 3619class ArrayAll(Func): 3620 arg_types = {"this": True, "expression": True} 3621 3622 3623class ArrayAny(Func): 3624 arg_types = {"this": True, "expression": True} 3625 3626 3627class ArrayConcat(Func): 3628 arg_types = {"this": True, "expressions": False} 3629 is_var_len_args = True 3630 3631 3632class ArrayContains(Binary, Func): 3633 pass 3634 3635 3636class ArrayContained(Binary): 3637 pass 3638 3639 3640class ArrayFilter(Func): 3641 arg_types = {"this": True, "expression": True} 3642 _sql_names = ["FILTER", "ARRAY_FILTER"] 3643 3644 3645class ArrayJoin(Func): 3646 arg_types = {"this": True, "expression": True, "null": False} 3647 3648 3649class ArraySize(Func): 3650 arg_types = {"this": True, "expression": False} 3651 3652 3653class ArraySort(Func): 3654 arg_types = {"this": True, "expression": False} 3655 3656 3657class ArraySum(Func): 3658 pass 3659 3660 3661class ArrayUnionAgg(AggFunc): 3662 pass 3663 3664 3665class Avg(AggFunc): 3666 pass 3667 3668 3669class AnyValue(AggFunc): 3670 pass 3671 3672 3673class Case(Func): 3674 arg_types = {"this": False, "ifs": True, "default": False} 3675 3676 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3677 instance = _maybe_copy(self, copy) 3678 instance.append( 3679 "ifs", 3680 If( 3681 this=maybe_parse(condition, copy=copy, **opts), 3682 true=maybe_parse(then, copy=copy, **opts), 3683 ), 3684 ) 3685 return instance 3686 3687 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3688 instance = _maybe_copy(self, copy) 3689 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3690 return instance 3691 3692 3693class Cast(Func): 3694 arg_types = {"this": True, "to": True} 3695 3696 @property 3697 def name(self) -> str: 3698 return self.this.name 3699 3700 @property 3701 def to(self): 3702 return self.args["to"] 3703 3704 @property 3705 def output_name(self): 3706 return self.name 3707 3708 def is_type(self, dtype: DataType.Type) -> bool: 3709 return self.to.is_type(dtype) 3710 3711 3712class CastToStrType(Func): 3713 arg_types = {"this": True, "expression": True} 3714 3715 3716class Collate(Binary): 3717 pass 3718 3719 3720class TryCast(Cast): 3721 pass 3722 3723 3724class Ceil(Func): 3725 arg_types = {"this": True, "decimals": False} 3726 _sql_names = ["CEIL", "CEILING"] 3727 3728 3729class Coalesce(Func): 3730 arg_types = {"this": True, "expressions": False} 3731 is_var_len_args = True 3732 3733 3734class Concat(Func): 3735 arg_types = {"expressions": True} 3736 is_var_len_args = True 3737 3738 3739class ConcatWs(Concat): 3740 _sql_names = ["CONCAT_WS"] 3741 3742 3743class Count(AggFunc): 3744 arg_types = {"this": False} 3745 3746 3747class CountIf(AggFunc): 3748 pass 3749 3750 3751class CurrentDate(Func): 3752 arg_types = {"this": False} 3753 3754 3755class CurrentDatetime(Func): 3756 arg_types = {"this": False} 3757 3758 3759class CurrentTime(Func): 3760 arg_types = {"this": False} 3761 3762 3763class CurrentTimestamp(Func): 3764 arg_types = {"this": False} 3765 3766 3767class CurrentUser(Func): 3768 arg_types = {"this": False} 3769 3770 3771class DateAdd(Func, TimeUnit): 3772 arg_types = {"this": True, "expression": True, "unit": False} 3773 3774 3775class DateSub(Func, TimeUnit): 3776 arg_types = {"this": True, "expression": True, "unit": False} 3777 3778 3779class DateDiff(Func, TimeUnit): 3780 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3781 arg_types = {"this": True, "expression": True, "unit": False} 3782 3783 3784class DateTrunc(Func): 3785 arg_types = {"unit": True, "this": True, "zone": False} 3786 3787 3788class DatetimeAdd(Func, TimeUnit): 3789 arg_types = {"this": True, "expression": True, "unit": False} 3790 3791 3792class DatetimeSub(Func, TimeUnit): 3793 arg_types = {"this": True, "expression": True, "unit": False} 3794 3795 3796class DatetimeDiff(Func, TimeUnit): 3797 arg_types = {"this": True, "expression": True, "unit": False} 3798 3799 3800class DatetimeTrunc(Func, TimeUnit): 3801 arg_types = {"this": True, "unit": True, "zone": False} 3802 3803 3804class DayOfWeek(Func): 3805 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3806 3807 3808class DayOfMonth(Func): 3809 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3810 3811 3812class DayOfYear(Func): 3813 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3814 3815 3816class WeekOfYear(Func): 3817 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3818 3819 3820class LastDateOfMonth(Func): 3821 pass 3822 3823 3824class Extract(Func): 3825 arg_types = {"this": True, "expression": True} 3826 3827 3828class TimestampAdd(Func, TimeUnit): 3829 arg_types = {"this": True, "expression": True, "unit": False} 3830 3831 3832class TimestampSub(Func, TimeUnit): 3833 arg_types = {"this": True, "expression": True, "unit": False} 3834 3835 3836class TimestampDiff(Func, TimeUnit): 3837 arg_types = {"this": True, "expression": True, "unit": False} 3838 3839 3840class TimestampTrunc(Func, TimeUnit): 3841 arg_types = {"this": True, "unit": True, "zone": False} 3842 3843 3844class TimeAdd(Func, TimeUnit): 3845 arg_types = {"this": True, "expression": True, "unit": False} 3846 3847 3848class TimeSub(Func, TimeUnit): 3849 arg_types = {"this": True, "expression": True, "unit": False} 3850 3851 3852class TimeDiff(Func, TimeUnit): 3853 arg_types = {"this": True, "expression": True, "unit": False} 3854 3855 3856class TimeTrunc(Func, TimeUnit): 3857 arg_types = {"this": True, "unit": True, "zone": False} 3858 3859 3860class DateFromParts(Func): 3861 _sql_names = ["DATEFROMPARTS"] 3862 arg_types = {"year": True, "month": True, "day": True} 3863 3864 3865class DateStrToDate(Func): 3866 pass 3867 3868 3869class DateToDateStr(Func): 3870 pass 3871 3872 3873class DateToDi(Func): 3874 pass 3875 3876 3877class Day(Func): 3878 pass 3879 3880 3881class Decode(Func): 3882 arg_types = {"this": True, "charset": True, "replace": False} 3883 3884 3885class DiToDate(Func): 3886 pass 3887 3888 3889class Encode(Func): 3890 arg_types = {"this": True, "charset": True} 3891 3892 3893class Exp(Func): 3894 pass 3895 3896 3897class Explode(Func): 3898 pass 3899 3900 3901class Floor(Func): 3902 arg_types = {"this": True, "decimals": False} 3903 3904 3905class FromBase64(Func): 3906 pass 3907 3908 3909class ToBase64(Func): 3910 pass 3911 3912 3913class Greatest(Func): 3914 arg_types = {"this": True, "expressions": False} 3915 is_var_len_args = True 3916 3917 3918class GroupConcat(Func): 3919 arg_types = {"this": True, "separator": False} 3920 3921 3922class Hex(Func): 3923 pass 3924 3925 3926class If(Func): 3927 arg_types = {"this": True, "true": True, "false": False} 3928 3929 3930class IfNull(Func): 3931 arg_types = {"this": True, "expression": False} 3932 _sql_names = ["IFNULL", "NVL"] 3933 3934 3935class Initcap(Func): 3936 arg_types = {"this": True, "expression": False} 3937 3938 3939class JSONKeyValue(Expression): 3940 arg_types = {"this": True, "expression": True} 3941 3942 3943class JSONObject(Func): 3944 arg_types = { 3945 "expressions": False, 3946 "null_handling": False, 3947 "unique_keys": False, 3948 "return_type": False, 3949 "format_json": False, 3950 "encoding": False, 3951 } 3952 3953 3954class OpenJSONColumnDef(Expression): 3955 arg_types = {"this": True, "kind": True, "path": False, "as_json": False} 3956 3957 3958class OpenJSON(Func): 3959 arg_types = {"this": True, "path": False, "expressions": False} 3960 3961 3962class JSONBContains(Binary): 3963 _sql_names = ["JSONB_CONTAINS"] 3964 3965 3966class JSONExtract(Binary, Func): 3967 _sql_names = ["JSON_EXTRACT"] 3968 3969 3970class JSONExtractScalar(JSONExtract): 3971 _sql_names = ["JSON_EXTRACT_SCALAR"] 3972 3973 3974class JSONBExtract(JSONExtract): 3975 _sql_names = ["JSONB_EXTRACT"] 3976 3977 3978class JSONBExtractScalar(JSONExtract): 3979 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3980 3981 3982class JSONFormat(Func): 3983 arg_types = {"this": False, "options": False} 3984 _sql_names = ["JSON_FORMAT"] 3985 3986 3987class Least(Func): 3988 arg_types = {"expressions": False} 3989 is_var_len_args = True 3990 3991 3992class Length(Func): 3993 pass 3994 3995 3996class Levenshtein(Func): 3997 arg_types = { 3998 "this": True, 3999 "expression": False, 4000 "ins_cost": False, 4001 "del_cost": False, 4002 "sub_cost": False, 4003 } 4004 4005 4006class Ln(Func): 4007 pass 4008 4009 4010class Log(Func): 4011 arg_types = {"this": True, "expression": False} 4012 4013 4014class Log2(Func): 4015 pass 4016 4017 4018class Log10(Func): 4019 pass 4020 4021 4022class LogicalOr(AggFunc): 4023 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 4024 4025 4026class LogicalAnd(AggFunc): 4027 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 4028 4029 4030class Lower(Func): 4031 _sql_names = ["LOWER", "LCASE"] 4032 4033 4034class Map(Func): 4035 arg_types = {"keys": False, "values": False} 4036 4037 4038class StarMap(Func): 4039 pass 4040 4041 4042class VarMap(Func): 4043 arg_types = {"keys": True, "values": True} 4044 is_var_len_args = True 4045 4046 4047# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 4048class MatchAgainst(Func): 4049 arg_types = {"this": True, "expressions": True, "modifier": False} 4050 4051 4052class Max(AggFunc): 4053 arg_types = {"this": True, "expressions": False} 4054 is_var_len_args = True 4055 4056 4057class MD5(Func): 4058 _sql_names = ["MD5"] 4059 4060 4061class Min(AggFunc): 4062 arg_types = {"this": True, "expressions": False} 4063 is_var_len_args = True 4064 4065 4066class Month(Func): 4067 pass 4068 4069 4070class Nvl2(Func): 4071 arg_types = {"this": True, "true": True, "false": False} 4072 4073 4074class Posexplode(Func): 4075 pass 4076 4077 4078class Pow(Binary, Func): 4079 _sql_names = ["POWER", "POW"] 4080 4081 4082class PercentileCont(AggFunc): 4083 arg_types = {"this": True, "expression": False} 4084 4085 4086class PercentileDisc(AggFunc): 4087 arg_types = {"this": True, "expression": False} 4088 4089 4090class Quantile(AggFunc): 4091 arg_types = {"this": True, "quantile": True} 4092 4093 4094class ApproxQuantile(Quantile): 4095 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 4096 4097 4098class RangeN(Func): 4099 arg_types = {"this": True, "expressions": True, "each": False} 4100 4101 4102class ReadCSV(Func): 4103 _sql_names = ["READ_CSV"] 4104 is_var_len_args = True 4105 arg_types = {"this": True, "expressions": False} 4106 4107 4108class Reduce(Func): 4109 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 4110 4111 4112class RegexpExtract(Func): 4113 arg_types = { 4114 "this": True, 4115 "expression": True, 4116 "position": False, 4117 "occurrence": False, 4118 "group": False, 4119 } 4120 4121 4122class RegexpLike(Func): 4123 arg_types = {"this": True, "expression": True, "flag": False} 4124 4125 4126class RegexpILike(Func): 4127 arg_types = {"this": True, "expression": True, "flag": False} 4128 4129 4130# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 4131# limit is the number of times a pattern is applied 4132class RegexpSplit(Func): 4133 arg_types = {"this": True, "expression": True, "limit": False} 4134 4135 4136class Repeat(Func): 4137 arg_types = {"this": True, "times": True} 4138 4139 4140class Round(Func): 4141 arg_types = {"this": True, "decimals": False} 4142 4143 4144class RowNumber(Func): 4145 arg_types: t.Dict[str, t.Any] = {} 4146 4147 4148class SafeDivide(Func): 4149 arg_types = {"this": True, "expression": True} 4150 4151 4152class SetAgg(AggFunc): 4153 pass 4154 4155 4156class SHA(Func): 4157 _sql_names = ["SHA", "SHA1"] 4158 4159 4160class SHA2(Func): 4161 _sql_names = ["SHA2"] 4162 arg_types = {"this": True, "length": False} 4163 4164 4165class SortArray(Func): 4166 arg_types = {"this": True, "asc": False} 4167 4168 4169class Split(Func): 4170 arg_types = {"this": True, "expression": True, "limit": False} 4171 4172 4173# Start may be omitted in the case of postgres 4174# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 4175class Substring(Func): 4176 arg_types = {"this": True, "start": False, "length": False} 4177 4178 4179class StandardHash(Func): 4180 arg_types = {"this": True, "expression": False} 4181 4182 4183class StrPosition(Func): 4184 arg_types = { 4185 "this": True, 4186 "substr": True, 4187 "position": False, 4188 "instance": False, 4189 } 4190 4191 4192class StrToDate(Func): 4193 arg_types = {"this": True, "format": True} 4194 4195 4196class StrToTime(Func): 4197 arg_types = {"this": True, "format": True} 4198 4199 4200# Spark allows unix_timestamp() 4201# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 4202class StrToUnix(Func): 4203 arg_types = {"this": False, "format": False} 4204 4205 4206class NumberToStr(Func): 4207 arg_types = {"this": True, "format": True} 4208 4209 4210class Struct(Func): 4211 arg_types = {"expressions": True} 4212 is_var_len_args = True 4213 4214 4215class StructExtract(Func): 4216 arg_types = {"this": True, "expression": True} 4217 4218 4219class Sum(AggFunc): 4220 pass 4221 4222 4223class Sqrt(Func): 4224 pass 4225 4226 4227class Stddev(AggFunc): 4228 pass 4229 4230 4231class StddevPop(AggFunc): 4232 pass 4233 4234 4235class StddevSamp(AggFunc): 4236 pass 4237 4238 4239class TimeToStr(Func): 4240 arg_types = {"this": True, "format": True} 4241 4242 4243class TimeToTimeStr(Func): 4244 pass 4245 4246 4247class TimeToUnix(Func): 4248 pass 4249 4250 4251class TimeStrToDate(Func): 4252 pass 4253 4254 4255class TimeStrToTime(Func): 4256 pass 4257 4258 4259class TimeStrToUnix(Func): 4260 pass 4261 4262 4263class Trim(Func): 4264 arg_types = { 4265 "this": True, 4266 "expression": False, 4267 "position": False, 4268 "collation": False, 4269 } 4270 4271 4272class TsOrDsAdd(Func, TimeUnit): 4273 arg_types = {"this": True, "expression": True, "unit": False} 4274 4275 4276class TsOrDsToDateStr(Func): 4277 pass 4278 4279 4280class TsOrDsToDate(Func): 4281 arg_types = {"this": True, "format": False} 4282 4283 4284class TsOrDiToDi(Func): 4285 pass 4286 4287 4288class Unhex(Func): 4289 pass 4290 4291 4292class UnixToStr(Func): 4293 arg_types = {"this": True, "format": False} 4294 4295 4296# https://prestodb.io/docs/current/functions/datetime.html 4297# presto has weird zone/hours/minutes 4298class UnixToTime(Func): 4299 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4300 4301 SECONDS = Literal.string("seconds") 4302 MILLIS = Literal.string("millis") 4303 MICROS = Literal.string("micros") 4304 4305 4306class UnixToTimeStr(Func): 4307 pass 4308 4309 4310class Upper(Func): 4311 _sql_names = ["UPPER", "UCASE"] 4312 4313 4314class Variance(AggFunc): 4315 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4316 4317 4318class VariancePop(AggFunc): 4319 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4320 4321 4322class Week(Func): 4323 arg_types = {"this": True, "mode": False} 4324 4325 4326class XMLTable(Func): 4327 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4328 4329 4330class Year(Func): 4331 pass 4332 4333 4334class Use(Expression): 4335 arg_types = {"this": True, "kind": False} 4336 4337 4338class Merge(Expression): 4339 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4340 4341 4342class When(Func): 4343 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4344 4345 4346# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html 4347# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16 4348class NextValueFor(Func): 4349 arg_types = {"this": True, "order": False} 4350 4351 4352def _norm_arg(arg): 4353 return arg.lower() if type(arg) is str else arg 4354 4355 4356ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4357 4358 4359# Helpers 4360@t.overload 4361def maybe_parse( 4362 sql_or_expression: ExpOrStr, 4363 *, 4364 into: t.Type[E], 4365 dialect: DialectType = None, 4366 prefix: t.Optional[str] = None, 4367 copy: bool = False, 4368 **opts, 4369) -> E: 4370 ... 4371 4372 4373@t.overload 4374def maybe_parse( 4375 sql_or_expression: str | E, 4376 *, 4377 into: t.Optional[IntoType] = None, 4378 dialect: DialectType = None, 4379 prefix: t.Optional[str] = None, 4380 copy: bool = False, 4381 **opts, 4382) -> E: 4383 ... 4384 4385 4386def maybe_parse( 4387 sql_or_expression: ExpOrStr, 4388 *, 4389 into: t.Optional[IntoType] = None, 4390 dialect: DialectType = None, 4391 prefix: t.Optional[str] = None, 4392 copy: bool = False, 4393 **opts, 4394) -> Expression: 4395 """Gracefully handle a possible string or expression. 4396 4397 Example: 4398 >>> maybe_parse("1") 4399 (LITERAL this: 1, is_string: False) 4400 >>> maybe_parse(to_identifier("x")) 4401 (IDENTIFIER this: x, quoted: False) 4402 4403 Args: 4404 sql_or_expression: the SQL code string or an expression 4405 into: the SQLGlot Expression to parse into 4406 dialect: the dialect used to parse the input expressions (in the case that an 4407 input expression is a SQL string). 4408 prefix: a string to prefix the sql with before it gets parsed 4409 (automatically includes a space) 4410 copy: whether or not to copy the expression. 4411 **opts: other options to use to parse the input expressions (again, in the case 4412 that an input expression is a SQL string). 4413 4414 Returns: 4415 Expression: the parsed or given expression. 4416 """ 4417 if isinstance(sql_or_expression, Expression): 4418 if copy: 4419 return sql_or_expression.copy() 4420 return sql_or_expression 4421 4422 import sqlglot 4423 4424 sql = str(sql_or_expression) 4425 if prefix: 4426 sql = f"{prefix} {sql}" 4427 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4428 4429 4430def _maybe_copy(instance, copy=True): 4431 return instance.copy() if copy else instance 4432 4433 4434def _is_wrong_expression(expression, into): 4435 return isinstance(expression, Expression) and not isinstance(expression, into) 4436 4437 4438def _apply_builder( 4439 expression, 4440 instance, 4441 arg, 4442 copy=True, 4443 prefix=None, 4444 into=None, 4445 dialect=None, 4446 **opts, 4447): 4448 if _is_wrong_expression(expression, into): 4449 expression = into(this=expression) 4450 instance = _maybe_copy(instance, copy) 4451 expression = maybe_parse( 4452 sql_or_expression=expression, 4453 prefix=prefix, 4454 into=into, 4455 dialect=dialect, 4456 **opts, 4457 ) 4458 instance.set(arg, expression) 4459 return instance 4460 4461 4462def _apply_child_list_builder( 4463 *expressions, 4464 instance, 4465 arg, 4466 append=True, 4467 copy=True, 4468 prefix=None, 4469 into=None, 4470 dialect=None, 4471 properties=None, 4472 **opts, 4473): 4474 instance = _maybe_copy(instance, copy) 4475 parsed = [] 4476 for expression in expressions: 4477 if _is_wrong_expression(expression, into): 4478 expression = into(expressions=[expression]) 4479 expression = maybe_parse( 4480 expression, 4481 into=into, 4482 dialect=dialect, 4483 prefix=prefix, 4484 **opts, 4485 ) 4486 parsed.extend(expression.expressions) 4487 4488 existing = instance.args.get(arg) 4489 if append and existing: 4490 parsed = existing.expressions + parsed 4491 4492 child = into(expressions=parsed) 4493 for k, v in (properties or {}).items(): 4494 child.set(k, v) 4495 instance.set(arg, child) 4496 return instance 4497 4498 4499def _apply_list_builder( 4500 *expressions, 4501 instance, 4502 arg, 4503 append=True, 4504 copy=True, 4505 prefix=None, 4506 into=None, 4507 dialect=None, 4508 **opts, 4509): 4510 inst = _maybe_copy(instance, copy) 4511 4512 expressions = [ 4513 maybe_parse( 4514 sql_or_expression=expression, 4515 into=into, 4516 prefix=prefix, 4517 dialect=dialect, 4518 **opts, 4519 ) 4520 for expression in expressions 4521 ] 4522 4523 existing_expressions = inst.args.get(arg) 4524 if append and existing_expressions: 4525 expressions = existing_expressions + expressions 4526 4527 inst.set(arg, expressions) 4528 return inst 4529 4530 4531def _apply_conjunction_builder( 4532 *expressions, 4533 instance, 4534 arg, 4535 into=None, 4536 append=True, 4537 copy=True, 4538 dialect=None, 4539 **opts, 4540): 4541 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4542 if not expressions: 4543 return instance 4544 4545 inst = _maybe_copy(instance, copy) 4546 4547 existing = inst.args.get(arg) 4548 if append and existing is not None: 4549 expressions = [existing.this if into else existing] + list(expressions) 4550 4551 node = and_(*expressions, dialect=dialect, copy=copy, **opts) 4552 4553 inst.set(arg, into(this=node) if into else node) 4554 return inst 4555 4556 4557def _apply_cte_builder( 4558 instance: E, 4559 alias: ExpOrStr, 4560 as_: ExpOrStr, 4561 recursive: t.Optional[bool] = None, 4562 append: bool = True, 4563 dialect: DialectType = None, 4564 copy: bool = True, 4565 **opts, 4566) -> E: 4567 alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts) 4568 as_expression = maybe_parse(as_, dialect=dialect, **opts) 4569 cte = CTE(this=as_expression, alias=alias_expression) 4570 return _apply_child_list_builder( 4571 cte, 4572 instance=instance, 4573 arg="with", 4574 append=append, 4575 copy=copy, 4576 into=With, 4577 properties={"recursive": recursive or False}, 4578 ) 4579 4580 4581def _combine(expressions, operator, dialect=None, copy=True, **opts): 4582 expressions = [ 4583 condition(expression, dialect=dialect, copy=copy, **opts) for expression in expressions 4584 ] 4585 this = expressions[0] 4586 if expressions[1:]: 4587 this = _wrap(this, Connector) 4588 for expression in expressions[1:]: 4589 this = operator(this=this, expression=_wrap(expression, Connector)) 4590 return this 4591 4592 4593def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: 4594 if isinstance(expression, kind): 4595 return Paren(this=expression) 4596 return expression 4597 4598 4599def union(left, right, distinct=True, dialect=None, **opts): 4600 """ 4601 Initializes a syntax tree from one UNION expression. 4602 4603 Example: 4604 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4605 'SELECT * FROM foo UNION SELECT * FROM bla' 4606 4607 Args: 4608 left (str | Expression): the SQL code string corresponding to the left-hand side. 4609 If an `Expression` instance is passed, it will be used as-is. 4610 right (str | Expression): the SQL code string corresponding to the right-hand side. 4611 If an `Expression` instance is passed, it will be used as-is. 4612 distinct (bool): set the DISTINCT flag if and only if this is true. 4613 dialect (str): the dialect used to parse the input expression. 4614 opts (kwargs): other options to use to parse the input expressions. 4615 Returns: 4616 Union: the syntax tree for the UNION expression. 4617 """ 4618 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4619 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4620 4621 return Union(this=left, expression=right, distinct=distinct) 4622 4623 4624def intersect(left, right, distinct=True, dialect=None, **opts): 4625 """ 4626 Initializes a syntax tree from one INTERSECT expression. 4627 4628 Example: 4629 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4630 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4631 4632 Args: 4633 left (str | Expression): the SQL code string corresponding to the left-hand side. 4634 If an `Expression` instance is passed, it will be used as-is. 4635 right (str | Expression): the SQL code string corresponding to the right-hand side. 4636 If an `Expression` instance is passed, it will be used as-is. 4637 distinct (bool): set the DISTINCT flag if and only if this is true. 4638 dialect (str): the dialect used to parse the input expression. 4639 opts (kwargs): other options to use to parse the input expressions. 4640 Returns: 4641 Intersect: the syntax tree for the INTERSECT expression. 4642 """ 4643 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4644 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4645 4646 return Intersect(this=left, expression=right, distinct=distinct) 4647 4648 4649def except_(left, right, distinct=True, dialect=None, **opts): 4650 """ 4651 Initializes a syntax tree from one EXCEPT expression. 4652 4653 Example: 4654 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4655 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4656 4657 Args: 4658 left (str | Expression): the SQL code string corresponding to the left-hand side. 4659 If an `Expression` instance is passed, it will be used as-is. 4660 right (str | Expression): the SQL code string corresponding to the right-hand side. 4661 If an `Expression` instance is passed, it will be used as-is. 4662 distinct (bool): set the DISTINCT flag if and only if this is true. 4663 dialect (str): the dialect used to parse the input expression. 4664 opts (kwargs): other options to use to parse the input expressions. 4665 Returns: 4666 Except: the syntax tree for the EXCEPT statement. 4667 """ 4668 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4669 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4670 4671 return Except(this=left, expression=right, distinct=distinct) 4672 4673 4674def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4675 """ 4676 Initializes a syntax tree from one or multiple SELECT expressions. 4677 4678 Example: 4679 >>> select("col1", "col2").from_("tbl").sql() 4680 'SELECT col1, col2 FROM tbl' 4681 4682 Args: 4683 *expressions: the SQL code string to parse as the expressions of a 4684 SELECT statement. If an Expression instance is passed, this is used as-is. 4685 dialect: the dialect used to parse the input expressions (in the case that an 4686 input expression is a SQL string). 4687 **opts: other options to use to parse the input expressions (again, in the case 4688 that an input expression is a SQL string). 4689 4690 Returns: 4691 Select: the syntax tree for the SELECT statement. 4692 """ 4693 return Select().select(*expressions, dialect=dialect, **opts) 4694 4695 4696def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4697 """ 4698 Initializes a syntax tree from a FROM expression. 4699 4700 Example: 4701 >>> from_("tbl").select("col1", "col2").sql() 4702 'SELECT col1, col2 FROM tbl' 4703 4704 Args: 4705 *expression: the SQL code string to parse as the FROM expressions of a 4706 SELECT statement. If an Expression instance is passed, this is used as-is. 4707 dialect: the dialect used to parse the input expression (in the case that the 4708 input expression is a SQL string). 4709 **opts: other options to use to parse the input expressions (again, in the case 4710 that the input expression is a SQL string). 4711 4712 Returns: 4713 Select: the syntax tree for the SELECT statement. 4714 """ 4715 return Select().from_(expression, dialect=dialect, **opts) 4716 4717 4718def update( 4719 table: str | Table, 4720 properties: dict, 4721 where: t.Optional[ExpOrStr] = None, 4722 from_: t.Optional[ExpOrStr] = None, 4723 dialect: DialectType = None, 4724 **opts, 4725) -> Update: 4726 """ 4727 Creates an update statement. 4728 4729 Example: 4730 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4731 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4732 4733 Args: 4734 *properties: dictionary of properties to set which are 4735 auto converted to sql objects eg None -> NULL 4736 where: sql conditional parsed into a WHERE statement 4737 from_: sql statement parsed into a FROM statement 4738 dialect: the dialect used to parse the input expressions. 4739 **opts: other options to use to parse the input expressions. 4740 4741 Returns: 4742 Update: the syntax tree for the UPDATE statement. 4743 """ 4744 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4745 update_expr.set( 4746 "expressions", 4747 [ 4748 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4749 for k, v in properties.items() 4750 ], 4751 ) 4752 if from_: 4753 update_expr.set( 4754 "from", 4755 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4756 ) 4757 if isinstance(where, Condition): 4758 where = Where(this=where) 4759 if where: 4760 update_expr.set( 4761 "where", 4762 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4763 ) 4764 return update_expr 4765 4766 4767def delete( 4768 table: ExpOrStr, 4769 where: t.Optional[ExpOrStr] = None, 4770 returning: t.Optional[ExpOrStr] = None, 4771 dialect: DialectType = None, 4772 **opts, 4773) -> Delete: 4774 """ 4775 Builds a delete statement. 4776 4777 Example: 4778 >>> delete("my_table", where="id > 1").sql() 4779 'DELETE FROM my_table WHERE id > 1' 4780 4781 Args: 4782 where: sql conditional parsed into a WHERE statement 4783 returning: sql conditional parsed into a RETURNING statement 4784 dialect: the dialect used to parse the input expressions. 4785 **opts: other options to use to parse the input expressions. 4786 4787 Returns: 4788 Delete: the syntax tree for the DELETE statement. 4789 """ 4790 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4791 if where: 4792 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4793 if returning: 4794 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4795 return delete_expr 4796 4797 4798def insert( 4799 expression: ExpOrStr, 4800 into: ExpOrStr, 4801 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 4802 overwrite: t.Optional[bool] = None, 4803 dialect: DialectType = None, 4804 copy: bool = True, 4805 **opts, 4806) -> Insert: 4807 """ 4808 Builds an INSERT statement. 4809 4810 Example: 4811 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 4812 'INSERT INTO tbl VALUES (1, 2, 3)' 4813 4814 Args: 4815 expression: the sql string or expression of the INSERT statement 4816 into: the tbl to insert data to. 4817 columns: optionally the table's column names. 4818 overwrite: whether to INSERT OVERWRITE or not. 4819 dialect: the dialect used to parse the input expressions. 4820 copy: whether or not to copy the expression. 4821 **opts: other options to use to parse the input expressions. 4822 4823 Returns: 4824 Insert: the syntax tree for the INSERT statement. 4825 """ 4826 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 4827 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 4828 4829 if columns: 4830 this = _apply_list_builder( 4831 *columns, 4832 instance=Schema(this=this), 4833 arg="expressions", 4834 into=Identifier, 4835 copy=False, 4836 dialect=dialect, 4837 **opts, 4838 ) 4839 4840 return Insert(this=this, expression=expr, overwrite=overwrite) 4841 4842 4843def condition(expression, dialect=None, copy=True, **opts) -> Condition: 4844 """ 4845 Initialize a logical condition expression. 4846 4847 Example: 4848 >>> condition("x=1").sql() 4849 'x = 1' 4850 4851 This is helpful for composing larger logical syntax trees: 4852 >>> where = condition("x=1") 4853 >>> where = where.and_("y=1") 4854 >>> Select().from_("tbl").select("*").where(where).sql() 4855 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4856 4857 Args: 4858 *expression (str | Expression): the SQL code string to parse. 4859 If an Expression instance is passed, this is used as-is. 4860 dialect (str): the dialect used to parse the input expression (in the case that the 4861 input expression is a SQL string). 4862 copy (bool): Whether or not to copy `expression` (only applies to expressions). 4863 **opts: other options to use to parse the input expressions (again, in the case 4864 that the input expression is a SQL string). 4865 4866 Returns: 4867 Condition: the expression 4868 """ 4869 return maybe_parse( # type: ignore 4870 expression, 4871 into=Condition, 4872 dialect=dialect, 4873 copy=copy, 4874 **opts, 4875 ) 4876 4877 4878def and_(*expressions, dialect=None, copy=True, **opts) -> And: 4879 """ 4880 Combine multiple conditions with an AND logical operator. 4881 4882 Example: 4883 >>> and_("x=1", and_("y=1", "z=1")).sql() 4884 'x = 1 AND (y = 1 AND z = 1)' 4885 4886 Args: 4887 *expressions (str | Expression): the SQL code strings to parse. 4888 If an Expression instance is passed, this is used as-is. 4889 dialect (str): the dialect used to parse the input expression. 4890 copy (bool): whether or not to copy `expressions` (only applies to Expressions). 4891 **opts: other options to use to parse the input expressions. 4892 4893 Returns: 4894 And: the new condition 4895 """ 4896 return _combine(expressions, And, dialect, copy=copy, **opts) 4897 4898 4899def or_(*expressions, dialect=None, copy=True, **opts) -> Or: 4900 """ 4901 Combine multiple conditions with an OR logical operator. 4902 4903 Example: 4904 >>> or_("x=1", or_("y=1", "z=1")).sql() 4905 'x = 1 OR (y = 1 OR z = 1)' 4906 4907 Args: 4908 *expressions (str | Expression): the SQL code strings to parse. 4909 If an Expression instance is passed, this is used as-is. 4910 dialect (str): the dialect used to parse the input expression. 4911 copy (bool): whether or not to copy `expressions` (only applies to Expressions). 4912 **opts: other options to use to parse the input expressions. 4913 4914 Returns: 4915 Or: the new condition 4916 """ 4917 return _combine(expressions, Or, dialect, copy=copy, **opts) 4918 4919 4920def not_(expression, dialect=None, copy=True, **opts) -> Not: 4921 """ 4922 Wrap a condition with a NOT operator. 4923 4924 Example: 4925 >>> not_("this_suit='black'").sql() 4926 "NOT this_suit = 'black'" 4927 4928 Args: 4929 expression (str | Expression): the SQL code strings to parse. 4930 If an Expression instance is passed, this is used as-is. 4931 dialect (str): the dialect used to parse the input expression. 4932 **opts: other options to use to parse the input expressions. 4933 4934 Returns: 4935 Not: the new condition 4936 """ 4937 this = condition( 4938 expression, 4939 dialect=dialect, 4940 copy=copy, 4941 **opts, 4942 ) 4943 return Not(this=_wrap(this, Connector)) 4944 4945 4946def paren(expression, copy=True) -> Paren: 4947 return Paren(this=_maybe_copy(expression, copy)) 4948 4949 4950SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4951 4952 4953@t.overload 4954def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None: 4955 ... 4956 4957 4958@t.overload 4959def to_identifier( 4960 name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True 4961) -> Identifier: 4962 ... 4963 4964 4965def to_identifier(name, quoted=None, copy=True): 4966 """Builds an identifier. 4967 4968 Args: 4969 name: The name to turn into an identifier. 4970 quoted: Whether or not force quote the identifier. 4971 copy: Whether or not to copy a passed in Identefier node. 4972 4973 Returns: 4974 The identifier ast node. 4975 """ 4976 4977 if name is None: 4978 return None 4979 4980 if isinstance(name, Identifier): 4981 identifier = _maybe_copy(name, copy) 4982 elif isinstance(name, str): 4983 identifier = Identifier( 4984 this=name, 4985 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4986 ) 4987 else: 4988 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4989 return identifier 4990 4991 4992INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4993 4994 4995def to_interval(interval: str | Literal) -> Interval: 4996 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4997 if isinstance(interval, Literal): 4998 if not interval.is_string: 4999 raise ValueError("Invalid interval string.") 5000 5001 interval = interval.this 5002 5003 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5004 5005 if not interval_parts: 5006 raise ValueError("Invalid interval string.") 5007 5008 return Interval( 5009 this=Literal.string(interval_parts.group(1)), 5010 unit=Var(this=interval_parts.group(2)), 5011 ) 5012 5013 5014@t.overload 5015def to_table(sql_path: str | Table, **kwargs) -> Table: 5016 ... 5017 5018 5019@t.overload 5020def to_table(sql_path: None, **kwargs) -> None: 5021 ... 5022 5023 5024def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 5025 """ 5026 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5027 If a table is passed in then that table is returned. 5028 5029 Args: 5030 sql_path: a `[catalog].[schema].[table]` string. 5031 5032 Returns: 5033 A table expression. 5034 """ 5035 if sql_path is None or isinstance(sql_path, Table): 5036 return sql_path 5037 if not isinstance(sql_path, str): 5038 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5039 5040 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 5041 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 5042 5043 5044def to_column(sql_path: str | Column, **kwargs) -> Column: 5045 """ 5046 Create a column from a `[table].[column]` sql path. Schema is optional. 5047 5048 If a column is passed in then that column is returned. 5049 5050 Args: 5051 sql_path: `[table].[column]` string 5052 Returns: 5053 Table: A column expression 5054 """ 5055 if sql_path is None or isinstance(sql_path, Column): 5056 return sql_path 5057 if not isinstance(sql_path, str): 5058 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5059 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 5060 5061 5062def alias_( 5063 expression: ExpOrStr, 5064 alias: str | Identifier, 5065 table: bool | t.Sequence[str | Identifier] = False, 5066 quoted: t.Optional[bool] = None, 5067 dialect: DialectType = None, 5068 copy: bool = True, 5069 **opts, 5070): 5071 """Create an Alias expression. 5072 5073 Example: 5074 >>> alias_('foo', 'bar').sql() 5075 'foo AS bar' 5076 5077 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5078 '(SELECT 1, 2) AS bar(a, b)' 5079 5080 Args: 5081 expression: the SQL code strings to parse. 5082 If an Expression instance is passed, this is used as-is. 5083 alias: the alias name to use. If the name has 5084 special characters it is quoted. 5085 table: Whether or not to create a table alias, can also be a list of columns. 5086 quoted: whether or not to quote the alias 5087 dialect: the dialect used to parse the input expression. 5088 copy: Whether or not to copy the expression. 5089 **opts: other options to use to parse the input expressions. 5090 5091 Returns: 5092 Alias: the aliased expression 5093 """ 5094 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5095 alias = to_identifier(alias, quoted=quoted) 5096 5097 if table: 5098 table_alias = TableAlias(this=alias) 5099 exp.set("alias", table_alias) 5100 5101 if not isinstance(table, bool): 5102 for column in table: 5103 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5104 5105 return exp 5106 5107 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5108 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5109 # for the complete Window expression. 5110 # 5111 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5112 5113 if "alias" in exp.arg_types and not isinstance(exp, Window): 5114 exp.set("alias", alias) 5115 return exp 5116 return Alias(this=exp, alias=alias) 5117 5118 5119def subquery(expression, alias=None, dialect=None, **opts): 5120 """ 5121 Build a subquery expression. 5122 5123 Example: 5124 >>> subquery('select x from tbl', 'bar').select('x').sql() 5125 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5126 5127 Args: 5128 expression (str | Expression): the SQL code strings to parse. 5129 If an Expression instance is passed, this is used as-is. 5130 alias (str | Expression): the alias name to use. 5131 dialect (str): the dialect used to parse the input expression. 5132 **opts: other options to use to parse the input expressions. 5133 5134 Returns: 5135 Select: a new select with the subquery expression included 5136 """ 5137 5138 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5139 return Select().from_(expression, dialect=dialect, **opts) 5140 5141 5142def column( 5143 col: str | Identifier, 5144 table: t.Optional[str | Identifier] = None, 5145 db: t.Optional[str | Identifier] = None, 5146 catalog: t.Optional[str | Identifier] = None, 5147 quoted: t.Optional[bool] = None, 5148) -> Column: 5149 """ 5150 Build a Column. 5151 5152 Args: 5153 col: column name 5154 table: table name 5155 db: db name 5156 catalog: catalog name 5157 quoted: whether or not to force quote each part 5158 Returns: 5159 Column: column instance 5160 """ 5161 return Column( 5162 this=to_identifier(col, quoted=quoted), 5163 table=to_identifier(table, quoted=quoted), 5164 db=to_identifier(db, quoted=quoted), 5165 catalog=to_identifier(catalog, quoted=quoted), 5166 ) 5167 5168 5169def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5170 """Cast an expression to a data type. 5171 5172 Example: 5173 >>> cast('x + 1', 'int').sql() 5174 'CAST(x + 1 AS INT)' 5175 5176 Args: 5177 expression: The expression to cast. 5178 to: The datatype to cast to. 5179 5180 Returns: 5181 A cast node. 5182 """ 5183 expression = maybe_parse(expression, **opts) 5184 return Cast(this=expression, to=DataType.build(to, **opts)) 5185 5186 5187def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 5188 """Build a Table. 5189 5190 Args: 5191 table (str | Expression): column name 5192 db (str | Expression): db name 5193 catalog (str | Expression): catalog name 5194 5195 Returns: 5196 Table: table instance 5197 """ 5198 return Table( 5199 this=to_identifier(table, quoted=quoted), 5200 db=to_identifier(db, quoted=quoted), 5201 catalog=to_identifier(catalog, quoted=quoted), 5202 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5203 ) 5204 5205 5206def values( 5207 values: t.Iterable[t.Tuple[t.Any, ...]], 5208 alias: t.Optional[str] = None, 5209 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5210) -> Values: 5211 """Build VALUES statement. 5212 5213 Example: 5214 >>> values([(1, '2')]).sql() 5215 "VALUES (1, '2')" 5216 5217 Args: 5218 values: values statements that will be converted to SQL 5219 alias: optional alias 5220 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5221 If either are provided then an alias is also required. 5222 5223 Returns: 5224 Values: the Values expression object 5225 """ 5226 if columns and not alias: 5227 raise ValueError("Alias is required when providing columns") 5228 5229 return Values( 5230 expressions=[convert(tup) for tup in values], 5231 alias=( 5232 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5233 if columns 5234 else (TableAlias(this=to_identifier(alias)) if alias else None) 5235 ), 5236 ) 5237 5238 5239def var(name: t.Optional[ExpOrStr]) -> Var: 5240 """Build a SQL variable. 5241 5242 Example: 5243 >>> repr(var('x')) 5244 '(VAR this: x)' 5245 5246 >>> repr(var(column('x', table='y'))) 5247 '(VAR this: x)' 5248 5249 Args: 5250 name: The name of the var or an expression who's name will become the var. 5251 5252 Returns: 5253 The new variable node. 5254 """ 5255 if not name: 5256 raise ValueError("Cannot convert empty name into var.") 5257 5258 if isinstance(name, Expression): 5259 name = name.name 5260 return Var(this=name) 5261 5262 5263def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5264 """Build ALTER TABLE... RENAME... expression 5265 5266 Args: 5267 old_name: The old name of the table 5268 new_name: The new name of the table 5269 5270 Returns: 5271 Alter table expression 5272 """ 5273 old_table = to_table(old_name) 5274 new_table = to_table(new_name) 5275 return AlterTable( 5276 this=old_table, 5277 actions=[ 5278 RenameTable(this=new_table), 5279 ], 5280 ) 5281 5282 5283def convert(value: t.Any, copy: bool = False) -> Expression: 5284 """Convert a python value into an expression object. 5285 5286 Raises an error if a conversion is not possible. 5287 5288 Args: 5289 value: A python object. 5290 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5291 5292 Returns: 5293 Expression: the equivalent expression object. 5294 """ 5295 if isinstance(value, Expression): 5296 return _maybe_copy(value, copy) 5297 if isinstance(value, str): 5298 return Literal.string(value) 5299 if isinstance(value, bool): 5300 return Boolean(this=value) 5301 if value is None or (isinstance(value, float) and math.isnan(value)): 5302 return NULL 5303 if isinstance(value, numbers.Number): 5304 return Literal.number(value) 5305 if isinstance(value, datetime.datetime): 5306 datetime_literal = Literal.string( 5307 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5308 ) 5309 return TimeStrToTime(this=datetime_literal) 5310 if isinstance(value, datetime.date): 5311 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5312 return DateStrToDate(this=date_literal) 5313 if isinstance(value, tuple): 5314 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5315 if isinstance(value, list): 5316 return Array(expressions=[convert(v, copy=copy) for v in value]) 5317 if isinstance(value, dict): 5318 return Map( 5319 keys=[convert(k, copy=copy) for k in value], 5320 values=[convert(v, copy=copy) for v in value.values()], 5321 ) 5322 raise ValueError(f"Cannot convert {value}") 5323 5324 5325def replace_children(expression, fun, *args, **kwargs): 5326 """ 5327 Replace children of an expression with the result of a lambda fun(child) -> exp. 5328 """ 5329 for k, v in expression.args.items(): 5330 is_list_arg = type(v) is list 5331 5332 child_nodes = v if is_list_arg else [v] 5333 new_child_nodes = [] 5334 5335 for cn in child_nodes: 5336 if isinstance(cn, Expression): 5337 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5338 new_child_nodes.append(child_node) 5339 child_node.parent = expression 5340 child_node.arg_key = k 5341 else: 5342 new_child_nodes.append(cn) 5343 5344 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 5345 5346 5347def column_table_names(expression): 5348 """ 5349 Return all table names referenced through columns in an expression. 5350 5351 Example: 5352 >>> import sqlglot 5353 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5354 ['c', 'a'] 5355 5356 Args: 5357 expression (sqlglot.Expression): expression to find table names 5358 5359 Returns: 5360 list: A list of unique names 5361 """ 5362 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 5363 5364 5365def table_name(table) -> str: 5366 """Get the full name of a table as a string. 5367 5368 Args: 5369 table (exp.Table | str): table expression node or string. 5370 5371 Examples: 5372 >>> from sqlglot import exp, parse_one 5373 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5374 'a.b.c' 5375 5376 Returns: 5377 The table name. 5378 """ 5379 5380 table = maybe_parse(table, into=Table) 5381 5382 if not table: 5383 raise ValueError(f"Cannot parse {table}") 5384 5385 return ".".join( 5386 part 5387 for part in ( 5388 table.text("catalog"), 5389 table.text("db"), 5390 table.name, 5391 ) 5392 if part 5393 ) 5394 5395 5396def replace_tables(expression, mapping): 5397 """Replace all tables in expression according to the mapping. 5398 5399 Args: 5400 expression (sqlglot.Expression): expression node to be transformed and replaced. 5401 mapping (Dict[str, str]): mapping of table names. 5402 5403 Examples: 5404 >>> from sqlglot import exp, parse_one 5405 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5406 'SELECT * FROM c' 5407 5408 Returns: 5409 The mapped expression. 5410 """ 5411 5412 def _replace_tables(node): 5413 if isinstance(node, Table): 5414 new_name = mapping.get(table_name(node)) 5415 if new_name: 5416 return to_table( 5417 new_name, 5418 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5419 ) 5420 return node 5421 5422 return expression.transform(_replace_tables) 5423 5424 5425def replace_placeholders(expression, *args, **kwargs): 5426 """Replace placeholders in an expression. 5427 5428 Args: 5429 expression (sqlglot.Expression): expression node to be transformed and replaced. 5430 args: positional names that will substitute unnamed placeholders in the given order. 5431 kwargs: keyword arguments that will substitute named placeholders. 5432 5433 Examples: 5434 >>> from sqlglot import exp, parse_one 5435 >>> replace_placeholders( 5436 ... parse_one("select * from :tbl where ? = ?"), 5437 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5438 ... ).sql() 5439 "SELECT * FROM foo WHERE str_col = 'b'" 5440 5441 Returns: 5442 The mapped expression. 5443 """ 5444 5445 def _replace_placeholders(node, args, **kwargs): 5446 if isinstance(node, Placeholder): 5447 if node.name: 5448 new_name = kwargs.get(node.name) 5449 if new_name: 5450 return convert(new_name) 5451 else: 5452 try: 5453 return convert(next(args)) 5454 except StopIteration: 5455 pass 5456 return node 5457 5458 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5459 5460 5461def expand( 5462 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5463) -> Expression: 5464 """Transforms an expression by expanding all referenced sources into subqueries. 5465 5466 Examples: 5467 >>> from sqlglot import parse_one 5468 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5469 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5470 5471 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5472 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5473 5474 Args: 5475 expression: The expression to expand. 5476 sources: A dictionary of name to Subqueryables. 5477 copy: Whether or not to copy the expression during transformation. Defaults to True. 5478 5479 Returns: 5480 The transformed expression. 5481 """ 5482 5483 def _expand(node: Expression): 5484 if isinstance(node, Table): 5485 name = table_name(node) 5486 source = sources.get(name) 5487 if source: 5488 subquery = source.subquery(node.alias or name) 5489 subquery.comments = [f"source: {name}"] 5490 return subquery.transform(_expand, copy=False) 5491 return node 5492 5493 return expression.transform(_expand, copy=copy) 5494 5495 5496def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5497 """ 5498 Returns a Func expression. 5499 5500 Examples: 5501 >>> func("abs", 5).sql() 5502 'ABS(5)' 5503 5504 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5505 'CAST(5 AS DOUBLE)' 5506 5507 Args: 5508 name: the name of the function to build. 5509 args: the args used to instantiate the function of interest. 5510 dialect: the source dialect. 5511 kwargs: the kwargs used to instantiate the function of interest. 5512 5513 Note: 5514 The arguments `args` and `kwargs` are mutually exclusive. 5515 5516 Returns: 5517 An instance of the function of interest, or an anonymous function, if `name` doesn't 5518 correspond to an existing `sqlglot.expressions.Func` class. 5519 """ 5520 if args and kwargs: 5521 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5522 5523 from sqlglot.dialects.dialect import Dialect 5524 5525 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5526 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5527 5528 parser = Dialect.get_or_raise(dialect)().parser() 5529 from_args_list = parser.FUNCTIONS.get(name.upper()) 5530 5531 if from_args_list: 5532 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5533 else: 5534 kwargs = kwargs or {"expressions": converted} 5535 function = Anonymous(this=name, **kwargs) 5536 5537 for error_message in function.error_messages(converted): 5538 raise ValueError(error_message) 5539 5540 return function 5541 5542 5543def true(): 5544 """ 5545 Returns a true Boolean expression. 5546 """ 5547 return Boolean(this=True) 5548 5549 5550def false(): 5551 """ 5552 Returns a false Boolean expression. 5553 """ 5554 return Boolean(this=False) 5555 5556 5557def null(): 5558 """ 5559 Returns a Null expression. 5560 """ 5561 return Null() 5562 5563 5564# TODO: deprecate this 5565TRUE = Boolean(this=True) 5566FALSE = Boolean(this=False) 5567NULL = 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 parent: a reference to the parent expression (or None, in case of root expressions). 69 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 70 uses to refer to it. 71 comments: a list of comments that are associated with a given expression. This is used in 72 order to preserve comments when transpiling SQL code. 73 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 74 optimizer, in order to enable some transformations that require type information. 75 76 Example: 77 >>> class Foo(Expression): 78 ... arg_types = {"this": True, "expression": False} 79 80 The above definition informs us that Foo is an Expression that requires an argument called 81 "this" and may also optionally receive an argument called "expression". 82 83 Args: 84 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 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 add_comments(self, comments: t.Optional[t.List[str]]) -> None: 263 if self.comments is None: 264 self.comments = [] 265 if comments: 266 self.comments.extend(comments) 267 268 def append(self, arg_key, value): 269 """ 270 Appends value to arg_key if it's a list or sets it as a new list. 271 272 Args: 273 arg_key (str): name of the list expression arg 274 value (Any): value to append to the list 275 """ 276 if not isinstance(self.args.get(arg_key), list): 277 self.args[arg_key] = [] 278 self.args[arg_key].append(value) 279 self._set_parent(arg_key, value) 280 281 def set(self, arg_key, value): 282 """ 283 Sets `arg_key` to `value`. 284 285 Args: 286 arg_key (str): name of the expression arg. 287 value: value to set the arg to. 288 """ 289 self.args[arg_key] = value 290 self._set_parent(arg_key, value) 291 292 def _set_parent(self, arg_key, value): 293 if hasattr(value, "parent"): 294 value.parent = self 295 value.arg_key = arg_key 296 elif type(value) is list: 297 for v in value: 298 if hasattr(v, "parent"): 299 v.parent = self 300 v.arg_key = arg_key 301 302 @property 303 def depth(self): 304 """ 305 Returns the depth of this tree. 306 """ 307 if self.parent: 308 return self.parent.depth + 1 309 return 0 310 311 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 312 """Yields the key and expression for all arguments, exploding list args.""" 313 for k, vs in self.args.items(): 314 if type(vs) is list: 315 for v in vs: 316 if hasattr(v, "parent"): 317 yield k, v 318 else: 319 if hasattr(vs, "parent"): 320 yield k, vs 321 322 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 323 """ 324 Returns the first node in this tree which matches at least one of 325 the specified types. 326 327 Args: 328 expression_types: the expression type(s) to match. 329 330 Returns: 331 The node which matches the criteria or None if no such node was found. 332 """ 333 return next(self.find_all(*expression_types, bfs=bfs), None) 334 335 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 336 """ 337 Returns a generator object which visits all nodes in this tree and only 338 yields those that match at least one of the specified expression types. 339 340 Args: 341 expression_types: the expression type(s) to match. 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression 349 350 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor) 364 365 @property 366 def parent_select(self): 367 """ 368 Returns the parent select statement. 369 """ 370 return self.find_ancestor(Select) 371 372 @property 373 def same_parent(self): 374 """Returns if the parent is the same class as itself.""" 375 return type(self.parent) is self.__class__ 376 377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression 385 386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune) 403 404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune) 419 420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k)) 439 440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression 448 449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self 456 457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 462 463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node 472 473 def __str__(self): 474 return self.sql() 475 476 def __repr__(self): 477 return self._to_s() 478 479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts) 493 494 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 495 indent = "" if not level else "\n" 496 indent += "".join([" "] * level) 497 left = f"({self.key.upper()} " 498 499 args: t.Dict[str, t.Any] = { 500 k: ", ".join( 501 v._to_s(hide_missing=hide_missing, level=level + 1) 502 if hasattr(v, "_to_s") 503 else str(v) 504 for v in ensure_list(vs) 505 if v is not None 506 ) 507 for k, vs in self.args.items() 508 } 509 args["comments"] = self.comments 510 args["type"] = self.type 511 args = {k: v for k, v in args.items() if v or not hide_missing} 512 513 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 514 right += ")" 515 516 return indent + left + right 517 518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node 544 545 def replace(self, expression): 546 """ 547 Swap out this expression with a new expression. 548 549 For example:: 550 551 >>> tree = Select().select("x").from_("tbl") 552 >>> tree.find(Column).replace(Column(this="y")) 553 (COLUMN this: y) 554 >>> tree.sql() 555 'SELECT y FROM tbl' 556 557 Args: 558 expression (Expression|None): new node 559 560 Returns: 561 The new expression or expressions. 562 """ 563 if not self.parent: 564 return expression 565 566 parent = self.parent 567 self.parent = None 568 569 replace_children(parent, lambda child: expression if child is self else child) 570 return expression 571 572 def pop(self): 573 """ 574 Remove this expression from its AST. 575 576 Returns: 577 The popped expression. 578 """ 579 self.replace(None) 580 return self 581 582 def assert_is(self, type_): 583 """ 584 Assert that this `Expression` is an instance of `type_`. 585 586 If it is NOT an instance of `type_`, this raises an assertion error. 587 Otherwise, this returns this expression. 588 589 Examples: 590 This is useful for type security in chained expressions: 591 592 >>> import sqlglot 593 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 594 'SELECT x, z FROM y' 595 """ 596 assert isinstance(self, type_) 597 return self 598 599 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 600 """ 601 Checks if this expression is valid (e.g. all mandatory args are set). 602 603 Args: 604 args: a sequence of values that were used to instantiate a Func expression. This is used 605 to check that the provided arguments don't exceed the function argument limit. 606 607 Returns: 608 A list of error messages for all possible errors that were found. 609 """ 610 errors: t.List[str] = [] 611 612 for k in self.args: 613 if k not in self.arg_types: 614 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 615 for k, mandatory in self.arg_types.items(): 616 v = self.args.get(k) 617 if mandatory and (v is None or (isinstance(v, list) and not v)): 618 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 619 620 if ( 621 args 622 and isinstance(self, Func) 623 and len(args) > len(self.arg_types) 624 and not self.is_var_len_args 625 ): 626 errors.append( 627 f"The number of provided arguments ({len(args)}) is greater than " 628 f"the maximum number of supported arguments ({len(self.arg_types)})" 629 ) 630 631 return errors 632 633 def dump(self): 634 """ 635 Dump this Expression to a JSON-serializable dict. 636 """ 637 from sqlglot.serde import dump 638 639 return dump(self) 640 641 @classmethod 642 def load(cls, obj): 643 """ 644 Load a dict (as returned by `Expression.dump`) into an Expression instance. 645 """ 646 from sqlglot.serde import load 647 648 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataType
type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
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.
268 def append(self, arg_key, value): 269 """ 270 Appends value to arg_key if it's a list or sets it as a new list. 271 272 Args: 273 arg_key (str): name of the list expression arg 274 value (Any): value to append to the list 275 """ 276 if not isinstance(self.args.get(arg_key), list): 277 self.args[arg_key] = [] 278 self.args[arg_key].append(value) 279 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
281 def set(self, arg_key, value): 282 """ 283 Sets `arg_key` to `value`. 284 285 Args: 286 arg_key (str): name of the expression arg. 287 value: value to set the arg to. 288 """ 289 self.args[arg_key] = value 290 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.
311 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 312 """Yields the key and expression for all arguments, exploding list args.""" 313 for k, vs in self.args.items(): 314 if type(vs) is list: 315 for v in vs: 316 if hasattr(v, "parent"): 317 yield k, v 318 else: 319 if hasattr(vs, "parent"): 320 yield k, vs
Yields the key and expression for all arguments, exploding list args.
322 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 323 """ 324 Returns the first node in this tree which matches at least one of 325 the specified types. 326 327 Args: 328 expression_types: the expression type(s) to match. 329 330 Returns: 331 The node which matches the criteria or None if no such node was found. 332 """ 333 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.
335 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 336 """ 337 Returns a generator object which visits all nodes in this tree and only 338 yields those that match at least one of the specified expression types. 339 340 Args: 341 expression_types: the expression type(s) to match. 342 343 Returns: 344 The generator object. 345 """ 346 for expression, *_ in self.walk(bfs=bfs): 347 if isinstance(expression, expression_types): 348 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The generator object.
350 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 351 """ 352 Returns a nearest parent matching expression_types. 353 354 Args: 355 expression_types: the expression type(s) to match. 356 357 Returns: 358 The parent node. 359 """ 360 ancestor = self.parent 361 while ancestor and not isinstance(ancestor, expression_types): 362 ancestor = ancestor.parent 363 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
377 def root(self) -> Expression: 378 """ 379 Returns the root expression of this tree. 380 """ 381 expression = self 382 while expression.parent: 383 expression = expression.parent 384 return expression
Returns the root expression of this tree.
386 def walk(self, bfs=True, prune=None): 387 """ 388 Returns a generator object which visits all nodes in this tree. 389 390 Args: 391 bfs (bool): if set to True the BFS traversal order will be applied, 392 otherwise the DFS traversal will be used instead. 393 prune ((node, parent, arg_key) -> bool): callable that returns True if 394 the generator should stop traversing this branch of the tree. 395 396 Returns: 397 the generator object. 398 """ 399 if bfs: 400 yield from self.bfs(prune=prune) 401 else: 402 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
404 def dfs(self, parent=None, key=None, prune=None): 405 """ 406 Returns a generator object which visits all nodes in this tree in 407 the DFS (Depth-first) order. 408 409 Returns: 410 The generator object. 411 """ 412 parent = parent or self.parent 413 yield self, parent, key 414 if prune and prune(self, parent, key): 415 return 416 417 for k, v in self.iter_expressions(): 418 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
420 def bfs(self, prune=None): 421 """ 422 Returns a generator object which visits all nodes in this tree in 423 the BFS (Breadth-first) order. 424 425 Returns: 426 The generator object. 427 """ 428 queue = deque([(self, self.parent, None)]) 429 430 while queue: 431 item, parent, key = queue.popleft() 432 433 yield item, parent, key 434 if prune and prune(item, parent, key): 435 continue 436 437 for k, v in item.iter_expressions(): 438 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
440 def unnest(self): 441 """ 442 Returns the first non parenthesis child or self. 443 """ 444 expression = self 445 while type(expression) is Paren: 446 expression = expression.this 447 return expression
Returns the first non parenthesis child or self.
449 def unalias(self): 450 """ 451 Returns the inner expression if this is an Alias. 452 """ 453 if isinstance(self, Alias): 454 return self.this 455 return self
Returns the inner expression if this is an Alias.
457 def unnest_operands(self): 458 """ 459 Returns unnested operands as a tuple. 460 """ 461 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
463 def flatten(self, unnest=True): 464 """ 465 Returns a generator which yields child nodes who's parents are the same class. 466 467 A AND B AND C -> [A, B, C] 468 """ 469 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 470 if not type(node) is self.__class__: 471 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
479 def sql(self, dialect: DialectType = None, **opts) -> str: 480 """ 481 Returns SQL string representation of this tree. 482 483 Args: 484 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 485 opts: other `sqlglot.generator.Generator` options. 486 487 Returns: 488 The SQL string. 489 """ 490 from sqlglot.dialects import Dialect 491 492 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generator
options.
Returns:
The SQL string.
518 def transform(self, fun, *args, copy=True, **kwargs): 519 """ 520 Recursively visits all tree nodes (excluding already transformed ones) 521 and applies the given transformation function to each node. 522 523 Args: 524 fun (function): a function which takes a node as an argument and returns a 525 new transformed node or the same node without modifications. If the function 526 returns None, then the corresponding node will be removed from the syntax tree. 527 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 528 modified in place. 529 530 Returns: 531 The transformed tree. 532 """ 533 node = self.copy() if copy else self 534 new_node = fun(node, *args, **kwargs) 535 536 if new_node is None or not isinstance(new_node, Expression): 537 return new_node 538 if new_node is not node: 539 new_node.parent = node.parent 540 return new_node 541 542 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 543 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
545 def replace(self, expression): 546 """ 547 Swap out this expression with a new expression. 548 549 For example:: 550 551 >>> tree = Select().select("x").from_("tbl") 552 >>> tree.find(Column).replace(Column(this="y")) 553 (COLUMN this: y) 554 >>> tree.sql() 555 'SELECT y FROM tbl' 556 557 Args: 558 expression (Expression|None): new node 559 560 Returns: 561 The new expression or expressions. 562 """ 563 if not self.parent: 564 return expression 565 566 parent = self.parent 567 self.parent = None 568 569 replace_children(parent, lambda child: expression if child is self else child) 570 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.
572 def pop(self): 573 """ 574 Remove this expression from its AST. 575 576 Returns: 577 The popped expression. 578 """ 579 self.replace(None) 580 return self
Remove this expression from its AST.
Returns:
The popped expression.
582 def assert_is(self, type_): 583 """ 584 Assert that this `Expression` is an instance of `type_`. 585 586 If it is NOT an instance of `type_`, this raises an assertion error. 587 Otherwise, this returns this expression. 588 589 Examples: 590 This is useful for type security in chained expressions: 591 592 >>> import sqlglot 593 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 594 'SELECT x, z FROM y' 595 """ 596 assert isinstance(self, type_) 597 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'
599 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 600 """ 601 Checks if this expression is valid (e.g. all mandatory args are set). 602 603 Args: 604 args: a sequence of values that were used to instantiate a Func expression. This is used 605 to check that the provided arguments don't exceed the function argument limit. 606 607 Returns: 608 A list of error messages for all possible errors that were found. 609 """ 610 errors: t.List[str] = [] 611 612 for k in self.args: 613 if k not in self.arg_types: 614 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 615 for k, mandatory in self.arg_types.items(): 616 v = self.args.get(k) 617 if mandatory and (v is None or (isinstance(v, list) and not v)): 618 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 619 620 if ( 621 args 622 and isinstance(self, Func) 623 and len(args) > len(self.arg_types) 624 and not self.is_var_len_args 625 ): 626 errors.append( 627 f"The number of provided arguments ({len(args)}) is greater than " 628 f"the maximum number of supported arguments ({len(self.arg_types)})" 629 ) 630 631 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.
633 def dump(self): 634 """ 635 Dump this Expression to a JSON-serializable dict. 636 """ 637 from sqlglot.serde import dump 638 639 return dump(self)
Dump this Expression to a JSON-serializable dict.
641 @classmethod 642 def load(cls, obj): 643 """ 644 Load a dict (as returned by `Expression.dump`) into an Expression instance. 645 """ 646 from sqlglot.serde import load 647 648 return load(obj)
Load a dict (as returned by Expression.dump
) into an Expression instance.
659class Condition(Expression): 660 def and_(self, *expressions, dialect=None, copy=True, **opts): 661 """ 662 AND this condition with one or multiple expressions. 663 664 Example: 665 >>> condition("x=1").and_("y=1").sql() 666 'x = 1 AND y = 1' 667 668 Args: 669 *expressions (str | Expression): the SQL code strings to parse. 670 If an `Expression` instance is passed, it will be used as-is. 671 dialect (str): the dialect used to parse the input expression. 672 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 673 opts (kwargs): other options to use to parse the input expressions. 674 675 Returns: 676 And: the new condition. 677 """ 678 return and_(self, *expressions, dialect=dialect, copy=copy, **opts) 679 680 def or_(self, *expressions, dialect=None, copy=True, **opts): 681 """ 682 OR this condition with one or multiple expressions. 683 684 Example: 685 >>> condition("x=1").or_("y=1").sql() 686 'x = 1 OR y = 1' 687 688 Args: 689 *expressions (str | Expression): the SQL code strings to parse. 690 If an `Expression` instance is passed, it will be used as-is. 691 dialect (str): the dialect used to parse the input expression. 692 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 693 opts (kwargs): other options to use to parse the input expressions. 694 695 Returns: 696 Or: the new condition. 697 """ 698 return or_(self, *expressions, dialect=dialect, copy=copy, **opts) 699 700 def not_(self, copy=True): 701 """ 702 Wrap this condition with NOT. 703 704 Example: 705 >>> condition("x=1").not_().sql() 706 'NOT x = 1' 707 708 Args: 709 copy (bool): whether or not to copy this object. 710 711 Returns: 712 Not: the new condition. 713 """ 714 return not_(self, copy=copy) 715 716 def as_( 717 self, 718 alias: str | Identifier, 719 quoted: t.Optional[bool] = None, 720 dialect: DialectType = None, 721 copy: bool = True, 722 **opts, 723 ) -> Alias: 724 return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts) 725 726 def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: 727 this = self.copy() 728 other = convert(other, copy=True) 729 if not isinstance(this, klass) and not isinstance(other, klass): 730 this = _wrap(this, Binary) 731 other = _wrap(other, Binary) 732 if reverse: 733 return klass(this=other, expression=this) 734 return klass(this=this, expression=other) 735 736 def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]): 737 return Bracket( 738 this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] 739 ) 740 741 def isin( 742 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts 743 ) -> In: 744 return In( 745 this=_maybe_copy(self, copy), 746 expressions=[convert(e, copy=copy) for e in expressions], 747 query=maybe_parse(query, copy=copy, **opts) if query else None, 748 ) 749 750 def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between: 751 return Between( 752 this=_maybe_copy(self, copy), 753 low=convert(low, copy=copy, **opts), 754 high=convert(high, copy=copy, **opts), 755 ) 756 757 def is_(self, other: ExpOrStr) -> Is: 758 return self._binop(Is, other) 759 760 def like(self, other: ExpOrStr) -> Like: 761 return self._binop(Like, other) 762 763 def ilike(self, other: ExpOrStr) -> ILike: 764 return self._binop(ILike, other) 765 766 def eq(self, other: t.Any) -> EQ: 767 return self._binop(EQ, other) 768 769 def neq(self, other: t.Any) -> NEQ: 770 return self._binop(NEQ, other) 771 772 def rlike(self, other: ExpOrStr) -> RegexpLike: 773 return self._binop(RegexpLike, other) 774 775 def __lt__(self, other: t.Any) -> LT: 776 return self._binop(LT, other) 777 778 def __le__(self, other: t.Any) -> LTE: 779 return self._binop(LTE, other) 780 781 def __gt__(self, other: t.Any) -> GT: 782 return self._binop(GT, other) 783 784 def __ge__(self, other: t.Any) -> GTE: 785 return self._binop(GTE, other) 786 787 def __add__(self, other: t.Any) -> Add: 788 return self._binop(Add, other) 789 790 def __radd__(self, other: t.Any) -> Add: 791 return self._binop(Add, other, reverse=True) 792 793 def __sub__(self, other: t.Any) -> Sub: 794 return self._binop(Sub, other) 795 796 def __rsub__(self, other: t.Any) -> Sub: 797 return self._binop(Sub, other, reverse=True) 798 799 def __mul__(self, other: t.Any) -> Mul: 800 return self._binop(Mul, other) 801 802 def __rmul__(self, other: t.Any) -> Mul: 803 return self._binop(Mul, other, reverse=True) 804 805 def __truediv__(self, other: t.Any) -> Div: 806 return self._binop(Div, other) 807 808 def __rtruediv__(self, other: t.Any) -> Div: 809 return self._binop(Div, other, reverse=True) 810 811 def __floordiv__(self, other: t.Any) -> IntDiv: 812 return self._binop(IntDiv, other) 813 814 def __rfloordiv__(self, other: t.Any) -> IntDiv: 815 return self._binop(IntDiv, other, reverse=True) 816 817 def __mod__(self, other: t.Any) -> Mod: 818 return self._binop(Mod, other) 819 820 def __rmod__(self, other: t.Any) -> Mod: 821 return self._binop(Mod, other, reverse=True) 822 823 def __pow__(self, other: t.Any) -> Pow: 824 return self._binop(Pow, other) 825 826 def __rpow__(self, other: t.Any) -> Pow: 827 return self._binop(Pow, other, reverse=True) 828 829 def __and__(self, other: t.Any) -> And: 830 return self._binop(And, other) 831 832 def __rand__(self, other: t.Any) -> And: 833 return self._binop(And, other, reverse=True) 834 835 def __or__(self, other: t.Any) -> Or: 836 return self._binop(Or, other) 837 838 def __ror__(self, other: t.Any) -> Or: 839 return self._binop(Or, other, reverse=True) 840 841 def __neg__(self) -> Neg: 842 return Neg(this=_wrap(self.copy(), Binary)) 843 844 def __invert__(self) -> Not: 845 return not_(self.copy())
660 def and_(self, *expressions, dialect=None, copy=True, **opts): 661 """ 662 AND this condition with one or multiple expressions. 663 664 Example: 665 >>> condition("x=1").and_("y=1").sql() 666 'x = 1 AND y = 1' 667 668 Args: 669 *expressions (str | Expression): the SQL code strings to parse. 670 If an `Expression` instance is passed, it will be used as-is. 671 dialect (str): the dialect used to parse the input expression. 672 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 673 opts (kwargs): other options to use to parse the input expressions. 674 675 Returns: 676 And: the new condition. 677 """ 678 return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (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.
- copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
680 def or_(self, *expressions, dialect=None, copy=True, **opts): 681 """ 682 OR this condition with one or multiple expressions. 683 684 Example: 685 >>> condition("x=1").or_("y=1").sql() 686 'x = 1 OR y = 1' 687 688 Args: 689 *expressions (str | Expression): the SQL code strings to parse. 690 If an `Expression` instance is passed, it will be used as-is. 691 dialect (str): the dialect used to parse the input expression. 692 copy (bool): whether or not to copy the involved expressions (only applies to Expressions). 693 opts (kwargs): other options to use to parse the input expressions. 694 695 Returns: 696 Or: the new condition. 697 """ 698 return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (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.
- copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
700 def not_(self, copy=True): 701 """ 702 Wrap this condition with NOT. 703 704 Example: 705 >>> condition("x=1").not_().sql() 706 'NOT x = 1' 707 708 Args: 709 copy (bool): whether or not to copy this object. 710 711 Returns: 712 Not: the new condition. 713 """ 714 return not_(self, copy=copy)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Arguments:
- copy (bool): whether or not to copy this object.
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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
852class DerivedTable(Expression): 853 @property 854 def alias_column_names(self): 855 table_alias = self.args.get("alias") 856 if not table_alias: 857 return [] 858 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 859 return [c.name for c in column_list] 860 861 @property 862 def selects(self): 863 return self.this.selects if isinstance(self.this, Subqueryable) else [] 864 865 @property 866 def named_selects(self): 867 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
870class Unionable(Expression): 871 def union(self, expression, distinct=True, dialect=None, **opts): 872 """ 873 Builds a UNION expression. 874 875 Example: 876 >>> import sqlglot 877 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 878 'SELECT * FROM foo UNION SELECT * FROM bla' 879 880 Args: 881 expression (str | Expression): the SQL code string. 882 If an `Expression` instance is passed, it will be used as-is. 883 distinct (bool): set the DISTINCT flag if and only if this is true. 884 dialect (str): the dialect used to parse the input expression. 885 opts (kwargs): other options to use to parse the input expressions. 886 Returns: 887 Union: the Union expression. 888 """ 889 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 890 891 def intersect(self, expression, distinct=True, dialect=None, **opts): 892 """ 893 Builds an INTERSECT expression. 894 895 Example: 896 >>> import sqlglot 897 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 898 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 899 900 Args: 901 expression (str | Expression): the SQL code string. 902 If an `Expression` instance is passed, it will be used as-is. 903 distinct (bool): set the DISTINCT flag if and only if this is true. 904 dialect (str): the dialect used to parse the input expression. 905 opts (kwargs): other options to use to parse the input expressions. 906 Returns: 907 Intersect: the Intersect expression 908 """ 909 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 910 911 def except_(self, expression, distinct=True, dialect=None, **opts): 912 """ 913 Builds an EXCEPT expression. 914 915 Example: 916 >>> import sqlglot 917 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 918 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 919 920 Args: 921 expression (str | Expression): the SQL code string. 922 If an `Expression` instance is passed, it will be used as-is. 923 distinct (bool): set the DISTINCT flag if and only if this is true. 924 dialect (str): the dialect used to parse the input expression. 925 opts (kwargs): other options to use to parse the input expressions. 926 Returns: 927 Except: the Except expression 928 """ 929 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
871 def union(self, expression, distinct=True, dialect=None, **opts): 872 """ 873 Builds a UNION expression. 874 875 Example: 876 >>> import sqlglot 877 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 878 'SELECT * FROM foo UNION SELECT * FROM bla' 879 880 Args: 881 expression (str | Expression): the SQL code string. 882 If an `Expression` instance is passed, it will be used as-is. 883 distinct (bool): set the DISTINCT flag if and only if this is true. 884 dialect (str): the dialect used to parse the input expression. 885 opts (kwargs): other options to use to parse the input expressions. 886 Returns: 887 Union: the Union expression. 888 """ 889 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.
891 def intersect(self, expression, distinct=True, dialect=None, **opts): 892 """ 893 Builds an INTERSECT expression. 894 895 Example: 896 >>> import sqlglot 897 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 898 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 899 900 Args: 901 expression (str | Expression): the SQL code string. 902 If an `Expression` instance is passed, it will be used as-is. 903 distinct (bool): set the DISTINCT flag if and only if this is true. 904 dialect (str): the dialect used to parse the input expression. 905 opts (kwargs): other options to use to parse the input expressions. 906 Returns: 907 Intersect: the Intersect expression 908 """ 909 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
911 def except_(self, expression, distinct=True, dialect=None, **opts): 912 """ 913 Builds an EXCEPT expression. 914 915 Example: 916 >>> import sqlglot 917 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 918 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 919 920 Args: 921 expression (str | Expression): the SQL code string. 922 If an `Expression` instance is passed, it will be used as-is. 923 distinct (bool): set the DISTINCT flag if and only if this is true. 924 dialect (str): the dialect used to parse the input expression. 925 opts (kwargs): other options to use to parse the input expressions. 926 Returns: 927 Except: the Except expression 928 """ 929 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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
932class UDTF(DerivedTable, Unionable): 933 @property 934 def selects(self): 935 alias = self.args.get("alias") 936 return alias.columns if alias else []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
939class Cache(Expression): 940 arg_types = { 941 "with": False, 942 "this": True, 943 "lazy": False, 944 "options": False, 945 "expression": False, 946 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
953class Create(Expression): 954 arg_types = { 955 "with": False, 956 "this": True, 957 "kind": True, 958 "expression": False, 959 "exists": False, 960 "properties": False, 961 "replace": False, 962 "unique": False, 963 "indexes": False, 964 "no_schema_binding": False, 965 "begin": False, 966 "clone": False, 967 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
971class Clone(Expression): 972 arg_types = { 973 "this": True, 974 "when": False, 975 "kind": False, 976 "expression": False, 977 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
992class SetItem(Expression): 993 arg_types = { 994 "this": False, 995 "expressions": False, 996 "kind": False, 997 "collate": False, # MySQL SET NAMES statement 998 "global": False, 999 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1002class Show(Expression): 1003 arg_types = { 1004 "this": True, 1005 "target": False, 1006 "offset": False, 1007 "limit": False, 1008 "like": False, 1009 "where": False, 1010 "db": False, 1011 "full": False, 1012 "mutex": False, 1013 "query": False, 1014 "channel": False, 1015 "global": False, 1016 "log": False, 1017 "position": False, 1018 "types": False, 1019 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1022class UserDefinedFunction(Expression): 1023 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1030class With(Expression): 1031 arg_types = {"expressions": True, "recursive": False} 1032 1033 @property 1034 def recursive(self) -> bool: 1035 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1046class TableAlias(Expression): 1047 arg_types = {"this": False, "columns": False} 1048 1049 @property 1050 def columns(self): 1051 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1066class Column(Condition): 1067 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1068 1069 @property 1070 def table(self) -> str: 1071 return self.text("table") 1072 1073 @property 1074 def db(self) -> str: 1075 return self.text("db") 1076 1077 @property 1078 def catalog(self) -> str: 1079 return self.text("catalog") 1080 1081 @property 1082 def output_name(self) -> str: 1083 return self.name 1084 1085 @property 1086 def parts(self) -> t.List[Identifier]: 1087 """Return the parts of a column in order catalog, db, table, name.""" 1088 return [ 1089 t.cast(Identifier, self.args[part]) 1090 for part in ("catalog", "db", "table", "this") 1091 if self.args.get(part) 1092 ] 1093 1094 def to_dot(self) -> Dot: 1095 """Converts the column into a dot expression.""" 1096 parts = self.parts 1097 parent = self.parent 1098 1099 while parent: 1100 if isinstance(parent, Dot): 1101 parts.append(parent.expression) 1102 parent = parent.parent 1103 1104 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.
1094 def to_dot(self) -> Dot: 1095 """Converts the column into a dot expression.""" 1096 parts = self.parts 1097 parent = self.parent 1098 1099 while parent: 1100 if isinstance(parent, Dot): 1101 parts.append(parent.expression) 1102 parent = parent.parent 1103 1104 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1111class ColumnDef(Expression): 1112 arg_types = { 1113 "this": True, 1114 "kind": False, 1115 "constraints": False, 1116 "exists": False, 1117 "position": False, 1118 } 1119 1120 @property 1121 def constraints(self) -> t.List[ColumnConstraint]: 1122 return self.args.get("constraints") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1125class AlterColumn(Expression): 1126 arg_types = { 1127 "this": True, 1128 "dtype": False, 1129 "collate": False, 1130 "using": False, 1131 "default": False, 1132 "drop": False, 1133 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1144class Comment(Expression): 1145 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1149class MergeTreeTTLAction(Expression): 1150 arg_types = { 1151 "this": True, 1152 "delete": False, 1153 "recompress": False, 1154 "to_disk": False, 1155 "to_volume": False, 1156 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1160class MergeTreeTTL(Expression): 1161 arg_types = { 1162 "expressions": True, 1163 "where": False, 1164 "group": False, 1165 "aggregates": False, 1166 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1169class ColumnConstraint(Expression): 1170 arg_types = {"this": False, "kind": True} 1171 1172 @property 1173 def kind(self) -> ColumnConstraintKind: 1174 return self.args["kind"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1221class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1222 # this: True -> ALWAYS, this: False -> BY DEFAULT 1223 arg_types = { 1224 "this": False, 1225 "on_null": False, 1226 "start": False, 1227 "increment": False, 1228 "minvalue": False, 1229 "maxvalue": False, 1230 "cycle": False, 1231 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1271class Delete(Expression): 1272 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1273 1274 def delete( 1275 self, 1276 table: ExpOrStr, 1277 dialect: DialectType = None, 1278 copy: bool = True, 1279 **opts, 1280 ) -> Delete: 1281 """ 1282 Create a DELETE expression or replace the table on an existing DELETE expression. 1283 1284 Example: 1285 >>> delete("tbl").sql() 1286 'DELETE FROM tbl' 1287 1288 Args: 1289 table: the table from which to delete. 1290 dialect: the dialect used to parse the input expression. 1291 copy: if `False`, modify this expression instance in-place. 1292 opts: other options to use to parse the input expressions. 1293 1294 Returns: 1295 Delete: the modified expression. 1296 """ 1297 return _apply_builder( 1298 expression=table, 1299 instance=self, 1300 arg="this", 1301 dialect=dialect, 1302 into=Table, 1303 copy=copy, 1304 **opts, 1305 ) 1306 1307 def where( 1308 self, 1309 *expressions: ExpOrStr, 1310 append: bool = True, 1311 dialect: DialectType = None, 1312 copy: bool = True, 1313 **opts, 1314 ) -> Delete: 1315 """ 1316 Append to or set the WHERE expressions. 1317 1318 Example: 1319 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1320 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1321 1322 Args: 1323 *expressions: the SQL code strings to parse. 1324 If an `Expression` instance is passed, it will be used as-is. 1325 Multiple expressions are combined with an AND operator. 1326 append: if `True`, AND the new expressions to any existing expression. 1327 Otherwise, this resets the expression. 1328 dialect: the dialect used to parse the input expressions. 1329 copy: if `False`, modify this expression instance in-place. 1330 opts: other options to use to parse the input expressions. 1331 1332 Returns: 1333 Delete: the modified expression. 1334 """ 1335 return _apply_conjunction_builder( 1336 *expressions, 1337 instance=self, 1338 arg="where", 1339 append=append, 1340 into=Where, 1341 dialect=dialect, 1342 copy=copy, 1343 **opts, 1344 ) 1345 1346 def returning( 1347 self, 1348 expression: ExpOrStr, 1349 dialect: DialectType = None, 1350 copy: bool = True, 1351 **opts, 1352 ) -> Delete: 1353 """ 1354 Set the RETURNING expression. Not supported by all dialects. 1355 1356 Example: 1357 >>> delete("tbl").returning("*", dialect="postgres").sql() 1358 'DELETE FROM tbl RETURNING *' 1359 1360 Args: 1361 expression: the SQL code strings to parse. 1362 If an `Expression` instance is passed, it will be used as-is. 1363 dialect: the dialect used to parse the input expressions. 1364 copy: if `False`, modify this expression instance in-place. 1365 opts: other options to use to parse the input expressions. 1366 1367 Returns: 1368 Delete: the modified expression. 1369 """ 1370 return _apply_builder( 1371 expression=expression, 1372 instance=self, 1373 arg="returning", 1374 prefix="RETURNING", 1375 dialect=dialect, 1376 copy=copy, 1377 into=Returning, 1378 **opts, 1379 )
1274 def delete( 1275 self, 1276 table: ExpOrStr, 1277 dialect: DialectType = None, 1278 copy: bool = True, 1279 **opts, 1280 ) -> Delete: 1281 """ 1282 Create a DELETE expression or replace the table on an existing DELETE expression. 1283 1284 Example: 1285 >>> delete("tbl").sql() 1286 'DELETE FROM tbl' 1287 1288 Args: 1289 table: the table from which to delete. 1290 dialect: the dialect used to parse the input expression. 1291 copy: if `False`, modify this expression instance in-place. 1292 opts: other options to use to parse the input expressions. 1293 1294 Returns: 1295 Delete: the modified expression. 1296 """ 1297 return _apply_builder( 1298 expression=table, 1299 instance=self, 1300 arg="this", 1301 dialect=dialect, 1302 into=Table, 1303 copy=copy, 1304 **opts, 1305 )
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.
1307 def where( 1308 self, 1309 *expressions: ExpOrStr, 1310 append: bool = True, 1311 dialect: DialectType = None, 1312 copy: bool = True, 1313 **opts, 1314 ) -> Delete: 1315 """ 1316 Append to or set the WHERE expressions. 1317 1318 Example: 1319 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1320 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1321 1322 Args: 1323 *expressions: the SQL code strings to parse. 1324 If an `Expression` instance is passed, it will be used as-is. 1325 Multiple expressions are combined with an AND operator. 1326 append: if `True`, AND the new expressions to any existing expression. 1327 Otherwise, this resets the expression. 1328 dialect: the dialect used to parse the input expressions. 1329 copy: if `False`, modify this expression instance in-place. 1330 opts: other options to use to parse the input expressions. 1331 1332 Returns: 1333 Delete: the modified expression. 1334 """ 1335 return _apply_conjunction_builder( 1336 *expressions, 1337 instance=self, 1338 arg="where", 1339 append=append, 1340 into=Where, 1341 dialect=dialect, 1342 copy=copy, 1343 **opts, 1344 )
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.
1346 def returning( 1347 self, 1348 expression: ExpOrStr, 1349 dialect: DialectType = None, 1350 copy: bool = True, 1351 **opts, 1352 ) -> Delete: 1353 """ 1354 Set the RETURNING expression. Not supported by all dialects. 1355 1356 Example: 1357 >>> delete("tbl").returning("*", dialect="postgres").sql() 1358 'DELETE FROM tbl RETURNING *' 1359 1360 Args: 1361 expression: the SQL code strings to parse. 1362 If an `Expression` instance is passed, it will be used as-is. 1363 dialect: the dialect used to parse the input expressions. 1364 copy: if `False`, modify this expression instance in-place. 1365 opts: other options to use to parse the input expressions. 1366 1367 Returns: 1368 Delete: the modified expression. 1369 """ 1370 return _apply_builder( 1371 expression=expression, 1372 instance=self, 1373 arg="returning", 1374 prefix="RETURNING", 1375 dialect=dialect, 1376 copy=copy, 1377 into=Returning, 1378 **opts, 1379 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1382class Drop(Expression): 1383 arg_types = { 1384 "this": False, 1385 "kind": False, 1386 "exists": False, 1387 "temporary": False, 1388 "materialized": False, 1389 "cascade": False, 1390 "constraints": False, 1391 "purge": False, 1392 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1403class Directory(Expression): 1404 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1405 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1408class ForeignKey(Expression): 1409 arg_types = { 1410 "expressions": True, 1411 "reference": False, 1412 "delete": False, 1413 "update": False, 1414 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1431class From(Expression): 1432 @property 1433 def name(self) -> str: 1434 return self.this.name 1435 1436 @property 1437 def alias_or_name(self) -> str: 1438 return self.this.alias_or_name
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1453class Identifier(Expression): 1454 arg_types = {"this": True, "quoted": False} 1455 1456 @property 1457 def quoted(self): 1458 return bool(self.args.get("quoted")) 1459 1460 @property 1461 def hashable_args(self) -> t.Any: 1462 if self.quoted and any(char.isupper() for char in self.this): 1463 return (self.this, self.quoted) 1464 return self.this.lower() 1465 1466 @property 1467 def output_name(self): 1468 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1471class Index(Expression): 1472 arg_types = { 1473 "this": False, 1474 "table": False, 1475 "where": False, 1476 "columns": False, 1477 "unique": False, 1478 "primary": False, 1479 "amp": False, # teradata 1480 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1483class Insert(Expression): 1484 arg_types = { 1485 "with": False, 1486 "this": True, 1487 "expression": False, 1488 "conflict": False, 1489 "returning": False, 1490 "overwrite": False, 1491 "exists": False, 1492 "partition": False, 1493 "alternative": False, 1494 } 1495 1496 def with_( 1497 self, 1498 alias: ExpOrStr, 1499 as_: ExpOrStr, 1500 recursive: t.Optional[bool] = None, 1501 append: bool = True, 1502 dialect: DialectType = None, 1503 copy: bool = True, 1504 **opts, 1505 ) -> Insert: 1506 """ 1507 Append to or set the common table expressions. 1508 1509 Example: 1510 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1511 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1512 1513 Args: 1514 alias: the SQL code string to parse as the table name. 1515 If an `Expression` instance is passed, this is used as-is. 1516 as_: the SQL code string to parse as the table expression. 1517 If an `Expression` instance is passed, it will be used as-is. 1518 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1519 append: if `True`, add to any existing expressions. 1520 Otherwise, this resets the expressions. 1521 dialect: the dialect used to parse the input expression. 1522 copy: if `False`, modify this expression instance in-place. 1523 opts: other options to use to parse the input expressions. 1524 1525 Returns: 1526 The modified expression. 1527 """ 1528 return _apply_cte_builder( 1529 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1530 )
1496 def with_( 1497 self, 1498 alias: ExpOrStr, 1499 as_: ExpOrStr, 1500 recursive: t.Optional[bool] = None, 1501 append: bool = True, 1502 dialect: DialectType = None, 1503 copy: bool = True, 1504 **opts, 1505 ) -> Insert: 1506 """ 1507 Append to or set the common table expressions. 1508 1509 Example: 1510 >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 1511 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte' 1512 1513 Args: 1514 alias: the SQL code string to parse as the table name. 1515 If an `Expression` instance is passed, this is used as-is. 1516 as_: the SQL code string to parse as the table expression. 1517 If an `Expression` instance is passed, it will be used as-is. 1518 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 1519 append: if `True`, add to any existing expressions. 1520 Otherwise, this resets the expressions. 1521 dialect: the dialect used to parse the input expression. 1522 copy: if `False`, modify this expression instance in-place. 1523 opts: other options to use to parse the input expressions. 1524 1525 Returns: 1526 The modified expression. 1527 """ 1528 return _apply_cte_builder( 1529 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 1530 )
Append to or set the common table expressions.
Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql() 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
- alias: the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_: the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive: set the RECURSIVE part of the expression. Defaults to
False
. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1533class OnConflict(Expression): 1534 arg_types = { 1535 "duplicate": False, 1536 "expressions": False, 1537 "nothing": False, 1538 "key": False, 1539 "constraint": False, 1540 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1557class LoadData(Expression): 1558 arg_types = { 1559 "this": True, 1560 "local": False, 1561 "overwrite": False, 1562 "inpath": True, 1563 "partition": False, 1564 "input_format": False, 1565 "serde": False, 1566 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1573class Fetch(Expression): 1574 arg_types = { 1575 "direction": False, 1576 "count": False, 1577 "percent": False, 1578 "with_ties": False, 1579 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1582class Group(Expression): 1583 arg_types = { 1584 "expressions": False, 1585 "grouping_sets": False, 1586 "cube": False, 1587 "rollup": False, 1588 "totals": False, 1589 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1600class Literal(Condition): 1601 arg_types = {"this": True, "is_string": True} 1602 1603 @property 1604 def hashable_args(self) -> t.Any: 1605 return (self.this, self.args.get("is_string")) 1606 1607 @classmethod 1608 def number(cls, number) -> Literal: 1609 return cls(this=str(number), is_string=False) 1610 1611 @classmethod 1612 def string(cls, string) -> Literal: 1613 return cls(this=str(string), is_string=True) 1614 1615 @property 1616 def output_name(self): 1617 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1620class Join(Expression): 1621 arg_types = { 1622 "this": True, 1623 "on": False, 1624 "side": False, 1625 "kind": False, 1626 "using": False, 1627 "natural": False, 1628 "global": False, 1629 "hint": False, 1630 } 1631 1632 @property 1633 def kind(self): 1634 return self.text("kind").upper() 1635 1636 @property 1637 def side(self): 1638 return self.text("side").upper() 1639 1640 @property 1641 def hint(self): 1642 return self.text("hint").upper() 1643 1644 @property 1645 def alias_or_name(self): 1646 return self.this.alias_or_name 1647 1648 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1649 """ 1650 Append to or set the ON expressions. 1651 1652 Example: 1653 >>> import sqlglot 1654 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1655 'JOIN x ON y = 1' 1656 1657 Args: 1658 *expressions (str | Expression): the SQL code strings to parse. 1659 If an `Expression` instance is passed, it will be used as-is. 1660 Multiple expressions are combined with an AND operator. 1661 append (bool): if `True`, AND the new expressions to any existing expression. 1662 Otherwise, this resets the expression. 1663 dialect (str): the dialect used to parse the input expressions. 1664 copy (bool): if `False`, modify this expression instance in-place. 1665 opts (kwargs): other options to use to parse the input expressions. 1666 1667 Returns: 1668 Join: the modified join expression. 1669 """ 1670 join = _apply_conjunction_builder( 1671 *expressions, 1672 instance=self, 1673 arg="on", 1674 append=append, 1675 dialect=dialect, 1676 copy=copy, 1677 **opts, 1678 ) 1679 1680 if join.kind == "CROSS": 1681 join.set("kind", None) 1682 1683 return join 1684 1685 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1686 """ 1687 Append to or set the USING expressions. 1688 1689 Example: 1690 >>> import sqlglot 1691 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1692 'JOIN x USING (foo, bla)' 1693 1694 Args: 1695 *expressions (str | Expression): the SQL code strings to parse. 1696 If an `Expression` instance is passed, it will be used as-is. 1697 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1698 Otherwise, this resets the expression. 1699 dialect (str): the dialect used to parse the input expressions. 1700 copy (bool): if `False`, modify this expression instance in-place. 1701 opts (kwargs): other options to use to parse the input expressions. 1702 1703 Returns: 1704 Join: the modified join expression. 1705 """ 1706 join = _apply_list_builder( 1707 *expressions, 1708 instance=self, 1709 arg="using", 1710 append=append, 1711 dialect=dialect, 1712 copy=copy, 1713 **opts, 1714 ) 1715 1716 if join.kind == "CROSS": 1717 join.set("kind", None) 1718 1719 return join
1648 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1649 """ 1650 Append to or set the ON expressions. 1651 1652 Example: 1653 >>> import sqlglot 1654 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1655 'JOIN x ON y = 1' 1656 1657 Args: 1658 *expressions (str | Expression): the SQL code strings to parse. 1659 If an `Expression` instance is passed, it will be used as-is. 1660 Multiple expressions are combined with an AND operator. 1661 append (bool): if `True`, AND the new expressions to any existing expression. 1662 Otherwise, this resets the expression. 1663 dialect (str): the dialect used to parse the input expressions. 1664 copy (bool): if `False`, modify this expression instance in-place. 1665 opts (kwargs): other options to use to parse the input expressions. 1666 1667 Returns: 1668 Join: the modified join expression. 1669 """ 1670 join = _apply_conjunction_builder( 1671 *expressions, 1672 instance=self, 1673 arg="on", 1674 append=append, 1675 dialect=dialect, 1676 copy=copy, 1677 **opts, 1678 ) 1679 1680 if join.kind == "CROSS": 1681 join.set("kind", None) 1682 1683 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.
1685 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1686 """ 1687 Append to or set the USING expressions. 1688 1689 Example: 1690 >>> import sqlglot 1691 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1692 'JOIN x USING (foo, bla)' 1693 1694 Args: 1695 *expressions (str | Expression): the SQL code strings to parse. 1696 If an `Expression` instance is passed, it will be used as-is. 1697 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1698 Otherwise, this resets the expression. 1699 dialect (str): the dialect used to parse the input expressions. 1700 copy (bool): if `False`, modify this expression instance in-place. 1701 opts (kwargs): other options to use to parse the input expressions. 1702 1703 Returns: 1704 Join: the modified join expression. 1705 """ 1706 join = _apply_list_builder( 1707 *expressions, 1708 instance=self, 1709 arg="using", 1710 append=append, 1711 dialect=dialect, 1712 copy=copy, 1713 **opts, 1714 ) 1715 1716 if join.kind == "CROSS": 1717 join.set("kind", None) 1718 1719 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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1722class Lateral(UDTF): 1723 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1726class MatchRecognize(Expression): 1727 arg_types = { 1728 "partition_by": False, 1729 "order": False, 1730 "measures": False, 1731 "rows": False, 1732 "after": False, 1733 "pattern": False, 1734 "define": False, 1735 "alias": False, 1736 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_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 AfterJournalProperty(Property): 1776 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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1787class BlockCompressionProperty(Property): 1788 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1803class DataBlocksizeProperty(Property): 1804 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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1843class InputOutputFormat(Expression): 1844 arg_types = {"input_format": False, "output_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1847class IsolatedLoadingProperty(Property): 1848 arg_types = { 1849 "no": True, 1850 "concurrent": True, 1851 "for_all": True, 1852 "for_insert": True, 1853 "for_none": True, 1854 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1873class LockingProperty(Property): 1874 arg_types = { 1875 "this": False, 1876 "kind": True, 1877 "for_or_in": True, 1878 "lock_type": True, 1879 "override": False, 1880 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1891class MergeBlockRatioProperty(Property): 1892 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1907class ReturnsProperty(Property): 1908 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1915class RowFormatDelimitedProperty(Property): 1916 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1917 arg_types = { 1918 "fields": False, 1919 "escaped": False, 1920 "collection_items": False, 1921 "map_keys": False, 1922 "lines": False, 1923 "null": False, 1924 "serde": False, 1925 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1980class Properties(Expression): 1981 arg_types = {"expressions": True} 1982 1983 NAME_TO_PROPERTY = { 1984 "ALGORITHM": AlgorithmProperty, 1985 "AUTO_INCREMENT": AutoIncrementProperty, 1986 "CHARACTER SET": CharacterSetProperty, 1987 "COLLATE": CollateProperty, 1988 "COMMENT": SchemaCommentProperty, 1989 "DEFINER": DefinerProperty, 1990 "DISTKEY": DistKeyProperty, 1991 "DISTSTYLE": DistStyleProperty, 1992 "ENGINE": EngineProperty, 1993 "EXECUTE AS": ExecuteAsProperty, 1994 "FORMAT": FileFormatProperty, 1995 "LANGUAGE": LanguageProperty, 1996 "LOCATION": LocationProperty, 1997 "PARTITIONED_BY": PartitionedByProperty, 1998 "RETURNS": ReturnsProperty, 1999 "ROW_FORMAT": RowFormatProperty, 2000 "SORTKEY": SortKeyProperty, 2001 } 2002 2003 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 2004 2005 # CREATE property locations 2006 # Form: schema specified 2007 # create [POST_CREATE] 2008 # table a [POST_NAME] 2009 # (b int) [POST_SCHEMA] 2010 # with ([POST_WITH]) 2011 # index (b) [POST_INDEX] 2012 # 2013 # Form: alias selection 2014 # create [POST_CREATE] 2015 # table a [POST_NAME] 2016 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 2017 # index (c) [POST_INDEX] 2018 class Location(AutoName): 2019 POST_CREATE = auto() 2020 POST_NAME = auto() 2021 POST_SCHEMA = auto() 2022 POST_WITH = auto() 2023 POST_ALIAS = auto() 2024 POST_EXPRESSION = auto() 2025 POST_INDEX = auto() 2026 UNSUPPORTED = auto() 2027 2028 @classmethod 2029 def from_dict(cls, properties_dict) -> Properties: 2030 expressions = [] 2031 for key, value in properties_dict.items(): 2032 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2033 if property_cls: 2034 expressions.append(property_cls(this=convert(value))) 2035 else: 2036 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2037 2038 return cls(expressions=expressions)
2028 @classmethod 2029 def from_dict(cls, properties_dict) -> Properties: 2030 expressions = [] 2031 for key, value in properties_dict.items(): 2032 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 2033 if property_cls: 2034 expressions.append(property_cls(this=convert(value))) 2035 else: 2036 expressions.append(Property(this=Literal.string(key), value=convert(value))) 2037 2038 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2018 class Location(AutoName): 2019 POST_CREATE = auto() 2020 POST_NAME = auto() 2021 POST_SCHEMA = auto() 2022 POST_WITH = auto() 2023 POST_ALIAS = auto() 2024 POST_EXPRESSION = auto() 2025 POST_INDEX = auto() 2026 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2050class Reference(Expression): 2051 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2054class Tuple(Expression): 2055 arg_types = {"expressions": False} 2056 2057 def isin( 2058 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts 2059 ) -> In: 2060 return In( 2061 this=_maybe_copy(self, copy), 2062 expressions=[convert(e, copy=copy) for e in expressions], 2063 query=maybe_parse(query, copy=copy, **opts) if query else None, 2064 )
2057 def isin( 2058 self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts 2059 ) -> In: 2060 return In( 2061 this=_maybe_copy(self, copy), 2062 expressions=[convert(e, copy=copy) for e in expressions], 2063 query=maybe_parse(query, copy=copy, **opts) if query else None, 2064 )
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2067class Subqueryable(Unionable): 2068 def subquery(self, alias=None, copy=True) -> Subquery: 2069 """ 2070 Convert this expression to an aliased expression that can be used as a Subquery. 2071 2072 Example: 2073 >>> subquery = Select().select("x").from_("tbl").subquery() 2074 >>> Select().select("x").from_(subquery).sql() 2075 'SELECT x FROM (SELECT x FROM tbl)' 2076 2077 Args: 2078 alias (str | Identifier): an optional alias for the subquery 2079 copy (bool): if `False`, modify this expression instance in-place. 2080 2081 Returns: 2082 Alias: the subquery 2083 """ 2084 instance = _maybe_copy(self, copy) 2085 if not isinstance(alias, Expression): 2086 alias = TableAlias(this=to_identifier(alias)) if alias else None 2087 2088 return Subquery(this=instance, alias=alias) 2089 2090 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2091 raise NotImplementedError 2092 2093 @property 2094 def ctes(self): 2095 with_ = self.args.get("with") 2096 if not with_: 2097 return [] 2098 return with_.expressions 2099 2100 @property 2101 def selects(self): 2102 raise NotImplementedError("Subqueryable objects must implement `selects`") 2103 2104 @property 2105 def named_selects(self): 2106 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 2107 2108 def with_( 2109 self, 2110 alias: ExpOrStr, 2111 as_: ExpOrStr, 2112 recursive: t.Optional[bool] = None, 2113 append: bool = True, 2114 dialect: DialectType = None, 2115 copy: bool = True, 2116 **opts, 2117 ) -> Subqueryable: 2118 """ 2119 Append to or set the common table expressions. 2120 2121 Example: 2122 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2123 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2124 2125 Args: 2126 alias: the SQL code string to parse as the table name. 2127 If an `Expression` instance is passed, this is used as-is. 2128 as_: the SQL code string to parse as the table expression. 2129 If an `Expression` instance is passed, it will be used as-is. 2130 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2131 append: if `True`, add to any existing expressions. 2132 Otherwise, this resets the expressions. 2133 dialect: the dialect used to parse the input expression. 2134 copy: if `False`, modify this expression instance in-place. 2135 opts: other options to use to parse the input expressions. 2136 2137 Returns: 2138 The modified expression. 2139 """ 2140 return _apply_cte_builder( 2141 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2142 )
2068 def subquery(self, alias=None, copy=True) -> Subquery: 2069 """ 2070 Convert this expression to an aliased expression that can be used as a Subquery. 2071 2072 Example: 2073 >>> subquery = Select().select("x").from_("tbl").subquery() 2074 >>> Select().select("x").from_(subquery).sql() 2075 'SELECT x FROM (SELECT x FROM tbl)' 2076 2077 Args: 2078 alias (str | Identifier): an optional alias for the subquery 2079 copy (bool): if `False`, modify this expression instance in-place. 2080 2081 Returns: 2082 Alias: the subquery 2083 """ 2084 instance = _maybe_copy(self, copy) 2085 if not isinstance(alias, Expression): 2086 alias = TableAlias(this=to_identifier(alias)) if alias else None 2087 2088 return Subquery(this=instance, alias=alias)
Convert this expression to an aliased expression that can be used as a Subquery.
Example:
>>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
- alias (str | Identifier): an optional alias for the subquery
- copy (bool): if
False
, modify this expression instance in-place.
Returns:
Alias: the subquery
2108 def with_( 2109 self, 2110 alias: ExpOrStr, 2111 as_: ExpOrStr, 2112 recursive: t.Optional[bool] = None, 2113 append: bool = True, 2114 dialect: DialectType = None, 2115 copy: bool = True, 2116 **opts, 2117 ) -> Subqueryable: 2118 """ 2119 Append to or set the common table expressions. 2120 2121 Example: 2122 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 2123 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 2124 2125 Args: 2126 alias: the SQL code string to parse as the table name. 2127 If an `Expression` instance is passed, this is used as-is. 2128 as_: the SQL code string to parse as the table expression. 2129 If an `Expression` instance is passed, it will be used as-is. 2130 recursive: set the RECURSIVE part of the expression. Defaults to `False`. 2131 append: if `True`, add to any existing expressions. 2132 Otherwise, this resets the expressions. 2133 dialect: the dialect used to parse the input expression. 2134 copy: if `False`, modify this expression instance in-place. 2135 opts: other options to use to parse the input expressions. 2136 2137 Returns: 2138 The modified expression. 2139 """ 2140 return _apply_cte_builder( 2141 self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts 2142 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias: the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_: the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive: set the RECURSIVE part of the expression. Defaults to
False
. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2168class Table(Expression): 2169 arg_types = { 2170 "this": True, 2171 "alias": False, 2172 "db": False, 2173 "catalog": False, 2174 "laterals": False, 2175 "joins": False, 2176 "pivots": False, 2177 "hints": False, 2178 "system_time": False, 2179 } 2180 2181 @property 2182 def db(self) -> str: 2183 return self.text("db") 2184 2185 @property 2186 def catalog(self) -> str: 2187 return self.text("catalog") 2188 2189 @property 2190 def parts(self) -> t.List[Identifier]: 2191 """Return the parts of a column in order catalog, db, table.""" 2192 return [ 2193 t.cast(Identifier, self.args[part]) 2194 for part in ("catalog", "db", "this") 2195 if self.args.get(part) 2196 ]
Return the parts of a column in order catalog, db, table.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2200class SystemTime(Expression): 2201 arg_types = { 2202 "this": False, 2203 "expression": False, 2204 "kind": True, 2205 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2208class Union(Subqueryable): 2209 arg_types = { 2210 "with": False, 2211 "this": True, 2212 "expression": True, 2213 "distinct": False, 2214 **QUERY_MODIFIERS, 2215 } 2216 2217 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2218 """ 2219 Set the LIMIT expression. 2220 2221 Example: 2222 >>> select("1").union(select("1")).limit(1).sql() 2223 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2224 2225 Args: 2226 expression (str | int | Expression): the SQL code string to parse. 2227 This can also be an integer. 2228 If a `Limit` instance is passed, this is used as-is. 2229 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2230 dialect (str): the dialect used to parse the input expression. 2231 copy (bool): if `False`, modify this expression instance in-place. 2232 opts (kwargs): other options to use to parse the input expressions. 2233 2234 Returns: 2235 Select: The limited subqueryable. 2236 """ 2237 return ( 2238 select("*") 2239 .from_(self.subquery(alias="_l_0", copy=copy)) 2240 .limit(expression, dialect=dialect, copy=False, **opts) 2241 ) 2242 2243 def select( 2244 self, 2245 *expressions: ExpOrStr, 2246 append: bool = True, 2247 dialect: DialectType = None, 2248 copy: bool = True, 2249 **opts, 2250 ) -> Union: 2251 """Append to or set the SELECT of the union recursively. 2252 2253 Example: 2254 >>> from sqlglot import parse_one 2255 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2256 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2257 2258 Args: 2259 *expressions: the SQL code strings to parse. 2260 If an `Expression` instance is passed, it will be used as-is. 2261 append: if `True`, add to any existing expressions. 2262 Otherwise, this resets the expressions. 2263 dialect: the dialect used to parse the input expressions. 2264 copy: if `False`, modify this expression instance in-place. 2265 opts: other options to use to parse the input expressions. 2266 2267 Returns: 2268 Union: the modified expression. 2269 """ 2270 this = self.copy() if copy else self 2271 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2272 this.expression.unnest().select( 2273 *expressions, append=append, dialect=dialect, copy=False, **opts 2274 ) 2275 return this 2276 2277 @property 2278 def named_selects(self): 2279 return self.this.unnest().named_selects 2280 2281 @property 2282 def is_star(self) -> bool: 2283 return self.this.is_star or self.expression.is_star 2284 2285 @property 2286 def selects(self): 2287 return self.this.unnest().selects 2288 2289 @property 2290 def left(self): 2291 return self.this 2292 2293 @property 2294 def right(self): 2295 return self.expression
2217 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2218 """ 2219 Set the LIMIT expression. 2220 2221 Example: 2222 >>> select("1").union(select("1")).limit(1).sql() 2223 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2224 2225 Args: 2226 expression (str | int | Expression): the SQL code string to parse. 2227 This can also be an integer. 2228 If a `Limit` instance is passed, this is used as-is. 2229 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2230 dialect (str): the dialect used to parse the input expression. 2231 copy (bool): if `False`, modify this expression instance in-place. 2232 opts (kwargs): other options to use to parse the input expressions. 2233 2234 Returns: 2235 Select: The limited subqueryable. 2236 """ 2237 return ( 2238 select("*") 2239 .from_(self.subquery(alias="_l_0", copy=copy)) 2240 .limit(expression, dialect=dialect, copy=False, **opts) 2241 )
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.
2243 def select( 2244 self, 2245 *expressions: ExpOrStr, 2246 append: bool = True, 2247 dialect: DialectType = None, 2248 copy: bool = True, 2249 **opts, 2250 ) -> Union: 2251 """Append to or set the SELECT of the union recursively. 2252 2253 Example: 2254 >>> from sqlglot import parse_one 2255 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2256 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2257 2258 Args: 2259 *expressions: the SQL code strings to parse. 2260 If an `Expression` instance is passed, it will be used as-is. 2261 append: if `True`, add to any existing expressions. 2262 Otherwise, this resets the expressions. 2263 dialect: the dialect used to parse the input expressions. 2264 copy: if `False`, modify this expression instance in-place. 2265 opts: other options to use to parse the input expressions. 2266 2267 Returns: 2268 Union: the modified expression. 2269 """ 2270 this = self.copy() if copy else self 2271 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2272 this.expression.unnest().select( 2273 *expressions, append=append, dialect=dialect, copy=False, **opts 2274 ) 2275 return this
Append to or set the SELECT of the union recursively.
Example:
>>> from sqlglot import parse_one >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - append: if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Union: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2306class Unnest(UDTF): 2307 arg_types = { 2308 "expressions": True, 2309 "ordinality": False, 2310 "alias": False, 2311 "offset": False, 2312 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2315class Update(Expression): 2316 arg_types = { 2317 "with": False, 2318 "this": False, 2319 "expressions": True, 2320 "from": False, 2321 "where": False, 2322 "returning": False, 2323 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2326class Values(UDTF): 2327 arg_types = { 2328 "expressions": True, 2329 "ordinality": False, 2330 "alias": False, 2331 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2348class Select(Subqueryable): 2349 arg_types = { 2350 "with": False, 2351 "kind": False, 2352 "expressions": False, 2353 "hint": False, 2354 "distinct": False, 2355 "struct": False, # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table 2356 "value": False, 2357 "into": False, 2358 "from": False, 2359 **QUERY_MODIFIERS, 2360 } 2361 2362 def from_( 2363 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2364 ) -> Select: 2365 """ 2366 Set the FROM expression. 2367 2368 Example: 2369 >>> Select().from_("tbl").select("x").sql() 2370 'SELECT x FROM tbl' 2371 2372 Args: 2373 expression : the SQL code strings to parse. 2374 If a `From` instance is passed, this is used as-is. 2375 If another `Expression` instance is passed, it will be wrapped in a `From`. 2376 dialect: the dialect used to parse the input expression. 2377 copy: if `False`, modify this expression instance in-place. 2378 opts: other options to use to parse the input expressions. 2379 2380 Returns: 2381 Select: the modified expression. 2382 """ 2383 return _apply_builder( 2384 expression=expression, 2385 instance=self, 2386 arg="from", 2387 into=From, 2388 prefix="FROM", 2389 dialect=dialect, 2390 copy=copy, 2391 **opts, 2392 ) 2393 2394 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2395 """ 2396 Set the GROUP BY expression. 2397 2398 Example: 2399 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2400 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2401 2402 Args: 2403 *expressions (str | Expression): the SQL code strings to parse. 2404 If a `Group` instance is passed, this is used as-is. 2405 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2406 If nothing is passed in then a group by is not applied to the expression 2407 append (bool): if `True`, add to any existing expressions. 2408 Otherwise, this flattens all the `Group` expression into a single expression. 2409 dialect (str): the dialect used to parse the input expression. 2410 copy (bool): if `False`, modify this expression instance in-place. 2411 opts (kwargs): other options to use to parse the input expressions. 2412 2413 Returns: 2414 Select: the modified expression. 2415 """ 2416 if not expressions: 2417 return self if not copy else self.copy() 2418 return _apply_child_list_builder( 2419 *expressions, 2420 instance=self, 2421 arg="group", 2422 append=append, 2423 copy=copy, 2424 prefix="GROUP BY", 2425 into=Group, 2426 dialect=dialect, 2427 **opts, 2428 ) 2429 2430 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2431 """ 2432 Set the ORDER BY expression. 2433 2434 Example: 2435 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2436 'SELECT x FROM tbl ORDER BY x DESC' 2437 2438 Args: 2439 *expressions (str | Expression): the SQL code strings to parse. 2440 If a `Group` instance is passed, this is used as-is. 2441 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2442 append (bool): if `True`, add to any existing expressions. 2443 Otherwise, this flattens all the `Order` expression into a single expression. 2444 dialect (str): the dialect used to parse the input expression. 2445 copy (bool): if `False`, modify this expression instance in-place. 2446 opts (kwargs): other options to use to parse the input expressions. 2447 2448 Returns: 2449 Select: the modified expression. 2450 """ 2451 return _apply_child_list_builder( 2452 *expressions, 2453 instance=self, 2454 arg="order", 2455 append=append, 2456 copy=copy, 2457 prefix="ORDER BY", 2458 into=Order, 2459 dialect=dialect, 2460 **opts, 2461 ) 2462 2463 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2464 """ 2465 Set the SORT BY expression. 2466 2467 Example: 2468 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2469 'SELECT x FROM tbl SORT BY x DESC' 2470 2471 Args: 2472 *expressions (str | Expression): the SQL code strings to parse. 2473 If a `Group` instance is passed, this is used as-is. 2474 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2475 append (bool): if `True`, add to any existing expressions. 2476 Otherwise, this flattens all the `Order` expression into a single expression. 2477 dialect (str): the dialect used to parse the input expression. 2478 copy (bool): if `False`, modify this expression instance in-place. 2479 opts (kwargs): other options to use to parse the input expressions. 2480 2481 Returns: 2482 Select: the modified expression. 2483 """ 2484 return _apply_child_list_builder( 2485 *expressions, 2486 instance=self, 2487 arg="sort", 2488 append=append, 2489 copy=copy, 2490 prefix="SORT BY", 2491 into=Sort, 2492 dialect=dialect, 2493 **opts, 2494 ) 2495 2496 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2497 """ 2498 Set the CLUSTER BY expression. 2499 2500 Example: 2501 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2502 'SELECT x FROM tbl CLUSTER BY x DESC' 2503 2504 Args: 2505 *expressions (str | Expression): the SQL code strings to parse. 2506 If a `Group` instance is passed, this is used as-is. 2507 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2508 append (bool): if `True`, add to any existing expressions. 2509 Otherwise, this flattens all the `Order` expression into a single expression. 2510 dialect (str): the dialect used to parse the input expression. 2511 copy (bool): if `False`, modify this expression instance in-place. 2512 opts (kwargs): other options to use to parse the input expressions. 2513 2514 Returns: 2515 Select: the modified expression. 2516 """ 2517 return _apply_child_list_builder( 2518 *expressions, 2519 instance=self, 2520 arg="cluster", 2521 append=append, 2522 copy=copy, 2523 prefix="CLUSTER BY", 2524 into=Cluster, 2525 dialect=dialect, 2526 **opts, 2527 ) 2528 2529 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2530 """ 2531 Set the LIMIT expression. 2532 2533 Example: 2534 >>> Select().from_("tbl").select("x").limit(10).sql() 2535 'SELECT x FROM tbl LIMIT 10' 2536 2537 Args: 2538 expression (str | int | Expression): the SQL code string to parse. 2539 This can also be an integer. 2540 If a `Limit` instance is passed, this is used as-is. 2541 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2542 dialect (str): the dialect used to parse the input expression. 2543 copy (bool): if `False`, modify this expression instance in-place. 2544 opts (kwargs): other options to use to parse the input expressions. 2545 2546 Returns: 2547 Select: the modified expression. 2548 """ 2549 return _apply_builder( 2550 expression=expression, 2551 instance=self, 2552 arg="limit", 2553 into=Limit, 2554 prefix="LIMIT", 2555 dialect=dialect, 2556 copy=copy, 2557 **opts, 2558 ) 2559 2560 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2561 """ 2562 Set the OFFSET expression. 2563 2564 Example: 2565 >>> Select().from_("tbl").select("x").offset(10).sql() 2566 'SELECT x FROM tbl OFFSET 10' 2567 2568 Args: 2569 expression (str | int | Expression): the SQL code string to parse. 2570 This can also be an integer. 2571 If a `Offset` instance is passed, this is used as-is. 2572 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2573 dialect (str): the dialect used to parse the input expression. 2574 copy (bool): if `False`, modify this expression instance in-place. 2575 opts (kwargs): other options to use to parse the input expressions. 2576 2577 Returns: 2578 Select: the modified expression. 2579 """ 2580 return _apply_builder( 2581 expression=expression, 2582 instance=self, 2583 arg="offset", 2584 into=Offset, 2585 prefix="OFFSET", 2586 dialect=dialect, 2587 copy=copy, 2588 **opts, 2589 ) 2590 2591 def select( 2592 self, 2593 *expressions: ExpOrStr, 2594 append: bool = True, 2595 dialect: DialectType = None, 2596 copy: bool = True, 2597 **opts, 2598 ) -> Select: 2599 """ 2600 Append to or set the SELECT expressions. 2601 2602 Example: 2603 >>> Select().select("x", "y").sql() 2604 'SELECT x, y' 2605 2606 Args: 2607 *expressions: the SQL code strings to parse. 2608 If an `Expression` instance is passed, it will be used as-is. 2609 append: if `True`, add to any existing expressions. 2610 Otherwise, this resets the expressions. 2611 dialect: the dialect used to parse the input expressions. 2612 copy: if `False`, modify this expression instance in-place. 2613 opts: other options to use to parse the input expressions. 2614 2615 Returns: 2616 Select: the modified expression. 2617 """ 2618 return _apply_list_builder( 2619 *expressions, 2620 instance=self, 2621 arg="expressions", 2622 append=append, 2623 dialect=dialect, 2624 copy=copy, 2625 **opts, 2626 ) 2627 2628 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2629 """ 2630 Append to or set the LATERAL expressions. 2631 2632 Example: 2633 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2634 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2635 2636 Args: 2637 *expressions (str | Expression): the SQL code strings to parse. 2638 If an `Expression` instance is passed, it will be used as-is. 2639 append (bool): if `True`, add to any existing expressions. 2640 Otherwise, this resets the expressions. 2641 dialect (str): the dialect used to parse the input expressions. 2642 copy (bool): if `False`, modify this expression instance in-place. 2643 opts (kwargs): other options to use to parse the input expressions. 2644 2645 Returns: 2646 Select: the modified expression. 2647 """ 2648 return _apply_list_builder( 2649 *expressions, 2650 instance=self, 2651 arg="laterals", 2652 append=append, 2653 into=Lateral, 2654 prefix="LATERAL VIEW", 2655 dialect=dialect, 2656 copy=copy, 2657 **opts, 2658 ) 2659 2660 def join( 2661 self, 2662 expression, 2663 on=None, 2664 using=None, 2665 append=True, 2666 join_type=None, 2667 join_alias=None, 2668 dialect=None, 2669 copy=True, 2670 **opts, 2671 ) -> Select: 2672 """ 2673 Append to or set the JOIN expressions. 2674 2675 Example: 2676 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2677 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2678 2679 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2680 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2681 2682 Use `join_type` to change the type of join: 2683 2684 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2685 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2686 2687 Args: 2688 expression (str | Expression): the SQL code string to parse. 2689 If an `Expression` instance is passed, it will be used as-is. 2690 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2691 If an `Expression` instance is passed, it will be used as-is. 2692 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2693 If an `Expression` instance is passed, it will be used as-is. 2694 append (bool): if `True`, add to any existing expressions. 2695 Otherwise, this resets the expressions. 2696 join_type (str): If set, alter the parsed join type 2697 dialect (str): the dialect used to parse the input expressions. 2698 copy (bool): if `False`, modify this expression instance in-place. 2699 opts (kwargs): other options to use to parse the input expressions. 2700 2701 Returns: 2702 Select: the modified expression. 2703 """ 2704 parse_args = {"dialect": dialect, **opts} 2705 2706 try: 2707 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2708 except ParseError: 2709 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2710 2711 join = expression if isinstance(expression, Join) else Join(this=expression) 2712 2713 if isinstance(join.this, Select): 2714 join.this.replace(join.this.subquery()) 2715 2716 if join_type: 2717 natural: t.Optional[Token] 2718 side: t.Optional[Token] 2719 kind: t.Optional[Token] 2720 2721 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2722 2723 if natural: 2724 join.set("natural", True) 2725 if side: 2726 join.set("side", side.text) 2727 if kind: 2728 join.set("kind", kind.text) 2729 2730 if on: 2731 on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts) 2732 join.set("on", on) 2733 2734 if using: 2735 join = _apply_list_builder( 2736 *ensure_collection(using), 2737 instance=join, 2738 arg="using", 2739 append=append, 2740 copy=copy, 2741 **opts, 2742 ) 2743 2744 if join_alias: 2745 join.set("this", alias_(join.this, join_alias, table=True)) 2746 return _apply_list_builder( 2747 join, 2748 instance=self, 2749 arg="joins", 2750 append=append, 2751 copy=copy, 2752 **opts, 2753 ) 2754 2755 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2756 """ 2757 Append to or set the WHERE expressions. 2758 2759 Example: 2760 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2761 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2762 2763 Args: 2764 *expressions (str | Expression): the SQL code strings to parse. 2765 If an `Expression` instance is passed, it will be used as-is. 2766 Multiple expressions are combined with an AND operator. 2767 append (bool): if `True`, AND the new expressions to any existing expression. 2768 Otherwise, this resets the expression. 2769 dialect (str): the dialect used to parse the input expressions. 2770 copy (bool): if `False`, modify this expression instance in-place. 2771 opts (kwargs): other options to use to parse the input expressions. 2772 2773 Returns: 2774 Select: the modified expression. 2775 """ 2776 return _apply_conjunction_builder( 2777 *expressions, 2778 instance=self, 2779 arg="where", 2780 append=append, 2781 into=Where, 2782 dialect=dialect, 2783 copy=copy, 2784 **opts, 2785 ) 2786 2787 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2788 """ 2789 Append to or set the HAVING expressions. 2790 2791 Example: 2792 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2793 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2794 2795 Args: 2796 *expressions (str | Expression): the SQL code strings to parse. 2797 If an `Expression` instance is passed, it will be used as-is. 2798 Multiple expressions are combined with an AND operator. 2799 append (bool): if `True`, AND the new expressions to any existing expression. 2800 Otherwise, this resets the expression. 2801 dialect (str): the dialect used to parse the input expressions. 2802 copy (bool): if `False`, modify this expression instance in-place. 2803 opts (kwargs): other options to use to parse the input expressions. 2804 2805 Returns: 2806 Select: the modified expression. 2807 """ 2808 return _apply_conjunction_builder( 2809 *expressions, 2810 instance=self, 2811 arg="having", 2812 append=append, 2813 into=Having, 2814 dialect=dialect, 2815 copy=copy, 2816 **opts, 2817 ) 2818 2819 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2820 return _apply_list_builder( 2821 *expressions, 2822 instance=self, 2823 arg="windows", 2824 append=append, 2825 into=Window, 2826 dialect=dialect, 2827 copy=copy, 2828 **opts, 2829 ) 2830 2831 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2832 return _apply_conjunction_builder( 2833 *expressions, 2834 instance=self, 2835 arg="qualify", 2836 append=append, 2837 into=Qualify, 2838 dialect=dialect, 2839 copy=copy, 2840 **opts, 2841 ) 2842 2843 def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select: 2844 """ 2845 Set the OFFSET expression. 2846 2847 Example: 2848 >>> Select().from_("tbl").select("x").distinct().sql() 2849 'SELECT DISTINCT x FROM tbl' 2850 2851 Args: 2852 ons: the expressions to distinct on 2853 distinct: whether the Select should be distinct 2854 copy: if `False`, modify this expression instance in-place. 2855 2856 Returns: 2857 Select: the modified expression. 2858 """ 2859 instance = _maybe_copy(self, copy) 2860 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None 2861 instance.set("distinct", Distinct(on=on) if distinct else None) 2862 return instance 2863 2864 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2865 """ 2866 Convert this expression to a CREATE TABLE AS statement. 2867 2868 Example: 2869 >>> Select().select("*").from_("tbl").ctas("x").sql() 2870 'CREATE TABLE x AS SELECT * FROM tbl' 2871 2872 Args: 2873 table (str | Expression): the SQL code string to parse as the table name. 2874 If another `Expression` instance is passed, it will be used as-is. 2875 properties (dict): an optional mapping of table properties 2876 dialect (str): the dialect used to parse the input table. 2877 copy (bool): if `False`, modify this expression instance in-place. 2878 opts (kwargs): other options to use to parse the input table. 2879 2880 Returns: 2881 Create: the CREATE TABLE AS expression 2882 """ 2883 instance = _maybe_copy(self, copy) 2884 table_expression = maybe_parse( 2885 table, 2886 into=Table, 2887 dialect=dialect, 2888 **opts, 2889 ) 2890 properties_expression = None 2891 if properties: 2892 properties_expression = Properties.from_dict(properties) 2893 2894 return Create( 2895 this=table_expression, 2896 kind="table", 2897 expression=instance, 2898 properties=properties_expression, 2899 ) 2900 2901 def lock(self, update: bool = True, copy: bool = True) -> Select: 2902 """ 2903 Set the locking read mode for this expression. 2904 2905 Examples: 2906 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2907 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2908 2909 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2910 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2911 2912 Args: 2913 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2914 copy: if `False`, modify this expression instance in-place. 2915 2916 Returns: 2917 The modified expression. 2918 """ 2919 2920 inst = _maybe_copy(self, copy) 2921 inst.set("locks", [Lock(update=update)]) 2922 2923 return inst 2924 2925 @property 2926 def named_selects(self) -> t.List[str]: 2927 return [e.output_name for e in self.expressions if e.alias_or_name] 2928 2929 @property 2930 def is_star(self) -> bool: 2931 return any(expression.is_star for expression in self.expressions) 2932 2933 @property 2934 def selects(self) -> t.List[Expression]: 2935 return self.expressions
2362 def from_( 2363 self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts 2364 ) -> Select: 2365 """ 2366 Set the FROM expression. 2367 2368 Example: 2369 >>> Select().from_("tbl").select("x").sql() 2370 'SELECT x FROM tbl' 2371 2372 Args: 2373 expression : the SQL code strings to parse. 2374 If a `From` instance is passed, this is used as-is. 2375 If another `Expression` instance is passed, it will be wrapped in a `From`. 2376 dialect: the dialect used to parse the input expression. 2377 copy: if `False`, modify this expression instance in-place. 2378 opts: other options to use to parse the input expressions. 2379 2380 Returns: 2381 Select: the modified expression. 2382 """ 2383 return _apply_builder( 2384 expression=expression, 2385 instance=self, 2386 arg="from", 2387 into=From, 2388 prefix="FROM", 2389 dialect=dialect, 2390 copy=copy, 2391 **opts, 2392 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- expression : the SQL code strings to parse.
If a
From
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aFrom
. - dialect: the dialect used to parse the input expression.
- copy: if
False
, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2394 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2395 """ 2396 Set the GROUP BY expression. 2397 2398 Example: 2399 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2400 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2401 2402 Args: 2403 *expressions (str | Expression): the SQL code strings to parse. 2404 If a `Group` instance is passed, this is used as-is. 2405 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2406 If nothing is passed in then a group by is not applied to the expression 2407 append (bool): if `True`, add to any existing expressions. 2408 Otherwise, this flattens all the `Group` expression into a single expression. 2409 dialect (str): the dialect used to parse the input expression. 2410 copy (bool): if `False`, modify this expression instance in-place. 2411 opts (kwargs): other options to use to parse the input expressions. 2412 2413 Returns: 2414 Select: the modified expression. 2415 """ 2416 if not expressions: 2417 return self if not copy else self.copy() 2418 return _apply_child_list_builder( 2419 *expressions, 2420 instance=self, 2421 arg="group", 2422 append=append, 2423 copy=copy, 2424 prefix="GROUP BY", 2425 into=Group, 2426 dialect=dialect, 2427 **opts, 2428 )
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.
2430 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2431 """ 2432 Set the ORDER BY expression. 2433 2434 Example: 2435 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2436 'SELECT x FROM tbl ORDER BY x DESC' 2437 2438 Args: 2439 *expressions (str | Expression): the SQL code strings to parse. 2440 If a `Group` instance is passed, this is used as-is. 2441 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2442 append (bool): if `True`, add to any existing expressions. 2443 Otherwise, this flattens all the `Order` expression into a single expression. 2444 dialect (str): the dialect used to parse the input expression. 2445 copy (bool): if `False`, modify this expression instance in-place. 2446 opts (kwargs): other options to use to parse the input expressions. 2447 2448 Returns: 2449 Select: the modified expression. 2450 """ 2451 return _apply_child_list_builder( 2452 *expressions, 2453 instance=self, 2454 arg="order", 2455 append=append, 2456 copy=copy, 2457 prefix="ORDER BY", 2458 into=Order, 2459 dialect=dialect, 2460 **opts, 2461 )
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.
2463 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2464 """ 2465 Set the SORT BY expression. 2466 2467 Example: 2468 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 2469 'SELECT x FROM tbl SORT BY x DESC' 2470 2471 Args: 2472 *expressions (str | Expression): the SQL code strings to parse. 2473 If a `Group` instance is passed, this is used as-is. 2474 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2475 append (bool): if `True`, add to any existing expressions. 2476 Otherwise, this flattens all the `Order` expression into a single expression. 2477 dialect (str): the dialect used to parse the input expression. 2478 copy (bool): if `False`, modify this expression instance in-place. 2479 opts (kwargs): other options to use to parse the input expressions. 2480 2481 Returns: 2482 Select: the modified expression. 2483 """ 2484 return _apply_child_list_builder( 2485 *expressions, 2486 instance=self, 2487 arg="sort", 2488 append=append, 2489 copy=copy, 2490 prefix="SORT BY", 2491 into=Sort, 2492 dialect=dialect, 2493 **opts, 2494 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (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.
2496 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2497 """ 2498 Set the CLUSTER BY expression. 2499 2500 Example: 2501 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 2502 'SELECT x FROM tbl CLUSTER BY x DESC' 2503 2504 Args: 2505 *expressions (str | Expression): the SQL code strings to parse. 2506 If a `Group` instance is passed, this is used as-is. 2507 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2508 append (bool): if `True`, add to any existing expressions. 2509 Otherwise, this flattens all the `Order` expression into a single expression. 2510 dialect (str): the dialect used to parse the input expression. 2511 copy (bool): if `False`, modify this expression instance in-place. 2512 opts (kwargs): other options to use to parse the input expressions. 2513 2514 Returns: 2515 Select: the modified expression. 2516 """ 2517 return _apply_child_list_builder( 2518 *expressions, 2519 instance=self, 2520 arg="cluster", 2521 append=append, 2522 copy=copy, 2523 prefix="CLUSTER BY", 2524 into=Cluster, 2525 dialect=dialect, 2526 **opts, 2527 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive") 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (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.
2529 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2530 """ 2531 Set the LIMIT expression. 2532 2533 Example: 2534 >>> Select().from_("tbl").select("x").limit(10).sql() 2535 'SELECT x FROM tbl LIMIT 10' 2536 2537 Args: 2538 expression (str | int | Expression): the SQL code string to parse. 2539 This can also be an integer. 2540 If a `Limit` instance is passed, this is used as-is. 2541 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2542 dialect (str): the dialect used to parse the input expression. 2543 copy (bool): if `False`, modify this expression instance in-place. 2544 opts (kwargs): other options to use to parse the input expressions. 2545 2546 Returns: 2547 Select: the modified expression. 2548 """ 2549 return _apply_builder( 2550 expression=expression, 2551 instance=self, 2552 arg="limit", 2553 into=Limit, 2554 prefix="LIMIT", 2555 dialect=dialect, 2556 copy=copy, 2557 **opts, 2558 )
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.
2560 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2561 """ 2562 Set the OFFSET expression. 2563 2564 Example: 2565 >>> Select().from_("tbl").select("x").offset(10).sql() 2566 'SELECT x FROM tbl OFFSET 10' 2567 2568 Args: 2569 expression (str | int | Expression): the SQL code string to parse. 2570 This can also be an integer. 2571 If a `Offset` instance is passed, this is used as-is. 2572 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2573 dialect (str): the dialect used to parse the input expression. 2574 copy (bool): if `False`, modify this expression instance in-place. 2575 opts (kwargs): other options to use to parse the input expressions. 2576 2577 Returns: 2578 Select: the modified expression. 2579 """ 2580 return _apply_builder( 2581 expression=expression, 2582 instance=self, 2583 arg="offset", 2584 into=Offset, 2585 prefix="OFFSET", 2586 dialect=dialect, 2587 copy=copy, 2588 **opts, 2589 )
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.
2591 def select( 2592 self, 2593 *expressions: ExpOrStr, 2594 append: bool = True, 2595 dialect: DialectType = None, 2596 copy: bool = True, 2597 **opts, 2598 ) -> Select: 2599 """ 2600 Append to or set the SELECT expressions. 2601 2602 Example: 2603 >>> Select().select("x", "y").sql() 2604 'SELECT x, y' 2605 2606 Args: 2607 *expressions: the SQL code strings to parse. 2608 If an `Expression` instance is passed, it will be used as-is. 2609 append: if `True`, add to any existing expressions. 2610 Otherwise, this resets the expressions. 2611 dialect: the dialect used to parse the input expressions. 2612 copy: if `False`, modify this expression instance in-place. 2613 opts: other options to use to parse the input expressions. 2614 2615 Returns: 2616 Select: the modified expression. 2617 """ 2618 return _apply_list_builder( 2619 *expressions, 2620 instance=self, 2621 arg="expressions", 2622 append=append, 2623 dialect=dialect, 2624 copy=copy, 2625 **opts, 2626 )
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.
2628 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2629 """ 2630 Append to or set the LATERAL expressions. 2631 2632 Example: 2633 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2634 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2635 2636 Args: 2637 *expressions (str | Expression): the SQL code strings to parse. 2638 If an `Expression` instance is passed, it will be used as-is. 2639 append (bool): if `True`, add to any existing expressions. 2640 Otherwise, this resets the expressions. 2641 dialect (str): the dialect used to parse the input expressions. 2642 copy (bool): if `False`, modify this expression instance in-place. 2643 opts (kwargs): other options to use to parse the input expressions. 2644 2645 Returns: 2646 Select: the modified expression. 2647 """ 2648 return _apply_list_builder( 2649 *expressions, 2650 instance=self, 2651 arg="laterals", 2652 append=append, 2653 into=Lateral, 2654 prefix="LATERAL VIEW", 2655 dialect=dialect, 2656 copy=copy, 2657 **opts, 2658 )
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.
2660 def join( 2661 self, 2662 expression, 2663 on=None, 2664 using=None, 2665 append=True, 2666 join_type=None, 2667 join_alias=None, 2668 dialect=None, 2669 copy=True, 2670 **opts, 2671 ) -> Select: 2672 """ 2673 Append to or set the JOIN expressions. 2674 2675 Example: 2676 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2677 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2678 2679 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2680 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2681 2682 Use `join_type` to change the type of join: 2683 2684 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2685 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2686 2687 Args: 2688 expression (str | Expression): the SQL code string to parse. 2689 If an `Expression` instance is passed, it will be used as-is. 2690 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2691 If an `Expression` instance is passed, it will be used as-is. 2692 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2693 If an `Expression` instance is passed, it will be used as-is. 2694 append (bool): if `True`, add to any existing expressions. 2695 Otherwise, this resets the expressions. 2696 join_type (str): If set, alter the parsed join type 2697 dialect (str): the dialect used to parse the input expressions. 2698 copy (bool): if `False`, modify this expression instance in-place. 2699 opts (kwargs): other options to use to parse the input expressions. 2700 2701 Returns: 2702 Select: the modified expression. 2703 """ 2704 parse_args = {"dialect": dialect, **opts} 2705 2706 try: 2707 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2708 except ParseError: 2709 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2710 2711 join = expression if isinstance(expression, Join) else Join(this=expression) 2712 2713 if isinstance(join.this, Select): 2714 join.this.replace(join.this.subquery()) 2715 2716 if join_type: 2717 natural: t.Optional[Token] 2718 side: t.Optional[Token] 2719 kind: t.Optional[Token] 2720 2721 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2722 2723 if natural: 2724 join.set("natural", True) 2725 if side: 2726 join.set("side", side.text) 2727 if kind: 2728 join.set("kind", kind.text) 2729 2730 if on: 2731 on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts) 2732 join.set("on", on) 2733 2734 if using: 2735 join = _apply_list_builder( 2736 *ensure_collection(using), 2737 instance=join, 2738 arg="using", 2739 append=append, 2740 copy=copy, 2741 **opts, 2742 ) 2743 2744 if join_alias: 2745 join.set("this", alias_(join.this, join_alias, table=True)) 2746 return _apply_list_builder( 2747 join, 2748 instance=self, 2749 arg="joins", 2750 append=append, 2751 copy=copy, 2752 **opts, 2753 )
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.
2755 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2756 """ 2757 Append to or set the WHERE expressions. 2758 2759 Example: 2760 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2761 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2762 2763 Args: 2764 *expressions (str | Expression): the SQL code strings to parse. 2765 If an `Expression` instance is passed, it will be used as-is. 2766 Multiple expressions are combined with an AND operator. 2767 append (bool): if `True`, AND the new expressions to any existing expression. 2768 Otherwise, this resets the expression. 2769 dialect (str): the dialect used to parse the input expressions. 2770 copy (bool): if `False`, modify this expression instance in-place. 2771 opts (kwargs): other options to use to parse the input expressions. 2772 2773 Returns: 2774 Select: the modified expression. 2775 """ 2776 return _apply_conjunction_builder( 2777 *expressions, 2778 instance=self, 2779 arg="where", 2780 append=append, 2781 into=Where, 2782 dialect=dialect, 2783 copy=copy, 2784 **opts, 2785 )
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.
2787 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2788 """ 2789 Append to or set the HAVING expressions. 2790 2791 Example: 2792 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2793 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2794 2795 Args: 2796 *expressions (str | Expression): the SQL code strings to parse. 2797 If an `Expression` instance is passed, it will be used as-is. 2798 Multiple expressions are combined with an AND operator. 2799 append (bool): if `True`, AND the new expressions to any existing expression. 2800 Otherwise, this resets the expression. 2801 dialect (str): the dialect used to parse the input expressions. 2802 copy (bool): if `False`, modify this expression instance in-place. 2803 opts (kwargs): other options to use to parse the input expressions. 2804 2805 Returns: 2806 Select: the modified expression. 2807 """ 2808 return _apply_conjunction_builder( 2809 *expressions, 2810 instance=self, 2811 arg="having", 2812 append=append, 2813 into=Having, 2814 dialect=dialect, 2815 copy=copy, 2816 **opts, 2817 )
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.
2843 def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select: 2844 """ 2845 Set the OFFSET expression. 2846 2847 Example: 2848 >>> Select().from_("tbl").select("x").distinct().sql() 2849 'SELECT DISTINCT x FROM tbl' 2850 2851 Args: 2852 ons: the expressions to distinct on 2853 distinct: whether the Select should be distinct 2854 copy: if `False`, modify this expression instance in-place. 2855 2856 Returns: 2857 Select: the modified expression. 2858 """ 2859 instance = _maybe_copy(self, copy) 2860 on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None 2861 instance.set("distinct", Distinct(on=on) if distinct else None) 2862 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- ons: the expressions to distinct on
- distinct: whether the Select should be distinct
- copy: if
False
, modify this expression instance in-place.
Returns:
Select: the modified expression.
2864 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2865 """ 2866 Convert this expression to a CREATE TABLE AS statement. 2867 2868 Example: 2869 >>> Select().select("*").from_("tbl").ctas("x").sql() 2870 'CREATE TABLE x AS SELECT * FROM tbl' 2871 2872 Args: 2873 table (str | Expression): the SQL code string to parse as the table name. 2874 If another `Expression` instance is passed, it will be used as-is. 2875 properties (dict): an optional mapping of table properties 2876 dialect (str): the dialect used to parse the input table. 2877 copy (bool): if `False`, modify this expression instance in-place. 2878 opts (kwargs): other options to use to parse the input table. 2879 2880 Returns: 2881 Create: the CREATE TABLE AS expression 2882 """ 2883 instance = _maybe_copy(self, copy) 2884 table_expression = maybe_parse( 2885 table, 2886 into=Table, 2887 dialect=dialect, 2888 **opts, 2889 ) 2890 properties_expression = None 2891 if properties: 2892 properties_expression = Properties.from_dict(properties) 2893 2894 return Create( 2895 this=table_expression, 2896 kind="table", 2897 expression=instance, 2898 properties=properties_expression, 2899 )
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
2901 def lock(self, update: bool = True, copy: bool = True) -> Select: 2902 """ 2903 Set the locking read mode for this expression. 2904 2905 Examples: 2906 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2907 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2908 2909 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2910 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2911 2912 Args: 2913 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2914 copy: if `False`, modify this expression instance in-place. 2915 2916 Returns: 2917 The modified expression. 2918 """ 2919 2920 inst = _maybe_copy(self, copy) 2921 inst.set("locks", [Lock(update=update)]) 2922 2923 return inst
Set the locking read mode for this expression.
Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
- update: if
True
, the locking type will beFOR UPDATE
, else it will beFOR SHARE
. - copy: if
False
, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2938class Subquery(DerivedTable, Unionable): 2939 arg_types = { 2940 "this": True, 2941 "alias": False, 2942 "with": False, 2943 **QUERY_MODIFIERS, 2944 } 2945 2946 def unnest(self): 2947 """ 2948 Returns the first non subquery. 2949 """ 2950 expression = self 2951 while isinstance(expression, Subquery): 2952 expression = expression.this 2953 return expression 2954 2955 @property 2956 def is_star(self) -> bool: 2957 return self.this.is_star 2958 2959 @property 2960 def output_name(self): 2961 return self.alias
2946 def unnest(self): 2947 """ 2948 Returns the first non subquery. 2949 """ 2950 expression = self 2951 while isinstance(expression, Subquery): 2952 expression = expression.this 2953 return expression
Returns the first non subquery.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2964class TableSample(Expression): 2965 arg_types = { 2966 "this": False, 2967 "method": False, 2968 "bucket_numerator": False, 2969 "bucket_denominator": False, 2970 "bucket_field": False, 2971 "percent": False, 2972 "rows": False, 2973 "size": False, 2974 "seed": False, 2975 "kind": False, 2976 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2979class Tag(Expression): 2980 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2981 2982 arg_types = { 2983 "this": False, 2984 "prefix": False, 2985 "postfix": False, 2986 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2989class Pivot(Expression): 2990 arg_types = { 2991 "alias": False, 2992 "expressions": True, 2993 "field": True, 2994 "unpivot": True, 2995 "columns": False, 2996 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2999class Window(Expression): 3000 arg_types = { 3001 "this": True, 3002 "partition_by": False, 3003 "order": False, 3004 "spec": False, 3005 "alias": False, 3006 "over": False, 3007 "first": False, 3008 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3011class WindowSpec(Expression): 3012 arg_types = { 3013 "kind": False, 3014 "start": False, 3015 "start_side": False, 3016 "end": False, 3017 "end_side": False, 3018 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3025class Star(Expression): 3026 arg_types = {"except": False, "replace": False} 3027 3028 @property 3029 def name(self) -> str: 3030 return "*" 3031 3032 @property 3033 def output_name(self): 3034 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3049class Null(Condition): 3050 arg_types: t.Dict[str, t.Any] = {} 3051 3052 @property 3053 def name(self) -> str: 3054 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3065class DataType(Expression): 3066 arg_types = { 3067 "this": True, 3068 "expressions": False, 3069 "nested": False, 3070 "values": False, 3071 "prefix": False, 3072 } 3073 3074 class Type(AutoName): 3075 ARRAY = auto() 3076 BIGDECIMAL = auto() 3077 BIGINT = auto() 3078 BIGSERIAL = auto() 3079 BINARY = auto() 3080 BIT = auto() 3081 BOOLEAN = auto() 3082 CHAR = auto() 3083 DATE = auto() 3084 DATETIME = auto() 3085 DATETIME64 = auto() 3086 DECIMAL = auto() 3087 DOUBLE = auto() 3088 FLOAT = auto() 3089 GEOGRAPHY = auto() 3090 GEOMETRY = auto() 3091 HLLSKETCH = auto() 3092 HSTORE = auto() 3093 IMAGE = auto() 3094 INET = auto() 3095 INT = auto() 3096 INT128 = auto() 3097 INT256 = auto() 3098 INTERVAL = auto() 3099 JSON = auto() 3100 JSONB = auto() 3101 LONGBLOB = auto() 3102 LONGTEXT = auto() 3103 MAP = auto() 3104 MEDIUMBLOB = auto() 3105 MEDIUMTEXT = auto() 3106 MONEY = auto() 3107 NCHAR = auto() 3108 NULL = auto() 3109 NULLABLE = auto() 3110 NVARCHAR = auto() 3111 OBJECT = auto() 3112 ROWVERSION = auto() 3113 SERIAL = auto() 3114 SMALLINT = auto() 3115 SMALLMONEY = auto() 3116 SMALLSERIAL = auto() 3117 STRUCT = auto() 3118 SUPER = auto() 3119 TEXT = auto() 3120 TIME = auto() 3121 TIMESTAMP = auto() 3122 TIMESTAMPTZ = auto() 3123 TIMESTAMPLTZ = auto() 3124 TINYINT = auto() 3125 UBIGINT = auto() 3126 UINT = auto() 3127 USMALLINT = auto() 3128 UTINYINT = auto() 3129 UNKNOWN = auto() # Sentinel value, useful for type annotation 3130 UINT128 = auto() 3131 UINT256 = auto() 3132 UNIQUEIDENTIFIER = auto() 3133 UUID = auto() 3134 VARBINARY = auto() 3135 VARCHAR = auto() 3136 VARIANT = auto() 3137 XML = auto() 3138 3139 TEXT_TYPES = { 3140 Type.CHAR, 3141 Type.NCHAR, 3142 Type.VARCHAR, 3143 Type.NVARCHAR, 3144 Type.TEXT, 3145 } 3146 3147 INTEGER_TYPES = { 3148 Type.INT, 3149 Type.TINYINT, 3150 Type.SMALLINT, 3151 Type.BIGINT, 3152 Type.INT128, 3153 Type.INT256, 3154 } 3155 3156 FLOAT_TYPES = { 3157 Type.FLOAT, 3158 Type.DOUBLE, 3159 } 3160 3161 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3162 3163 TEMPORAL_TYPES = { 3164 Type.TIMESTAMP, 3165 Type.TIMESTAMPTZ, 3166 Type.TIMESTAMPLTZ, 3167 Type.DATE, 3168 Type.DATETIME, 3169 Type.DATETIME64, 3170 } 3171 3172 @classmethod 3173 def build( 3174 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3175 ) -> DataType: 3176 from sqlglot import parse_one 3177 3178 if isinstance(dtype, str): 3179 if dtype.upper() in cls.Type.__members__: 3180 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3181 else: 3182 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3183 3184 if data_type_exp is None: 3185 raise ValueError(f"Unparsable data type value: {dtype}") 3186 elif isinstance(dtype, DataType.Type): 3187 data_type_exp = DataType(this=dtype) 3188 elif isinstance(dtype, DataType): 3189 return dtype 3190 else: 3191 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3192 3193 return DataType(**{**data_type_exp.args, **kwargs}) 3194 3195 def is_type(self, dtype: DataType.Type) -> bool: 3196 return self.this == dtype
3172 @classmethod 3173 def build( 3174 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3175 ) -> DataType: 3176 from sqlglot import parse_one 3177 3178 if isinstance(dtype, str): 3179 if dtype.upper() in cls.Type.__members__: 3180 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3181 else: 3182 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3183 3184 if data_type_exp is None: 3185 raise ValueError(f"Unparsable data type value: {dtype}") 3186 elif isinstance(dtype, DataType.Type): 3187 data_type_exp = DataType(this=dtype) 3188 elif isinstance(dtype, DataType): 3189 return dtype 3190 else: 3191 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3192 3193 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3074 class Type(AutoName): 3075 ARRAY = auto() 3076 BIGDECIMAL = auto() 3077 BIGINT = auto() 3078 BIGSERIAL = auto() 3079 BINARY = auto() 3080 BIT = auto() 3081 BOOLEAN = auto() 3082 CHAR = auto() 3083 DATE = auto() 3084 DATETIME = auto() 3085 DATETIME64 = auto() 3086 DECIMAL = auto() 3087 DOUBLE = auto() 3088 FLOAT = auto() 3089 GEOGRAPHY = auto() 3090 GEOMETRY = auto() 3091 HLLSKETCH = auto() 3092 HSTORE = auto() 3093 IMAGE = auto() 3094 INET = auto() 3095 INT = auto() 3096 INT128 = auto() 3097 INT256 = auto() 3098 INTERVAL = auto() 3099 JSON = auto() 3100 JSONB = auto() 3101 LONGBLOB = auto() 3102 LONGTEXT = auto() 3103 MAP = auto() 3104 MEDIUMBLOB = auto() 3105 MEDIUMTEXT = auto() 3106 MONEY = auto() 3107 NCHAR = auto() 3108 NULL = auto() 3109 NULLABLE = auto() 3110 NVARCHAR = auto() 3111 OBJECT = auto() 3112 ROWVERSION = auto() 3113 SERIAL = auto() 3114 SMALLINT = auto() 3115 SMALLMONEY = auto() 3116 SMALLSERIAL = auto() 3117 STRUCT = auto() 3118 SUPER = auto() 3119 TEXT = auto() 3120 TIME = auto() 3121 TIMESTAMP = auto() 3122 TIMESTAMPTZ = auto() 3123 TIMESTAMPLTZ = auto() 3124 TINYINT = auto() 3125 UBIGINT = auto() 3126 UINT = auto() 3127 USMALLINT = auto() 3128 UTINYINT = auto() 3129 UNKNOWN = auto() # Sentinel value, useful for type annotation 3130 UINT128 = auto() 3131 UINT256 = auto() 3132 UNIQUEIDENTIFIER = auto() 3133 UUID = auto() 3134 VARBINARY = auto() 3135 VARCHAR = auto() 3136 VARIANT = auto() 3137 XML = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3243class AddConstraint(Expression): 3244 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3252class Binary(Condition): 3253 arg_types = {"this": True, "expression": True} 3254 3255 @property 3256 def left(self): 3257 return self.this 3258 3259 @property 3260 def right(self): 3261 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3308class Dot(Binary): 3309 @property 3310 def name(self) -> str: 3311 return self.expression.name 3312 3313 @classmethod 3314 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3315 """Build a Dot object with a sequence of expressions.""" 3316 if len(expressions) < 2: 3317 raise ValueError(f"Dot requires >= 2 expressions.") 3318 3319 a, b, *expressions = expressions 3320 dot = Dot(this=a, expression=b) 3321 3322 for expression in expressions: 3323 dot = Dot(this=dot, expression=expression) 3324 3325 return dot
3313 @classmethod 3314 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3315 """Build a Dot object with a sequence of expressions.""" 3316 if len(expressions) < 2: 3317 raise ValueError(f"Dot requires >= 2 expressions.") 3318 3319 a, b, *expressions = expressions 3320 dot = Dot(this=a, expression=b) 3321 3322 for expression in expressions: 3323 dot = Dot(this=dot, expression=expression) 3324 3325 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3450class Alias(Expression): 3451 arg_types = {"this": True, "alias": False} 3452 3453 @property 3454 def output_name(self): 3455 return self.alias
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3458class Aliases(Expression): 3459 arg_types = {"this": True, "expressions": True} 3460 3461 @property 3462 def aliases(self): 3463 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3482class In(Predicate): 3483 arg_types = { 3484 "this": True, 3485 "expressions": False, 3486 "query": False, 3487 "unnest": False, 3488 "field": False, 3489 "is_global": False, 3490 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3493class TimeUnit(Expression): 3494 """Automatically converts unit arg into a var.""" 3495 3496 arg_types = {"unit": False} 3497 3498 def __init__(self, **args): 3499 unit = args.get("unit") 3500 if isinstance(unit, (Column, Literal)): 3501 args["unit"] = Var(this=unit.name) 3502 elif isinstance(unit, Week): 3503 unit.set("this", Var(this=unit.this.name)) 3504 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3507class Interval(TimeUnit): 3508 arg_types = {"this": False, "unit": False} 3509 3510 @property 3511 def unit(self) -> t.Optional[Var]: 3512 return self.args.get("unit")
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3524class Func(Condition): 3525 """ 3526 The base class for all function expressions. 3527 3528 Attributes: 3529 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3530 treated as a variable length argument and the argument's value will be stored as a list. 3531 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3532 for this function expression. These values are used to map this node to a name during parsing 3533 as well as to provide the function's name during SQL string generation. By default the SQL 3534 name is set to the expression's class name transformed to snake case. 3535 """ 3536 3537 is_var_len_args = False 3538 3539 @classmethod 3540 def from_arg_list(cls, args): 3541 if cls.is_var_len_args: 3542 all_arg_keys = list(cls.arg_types) 3543 # If this function supports variable length argument treat the last argument as such. 3544 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3545 num_non_var = len(non_var_len_arg_keys) 3546 3547 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3548 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3549 else: 3550 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3551 3552 return cls(**args_dict) 3553 3554 @classmethod 3555 def sql_names(cls): 3556 if cls is Func: 3557 raise NotImplementedError( 3558 "SQL name is only supported by concrete function implementations" 3559 ) 3560 if "_sql_names" not in cls.__dict__: 3561 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3562 return cls._sql_names 3563 3564 @classmethod 3565 def sql_name(cls): 3566 return cls.sql_names()[0] 3567 3568 @classmethod 3569 def default_parser_mappings(cls): 3570 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.
3539 @classmethod 3540 def from_arg_list(cls, args): 3541 if cls.is_var_len_args: 3542 all_arg_keys = list(cls.arg_types) 3543 # If this function supports variable length argument treat the last argument as such. 3544 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3545 num_non_var = len(non_var_len_arg_keys) 3546 3547 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3548 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3549 else: 3550 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3551 3552 return cls(**args_dict)
3554 @classmethod 3555 def sql_names(cls): 3556 if cls is Func: 3557 raise NotImplementedError( 3558 "SQL name is only supported by concrete function implementations" 3559 ) 3560 if "_sql_names" not in cls.__dict__: 3561 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3562 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3577class ParameterizedAgg(AggFunc): 3578 arg_types = {"this": True, "expressions": True, "params": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3585class Anonymous(Func): 3586 arg_types = {"this": True, "expressions": False} 3587 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3592class Hll(AggFunc): 3593 arg_types = {"this": True, "expressions": False} 3594 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3597class ApproxDistinct(AggFunc): 3598 arg_types = {"this": True, "accuracy": False} 3599 _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3628class ArrayConcat(Func): 3629 arg_types = {"this": True, "expressions": False} 3630 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3641class ArrayFilter(Func): 3642 arg_types = {"this": True, "expression": True} 3643 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3674class Case(Func): 3675 arg_types = {"this": False, "ifs": True, "default": False} 3676 3677 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3678 instance = _maybe_copy(self, copy) 3679 instance.append( 3680 "ifs", 3681 If( 3682 this=maybe_parse(condition, copy=copy, **opts), 3683 true=maybe_parse(then, copy=copy, **opts), 3684 ), 3685 ) 3686 return instance 3687 3688 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3689 instance = _maybe_copy(self, copy) 3690 instance.set("default", maybe_parse(condition, copy=copy, **opts)) 3691 return instance
3677 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3678 instance = _maybe_copy(self, copy) 3679 instance.append( 3680 "ifs", 3681 If( 3682 this=maybe_parse(condition, copy=copy, **opts), 3683 true=maybe_parse(then, copy=copy, **opts), 3684 ), 3685 ) 3686 return instance
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3694class Cast(Func): 3695 arg_types = {"this": True, "to": True} 3696 3697 @property 3698 def name(self) -> str: 3699 return self.this.name 3700 3701 @property 3702 def to(self): 3703 return self.args["to"] 3704 3705 @property 3706 def output_name(self): 3707 return self.name 3708 3709 def is_type(self, dtype: DataType.Type) -> bool: 3710 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
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3725class Ceil(Func): 3726 arg_types = {"this": True, "decimals": False} 3727 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3730class Coalesce(Func): 3731 arg_types = {"this": True, "expressions": False} 3732 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3772class DateAdd(Func, TimeUnit): 3773 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3776class DateSub(Func, TimeUnit): 3777 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3780class DateDiff(Func, TimeUnit): 3781 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3782 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3789class DatetimeAdd(Func, TimeUnit): 3790 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3793class DatetimeSub(Func, TimeUnit): 3794 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3797class DatetimeDiff(Func, TimeUnit): 3798 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3801class DatetimeTrunc(Func, TimeUnit): 3802 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3829class TimestampAdd(Func, TimeUnit): 3830 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3833class TimestampSub(Func, TimeUnit): 3834 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3837class TimestampDiff(Func, TimeUnit): 3838 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3841class TimestampTrunc(Func, TimeUnit): 3842 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3845class TimeAdd(Func, TimeUnit): 3846 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3849class TimeSub(Func, TimeUnit): 3850 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3853class TimeDiff(Func, TimeUnit): 3854 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3861class DateFromParts(Func): 3862 _sql_names = ["DATEFROMPARTS"] 3863 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3914class Greatest(Func): 3915 arg_types = {"this": True, "expressions": False} 3916 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3931class IfNull(Func): 3932 arg_types = {"this": True, "expression": False} 3933 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3944class JSONObject(Func): 3945 arg_types = { 3946 "expressions": False, 3947 "null_handling": False, 3948 "unique_keys": False, 3949 "return_type": False, 3950 "format_json": False, 3951 "encoding": False, 3952 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3955class OpenJSONColumnDef(Expression): 3956 arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3983class JSONFormat(Func): 3984 arg_types = {"this": False, "options": False} 3985 _sql_names = ["JSON_FORMAT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3997class Levenshtein(Func): 3998 arg_types = { 3999 "this": True, 4000 "expression": False, 4001 "ins_cost": False, 4002 "del_cost": False, 4003 "sub_cost": False, 4004 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4049class MatchAgainst(Func): 4050 arg_types = {"this": True, "expressions": True, "modifier": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4053class Max(AggFunc): 4054 arg_types = {"this": True, "expressions": False} 4055 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4062class Min(AggFunc): 4063 arg_types = {"this": True, "expressions": False} 4064 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4095class ApproxQuantile(Quantile): 4096 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4103class ReadCSV(Func): 4104 _sql_names = ["READ_CSV"] 4105 is_var_len_args = True 4106 arg_types = {"this": True, "expressions": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4109class Reduce(Func): 4110 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4113class RegexpExtract(Func): 4114 arg_types = { 4115 "this": True, 4116 "expression": True, 4117 "position": False, 4118 "occurrence": False, 4119 "group": False, 4120 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4184class StrPosition(Func): 4185 arg_types = { 4186 "this": True, 4187 "substr": True, 4188 "position": False, 4189 "instance": False, 4190 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4264class Trim(Func): 4265 arg_types = { 4266 "this": True, 4267 "expression": False, 4268 "position": False, 4269 "collation": False, 4270 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4273class TsOrDsAdd(Func, TimeUnit): 4274 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4299class UnixToTime(Func): 4300 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4301 4302 SECONDS = Literal.string("seconds") 4303 MILLIS = Literal.string("millis") 4304 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4327class XMLTable(Func): 4328 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4339class Merge(Expression): 4340 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4343class When(Func): 4344 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- add_comments
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4387def maybe_parse( 4388 sql_or_expression: ExpOrStr, 4389 *, 4390 into: t.Optional[IntoType] = None, 4391 dialect: DialectType = None, 4392 prefix: t.Optional[str] = None, 4393 copy: bool = False, 4394 **opts, 4395) -> Expression: 4396 """Gracefully handle a possible string or expression. 4397 4398 Example: 4399 >>> maybe_parse("1") 4400 (LITERAL this: 1, is_string: False) 4401 >>> maybe_parse(to_identifier("x")) 4402 (IDENTIFIER this: x, quoted: False) 4403 4404 Args: 4405 sql_or_expression: the SQL code string or an expression 4406 into: the SQLGlot Expression to parse into 4407 dialect: the dialect used to parse the input expressions (in the case that an 4408 input expression is a SQL string). 4409 prefix: a string to prefix the sql with before it gets parsed 4410 (automatically includes a space) 4411 copy: whether or not to copy the expression. 4412 **opts: other options to use to parse the input expressions (again, in the case 4413 that an input expression is a SQL string). 4414 4415 Returns: 4416 Expression: the parsed or given expression. 4417 """ 4418 if isinstance(sql_or_expression, Expression): 4419 if copy: 4420 return sql_or_expression.copy() 4421 return sql_or_expression 4422 4423 import sqlglot 4424 4425 sql = str(sql_or_expression) 4426 if prefix: 4427 sql = f"{prefix} {sql}" 4428 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.
4600def union(left, right, distinct=True, dialect=None, **opts): 4601 """ 4602 Initializes a syntax tree from one UNION expression. 4603 4604 Example: 4605 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4606 'SELECT * FROM foo UNION SELECT * FROM bla' 4607 4608 Args: 4609 left (str | Expression): the SQL code string corresponding to the left-hand side. 4610 If an `Expression` instance is passed, it will be used as-is. 4611 right (str | Expression): the SQL code string corresponding to the right-hand side. 4612 If an `Expression` instance is passed, it will be used as-is. 4613 distinct (bool): set the DISTINCT flag if and only if this is true. 4614 dialect (str): the dialect used to parse the input expression. 4615 opts (kwargs): other options to use to parse the input expressions. 4616 Returns: 4617 Union: the syntax tree for the UNION expression. 4618 """ 4619 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4620 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4621 4622 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.
4625def intersect(left, right, distinct=True, dialect=None, **opts): 4626 """ 4627 Initializes a syntax tree from one INTERSECT expression. 4628 4629 Example: 4630 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4631 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4632 4633 Args: 4634 left (str | Expression): the SQL code string corresponding to the left-hand side. 4635 If an `Expression` instance is passed, it will be used as-is. 4636 right (str | Expression): the SQL code string corresponding to the right-hand side. 4637 If an `Expression` instance is passed, it will be used as-is. 4638 distinct (bool): set the DISTINCT flag if and only if this is true. 4639 dialect (str): the dialect used to parse the input expression. 4640 opts (kwargs): other options to use to parse the input expressions. 4641 Returns: 4642 Intersect: the syntax tree for the INTERSECT expression. 4643 """ 4644 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4645 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4646 4647 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.
4650def except_(left, right, distinct=True, dialect=None, **opts): 4651 """ 4652 Initializes a syntax tree from one EXCEPT expression. 4653 4654 Example: 4655 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4656 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4657 4658 Args: 4659 left (str | Expression): the SQL code string corresponding to the left-hand side. 4660 If an `Expression` instance is passed, it will be used as-is. 4661 right (str | Expression): the SQL code string corresponding to the right-hand side. 4662 If an `Expression` instance is passed, it will be used as-is. 4663 distinct (bool): set the DISTINCT flag if and only if this is true. 4664 dialect (str): the dialect used to parse the input expression. 4665 opts (kwargs): other options to use to parse the input expressions. 4666 Returns: 4667 Except: the syntax tree for the EXCEPT statement. 4668 """ 4669 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4670 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4671 4672 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.
4675def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4676 """ 4677 Initializes a syntax tree from one or multiple SELECT expressions. 4678 4679 Example: 4680 >>> select("col1", "col2").from_("tbl").sql() 4681 'SELECT col1, col2 FROM tbl' 4682 4683 Args: 4684 *expressions: the SQL code string to parse as the expressions of a 4685 SELECT statement. If an Expression instance is passed, this is used as-is. 4686 dialect: the dialect used to parse the input expressions (in the case that an 4687 input expression is a SQL string). 4688 **opts: other options to use to parse the input expressions (again, in the case 4689 that an input expression is a SQL string). 4690 4691 Returns: 4692 Select: the syntax tree for the SELECT statement. 4693 """ 4694 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.
4697def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4698 """ 4699 Initializes a syntax tree from a FROM expression. 4700 4701 Example: 4702 >>> from_("tbl").select("col1", "col2").sql() 4703 'SELECT col1, col2 FROM tbl' 4704 4705 Args: 4706 *expression: the SQL code string to parse as the FROM expressions of a 4707 SELECT statement. If an Expression instance is passed, this is used as-is. 4708 dialect: the dialect used to parse the input expression (in the case that the 4709 input expression is a SQL string). 4710 **opts: other options to use to parse the input expressions (again, in the case 4711 that the input expression is a SQL string). 4712 4713 Returns: 4714 Select: the syntax tree for the SELECT statement. 4715 """ 4716 return Select().from_(expression, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4719def update( 4720 table: str | Table, 4721 properties: dict, 4722 where: t.Optional[ExpOrStr] = None, 4723 from_: t.Optional[ExpOrStr] = None, 4724 dialect: DialectType = None, 4725 **opts, 4726) -> Update: 4727 """ 4728 Creates an update statement. 4729 4730 Example: 4731 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4732 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4733 4734 Args: 4735 *properties: dictionary of properties to set which are 4736 auto converted to sql objects eg None -> NULL 4737 where: sql conditional parsed into a WHERE statement 4738 from_: sql statement parsed into a FROM statement 4739 dialect: the dialect used to parse the input expressions. 4740 **opts: other options to use to parse the input expressions. 4741 4742 Returns: 4743 Update: the syntax tree for the UPDATE statement. 4744 """ 4745 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4746 update_expr.set( 4747 "expressions", 4748 [ 4749 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4750 for k, v in properties.items() 4751 ], 4752 ) 4753 if from_: 4754 update_expr.set( 4755 "from", 4756 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4757 ) 4758 if isinstance(where, Condition): 4759 where = Where(this=where) 4760 if where: 4761 update_expr.set( 4762 "where", 4763 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4764 ) 4765 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.
4768def delete( 4769 table: ExpOrStr, 4770 where: t.Optional[ExpOrStr] = None, 4771 returning: t.Optional[ExpOrStr] = None, 4772 dialect: DialectType = None, 4773 **opts, 4774) -> Delete: 4775 """ 4776 Builds a delete statement. 4777 4778 Example: 4779 >>> delete("my_table", where="id > 1").sql() 4780 'DELETE FROM my_table WHERE id > 1' 4781 4782 Args: 4783 where: sql conditional parsed into a WHERE statement 4784 returning: sql conditional parsed into a RETURNING statement 4785 dialect: the dialect used to parse the input expressions. 4786 **opts: other options to use to parse the input expressions. 4787 4788 Returns: 4789 Delete: the syntax tree for the DELETE statement. 4790 """ 4791 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4792 if where: 4793 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4794 if returning: 4795 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4796 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.
4799def insert( 4800 expression: ExpOrStr, 4801 into: ExpOrStr, 4802 columns: t.Optional[t.Sequence[ExpOrStr]] = None, 4803 overwrite: t.Optional[bool] = None, 4804 dialect: DialectType = None, 4805 copy: bool = True, 4806 **opts, 4807) -> Insert: 4808 """ 4809 Builds an INSERT statement. 4810 4811 Example: 4812 >>> insert("VALUES (1, 2, 3)", "tbl").sql() 4813 'INSERT INTO tbl VALUES (1, 2, 3)' 4814 4815 Args: 4816 expression: the sql string or expression of the INSERT statement 4817 into: the tbl to insert data to. 4818 columns: optionally the table's column names. 4819 overwrite: whether to INSERT OVERWRITE or not. 4820 dialect: the dialect used to parse the input expressions. 4821 copy: whether or not to copy the expression. 4822 **opts: other options to use to parse the input expressions. 4823 4824 Returns: 4825 Insert: the syntax tree for the INSERT statement. 4826 """ 4827 expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 4828 this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts) 4829 4830 if columns: 4831 this = _apply_list_builder( 4832 *columns, 4833 instance=Schema(this=this), 4834 arg="expressions", 4835 into=Identifier, 4836 copy=False, 4837 dialect=dialect, 4838 **opts, 4839 ) 4840 4841 return Insert(this=this, expression=expr, overwrite=overwrite)
Builds an INSERT statement.
Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql() 'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
- expression: the sql string or expression of the INSERT statement
- into: the tbl to insert data to.
- columns: optionally the table's column names.
- overwrite: whether to INSERT OVERWRITE or not.
- dialect: the dialect used to parse the input expressions.
- copy: whether or not to copy the expression.
- **opts: other options to use to parse the input expressions.
Returns:
Insert: the syntax tree for the INSERT statement.
4844def condition(expression, dialect=None, copy=True, **opts) -> Condition: 4845 """ 4846 Initialize a logical condition expression. 4847 4848 Example: 4849 >>> condition("x=1").sql() 4850 'x = 1' 4851 4852 This is helpful for composing larger logical syntax trees: 4853 >>> where = condition("x=1") 4854 >>> where = where.and_("y=1") 4855 >>> Select().from_("tbl").select("*").where(where).sql() 4856 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4857 4858 Args: 4859 *expression (str | Expression): the SQL code string to parse. 4860 If an Expression instance is passed, this is used as-is. 4861 dialect (str): the dialect used to parse the input expression (in the case that the 4862 input expression is a SQL string). 4863 copy (bool): Whether or not to copy `expression` (only applies to expressions). 4864 **opts: other options to use to parse the input expressions (again, in the case 4865 that the input expression is a SQL string). 4866 4867 Returns: 4868 Condition: the expression 4869 """ 4870 return maybe_parse( # type: ignore 4871 expression, 4872 into=Condition, 4873 dialect=dialect, 4874 copy=copy, 4875 **opts, 4876 )
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).
- copy (bool): Whether or not to copy
expression
(only applies to expressions). - **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4879def and_(*expressions, dialect=None, copy=True, **opts) -> And: 4880 """ 4881 Combine multiple conditions with an AND logical operator. 4882 4883 Example: 4884 >>> and_("x=1", and_("y=1", "z=1")).sql() 4885 'x = 1 AND (y = 1 AND z = 1)' 4886 4887 Args: 4888 *expressions (str | Expression): the SQL code strings to parse. 4889 If an Expression instance is passed, this is used as-is. 4890 dialect (str): the dialect used to parse the input expression. 4891 copy (bool): whether or not to copy `expressions` (only applies to Expressions). 4892 **opts: other options to use to parse the input expressions. 4893 4894 Returns: 4895 And: the new condition 4896 """ 4897 return _combine(expressions, And, dialect, copy=copy, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (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.
- copy (bool): whether or not to copy
expressions
(only applies to Expressions). - **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4900def or_(*expressions, dialect=None, copy=True, **opts) -> Or: 4901 """ 4902 Combine multiple conditions with an OR logical operator. 4903 4904 Example: 4905 >>> or_("x=1", or_("y=1", "z=1")).sql() 4906 'x = 1 OR (y = 1 OR z = 1)' 4907 4908 Args: 4909 *expressions (str | Expression): the SQL code strings to parse. 4910 If an Expression instance is passed, this is used as-is. 4911 dialect (str): the dialect used to parse the input expression. 4912 copy (bool): whether or not to copy `expressions` (only applies to Expressions). 4913 **opts: other options to use to parse the input expressions. 4914 4915 Returns: 4916 Or: the new condition 4917 """ 4918 return _combine(expressions, Or, dialect, copy=copy, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (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.
- copy (bool): whether or not to copy
expressions
(only applies to Expressions). - **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4921def not_(expression, dialect=None, copy=True, **opts) -> Not: 4922 """ 4923 Wrap a condition with a NOT operator. 4924 4925 Example: 4926 >>> not_("this_suit='black'").sql() 4927 "NOT this_suit = 'black'" 4928 4929 Args: 4930 expression (str | Expression): the SQL code strings to parse. 4931 If an Expression instance is passed, this is used as-is. 4932 dialect (str): the dialect used to parse the input expression. 4933 **opts: other options to use to parse the input expressions. 4934 4935 Returns: 4936 Not: the new condition 4937 """ 4938 this = condition( 4939 expression, 4940 dialect=dialect, 4941 copy=copy, 4942 **opts, 4943 ) 4944 return Not(this=_wrap(this, Connector))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (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
4966def to_identifier(name, quoted=None, copy=True): 4967 """Builds an identifier. 4968 4969 Args: 4970 name: The name to turn into an identifier. 4971 quoted: Whether or not force quote the identifier. 4972 copy: Whether or not to copy a passed in Identefier node. 4973 4974 Returns: 4975 The identifier ast node. 4976 """ 4977 4978 if name is None: 4979 return None 4980 4981 if isinstance(name, Identifier): 4982 identifier = _maybe_copy(name, copy) 4983 elif isinstance(name, str): 4984 identifier = Identifier( 4985 this=name, 4986 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4987 ) 4988 else: 4989 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4990 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
- copy: Whether or not to copy a passed in Identefier node.
Returns:
The identifier ast node.
4996def to_interval(interval: str | Literal) -> Interval: 4997 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4998 if isinstance(interval, Literal): 4999 if not interval.is_string: 5000 raise ValueError("Invalid interval string.") 5001 5002 interval = interval.this 5003 5004 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 5005 5006 if not interval_parts: 5007 raise ValueError("Invalid interval string.") 5008 5009 return Interval( 5010 this=Literal.string(interval_parts.group(1)), 5011 unit=Var(this=interval_parts.group(2)), 5012 )
Builds an interval expression from a string like '1 day' or '5 months'.
5025def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 5026 """ 5027 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 5028 If a table is passed in then that table is returned. 5029 5030 Args: 5031 sql_path: a `[catalog].[schema].[table]` string. 5032 5033 Returns: 5034 A table expression. 5035 """ 5036 if sql_path is None or isinstance(sql_path, Table): 5037 return sql_path 5038 if not isinstance(sql_path, str): 5039 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 5040 5041 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 5042 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.
5045def to_column(sql_path: str | Column, **kwargs) -> Column: 5046 """ 5047 Create a column from a `[table].[column]` sql path. Schema is optional. 5048 5049 If a column is passed in then that column is returned. 5050 5051 Args: 5052 sql_path: `[table].[column]` string 5053 Returns: 5054 Table: A column expression 5055 """ 5056 if sql_path is None or isinstance(sql_path, Column): 5057 return sql_path 5058 if not isinstance(sql_path, str): 5059 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 5060 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
5063def alias_( 5064 expression: ExpOrStr, 5065 alias: str | Identifier, 5066 table: bool | t.Sequence[str | Identifier] = False, 5067 quoted: t.Optional[bool] = None, 5068 dialect: DialectType = None, 5069 copy: bool = True, 5070 **opts, 5071): 5072 """Create an Alias expression. 5073 5074 Example: 5075 >>> alias_('foo', 'bar').sql() 5076 'foo AS bar' 5077 5078 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 5079 '(SELECT 1, 2) AS bar(a, b)' 5080 5081 Args: 5082 expression: the SQL code strings to parse. 5083 If an Expression instance is passed, this is used as-is. 5084 alias: the alias name to use. If the name has 5085 special characters it is quoted. 5086 table: Whether or not to create a table alias, can also be a list of columns. 5087 quoted: whether or not to quote the alias 5088 dialect: the dialect used to parse the input expression. 5089 copy: Whether or not to copy the expression. 5090 **opts: other options to use to parse the input expressions. 5091 5092 Returns: 5093 Alias: the aliased expression 5094 """ 5095 exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) 5096 alias = to_identifier(alias, quoted=quoted) 5097 5098 if table: 5099 table_alias = TableAlias(this=alias) 5100 exp.set("alias", table_alias) 5101 5102 if not isinstance(table, bool): 5103 for column in table: 5104 table_alias.append("columns", to_identifier(column, quoted=quoted)) 5105 5106 return exp 5107 5108 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 5109 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 5110 # for the complete Window expression. 5111 # 5112 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 5113 5114 if "alias" in exp.arg_types and not isinstance(exp, Window): 5115 exp.set("alias", alias) 5116 return exp 5117 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- copy: Whether or not to copy the expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
5120def subquery(expression, alias=None, dialect=None, **opts): 5121 """ 5122 Build a subquery expression. 5123 5124 Example: 5125 >>> subquery('select x from tbl', 'bar').select('x').sql() 5126 'SELECT x FROM (SELECT x FROM tbl) AS bar' 5127 5128 Args: 5129 expression (str | Expression): the SQL code strings to parse. 5130 If an Expression instance is passed, this is used as-is. 5131 alias (str | Expression): the alias name to use. 5132 dialect (str): the dialect used to parse the input expression. 5133 **opts: other options to use to parse the input expressions. 5134 5135 Returns: 5136 Select: a new select with the subquery expression included 5137 """ 5138 5139 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 5140 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
5143def column( 5144 col: str | Identifier, 5145 table: t.Optional[str | Identifier] = None, 5146 db: t.Optional[str | Identifier] = None, 5147 catalog: t.Optional[str | Identifier] = None, 5148 quoted: t.Optional[bool] = None, 5149) -> Column: 5150 """ 5151 Build a Column. 5152 5153 Args: 5154 col: column name 5155 table: table name 5156 db: db name 5157 catalog: catalog name 5158 quoted: whether or not to force quote each part 5159 Returns: 5160 Column: column instance 5161 """ 5162 return Column( 5163 this=to_identifier(col, quoted=quoted), 5164 table=to_identifier(table, quoted=quoted), 5165 db=to_identifier(db, quoted=quoted), 5166 catalog=to_identifier(catalog, quoted=quoted), 5167 )
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
5170def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 5171 """Cast an expression to a data type. 5172 5173 Example: 5174 >>> cast('x + 1', 'int').sql() 5175 'CAST(x + 1 AS INT)' 5176 5177 Args: 5178 expression: The expression to cast. 5179 to: The datatype to cast to. 5180 5181 Returns: 5182 A cast node. 5183 """ 5184 expression = maybe_parse(expression, **opts) 5185 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.
5188def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 5189 """Build a Table. 5190 5191 Args: 5192 table (str | Expression): column name 5193 db (str | Expression): db name 5194 catalog (str | Expression): catalog name 5195 5196 Returns: 5197 Table: table instance 5198 """ 5199 return Table( 5200 this=to_identifier(table, quoted=quoted), 5201 db=to_identifier(db, quoted=quoted), 5202 catalog=to_identifier(catalog, quoted=quoted), 5203 alias=TableAlias(this=to_identifier(alias)) if alias else None, 5204 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
5207def values( 5208 values: t.Iterable[t.Tuple[t.Any, ...]], 5209 alias: t.Optional[str] = None, 5210 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 5211) -> Values: 5212 """Build VALUES statement. 5213 5214 Example: 5215 >>> values([(1, '2')]).sql() 5216 "VALUES (1, '2')" 5217 5218 Args: 5219 values: values statements that will be converted to SQL 5220 alias: optional alias 5221 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5222 If either are provided then an alias is also required. 5223 5224 Returns: 5225 Values: the Values expression object 5226 """ 5227 if columns and not alias: 5228 raise ValueError("Alias is required when providing columns") 5229 5230 return Values( 5231 expressions=[convert(tup) for tup in values], 5232 alias=( 5233 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5234 if columns 5235 else (TableAlias(this=to_identifier(alias)) if alias else None) 5236 ), 5237 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:
Values: the Values expression object
5240def var(name: t.Optional[ExpOrStr]) -> Var: 5241 """Build a SQL variable. 5242 5243 Example: 5244 >>> repr(var('x')) 5245 '(VAR this: x)' 5246 5247 >>> repr(var(column('x', table='y'))) 5248 '(VAR this: x)' 5249 5250 Args: 5251 name: The name of the var or an expression who's name will become the var. 5252 5253 Returns: 5254 The new variable node. 5255 """ 5256 if not name: 5257 raise ValueError("Cannot convert empty name into var.") 5258 5259 if isinstance(name, Expression): 5260 name = name.name 5261 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.
5264def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5265 """Build ALTER TABLE... RENAME... expression 5266 5267 Args: 5268 old_name: The old name of the table 5269 new_name: The new name of the table 5270 5271 Returns: 5272 Alter table expression 5273 """ 5274 old_table = to_table(old_name) 5275 new_table = to_table(new_name) 5276 return AlterTable( 5277 this=old_table, 5278 actions=[ 5279 RenameTable(this=new_table), 5280 ], 5281 )
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
5284def convert(value: t.Any, copy: bool = False) -> Expression: 5285 """Convert a python value into an expression object. 5286 5287 Raises an error if a conversion is not possible. 5288 5289 Args: 5290 value: A python object. 5291 copy: Whether or not to copy `value` (only applies to Expressions and collections). 5292 5293 Returns: 5294 Expression: the equivalent expression object. 5295 """ 5296 if isinstance(value, Expression): 5297 return _maybe_copy(value, copy) 5298 if isinstance(value, str): 5299 return Literal.string(value) 5300 if isinstance(value, bool): 5301 return Boolean(this=value) 5302 if value is None or (isinstance(value, float) and math.isnan(value)): 5303 return NULL 5304 if isinstance(value, numbers.Number): 5305 return Literal.number(value) 5306 if isinstance(value, datetime.datetime): 5307 datetime_literal = Literal.string( 5308 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5309 ) 5310 return TimeStrToTime(this=datetime_literal) 5311 if isinstance(value, datetime.date): 5312 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5313 return DateStrToDate(this=date_literal) 5314 if isinstance(value, tuple): 5315 return Tuple(expressions=[convert(v, copy=copy) for v in value]) 5316 if isinstance(value, list): 5317 return Array(expressions=[convert(v, copy=copy) for v in value]) 5318 if isinstance(value, dict): 5319 return Map( 5320 keys=[convert(k, copy=copy) for k in value], 5321 values=[convert(v, copy=copy) for v in value.values()], 5322 ) 5323 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value: A python object.
- copy: Whether or not to copy
value
(only applies to Expressions and collections).
Returns:
Expression: the equivalent expression object.
5326def replace_children(expression, fun, *args, **kwargs): 5327 """ 5328 Replace children of an expression with the result of a lambda fun(child) -> exp. 5329 """ 5330 for k, v in expression.args.items(): 5331 is_list_arg = type(v) is list 5332 5333 child_nodes = v if is_list_arg else [v] 5334 new_child_nodes = [] 5335 5336 for cn in child_nodes: 5337 if isinstance(cn, Expression): 5338 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5339 new_child_nodes.append(child_node) 5340 child_node.parent = expression 5341 child_node.arg_key = k 5342 else: 5343 new_child_nodes.append(cn) 5344 5345 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.
5348def column_table_names(expression): 5349 """ 5350 Return all table names referenced through columns in an expression. 5351 5352 Example: 5353 >>> import sqlglot 5354 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5355 ['c', 'a'] 5356 5357 Args: 5358 expression (sqlglot.Expression): expression to find table names 5359 5360 Returns: 5361 list: A list of unique names 5362 """ 5363 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
5366def table_name(table) -> str: 5367 """Get the full name of a table as a string. 5368 5369 Args: 5370 table (exp.Table | str): table expression node or string. 5371 5372 Examples: 5373 >>> from sqlglot import exp, parse_one 5374 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5375 'a.b.c' 5376 5377 Returns: 5378 The table name. 5379 """ 5380 5381 table = maybe_parse(table, into=Table) 5382 5383 if not table: 5384 raise ValueError(f"Cannot parse {table}") 5385 5386 return ".".join( 5387 part 5388 for part in ( 5389 table.text("catalog"), 5390 table.text("db"), 5391 table.name, 5392 ) 5393 if part 5394 )
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.
5397def replace_tables(expression, mapping): 5398 """Replace all tables in expression according to the mapping. 5399 5400 Args: 5401 expression (sqlglot.Expression): expression node to be transformed and replaced. 5402 mapping (Dict[str, str]): mapping of table names. 5403 5404 Examples: 5405 >>> from sqlglot import exp, parse_one 5406 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5407 'SELECT * FROM c' 5408 5409 Returns: 5410 The mapped expression. 5411 """ 5412 5413 def _replace_tables(node): 5414 if isinstance(node, Table): 5415 new_name = mapping.get(table_name(node)) 5416 if new_name: 5417 return to_table( 5418 new_name, 5419 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5420 ) 5421 return node 5422 5423 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.
5426def replace_placeholders(expression, *args, **kwargs): 5427 """Replace placeholders in an expression. 5428 5429 Args: 5430 expression (sqlglot.Expression): expression node to be transformed and replaced. 5431 args: positional names that will substitute unnamed placeholders in the given order. 5432 kwargs: keyword arguments that will substitute named placeholders. 5433 5434 Examples: 5435 >>> from sqlglot import exp, parse_one 5436 >>> replace_placeholders( 5437 ... parse_one("select * from :tbl where ? = ?"), 5438 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5439 ... ).sql() 5440 "SELECT * FROM foo WHERE str_col = 'b'" 5441 5442 Returns: 5443 The mapped expression. 5444 """ 5445 5446 def _replace_placeholders(node, args, **kwargs): 5447 if isinstance(node, Placeholder): 5448 if node.name: 5449 new_name = kwargs.get(node.name) 5450 if new_name: 5451 return convert(new_name) 5452 else: 5453 try: 5454 return convert(next(args)) 5455 except StopIteration: 5456 pass 5457 return node 5458 5459 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") ... ).sql() "SELECT * FROM foo WHERE str_col = 'b'"
Returns:
The mapped expression.
5462def expand( 5463 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5464) -> Expression: 5465 """Transforms an expression by expanding all referenced sources into subqueries. 5466 5467 Examples: 5468 >>> from sqlglot import parse_one 5469 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5470 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5471 5472 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5473 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5474 5475 Args: 5476 expression: The expression to expand. 5477 sources: A dictionary of name to Subqueryables. 5478 copy: Whether or not to copy the expression during transformation. Defaults to True. 5479 5480 Returns: 5481 The transformed expression. 5482 """ 5483 5484 def _expand(node: Expression): 5485 if isinstance(node, Table): 5486 name = table_name(node) 5487 source = sources.get(name) 5488 if source: 5489 subquery = source.subquery(node.alias or name) 5490 subquery.comments = [f"source: {name}"] 5491 return subquery.transform(_expand, copy=False) 5492 return node 5493 5494 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5497def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5498 """ 5499 Returns a Func expression. 5500 5501 Examples: 5502 >>> func("abs", 5).sql() 5503 'ABS(5)' 5504 5505 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5506 'CAST(5 AS DOUBLE)' 5507 5508 Args: 5509 name: the name of the function to build. 5510 args: the args used to instantiate the function of interest. 5511 dialect: the source dialect. 5512 kwargs: the kwargs used to instantiate the function of interest. 5513 5514 Note: 5515 The arguments `args` and `kwargs` are mutually exclusive. 5516 5517 Returns: 5518 An instance of the function of interest, or an anonymous function, if `name` doesn't 5519 correspond to an existing `sqlglot.expressions.Func` class. 5520 """ 5521 if args and kwargs: 5522 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5523 5524 from sqlglot.dialects.dialect import Dialect 5525 5526 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5527 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5528 5529 parser = Dialect.get_or_raise(dialect)().parser() 5530 from_args_list = parser.FUNCTIONS.get(name.upper()) 5531 5532 if from_args_list: 5533 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5534 else: 5535 kwargs = kwargs or {"expressions": converted} 5536 function = Anonymous(this=name, **kwargs) 5537 5538 for error_message in function.error_messages(converted): 5539 raise ValueError(error_message) 5540 5541 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.
5544def true(): 5545 """ 5546 Returns a true Boolean expression. 5547 """ 5548 return Boolean(this=True)
Returns a true Boolean expression.
5551def false(): 5552 """ 5553 Returns a false Boolean expression. 5554 """ 5555 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.