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