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 seq_get, 30 split_num_words, 31 subclasses, 32) 33from sqlglot.tokens import Token 34 35if t.TYPE_CHECKING: 36 from sqlglot.dialects.dialect import DialectType 37 38E = t.TypeVar("E", bound="Expression") 39 40 41class _Expression(type): 42 def __new__(cls, clsname, bases, attrs): 43 klass = super().__new__(cls, clsname, bases, attrs) 44 45 # When an Expression class is created, its key is automatically set to be 46 # the lowercase version of the class' name. 47 klass.key = clsname.lower() 48 49 # This is so that docstrings are not inherited in pdoc 50 klass.__doc__ = klass.__doc__ or "" 51 52 return klass 53 54 55class Expression(metaclass=_Expression): 56 """ 57 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 58 context, such as its child expressions, their names (arg keys), and whether a given child expression 59 is optional or not. 60 61 Attributes: 62 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 63 and representing expressions as strings. 64 arg_types: determines what arguments (child nodes) are supported by an expression. It 65 maps arg keys to booleans that indicate whether the corresponding args are optional. 66 67 Example: 68 >>> class Foo(Expression): 69 ... arg_types = {"this": True, "expression": False} 70 71 The above definition informs us that Foo is an Expression that requires an argument called 72 "this" and may also optionally receive an argument called "expression". 73 74 Args: 75 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 76 parent: a reference to the parent expression (or None, in case of root expressions). 77 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 78 uses to refer to it. 79 comments: a list of comments that are associated with a given expression. This is used in 80 order to preserve comments when transpiling SQL code. 81 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 82 optimizer, in order to enable some transformations that require type information. 83 """ 84 85 key = "expression" 86 arg_types = {"this": True} 87 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta") 88 89 def __init__(self, **args: t.Any): 90 self.args: t.Dict[str, t.Any] = args 91 self.parent: t.Optional[Expression] = None 92 self.arg_key: t.Optional[str] = None 93 self.comments: t.Optional[t.List[str]] = None 94 self._type: t.Optional[DataType] = None 95 self._meta: t.Optional[t.Dict[str, t.Any]] = None 96 97 for arg_key, value in self.args.items(): 98 self._set_parent(arg_key, value) 99 100 def __eq__(self, other) -> bool: 101 return type(self) is type(other) and _norm_args(self) == _norm_args(other) 102 103 def __hash__(self) -> int: 104 return hash( 105 ( 106 self.key, 107 tuple( 108 (k, tuple(v) if isinstance(v, list) else v) for k, v in _norm_args(self).items() 109 ), 110 ) 111 ) 112 113 @property 114 def this(self): 115 """ 116 Retrieves the argument with key "this". 117 """ 118 return self.args.get("this") 119 120 @property 121 def expression(self): 122 """ 123 Retrieves the argument with key "expression". 124 """ 125 return self.args.get("expression") 126 127 @property 128 def expressions(self): 129 """ 130 Retrieves the argument with key "expressions". 131 """ 132 return self.args.get("expressions") or [] 133 134 def text(self, key) -> str: 135 """ 136 Returns a textual representation of the argument corresponding to "key". This can only be used 137 for args that are strings or leaf Expression instances, such as identifiers and literals. 138 """ 139 field = self.args.get(key) 140 if isinstance(field, str): 141 return field 142 if isinstance(field, (Identifier, Literal, Var)): 143 return field.this 144 if isinstance(field, (Star, Null)): 145 return field.name 146 return "" 147 148 @property 149 def is_string(self) -> bool: 150 """ 151 Checks whether a Literal expression is a string. 152 """ 153 return isinstance(self, Literal) and self.args["is_string"] 154 155 @property 156 def is_number(self) -> bool: 157 """ 158 Checks whether a Literal expression is a number. 159 """ 160 return isinstance(self, Literal) and not self.args["is_string"] 161 162 @property 163 def is_int(self) -> bool: 164 """ 165 Checks whether a Literal expression is an integer. 166 """ 167 if self.is_number: 168 try: 169 int(self.name) 170 return True 171 except ValueError: 172 pass 173 return False 174 175 @property 176 def is_star(self) -> bool: 177 """Checks whether an expression is a star.""" 178 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 179 180 @property 181 def alias(self) -> str: 182 """ 183 Returns the alias of the expression, or an empty string if it's not aliased. 184 """ 185 if isinstance(self.args.get("alias"), TableAlias): 186 return self.args["alias"].name 187 return self.text("alias") 188 189 @property 190 def name(self) -> str: 191 return self.text("this") 192 193 @property 194 def alias_or_name(self): 195 return self.alias or self.name 196 197 @property 198 def output_name(self): 199 """ 200 Name of the output column if this expression is a selection. 201 202 If the Expression has no output name, an empty string is returned. 203 204 Example: 205 >>> from sqlglot import parse_one 206 >>> parse_one("SELECT a").expressions[0].output_name 207 'a' 208 >>> parse_one("SELECT b AS c").expressions[0].output_name 209 'c' 210 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 211 '' 212 """ 213 return "" 214 215 @property 216 def type(self) -> t.Optional[DataType]: 217 return self._type 218 219 @type.setter 220 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 221 if dtype and not isinstance(dtype, DataType): 222 dtype = DataType.build(dtype) 223 self._type = dtype # type: ignore 224 225 @property 226 def meta(self) -> t.Dict[str, t.Any]: 227 if self._meta is None: 228 self._meta = {} 229 return self._meta 230 231 def __deepcopy__(self, memo): 232 copy = self.__class__(**deepcopy(self.args)) 233 if self.comments is not None: 234 copy.comments = deepcopy(self.comments) 235 236 if self._type is not None: 237 copy._type = self._type.copy() 238 239 if self._meta is not None: 240 copy._meta = deepcopy(self._meta) 241 242 return copy 243 244 def copy(self): 245 """ 246 Returns a deep copy of the expression. 247 """ 248 new = deepcopy(self) 249 new.parent = self.parent 250 for item, parent, _ in new.bfs(): 251 if isinstance(item, Expression) and parent: 252 item.parent = parent 253 return new 254 255 def append(self, arg_key, value): 256 """ 257 Appends value to arg_key if it's a list or sets it as a new list. 258 259 Args: 260 arg_key (str): name of the list expression arg 261 value (Any): value to append to the list 262 """ 263 if not isinstance(self.args.get(arg_key), list): 264 self.args[arg_key] = [] 265 self.args[arg_key].append(value) 266 self._set_parent(arg_key, value) 267 268 def set(self, arg_key, value): 269 """ 270 Sets `arg_key` to `value`. 271 272 Args: 273 arg_key (str): name of the expression arg. 274 value: value to set the arg to. 275 """ 276 self.args[arg_key] = value 277 self._set_parent(arg_key, value) 278 279 def _set_parent(self, arg_key, value): 280 if isinstance(value, Expression): 281 value.parent = self 282 value.arg_key = arg_key 283 elif isinstance(value, list): 284 for v in value: 285 if isinstance(v, Expression): 286 v.parent = self 287 v.arg_key = arg_key 288 289 @property 290 def depth(self): 291 """ 292 Returns the depth of this tree. 293 """ 294 if self.parent: 295 return self.parent.depth + 1 296 return 0 297 298 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 299 """ 300 Returns the first node in this tree which matches at least one of 301 the specified types. 302 303 Args: 304 expression_types (type): the expression type(s) to match. 305 306 Returns: 307 The node which matches the criteria or None if no such node was found. 308 """ 309 return next(self.find_all(*expression_types, bfs=bfs), None) 310 311 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 312 """ 313 Returns a generator object which visits all nodes in this tree and only 314 yields those that match at least one of the specified expression types. 315 316 Args: 317 expression_types (type): the expression type(s) to match. 318 319 Returns: 320 The generator object. 321 """ 322 for expression, _, _ in self.walk(bfs=bfs): 323 if isinstance(expression, expression_types): 324 yield expression 325 326 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 327 """ 328 Returns a nearest parent matching expression_types. 329 330 Args: 331 expression_types (type): the expression type(s) to match. 332 333 Returns: 334 The parent node. 335 """ 336 ancestor = self.parent 337 while ancestor and not isinstance(ancestor, expression_types): 338 ancestor = ancestor.parent 339 # ignore type because mypy doesn't know that we're checking type in the loop 340 return ancestor # type: ignore[return-value] 341 342 @property 343 def parent_select(self): 344 """ 345 Returns the parent select statement. 346 """ 347 return self.find_ancestor(Select) 348 349 def root(self) -> Expression: 350 """ 351 Returns the root expression of this tree. 352 """ 353 expression = self 354 while expression.parent: 355 expression = expression.parent 356 return expression 357 358 def walk(self, bfs=True, prune=None): 359 """ 360 Returns a generator object which visits all nodes in this tree. 361 362 Args: 363 bfs (bool): if set to True the BFS traversal order will be applied, 364 otherwise the DFS traversal will be used instead. 365 prune ((node, parent, arg_key) -> bool): callable that returns True if 366 the generator should stop traversing this branch of the tree. 367 368 Returns: 369 the generator object. 370 """ 371 if bfs: 372 yield from self.bfs(prune=prune) 373 else: 374 yield from self.dfs(prune=prune) 375 376 def dfs(self, parent=None, key=None, prune=None): 377 """ 378 Returns a generator object which visits all nodes in this tree in 379 the DFS (Depth-first) order. 380 381 Returns: 382 The generator object. 383 """ 384 parent = parent or self.parent 385 yield self, parent, key 386 if prune and prune(self, parent, key): 387 return 388 389 for k, v in self.args.items(): 390 for node in ensure_collection(v): 391 if isinstance(node, Expression): 392 yield from node.dfs(self, k, prune) 393 394 def bfs(self, prune=None): 395 """ 396 Returns a generator object which visits all nodes in this tree in 397 the BFS (Breadth-first) order. 398 399 Returns: 400 The generator object. 401 """ 402 queue = deque([(self, self.parent, None)]) 403 404 while queue: 405 item, parent, key = queue.popleft() 406 407 yield item, parent, key 408 if prune and prune(item, parent, key): 409 continue 410 411 if isinstance(item, Expression): 412 for k, v in item.args.items(): 413 for node in ensure_collection(v): 414 if isinstance(node, Expression): 415 queue.append((node, item, k)) 416 417 def unnest(self): 418 """ 419 Returns the first non parenthesis child or self. 420 """ 421 expression = self 422 while isinstance(expression, Paren): 423 expression = expression.this 424 return expression 425 426 def unalias(self): 427 """ 428 Returns the inner expression if this is an Alias. 429 """ 430 if isinstance(self, Alias): 431 return self.this 432 return self 433 434 def unnest_operands(self): 435 """ 436 Returns unnested operands as a tuple. 437 """ 438 return tuple(arg.unnest() for arg in self.args.values() if arg) 439 440 def flatten(self, unnest=True): 441 """ 442 Returns a generator which yields child nodes who's parents are the same class. 443 444 A AND B AND C -> [A, B, C] 445 """ 446 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)): 447 if not isinstance(node, self.__class__): 448 yield node.unnest() if unnest else node 449 450 def __str__(self): 451 return self.sql() 452 453 def __repr__(self): 454 return self._to_s() 455 456 def sql(self, dialect: DialectType = None, **opts) -> str: 457 """ 458 Returns SQL string representation of this tree. 459 460 Args: 461 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 462 opts: other `sqlglot.generator.Generator` options. 463 464 Returns: 465 The SQL string. 466 """ 467 from sqlglot.dialects import Dialect 468 469 return Dialect.get_or_raise(dialect)().generate(self, **opts) 470 471 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 472 indent = "" if not level else "\n" 473 indent += "".join([" "] * level) 474 left = f"({self.key.upper()} " 475 476 args: t.Dict[str, t.Any] = { 477 k: ", ".join( 478 v._to_s(hide_missing=hide_missing, level=level + 1) 479 if hasattr(v, "_to_s") 480 else str(v) 481 for v in ensure_collection(vs) 482 if v is not None 483 ) 484 for k, vs in self.args.items() 485 } 486 args["comments"] = self.comments 487 args["type"] = self.type 488 args = {k: v for k, v in args.items() if v or not hide_missing} 489 490 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 491 right += ")" 492 493 return indent + left + right 494 495 def transform(self, fun, *args, copy=True, **kwargs): 496 """ 497 Recursively visits all tree nodes (excluding already transformed ones) 498 and applies the given transformation function to each node. 499 500 Args: 501 fun (function): a function which takes a node as an argument and returns a 502 new transformed node or the same node without modifications. If the function 503 returns None, then the corresponding node will be removed from the syntax tree. 504 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 505 modified in place. 506 507 Returns: 508 The transformed tree. 509 """ 510 node = self.copy() if copy else self 511 new_node = fun(node, *args, **kwargs) 512 513 if new_node is None or not isinstance(new_node, Expression): 514 return new_node 515 if new_node is not node: 516 new_node.parent = node.parent 517 return new_node 518 519 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 520 return new_node 521 522 def replace(self, expression): 523 """ 524 Swap out this expression with a new expression. 525 526 For example:: 527 528 >>> tree = Select().select("x").from_("tbl") 529 >>> tree.find(Column).replace(Column(this="y")) 530 (COLUMN this: y) 531 >>> tree.sql() 532 'SELECT y FROM tbl' 533 534 Args: 535 expression (Expression|None): new node 536 537 Returns: 538 The new expression or expressions. 539 """ 540 if not self.parent: 541 return expression 542 543 parent = self.parent 544 self.parent = None 545 546 replace_children(parent, lambda child: expression if child is self else child) 547 return expression 548 549 def pop(self): 550 """ 551 Remove this expression from its AST. 552 """ 553 self.replace(None) 554 555 def assert_is(self, type_): 556 """ 557 Assert that this `Expression` is an instance of `type_`. 558 559 If it is NOT an instance of `type_`, this raises an assertion error. 560 Otherwise, this returns this expression. 561 562 Examples: 563 This is useful for type security in chained expressions: 564 565 >>> import sqlglot 566 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 567 'SELECT x, z FROM y' 568 """ 569 assert isinstance(self, type_) 570 return self 571 572 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 573 """ 574 Checks if this expression is valid (e.g. all mandatory args are set). 575 576 Args: 577 args: a sequence of values that were used to instantiate a Func expression. This is used 578 to check that the provided arguments don't exceed the function argument limit. 579 580 Returns: 581 A list of error messages for all possible errors that were found. 582 """ 583 errors: t.List[str] = [] 584 585 for k in self.args: 586 if k not in self.arg_types: 587 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 588 for k, mandatory in self.arg_types.items(): 589 v = self.args.get(k) 590 if mandatory and (v is None or (isinstance(v, list) and not v)): 591 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 592 593 if ( 594 args 595 and isinstance(self, Func) 596 and len(args) > len(self.arg_types) 597 and not self.is_var_len_args 598 ): 599 errors.append( 600 f"The number of provided arguments ({len(args)}) is greater than " 601 f"the maximum number of supported arguments ({len(self.arg_types)})" 602 ) 603 604 return errors 605 606 def dump(self): 607 """ 608 Dump this Expression to a JSON-serializable dict. 609 """ 610 from sqlglot.serde import dump 611 612 return dump(self) 613 614 @classmethod 615 def load(cls, obj): 616 """ 617 Load a dict (as returned by `Expression.dump`) into an Expression instance. 618 """ 619 from sqlglot.serde import load 620 621 return load(obj) 622 623 624IntoType = t.Union[ 625 str, 626 t.Type[Expression], 627 t.Collection[t.Union[str, t.Type[Expression]]], 628] 629 630 631class Condition(Expression): 632 def and_(self, *expressions, dialect=None, **opts): 633 """ 634 AND this condition with one or multiple expressions. 635 636 Example: 637 >>> condition("x=1").and_("y=1").sql() 638 'x = 1 AND y = 1' 639 640 Args: 641 *expressions (str | Expression): the SQL code strings to parse. 642 If an `Expression` instance is passed, it will be used as-is. 643 dialect (str): the dialect used to parse the input expression. 644 opts (kwargs): other options to use to parse the input expressions. 645 646 Returns: 647 And: the new condition. 648 """ 649 return and_(self, *expressions, dialect=dialect, **opts) 650 651 def or_(self, *expressions, dialect=None, **opts): 652 """ 653 OR this condition with one or multiple expressions. 654 655 Example: 656 >>> condition("x=1").or_("y=1").sql() 657 'x = 1 OR y = 1' 658 659 Args: 660 *expressions (str | Expression): the SQL code strings to parse. 661 If an `Expression` instance is passed, it will be used as-is. 662 dialect (str): the dialect used to parse the input expression. 663 opts (kwargs): other options to use to parse the input expressions. 664 665 Returns: 666 Or: the new condition. 667 """ 668 return or_(self, *expressions, dialect=dialect, **opts) 669 670 def not_(self): 671 """ 672 Wrap this condition with NOT. 673 674 Example: 675 >>> condition("x=1").not_().sql() 676 'NOT x = 1' 677 678 Returns: 679 Not: the new condition. 680 """ 681 return not_(self) 682 683 684class Predicate(Condition): 685 """Relationships like x = y, x > 1, x >= y.""" 686 687 688class DerivedTable(Expression): 689 @property 690 def alias_column_names(self): 691 table_alias = self.args.get("alias") 692 if not table_alias: 693 return [] 694 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 695 return [c.name for c in column_list] 696 697 @property 698 def selects(self): 699 alias = self.args.get("alias") 700 701 if alias: 702 return alias.columns 703 return [] 704 705 @property 706 def named_selects(self): 707 return [select.output_name for select in self.selects] 708 709 710class Unionable(Expression): 711 def union(self, expression, distinct=True, dialect=None, **opts): 712 """ 713 Builds a UNION expression. 714 715 Example: 716 >>> import sqlglot 717 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 718 'SELECT * FROM foo UNION SELECT * FROM bla' 719 720 Args: 721 expression (str | Expression): the SQL code string. 722 If an `Expression` instance is passed, it will be used as-is. 723 distinct (bool): set the DISTINCT flag if and only if this is true. 724 dialect (str): the dialect used to parse the input expression. 725 opts (kwargs): other options to use to parse the input expressions. 726 Returns: 727 Union: the Union expression. 728 """ 729 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 730 731 def intersect(self, expression, distinct=True, dialect=None, **opts): 732 """ 733 Builds an INTERSECT expression. 734 735 Example: 736 >>> import sqlglot 737 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 738 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 739 740 Args: 741 expression (str | Expression): the SQL code string. 742 If an `Expression` instance is passed, it will be used as-is. 743 distinct (bool): set the DISTINCT flag if and only if this is true. 744 dialect (str): the dialect used to parse the input expression. 745 opts (kwargs): other options to use to parse the input expressions. 746 Returns: 747 Intersect: the Intersect expression 748 """ 749 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 750 751 def except_(self, expression, distinct=True, dialect=None, **opts): 752 """ 753 Builds an EXCEPT expression. 754 755 Example: 756 >>> import sqlglot 757 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 758 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 759 760 Args: 761 expression (str | Expression): the SQL code string. 762 If an `Expression` instance is passed, it will be used as-is. 763 distinct (bool): set the DISTINCT flag if and only if this is true. 764 dialect (str): the dialect used to parse the input expression. 765 opts (kwargs): other options to use to parse the input expressions. 766 Returns: 767 Except: the Except expression 768 """ 769 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 770 771 772class UDTF(DerivedTable, Unionable): 773 pass 774 775 776class Cache(Expression): 777 arg_types = { 778 "with": False, 779 "this": True, 780 "lazy": False, 781 "options": False, 782 "expression": False, 783 } 784 785 786class Uncache(Expression): 787 arg_types = {"this": True, "exists": False} 788 789 790class Create(Expression): 791 arg_types = { 792 "with": False, 793 "this": True, 794 "kind": True, 795 "expression": False, 796 "exists": False, 797 "properties": False, 798 "replace": False, 799 "unique": False, 800 "volatile": False, 801 "indexes": False, 802 "no_schema_binding": False, 803 "begin": False, 804 } 805 806 807class Describe(Expression): 808 arg_types = {"this": True, "kind": False} 809 810 811class Set(Expression): 812 arg_types = {"expressions": True} 813 814 815class SetItem(Expression): 816 arg_types = { 817 "this": False, 818 "expressions": False, 819 "kind": False, 820 "collate": False, # MySQL SET NAMES statement 821 "global": False, 822 } 823 824 825class Show(Expression): 826 arg_types = { 827 "this": True, 828 "target": False, 829 "offset": False, 830 "limit": False, 831 "like": False, 832 "where": False, 833 "db": False, 834 "full": False, 835 "mutex": False, 836 "query": False, 837 "channel": False, 838 "global": False, 839 "log": False, 840 "position": False, 841 "types": False, 842 } 843 844 845class UserDefinedFunction(Expression): 846 arg_types = {"this": True, "expressions": False, "wrapped": False} 847 848 849class CharacterSet(Expression): 850 arg_types = {"this": True, "default": False} 851 852 853class With(Expression): 854 arg_types = {"expressions": True, "recursive": False} 855 856 @property 857 def recursive(self) -> bool: 858 return bool(self.args.get("recursive")) 859 860 861class WithinGroup(Expression): 862 arg_types = {"this": True, "expression": False} 863 864 865class CTE(DerivedTable): 866 arg_types = {"this": True, "alias": True} 867 868 869class TableAlias(Expression): 870 arg_types = {"this": False, "columns": False} 871 872 @property 873 def columns(self): 874 return self.args.get("columns") or [] 875 876 877class BitString(Condition): 878 pass 879 880 881class HexString(Condition): 882 pass 883 884 885class ByteString(Condition): 886 pass 887 888 889class Column(Condition): 890 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 891 892 @property 893 def table(self) -> str: 894 return self.text("table") 895 896 @property 897 def db(self) -> str: 898 return self.text("db") 899 900 @property 901 def catalog(self) -> str: 902 return self.text("catalog") 903 904 @property 905 def output_name(self) -> str: 906 return self.name 907 908 909class ColumnDef(Expression): 910 arg_types = { 911 "this": True, 912 "kind": False, 913 "constraints": False, 914 "exists": False, 915 } 916 917 918class AlterColumn(Expression): 919 arg_types = { 920 "this": True, 921 "dtype": False, 922 "collate": False, 923 "using": False, 924 "default": False, 925 "drop": False, 926 } 927 928 929class RenameTable(Expression): 930 pass 931 932 933class SetTag(Expression): 934 arg_types = {"expressions": True, "unset": False} 935 936 937class Comment(Expression): 938 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 939 940 941class ColumnConstraint(Expression): 942 arg_types = {"this": False, "kind": True} 943 944 945class ColumnConstraintKind(Expression): 946 pass 947 948 949class AutoIncrementColumnConstraint(ColumnConstraintKind): 950 pass 951 952 953class CaseSpecificColumnConstraint(ColumnConstraintKind): 954 arg_types = {"not_": True} 955 956 957class CharacterSetColumnConstraint(ColumnConstraintKind): 958 arg_types = {"this": True} 959 960 961class CheckColumnConstraint(ColumnConstraintKind): 962 pass 963 964 965class CollateColumnConstraint(ColumnConstraintKind): 966 pass 967 968 969class CommentColumnConstraint(ColumnConstraintKind): 970 pass 971 972 973class CompressColumnConstraint(ColumnConstraintKind): 974 pass 975 976 977class DateFormatColumnConstraint(ColumnConstraintKind): 978 arg_types = {"this": True} 979 980 981class DefaultColumnConstraint(ColumnConstraintKind): 982 pass 983 984 985class EncodeColumnConstraint(ColumnConstraintKind): 986 pass 987 988 989class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 990 # this: True -> ALWAYS, this: False -> BY DEFAULT 991 arg_types = { 992 "this": False, 993 "start": False, 994 "increment": False, 995 "minvalue": False, 996 "maxvalue": False, 997 "cycle": False, 998 } 999 1000 1001class InlineLengthColumnConstraint(ColumnConstraintKind): 1002 pass 1003 1004 1005class NotNullColumnConstraint(ColumnConstraintKind): 1006 arg_types = {"allow_null": False} 1007 1008 1009class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1010 arg_types = {"desc": False} 1011 1012 1013class TitleColumnConstraint(ColumnConstraintKind): 1014 pass 1015 1016 1017class UniqueColumnConstraint(ColumnConstraintKind): 1018 arg_types: t.Dict[str, t.Any] = {} 1019 1020 1021class UppercaseColumnConstraint(ColumnConstraintKind): 1022 arg_types: t.Dict[str, t.Any] = {} 1023 1024 1025class PathColumnConstraint(ColumnConstraintKind): 1026 pass 1027 1028 1029class Constraint(Expression): 1030 arg_types = {"this": True, "expressions": True} 1031 1032 1033class Delete(Expression): 1034 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1035 1036 1037class Drop(Expression): 1038 arg_types = { 1039 "this": False, 1040 "kind": False, 1041 "exists": False, 1042 "temporary": False, 1043 "materialized": False, 1044 "cascade": False, 1045 } 1046 1047 1048class Filter(Expression): 1049 arg_types = {"this": True, "expression": True} 1050 1051 1052class Check(Expression): 1053 pass 1054 1055 1056class Directory(Expression): 1057 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1058 arg_types = {"this": True, "local": False, "row_format": False} 1059 1060 1061class ForeignKey(Expression): 1062 arg_types = { 1063 "expressions": True, 1064 "reference": False, 1065 "delete": False, 1066 "update": False, 1067 } 1068 1069 1070class PrimaryKey(Expression): 1071 arg_types = {"expressions": True, "options": False} 1072 1073 1074class Unique(Expression): 1075 arg_types = {"expressions": True} 1076 1077 1078# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1079# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1080class Into(Expression): 1081 arg_types = {"this": True, "temporary": False, "unlogged": False} 1082 1083 1084class From(Expression): 1085 arg_types = {"expressions": True} 1086 1087 1088class Having(Expression): 1089 pass 1090 1091 1092class Hint(Expression): 1093 arg_types = {"expressions": True} 1094 1095 1096class JoinHint(Expression): 1097 arg_types = {"this": True, "expressions": True} 1098 1099 1100class Identifier(Expression): 1101 arg_types = {"this": True, "quoted": False} 1102 1103 @property 1104 def quoted(self): 1105 return bool(self.args.get("quoted")) 1106 1107 def __eq__(self, other): 1108 return isinstance(other, self.__class__) and _norm_arg(self.this) == _norm_arg(other.this) 1109 1110 def __hash__(self): 1111 return hash((self.key, self.this.lower())) 1112 1113 @property 1114 def output_name(self): 1115 return self.name 1116 1117 1118class Index(Expression): 1119 arg_types = { 1120 "this": False, 1121 "table": False, 1122 "where": False, 1123 "columns": False, 1124 "unique": False, 1125 "primary": False, 1126 "amp": False, # teradata 1127 } 1128 1129 1130class Insert(Expression): 1131 arg_types = { 1132 "with": False, 1133 "this": True, 1134 "expression": False, 1135 "returning": False, 1136 "overwrite": False, 1137 "exists": False, 1138 "partition": False, 1139 "alternative": False, 1140 } 1141 1142 1143class Returning(Expression): 1144 arg_types = {"expressions": True} 1145 1146 1147# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1148class Introducer(Expression): 1149 arg_types = {"this": True, "expression": True} 1150 1151 1152# national char, like n'utf8' 1153class National(Expression): 1154 pass 1155 1156 1157class LoadData(Expression): 1158 arg_types = { 1159 "this": True, 1160 "local": False, 1161 "overwrite": False, 1162 "inpath": True, 1163 "partition": False, 1164 "input_format": False, 1165 "serde": False, 1166 } 1167 1168 1169class Partition(Expression): 1170 arg_types = {"expressions": True} 1171 1172 1173class Fetch(Expression): 1174 arg_types = {"direction": False, "count": False} 1175 1176 1177class Group(Expression): 1178 arg_types = { 1179 "expressions": False, 1180 "grouping_sets": False, 1181 "cube": False, 1182 "rollup": False, 1183 } 1184 1185 1186class Lambda(Expression): 1187 arg_types = {"this": True, "expressions": True} 1188 1189 1190class Limit(Expression): 1191 arg_types = {"this": False, "expression": True} 1192 1193 1194class Literal(Condition): 1195 arg_types = {"this": True, "is_string": True} 1196 1197 def __eq__(self, other): 1198 return ( 1199 isinstance(other, Literal) 1200 and self.this == other.this 1201 and self.args["is_string"] == other.args["is_string"] 1202 ) 1203 1204 def __hash__(self): 1205 return hash((self.key, self.this, self.args["is_string"])) 1206 1207 @classmethod 1208 def number(cls, number) -> Literal: 1209 return cls(this=str(number), is_string=False) 1210 1211 @classmethod 1212 def string(cls, string) -> Literal: 1213 return cls(this=str(string), is_string=True) 1214 1215 @property 1216 def output_name(self): 1217 return self.name 1218 1219 1220class Join(Expression): 1221 arg_types = { 1222 "this": True, 1223 "on": False, 1224 "side": False, 1225 "kind": False, 1226 "using": False, 1227 "natural": False, 1228 } 1229 1230 @property 1231 def kind(self): 1232 return self.text("kind").upper() 1233 1234 @property 1235 def side(self): 1236 return self.text("side").upper() 1237 1238 @property 1239 def alias_or_name(self): 1240 return self.this.alias_or_name 1241 1242 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1243 """ 1244 Append to or set the ON expressions. 1245 1246 Example: 1247 >>> import sqlglot 1248 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1249 'JOIN x ON y = 1' 1250 1251 Args: 1252 *expressions (str | Expression): the SQL code strings to parse. 1253 If an `Expression` instance is passed, it will be used as-is. 1254 Multiple expressions are combined with an AND operator. 1255 append (bool): if `True`, AND the new expressions to any existing expression. 1256 Otherwise, this resets the expression. 1257 dialect (str): the dialect used to parse the input expressions. 1258 copy (bool): if `False`, modify this expression instance in-place. 1259 opts (kwargs): other options to use to parse the input expressions. 1260 1261 Returns: 1262 Join: the modified join expression. 1263 """ 1264 join = _apply_conjunction_builder( 1265 *expressions, 1266 instance=self, 1267 arg="on", 1268 append=append, 1269 dialect=dialect, 1270 copy=copy, 1271 **opts, 1272 ) 1273 1274 if join.kind == "CROSS": 1275 join.set("kind", None) 1276 1277 return join 1278 1279 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1280 """ 1281 Append to or set the USING expressions. 1282 1283 Example: 1284 >>> import sqlglot 1285 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1286 'JOIN x USING (foo, bla)' 1287 1288 Args: 1289 *expressions (str | Expression): the SQL code strings to parse. 1290 If an `Expression` instance is passed, it will be used as-is. 1291 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1292 Otherwise, this resets the expression. 1293 dialect (str): the dialect used to parse the input expressions. 1294 copy (bool): if `False`, modify this expression instance in-place. 1295 opts (kwargs): other options to use to parse the input expressions. 1296 1297 Returns: 1298 Join: the modified join expression. 1299 """ 1300 join = _apply_list_builder( 1301 *expressions, 1302 instance=self, 1303 arg="using", 1304 append=append, 1305 dialect=dialect, 1306 copy=copy, 1307 **opts, 1308 ) 1309 1310 if join.kind == "CROSS": 1311 join.set("kind", None) 1312 1313 return join 1314 1315 1316class Lateral(UDTF): 1317 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1318 1319 1320class MatchRecognize(Expression): 1321 arg_types = { 1322 "partition_by": False, 1323 "order": False, 1324 "measures": False, 1325 "rows": False, 1326 "after": False, 1327 "pattern": False, 1328 "define": False, 1329 } 1330 1331 1332# Clickhouse FROM FINAL modifier 1333# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1334class Final(Expression): 1335 pass 1336 1337 1338class Offset(Expression): 1339 arg_types = {"this": False, "expression": True} 1340 1341 1342class Order(Expression): 1343 arg_types = {"this": False, "expressions": True} 1344 1345 1346# hive specific sorts 1347# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1348class Cluster(Order): 1349 pass 1350 1351 1352class Distribute(Order): 1353 pass 1354 1355 1356class Sort(Order): 1357 pass 1358 1359 1360class Ordered(Expression): 1361 arg_types = {"this": True, "desc": True, "nulls_first": True} 1362 1363 1364class Property(Expression): 1365 arg_types = {"this": True, "value": True} 1366 1367 1368class AfterJournalProperty(Property): 1369 arg_types = {"no": True, "dual": False, "local": False} 1370 1371 1372class AlgorithmProperty(Property): 1373 arg_types = {"this": True} 1374 1375 1376class AutoIncrementProperty(Property): 1377 arg_types = {"this": True} 1378 1379 1380class BlockCompressionProperty(Property): 1381 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1382 1383 1384class CharacterSetProperty(Property): 1385 arg_types = {"this": True, "default": True} 1386 1387 1388class ChecksumProperty(Property): 1389 arg_types = {"on": False, "default": False} 1390 1391 1392class CollateProperty(Property): 1393 arg_types = {"this": True} 1394 1395 1396class DataBlocksizeProperty(Property): 1397 arg_types = {"size": False, "units": False, "min": False, "default": False} 1398 1399 1400class DefinerProperty(Property): 1401 arg_types = {"this": True} 1402 1403 1404class DistKeyProperty(Property): 1405 arg_types = {"this": True} 1406 1407 1408class DistStyleProperty(Property): 1409 arg_types = {"this": True} 1410 1411 1412class EngineProperty(Property): 1413 arg_types = {"this": True} 1414 1415 1416class ExecuteAsProperty(Property): 1417 arg_types = {"this": True} 1418 1419 1420class ExternalProperty(Property): 1421 arg_types = {"this": False} 1422 1423 1424class FallbackProperty(Property): 1425 arg_types = {"no": True, "protection": False} 1426 1427 1428class FileFormatProperty(Property): 1429 arg_types = {"this": True} 1430 1431 1432class FreespaceProperty(Property): 1433 arg_types = {"this": True, "percent": False} 1434 1435 1436class IsolatedLoadingProperty(Property): 1437 arg_types = { 1438 "no": True, 1439 "concurrent": True, 1440 "for_all": True, 1441 "for_insert": True, 1442 "for_none": True, 1443 } 1444 1445 1446class JournalProperty(Property): 1447 arg_types = {"no": True, "dual": False, "before": False} 1448 1449 1450class LanguageProperty(Property): 1451 arg_types = {"this": True} 1452 1453 1454class LikeProperty(Property): 1455 arg_types = {"this": True, "expressions": False} 1456 1457 1458class LocationProperty(Property): 1459 arg_types = {"this": True} 1460 1461 1462class LockingProperty(Property): 1463 arg_types = { 1464 "this": False, 1465 "kind": True, 1466 "for_or_in": True, 1467 "lock_type": True, 1468 "override": False, 1469 } 1470 1471 1472class LogProperty(Property): 1473 arg_types = {"no": True} 1474 1475 1476class MaterializedProperty(Property): 1477 arg_types = {"this": False} 1478 1479 1480class MergeBlockRatioProperty(Property): 1481 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1482 1483 1484class NoPrimaryIndexProperty(Property): 1485 arg_types = {"this": False} 1486 1487 1488class OnCommitProperty(Property): 1489 arg_type = {"this": False} 1490 1491 1492class PartitionedByProperty(Property): 1493 arg_types = {"this": True} 1494 1495 1496class ReturnsProperty(Property): 1497 arg_types = {"this": True, "is_table": False, "table": False} 1498 1499 1500class RowFormatDelimitedProperty(Property): 1501 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1502 arg_types = { 1503 "fields": False, 1504 "escaped": False, 1505 "collection_items": False, 1506 "map_keys": False, 1507 "lines": False, 1508 "null": False, 1509 "serde": False, 1510 } 1511 1512 1513class RowFormatSerdeProperty(Property): 1514 arg_types = {"this": True} 1515 1516 1517class SchemaCommentProperty(Property): 1518 arg_types = {"this": True} 1519 1520 1521class SerdeProperties(Property): 1522 arg_types = {"expressions": True} 1523 1524 1525class SetProperty(Property): 1526 arg_types = {"multi": True} 1527 1528 1529class SortKeyProperty(Property): 1530 arg_types = {"this": True, "compound": False} 1531 1532 1533class SqlSecurityProperty(Property): 1534 arg_types = {"definer": True} 1535 1536 1537class TableFormatProperty(Property): 1538 arg_types = {"this": True} 1539 1540 1541class TemporaryProperty(Property): 1542 arg_types = {"global_": True} 1543 1544 1545class TransientProperty(Property): 1546 arg_types = {"this": False} 1547 1548 1549class VolatilityProperty(Property): 1550 arg_types = {"this": True} 1551 1552 1553class WithDataProperty(Property): 1554 arg_types = {"no": True, "statistics": False} 1555 1556 1557class WithJournalTableProperty(Property): 1558 arg_types = {"this": True} 1559 1560 1561class Properties(Expression): 1562 arg_types = {"expressions": True} 1563 1564 NAME_TO_PROPERTY = { 1565 "ALGORITHM": AlgorithmProperty, 1566 "AUTO_INCREMENT": AutoIncrementProperty, 1567 "CHARACTER SET": CharacterSetProperty, 1568 "COLLATE": CollateProperty, 1569 "COMMENT": SchemaCommentProperty, 1570 "DEFINER": DefinerProperty, 1571 "DISTKEY": DistKeyProperty, 1572 "DISTSTYLE": DistStyleProperty, 1573 "ENGINE": EngineProperty, 1574 "EXECUTE AS": ExecuteAsProperty, 1575 "FORMAT": FileFormatProperty, 1576 "LANGUAGE": LanguageProperty, 1577 "LOCATION": LocationProperty, 1578 "PARTITIONED_BY": PartitionedByProperty, 1579 "RETURNS": ReturnsProperty, 1580 "SORTKEY": SortKeyProperty, 1581 "TABLE_FORMAT": TableFormatProperty, 1582 } 1583 1584 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1585 1586 # CREATE property locations 1587 # Form: schema specified 1588 # create [POST_CREATE] 1589 # table a [POST_NAME] 1590 # (b int) [POST_SCHEMA] 1591 # with ([POST_WITH]) 1592 # index (b) [POST_INDEX] 1593 # 1594 # Form: alias selection 1595 # create [POST_CREATE] 1596 # table a [POST_NAME] 1597 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1598 # index (c) [POST_INDEX] 1599 class Location(AutoName): 1600 POST_CREATE = auto() 1601 POST_NAME = auto() 1602 POST_SCHEMA = auto() 1603 POST_WITH = auto() 1604 POST_ALIAS = auto() 1605 POST_EXPRESSION = auto() 1606 POST_INDEX = auto() 1607 UNSUPPORTED = auto() 1608 1609 @classmethod 1610 def from_dict(cls, properties_dict) -> Properties: 1611 expressions = [] 1612 for key, value in properties_dict.items(): 1613 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1614 if property_cls: 1615 expressions.append(property_cls(this=convert(value))) 1616 else: 1617 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1618 1619 return cls(expressions=expressions) 1620 1621 1622class Qualify(Expression): 1623 pass 1624 1625 1626# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 1627class Return(Expression): 1628 pass 1629 1630 1631class Reference(Expression): 1632 arg_types = {"this": True, "expressions": False, "options": False} 1633 1634 1635class Tuple(Expression): 1636 arg_types = {"expressions": False} 1637 1638 1639class Subqueryable(Unionable): 1640 def subquery(self, alias=None, copy=True) -> Subquery: 1641 """ 1642 Convert this expression to an aliased expression that can be used as a Subquery. 1643 1644 Example: 1645 >>> subquery = Select().select("x").from_("tbl").subquery() 1646 >>> Select().select("x").from_(subquery).sql() 1647 'SELECT x FROM (SELECT x FROM tbl)' 1648 1649 Args: 1650 alias (str | Identifier): an optional alias for the subquery 1651 copy (bool): if `False`, modify this expression instance in-place. 1652 1653 Returns: 1654 Alias: the subquery 1655 """ 1656 instance = _maybe_copy(self, copy) 1657 return Subquery( 1658 this=instance, 1659 alias=TableAlias(this=to_identifier(alias)), 1660 ) 1661 1662 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1663 raise NotImplementedError 1664 1665 @property 1666 def ctes(self): 1667 with_ = self.args.get("with") 1668 if not with_: 1669 return [] 1670 return with_.expressions 1671 1672 @property 1673 def selects(self): 1674 raise NotImplementedError("Subqueryable objects must implement `selects`") 1675 1676 @property 1677 def named_selects(self): 1678 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1679 1680 def with_( 1681 self, 1682 alias, 1683 as_, 1684 recursive=None, 1685 append=True, 1686 dialect=None, 1687 copy=True, 1688 **opts, 1689 ): 1690 """ 1691 Append to or set the common table expressions. 1692 1693 Example: 1694 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1695 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1696 1697 Args: 1698 alias (str | Expression): the SQL code string to parse as the table name. 1699 If an `Expression` instance is passed, this is used as-is. 1700 as_ (str | Expression): the SQL code string to parse as the table expression. 1701 If an `Expression` instance is passed, it will be used as-is. 1702 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1703 append (bool): if `True`, add to any existing expressions. 1704 Otherwise, this resets the expressions. 1705 dialect (str): the dialect used to parse the input expression. 1706 copy (bool): if `False`, modify this expression instance in-place. 1707 opts (kwargs): other options to use to parse the input expressions. 1708 1709 Returns: 1710 Select: the modified expression. 1711 """ 1712 alias_expression = maybe_parse( 1713 alias, 1714 dialect=dialect, 1715 into=TableAlias, 1716 **opts, 1717 ) 1718 as_expression = maybe_parse( 1719 as_, 1720 dialect=dialect, 1721 **opts, 1722 ) 1723 cte = CTE( 1724 this=as_expression, 1725 alias=alias_expression, 1726 ) 1727 return _apply_child_list_builder( 1728 cte, 1729 instance=self, 1730 arg="with", 1731 append=append, 1732 copy=copy, 1733 into=With, 1734 properties={"recursive": recursive or False}, 1735 ) 1736 1737 1738QUERY_MODIFIERS = { 1739 "match": False, 1740 "laterals": False, 1741 "joins": False, 1742 "pivots": False, 1743 "where": False, 1744 "group": False, 1745 "having": False, 1746 "qualify": False, 1747 "windows": False, 1748 "distribute": False, 1749 "sort": False, 1750 "cluster": False, 1751 "order": False, 1752 "limit": False, 1753 "offset": False, 1754 "lock": False, 1755 "sample": False, 1756} 1757 1758 1759class Table(Expression): 1760 arg_types = { 1761 "this": True, 1762 "alias": False, 1763 "db": False, 1764 "catalog": False, 1765 "laterals": False, 1766 "joins": False, 1767 "pivots": False, 1768 "hints": False, 1769 "system_time": False, 1770 } 1771 1772 @property 1773 def db(self) -> str: 1774 return self.text("db") 1775 1776 @property 1777 def catalog(self) -> str: 1778 return self.text("catalog") 1779 1780 1781# See the TSQL "Querying data in a system-versioned temporal table" page 1782class SystemTime(Expression): 1783 arg_types = { 1784 "this": False, 1785 "expression": False, 1786 "kind": True, 1787 } 1788 1789 1790class Union(Subqueryable): 1791 arg_types = { 1792 "with": False, 1793 "this": True, 1794 "expression": True, 1795 "distinct": False, 1796 **QUERY_MODIFIERS, 1797 } 1798 1799 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1800 """ 1801 Set the LIMIT expression. 1802 1803 Example: 1804 >>> select("1").union(select("1")).limit(1).sql() 1805 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1806 1807 Args: 1808 expression (str | int | Expression): the SQL code string to parse. 1809 This can also be an integer. 1810 If a `Limit` instance is passed, this is used as-is. 1811 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1812 dialect (str): the dialect used to parse the input expression. 1813 copy (bool): if `False`, modify this expression instance in-place. 1814 opts (kwargs): other options to use to parse the input expressions. 1815 1816 Returns: 1817 Select: The limited subqueryable. 1818 """ 1819 return ( 1820 select("*") 1821 .from_(self.subquery(alias="_l_0", copy=copy)) 1822 .limit(expression, dialect=dialect, copy=False, **opts) 1823 ) 1824 1825 def select( 1826 self, 1827 *expressions: str | Expression, 1828 append: bool = True, 1829 dialect: DialectType = None, 1830 copy: bool = True, 1831 **opts, 1832 ) -> Union: 1833 """Append to or set the SELECT of the union recursively. 1834 1835 Example: 1836 >>> from sqlglot import parse_one 1837 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1838 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1839 1840 Args: 1841 *expressions: the SQL code strings to parse. 1842 If an `Expression` instance is passed, it will be used as-is. 1843 append: if `True`, add to any existing expressions. 1844 Otherwise, this resets the expressions. 1845 dialect: the dialect used to parse the input expressions. 1846 copy: if `False`, modify this expression instance in-place. 1847 opts: other options to use to parse the input expressions. 1848 1849 Returns: 1850 Union: the modified expression. 1851 """ 1852 this = self.copy() if copy else self 1853 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1854 this.expression.unnest().select( 1855 *expressions, append=append, dialect=dialect, copy=False, **opts 1856 ) 1857 return this 1858 1859 @property 1860 def named_selects(self): 1861 return self.this.unnest().named_selects 1862 1863 @property 1864 def is_star(self) -> bool: 1865 return self.this.is_star or self.expression.is_star 1866 1867 @property 1868 def selects(self): 1869 return self.this.unnest().selects 1870 1871 @property 1872 def left(self): 1873 return self.this 1874 1875 @property 1876 def right(self): 1877 return self.expression 1878 1879 1880class Except(Union): 1881 pass 1882 1883 1884class Intersect(Union): 1885 pass 1886 1887 1888class Unnest(UDTF): 1889 arg_types = { 1890 "expressions": True, 1891 "ordinality": False, 1892 "alias": False, 1893 "offset": False, 1894 } 1895 1896 1897class Update(Expression): 1898 arg_types = { 1899 "with": False, 1900 "this": False, 1901 "expressions": True, 1902 "from": False, 1903 "where": False, 1904 "returning": False, 1905 } 1906 1907 1908class Values(UDTF): 1909 arg_types = { 1910 "expressions": True, 1911 "ordinality": False, 1912 "alias": False, 1913 } 1914 1915 1916class Var(Expression): 1917 pass 1918 1919 1920class Schema(Expression): 1921 arg_types = {"this": False, "expressions": False} 1922 1923 1924# Used to represent the FOR UPDATE and FOR SHARE locking read types. 1925# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html 1926class Lock(Expression): 1927 arg_types = {"update": True} 1928 1929 1930class Select(Subqueryable): 1931 arg_types = { 1932 "with": False, 1933 "expressions": False, 1934 "hint": False, 1935 "distinct": False, 1936 "into": False, 1937 "from": False, 1938 **QUERY_MODIFIERS, 1939 } 1940 1941 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1942 """ 1943 Set the FROM expression. 1944 1945 Example: 1946 >>> Select().from_("tbl").select("x").sql() 1947 'SELECT x FROM tbl' 1948 1949 Args: 1950 *expressions (str | Expression): the SQL code strings to parse. 1951 If a `From` instance is passed, this is used as-is. 1952 If another `Expression` instance is passed, it will be wrapped in a `From`. 1953 append (bool): if `True`, add to any existing expressions. 1954 Otherwise, this flattens all the `From` expression into a single expression. 1955 dialect (str): the dialect used to parse the input expression. 1956 copy (bool): if `False`, modify this expression instance in-place. 1957 opts (kwargs): other options to use to parse the input expressions. 1958 1959 Returns: 1960 Select: the modified expression. 1961 """ 1962 return _apply_child_list_builder( 1963 *expressions, 1964 instance=self, 1965 arg="from", 1966 append=append, 1967 copy=copy, 1968 prefix="FROM", 1969 into=From, 1970 dialect=dialect, 1971 **opts, 1972 ) 1973 1974 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1975 """ 1976 Set the GROUP BY expression. 1977 1978 Example: 1979 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 1980 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 1981 1982 Args: 1983 *expressions (str | Expression): the SQL code strings to parse. 1984 If a `Group` instance is passed, this is used as-is. 1985 If another `Expression` instance is passed, it will be wrapped in a `Group`. 1986 If nothing is passed in then a group by is not applied to the expression 1987 append (bool): if `True`, add to any existing expressions. 1988 Otherwise, this flattens all the `Group` expression into a single expression. 1989 dialect (str): the dialect used to parse the input expression. 1990 copy (bool): if `False`, modify this expression instance in-place. 1991 opts (kwargs): other options to use to parse the input expressions. 1992 1993 Returns: 1994 Select: the modified expression. 1995 """ 1996 if not expressions: 1997 return self if not copy else self.copy() 1998 return _apply_child_list_builder( 1999 *expressions, 2000 instance=self, 2001 arg="group", 2002 append=append, 2003 copy=copy, 2004 prefix="GROUP BY", 2005 into=Group, 2006 dialect=dialect, 2007 **opts, 2008 ) 2009 2010 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2011 """ 2012 Set the ORDER BY expression. 2013 2014 Example: 2015 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2016 'SELECT x FROM tbl ORDER BY x DESC' 2017 2018 Args: 2019 *expressions (str | Expression): the SQL code strings to parse. 2020 If a `Group` instance is passed, this is used as-is. 2021 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2022 append (bool): if `True`, add to any existing expressions. 2023 Otherwise, this flattens all the `Order` expression into a single expression. 2024 dialect (str): the dialect used to parse the input expression. 2025 copy (bool): if `False`, modify this expression instance in-place. 2026 opts (kwargs): other options to use to parse the input expressions. 2027 2028 Returns: 2029 Select: the modified expression. 2030 """ 2031 return _apply_child_list_builder( 2032 *expressions, 2033 instance=self, 2034 arg="order", 2035 append=append, 2036 copy=copy, 2037 prefix="ORDER BY", 2038 into=Order, 2039 dialect=dialect, 2040 **opts, 2041 ) 2042 2043 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2044 """ 2045 Set the SORT BY expression. 2046 2047 Example: 2048 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2049 'SELECT x FROM tbl SORT BY x DESC' 2050 2051 Args: 2052 *expressions (str | Expression): the SQL code strings to parse. 2053 If a `Group` instance is passed, this is used as-is. 2054 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2055 append (bool): if `True`, add to any existing expressions. 2056 Otherwise, this flattens all the `Order` expression into a single expression. 2057 dialect (str): the dialect used to parse the input expression. 2058 copy (bool): if `False`, modify this expression instance in-place. 2059 opts (kwargs): other options to use to parse the input expressions. 2060 2061 Returns: 2062 Select: the modified expression. 2063 """ 2064 return _apply_child_list_builder( 2065 *expressions, 2066 instance=self, 2067 arg="sort", 2068 append=append, 2069 copy=copy, 2070 prefix="SORT BY", 2071 into=Sort, 2072 dialect=dialect, 2073 **opts, 2074 ) 2075 2076 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2077 """ 2078 Set the CLUSTER BY expression. 2079 2080 Example: 2081 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2082 'SELECT x FROM tbl CLUSTER BY x DESC' 2083 2084 Args: 2085 *expressions (str | Expression): the SQL code strings to parse. 2086 If a `Group` instance is passed, this is used as-is. 2087 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2088 append (bool): if `True`, add to any existing expressions. 2089 Otherwise, this flattens all the `Order` expression into a single expression. 2090 dialect (str): the dialect used to parse the input expression. 2091 copy (bool): if `False`, modify this expression instance in-place. 2092 opts (kwargs): other options to use to parse the input expressions. 2093 2094 Returns: 2095 Select: the modified expression. 2096 """ 2097 return _apply_child_list_builder( 2098 *expressions, 2099 instance=self, 2100 arg="cluster", 2101 append=append, 2102 copy=copy, 2103 prefix="CLUSTER BY", 2104 into=Cluster, 2105 dialect=dialect, 2106 **opts, 2107 ) 2108 2109 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2110 """ 2111 Set the LIMIT expression. 2112 2113 Example: 2114 >>> Select().from_("tbl").select("x").limit(10).sql() 2115 'SELECT x FROM tbl LIMIT 10' 2116 2117 Args: 2118 expression (str | int | Expression): the SQL code string to parse. 2119 This can also be an integer. 2120 If a `Limit` instance is passed, this is used as-is. 2121 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2122 dialect (str): the dialect used to parse the input expression. 2123 copy (bool): if `False`, modify this expression instance in-place. 2124 opts (kwargs): other options to use to parse the input expressions. 2125 2126 Returns: 2127 Select: the modified expression. 2128 """ 2129 return _apply_builder( 2130 expression=expression, 2131 instance=self, 2132 arg="limit", 2133 into=Limit, 2134 prefix="LIMIT", 2135 dialect=dialect, 2136 copy=copy, 2137 **opts, 2138 ) 2139 2140 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2141 """ 2142 Set the OFFSET expression. 2143 2144 Example: 2145 >>> Select().from_("tbl").select("x").offset(10).sql() 2146 'SELECT x FROM tbl OFFSET 10' 2147 2148 Args: 2149 expression (str | int | Expression): the SQL code string to parse. 2150 This can also be an integer. 2151 If a `Offset` instance is passed, this is used as-is. 2152 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2153 dialect (str): the dialect used to parse the input expression. 2154 copy (bool): if `False`, modify this expression instance in-place. 2155 opts (kwargs): other options to use to parse the input expressions. 2156 2157 Returns: 2158 Select: the modified expression. 2159 """ 2160 return _apply_builder( 2161 expression=expression, 2162 instance=self, 2163 arg="offset", 2164 into=Offset, 2165 prefix="OFFSET", 2166 dialect=dialect, 2167 copy=copy, 2168 **opts, 2169 ) 2170 2171 def select( 2172 self, 2173 *expressions: str | Expression, 2174 append: bool = True, 2175 dialect: DialectType = None, 2176 copy: bool = True, 2177 **opts, 2178 ) -> Select: 2179 """ 2180 Append to or set the SELECT expressions. 2181 2182 Example: 2183 >>> Select().select("x", "y").sql() 2184 'SELECT x, y' 2185 2186 Args: 2187 *expressions: the SQL code strings to parse. 2188 If an `Expression` instance is passed, it will be used as-is. 2189 append: if `True`, add to any existing expressions. 2190 Otherwise, this resets the expressions. 2191 dialect: the dialect used to parse the input expressions. 2192 copy: if `False`, modify this expression instance in-place. 2193 opts: other options to use to parse the input expressions. 2194 2195 Returns: 2196 Select: the modified expression. 2197 """ 2198 return _apply_list_builder( 2199 *expressions, 2200 instance=self, 2201 arg="expressions", 2202 append=append, 2203 dialect=dialect, 2204 copy=copy, 2205 **opts, 2206 ) 2207 2208 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2209 """ 2210 Append to or set the LATERAL expressions. 2211 2212 Example: 2213 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2214 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2215 2216 Args: 2217 *expressions (str | Expression): the SQL code strings to parse. 2218 If an `Expression` instance is passed, it will be used as-is. 2219 append (bool): if `True`, add to any existing expressions. 2220 Otherwise, this resets the expressions. 2221 dialect (str): the dialect used to parse the input expressions. 2222 copy (bool): if `False`, modify this expression instance in-place. 2223 opts (kwargs): other options to use to parse the input expressions. 2224 2225 Returns: 2226 Select: the modified expression. 2227 """ 2228 return _apply_list_builder( 2229 *expressions, 2230 instance=self, 2231 arg="laterals", 2232 append=append, 2233 into=Lateral, 2234 prefix="LATERAL VIEW", 2235 dialect=dialect, 2236 copy=copy, 2237 **opts, 2238 ) 2239 2240 def join( 2241 self, 2242 expression, 2243 on=None, 2244 using=None, 2245 append=True, 2246 join_type=None, 2247 join_alias=None, 2248 dialect=None, 2249 copy=True, 2250 **opts, 2251 ) -> Select: 2252 """ 2253 Append to or set the JOIN expressions. 2254 2255 Example: 2256 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2257 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2258 2259 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2260 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2261 2262 Use `join_type` to change the type of join: 2263 2264 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2265 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2266 2267 Args: 2268 expression (str | Expression): the SQL code string to parse. 2269 If an `Expression` instance is passed, it will be used as-is. 2270 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2271 If an `Expression` instance is passed, it will be used as-is. 2272 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2273 If an `Expression` instance is passed, it will be used as-is. 2274 append (bool): if `True`, add to any existing expressions. 2275 Otherwise, this resets the expressions. 2276 join_type (str): If set, alter the parsed join type 2277 dialect (str): the dialect used to parse the input expressions. 2278 copy (bool): if `False`, modify this expression instance in-place. 2279 opts (kwargs): other options to use to parse the input expressions. 2280 2281 Returns: 2282 Select: the modified expression. 2283 """ 2284 parse_args = {"dialect": dialect, **opts} 2285 2286 try: 2287 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2288 except ParseError: 2289 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2290 2291 join = expression if isinstance(expression, Join) else Join(this=expression) 2292 2293 if isinstance(join.this, Select): 2294 join.this.replace(join.this.subquery()) 2295 2296 if join_type: 2297 natural: t.Optional[Token] 2298 side: t.Optional[Token] 2299 kind: t.Optional[Token] 2300 2301 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2302 2303 if natural: 2304 join.set("natural", True) 2305 if side: 2306 join.set("side", side.text) 2307 if kind: 2308 join.set("kind", kind.text) 2309 2310 if on: 2311 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2312 join.set("on", on) 2313 2314 if using: 2315 join = _apply_list_builder( 2316 *ensure_collection(using), 2317 instance=join, 2318 arg="using", 2319 append=append, 2320 copy=copy, 2321 **opts, 2322 ) 2323 2324 if join_alias: 2325 join.set("this", alias_(join.this, join_alias, table=True)) 2326 return _apply_list_builder( 2327 join, 2328 instance=self, 2329 arg="joins", 2330 append=append, 2331 copy=copy, 2332 **opts, 2333 ) 2334 2335 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2336 """ 2337 Append to or set the WHERE expressions. 2338 2339 Example: 2340 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2341 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2342 2343 Args: 2344 *expressions (str | Expression): the SQL code strings to parse. 2345 If an `Expression` instance is passed, it will be used as-is. 2346 Multiple expressions are combined with an AND operator. 2347 append (bool): if `True`, AND the new expressions to any existing expression. 2348 Otherwise, this resets the expression. 2349 dialect (str): the dialect used to parse the input expressions. 2350 copy (bool): if `False`, modify this expression instance in-place. 2351 opts (kwargs): other options to use to parse the input expressions. 2352 2353 Returns: 2354 Select: the modified expression. 2355 """ 2356 return _apply_conjunction_builder( 2357 *expressions, 2358 instance=self, 2359 arg="where", 2360 append=append, 2361 into=Where, 2362 dialect=dialect, 2363 copy=copy, 2364 **opts, 2365 ) 2366 2367 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2368 """ 2369 Append to or set the HAVING expressions. 2370 2371 Example: 2372 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2373 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2374 2375 Args: 2376 *expressions (str | Expression): the SQL code strings to parse. 2377 If an `Expression` instance is passed, it will be used as-is. 2378 Multiple expressions are combined with an AND operator. 2379 append (bool): if `True`, AND the new expressions to any existing expression. 2380 Otherwise, this resets the expression. 2381 dialect (str): the dialect used to parse the input expressions. 2382 copy (bool): if `False`, modify this expression instance in-place. 2383 opts (kwargs): other options to use to parse the input expressions. 2384 2385 Returns: 2386 Select: the modified expression. 2387 """ 2388 return _apply_conjunction_builder( 2389 *expressions, 2390 instance=self, 2391 arg="having", 2392 append=append, 2393 into=Having, 2394 dialect=dialect, 2395 copy=copy, 2396 **opts, 2397 ) 2398 2399 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2400 return _apply_list_builder( 2401 *expressions, 2402 instance=self, 2403 arg="windows", 2404 append=append, 2405 into=Window, 2406 dialect=dialect, 2407 copy=copy, 2408 **opts, 2409 ) 2410 2411 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2412 return _apply_conjunction_builder( 2413 *expressions, 2414 instance=self, 2415 arg="qualify", 2416 append=append, 2417 into=Qualify, 2418 dialect=dialect, 2419 copy=copy, 2420 **opts, 2421 ) 2422 2423 def distinct(self, distinct=True, copy=True) -> Select: 2424 """ 2425 Set the OFFSET expression. 2426 2427 Example: 2428 >>> Select().from_("tbl").select("x").distinct().sql() 2429 'SELECT DISTINCT x FROM tbl' 2430 2431 Args: 2432 distinct (bool): whether the Select should be distinct 2433 copy (bool): if `False`, modify this expression instance in-place. 2434 2435 Returns: 2436 Select: the modified expression. 2437 """ 2438 instance = _maybe_copy(self, copy) 2439 instance.set("distinct", Distinct() if distinct else None) 2440 return instance 2441 2442 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2443 """ 2444 Convert this expression to a CREATE TABLE AS statement. 2445 2446 Example: 2447 >>> Select().select("*").from_("tbl").ctas("x").sql() 2448 'CREATE TABLE x AS SELECT * FROM tbl' 2449 2450 Args: 2451 table (str | Expression): the SQL code string to parse as the table name. 2452 If another `Expression` instance is passed, it will be used as-is. 2453 properties (dict): an optional mapping of table properties 2454 dialect (str): the dialect used to parse the input table. 2455 copy (bool): if `False`, modify this expression instance in-place. 2456 opts (kwargs): other options to use to parse the input table. 2457 2458 Returns: 2459 Create: the CREATE TABLE AS expression 2460 """ 2461 instance = _maybe_copy(self, copy) 2462 table_expression = maybe_parse( 2463 table, 2464 into=Table, 2465 dialect=dialect, 2466 **opts, 2467 ) 2468 properties_expression = None 2469 if properties: 2470 properties_expression = Properties.from_dict(properties) 2471 2472 return Create( 2473 this=table_expression, 2474 kind="table", 2475 expression=instance, 2476 properties=properties_expression, 2477 ) 2478 2479 def lock(self, update: bool = True, copy: bool = True) -> Select: 2480 """ 2481 Set the locking read mode for this expression. 2482 2483 Examples: 2484 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2485 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2486 2487 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2488 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2489 2490 Args: 2491 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2492 copy: if `False`, modify this expression instance in-place. 2493 2494 Returns: 2495 The modified expression. 2496 """ 2497 2498 inst = _maybe_copy(self, copy) 2499 inst.set("lock", Lock(update=update)) 2500 2501 return inst 2502 2503 @property 2504 def named_selects(self) -> t.List[str]: 2505 return [e.output_name for e in self.expressions if e.alias_or_name] 2506 2507 @property 2508 def is_star(self) -> bool: 2509 return any(expression.is_star for expression in self.expressions) 2510 2511 @property 2512 def selects(self) -> t.List[Expression]: 2513 return self.expressions 2514 2515 2516class Subquery(DerivedTable, Unionable): 2517 arg_types = { 2518 "this": True, 2519 "alias": False, 2520 "with": False, 2521 **QUERY_MODIFIERS, 2522 } 2523 2524 def unnest(self): 2525 """ 2526 Returns the first non subquery. 2527 """ 2528 expression = self 2529 while isinstance(expression, Subquery): 2530 expression = expression.this 2531 return expression 2532 2533 @property 2534 def is_star(self) -> bool: 2535 return self.this.is_star 2536 2537 @property 2538 def output_name(self): 2539 return self.alias 2540 2541 2542class TableSample(Expression): 2543 arg_types = { 2544 "this": False, 2545 "method": False, 2546 "bucket_numerator": False, 2547 "bucket_denominator": False, 2548 "bucket_field": False, 2549 "percent": False, 2550 "rows": False, 2551 "size": False, 2552 "seed": False, 2553 "kind": False, 2554 } 2555 2556 2557class Tag(Expression): 2558 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2559 2560 arg_types = { 2561 "this": False, 2562 "prefix": False, 2563 "postfix": False, 2564 } 2565 2566 2567class Pivot(Expression): 2568 arg_types = { 2569 "this": False, 2570 "alias": False, 2571 "expressions": True, 2572 "field": True, 2573 "unpivot": True, 2574 } 2575 2576 2577class Window(Expression): 2578 arg_types = { 2579 "this": True, 2580 "partition_by": False, 2581 "order": False, 2582 "spec": False, 2583 "alias": False, 2584 } 2585 2586 2587class WindowSpec(Expression): 2588 arg_types = { 2589 "kind": False, 2590 "start": False, 2591 "start_side": False, 2592 "end": False, 2593 "end_side": False, 2594 } 2595 2596 2597class Where(Expression): 2598 pass 2599 2600 2601class Star(Expression): 2602 arg_types = {"except": False, "replace": False} 2603 2604 @property 2605 def name(self) -> str: 2606 return "*" 2607 2608 @property 2609 def output_name(self): 2610 return self.name 2611 2612 2613class Parameter(Expression): 2614 arg_types = {"this": True, "wrapped": False} 2615 2616 2617class SessionParameter(Expression): 2618 arg_types = {"this": True, "kind": False} 2619 2620 2621class Placeholder(Expression): 2622 arg_types = {"this": False} 2623 2624 2625class Null(Condition): 2626 arg_types: t.Dict[str, t.Any] = {} 2627 2628 @property 2629 def name(self) -> str: 2630 return "NULL" 2631 2632 2633class Boolean(Condition): 2634 pass 2635 2636 2637class DataType(Expression): 2638 arg_types = { 2639 "this": True, 2640 "expressions": False, 2641 "nested": False, 2642 "values": False, 2643 "prefix": False, 2644 } 2645 2646 class Type(AutoName): 2647 CHAR = auto() 2648 NCHAR = auto() 2649 VARCHAR = auto() 2650 NVARCHAR = auto() 2651 TEXT = auto() 2652 MEDIUMTEXT = auto() 2653 LONGTEXT = auto() 2654 MEDIUMBLOB = auto() 2655 LONGBLOB = auto() 2656 BINARY = auto() 2657 VARBINARY = auto() 2658 INT = auto() 2659 TINYINT = auto() 2660 SMALLINT = auto() 2661 BIGINT = auto() 2662 FLOAT = auto() 2663 DOUBLE = auto() 2664 DECIMAL = auto() 2665 BOOLEAN = auto() 2666 JSON = auto() 2667 JSONB = auto() 2668 INTERVAL = auto() 2669 TIME = auto() 2670 TIMESTAMP = auto() 2671 TIMESTAMPTZ = auto() 2672 TIMESTAMPLTZ = auto() 2673 DATE = auto() 2674 DATETIME = auto() 2675 ARRAY = auto() 2676 MAP = auto() 2677 UUID = auto() 2678 GEOGRAPHY = auto() 2679 GEOMETRY = auto() 2680 STRUCT = auto() 2681 NULLABLE = auto() 2682 HLLSKETCH = auto() 2683 HSTORE = auto() 2684 SUPER = auto() 2685 SERIAL = auto() 2686 SMALLSERIAL = auto() 2687 BIGSERIAL = auto() 2688 XML = auto() 2689 UNIQUEIDENTIFIER = auto() 2690 MONEY = auto() 2691 SMALLMONEY = auto() 2692 ROWVERSION = auto() 2693 IMAGE = auto() 2694 VARIANT = auto() 2695 OBJECT = auto() 2696 INET = auto() 2697 NULL = auto() 2698 UNKNOWN = auto() # Sentinel value, useful for type annotation 2699 2700 TEXT_TYPES = { 2701 Type.CHAR, 2702 Type.NCHAR, 2703 Type.VARCHAR, 2704 Type.NVARCHAR, 2705 Type.TEXT, 2706 } 2707 2708 INTEGER_TYPES = { 2709 Type.INT, 2710 Type.TINYINT, 2711 Type.SMALLINT, 2712 Type.BIGINT, 2713 } 2714 2715 FLOAT_TYPES = { 2716 Type.FLOAT, 2717 Type.DOUBLE, 2718 } 2719 2720 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2721 2722 TEMPORAL_TYPES = { 2723 Type.TIMESTAMP, 2724 Type.TIMESTAMPTZ, 2725 Type.TIMESTAMPLTZ, 2726 Type.DATE, 2727 Type.DATETIME, 2728 } 2729 2730 @classmethod 2731 def build( 2732 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2733 ) -> DataType: 2734 from sqlglot import parse_one 2735 2736 if isinstance(dtype, str): 2737 if dtype.upper() in cls.Type.__members__: 2738 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2739 else: 2740 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2741 if data_type_exp is None: 2742 raise ValueError(f"Unparsable data type value: {dtype}") 2743 elif isinstance(dtype, DataType.Type): 2744 data_type_exp = DataType(this=dtype) 2745 elif isinstance(dtype, DataType): 2746 return dtype 2747 else: 2748 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2749 return DataType(**{**data_type_exp.args, **kwargs}) 2750 2751 def is_type(self, dtype: DataType.Type) -> bool: 2752 return self.this == dtype 2753 2754 2755# https://www.postgresql.org/docs/15/datatype-pseudo.html 2756class PseudoType(Expression): 2757 pass 2758 2759 2760class StructKwarg(Expression): 2761 arg_types = {"this": True, "expression": True} 2762 2763 2764# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 2765class SubqueryPredicate(Predicate): 2766 pass 2767 2768 2769class All(SubqueryPredicate): 2770 pass 2771 2772 2773class Any(SubqueryPredicate): 2774 pass 2775 2776 2777class Exists(SubqueryPredicate): 2778 pass 2779 2780 2781# Commands to interact with the databases or engines. For most of the command 2782# expressions we parse whatever comes after the command's name as a string. 2783class Command(Expression): 2784 arg_types = {"this": True, "expression": False} 2785 2786 2787class Transaction(Expression): 2788 arg_types = {"this": False, "modes": False} 2789 2790 2791class Commit(Expression): 2792 arg_types = {"chain": False} 2793 2794 2795class Rollback(Expression): 2796 arg_types = {"savepoint": False} 2797 2798 2799class AlterTable(Expression): 2800 arg_types = {"this": True, "actions": True, "exists": False} 2801 2802 2803class AddConstraint(Expression): 2804 arg_types = {"this": False, "expression": False, "enforced": False} 2805 2806 2807class DropPartition(Expression): 2808 arg_types = {"expressions": True, "exists": False} 2809 2810 2811# Binary expressions like (ADD a b) 2812class Binary(Expression): 2813 arg_types = {"this": True, "expression": True} 2814 2815 @property 2816 def left(self): 2817 return self.this 2818 2819 @property 2820 def right(self): 2821 return self.expression 2822 2823 2824class Add(Binary): 2825 pass 2826 2827 2828class Connector(Binary, Condition): 2829 pass 2830 2831 2832class And(Connector): 2833 pass 2834 2835 2836class Or(Connector): 2837 pass 2838 2839 2840class BitwiseAnd(Binary): 2841 pass 2842 2843 2844class BitwiseLeftShift(Binary): 2845 pass 2846 2847 2848class BitwiseOr(Binary): 2849 pass 2850 2851 2852class BitwiseRightShift(Binary): 2853 pass 2854 2855 2856class BitwiseXor(Binary): 2857 pass 2858 2859 2860class Div(Binary): 2861 pass 2862 2863 2864class FloatDiv(Binary): 2865 pass 2866 2867 2868class Overlaps(Binary): 2869 pass 2870 2871 2872class Dot(Binary): 2873 @property 2874 def name(self) -> str: 2875 return self.expression.name 2876 2877 2878class DPipe(Binary): 2879 pass 2880 2881 2882class EQ(Binary, Predicate): 2883 pass 2884 2885 2886class NullSafeEQ(Binary, Predicate): 2887 pass 2888 2889 2890class NullSafeNEQ(Binary, Predicate): 2891 pass 2892 2893 2894class Distance(Binary): 2895 pass 2896 2897 2898class Escape(Binary): 2899 pass 2900 2901 2902class Glob(Binary, Predicate): 2903 pass 2904 2905 2906class GT(Binary, Predicate): 2907 pass 2908 2909 2910class GTE(Binary, Predicate): 2911 pass 2912 2913 2914class ILike(Binary, Predicate): 2915 pass 2916 2917 2918class ILikeAny(Binary, Predicate): 2919 pass 2920 2921 2922class IntDiv(Binary): 2923 pass 2924 2925 2926class Is(Binary, Predicate): 2927 pass 2928 2929 2930class Kwarg(Binary): 2931 """Kwarg in special functions like func(kwarg => y).""" 2932 2933 2934class Like(Binary, Predicate): 2935 pass 2936 2937 2938class LikeAny(Binary, Predicate): 2939 pass 2940 2941 2942class LT(Binary, Predicate): 2943 pass 2944 2945 2946class LTE(Binary, Predicate): 2947 pass 2948 2949 2950class Mod(Binary): 2951 pass 2952 2953 2954class Mul(Binary): 2955 pass 2956 2957 2958class NEQ(Binary, Predicate): 2959 pass 2960 2961 2962class SimilarTo(Binary, Predicate): 2963 pass 2964 2965 2966class Slice(Binary): 2967 arg_types = {"this": False, "expression": False} 2968 2969 2970class Sub(Binary): 2971 pass 2972 2973 2974# Unary Expressions 2975# (NOT a) 2976class Unary(Expression): 2977 pass 2978 2979 2980class BitwiseNot(Unary): 2981 pass 2982 2983 2984class Not(Unary, Condition): 2985 pass 2986 2987 2988class Paren(Unary, Condition): 2989 arg_types = {"this": True, "with": False} 2990 2991 2992class Neg(Unary): 2993 pass 2994 2995 2996# Special Functions 2997class Alias(Expression): 2998 arg_types = {"this": True, "alias": False} 2999 3000 @property 3001 def output_name(self): 3002 return self.alias 3003 3004 3005class Aliases(Expression): 3006 arg_types = {"this": True, "expressions": True} 3007 3008 @property 3009 def aliases(self): 3010 return self.expressions 3011 3012 3013class AtTimeZone(Expression): 3014 arg_types = {"this": True, "zone": True} 3015 3016 3017class Between(Predicate): 3018 arg_types = {"this": True, "low": True, "high": True} 3019 3020 3021class Bracket(Condition): 3022 arg_types = {"this": True, "expressions": True} 3023 3024 3025class Distinct(Expression): 3026 arg_types = {"expressions": False, "on": False} 3027 3028 3029class In(Predicate): 3030 arg_types = { 3031 "this": True, 3032 "expressions": False, 3033 "query": False, 3034 "unnest": False, 3035 "field": False, 3036 "is_global": False, 3037 } 3038 3039 3040class TimeUnit(Expression): 3041 """Automatically converts unit arg into a var.""" 3042 3043 arg_types = {"unit": False} 3044 3045 def __init__(self, **args): 3046 unit = args.get("unit") 3047 if isinstance(unit, Column): 3048 args["unit"] = Var(this=unit.name) 3049 elif isinstance(unit, Week): 3050 unit.set("this", Var(this=unit.this.name)) 3051 super().__init__(**args) 3052 3053 3054class Interval(TimeUnit): 3055 arg_types = {"this": False, "unit": False} 3056 3057 3058class IgnoreNulls(Expression): 3059 pass 3060 3061 3062class RespectNulls(Expression): 3063 pass 3064 3065 3066# Functions 3067class Func(Condition): 3068 """ 3069 The base class for all function expressions. 3070 3071 Attributes: 3072 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3073 treated as a variable length argument and the argument's value will be stored as a list. 3074 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3075 for this function expression. These values are used to map this node to a name during parsing 3076 as well as to provide the function's name during SQL string generation. By default the SQL 3077 name is set to the expression's class name transformed to snake case. 3078 """ 3079 3080 is_var_len_args = False 3081 3082 @classmethod 3083 def from_arg_list(cls, args): 3084 if cls.is_var_len_args: 3085 all_arg_keys = list(cls.arg_types) 3086 # If this function supports variable length argument treat the last argument as such. 3087 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3088 num_non_var = len(non_var_len_arg_keys) 3089 3090 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3091 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3092 else: 3093 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3094 3095 return cls(**args_dict) 3096 3097 @classmethod 3098 def sql_names(cls): 3099 if cls is Func: 3100 raise NotImplementedError( 3101 "SQL name is only supported by concrete function implementations" 3102 ) 3103 if "_sql_names" not in cls.__dict__: 3104 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3105 return cls._sql_names 3106 3107 @classmethod 3108 def sql_name(cls): 3109 return cls.sql_names()[0] 3110 3111 @classmethod 3112 def default_parser_mappings(cls): 3113 return {name: cls.from_arg_list for name in cls.sql_names()} 3114 3115 3116class AggFunc(Func): 3117 pass 3118 3119 3120class Abs(Func): 3121 pass 3122 3123 3124class Anonymous(Func): 3125 arg_types = {"this": True, "expressions": False} 3126 is_var_len_args = True 3127 3128 3129class ApproxDistinct(AggFunc): 3130 arg_types = {"this": True, "accuracy": False} 3131 3132 3133class Array(Func): 3134 arg_types = {"expressions": False} 3135 is_var_len_args = True 3136 3137 3138class GenerateSeries(Func): 3139 arg_types = {"start": True, "end": True, "step": False} 3140 3141 3142class ArrayAgg(AggFunc): 3143 pass 3144 3145 3146class ArrayAll(Func): 3147 arg_types = {"this": True, "expression": True} 3148 3149 3150class ArrayAny(Func): 3151 arg_types = {"this": True, "expression": True} 3152 3153 3154class ArrayConcat(Func): 3155 arg_types = {"this": True, "expressions": False} 3156 is_var_len_args = True 3157 3158 3159class ArrayContains(Func): 3160 arg_types = {"this": True, "expression": True} 3161 3162 3163class ArrayFilter(Func): 3164 arg_types = {"this": True, "expression": True} 3165 _sql_names = ["FILTER", "ARRAY_FILTER"] 3166 3167 3168class ArrayJoin(Func): 3169 arg_types = {"this": True, "expression": True, "null": False} 3170 3171 3172class ArraySize(Func): 3173 arg_types = {"this": True, "expression": False} 3174 3175 3176class ArraySort(Func): 3177 arg_types = {"this": True, "expression": False} 3178 3179 3180class ArraySum(Func): 3181 pass 3182 3183 3184class ArrayUnionAgg(AggFunc): 3185 pass 3186 3187 3188class Avg(AggFunc): 3189 pass 3190 3191 3192class AnyValue(AggFunc): 3193 pass 3194 3195 3196class Case(Func): 3197 arg_types = {"this": False, "ifs": True, "default": False} 3198 3199 3200class Cast(Func): 3201 arg_types = {"this": True, "to": True} 3202 3203 @property 3204 def name(self) -> str: 3205 return self.this.name 3206 3207 @property 3208 def to(self): 3209 return self.args["to"] 3210 3211 @property 3212 def output_name(self): 3213 return self.name 3214 3215 def is_type(self, dtype: DataType.Type) -> bool: 3216 return self.to.is_type(dtype) 3217 3218 3219class Collate(Binary): 3220 pass 3221 3222 3223class TryCast(Cast): 3224 pass 3225 3226 3227class Ceil(Func): 3228 arg_types = {"this": True, "decimals": False} 3229 _sql_names = ["CEIL", "CEILING"] 3230 3231 3232class Coalesce(Func): 3233 arg_types = {"this": True, "expressions": False} 3234 is_var_len_args = True 3235 3236 3237class Concat(Func): 3238 arg_types = {"expressions": True} 3239 is_var_len_args = True 3240 3241 3242class ConcatWs(Concat): 3243 _sql_names = ["CONCAT_WS"] 3244 3245 3246class Count(AggFunc): 3247 arg_types = {"this": False} 3248 3249 3250class CurrentDate(Func): 3251 arg_types = {"this": False} 3252 3253 3254class CurrentDatetime(Func): 3255 arg_types = {"this": False} 3256 3257 3258class CurrentTime(Func): 3259 arg_types = {"this": False} 3260 3261 3262class CurrentTimestamp(Func): 3263 arg_types = {"this": False} 3264 3265 3266class DateAdd(Func, TimeUnit): 3267 arg_types = {"this": True, "expression": True, "unit": False} 3268 3269 3270class DateSub(Func, TimeUnit): 3271 arg_types = {"this": True, "expression": True, "unit": False} 3272 3273 3274class DateDiff(Func, TimeUnit): 3275 arg_types = {"this": True, "expression": True, "unit": False} 3276 3277 3278class DateTrunc(Func): 3279 arg_types = {"unit": True, "this": True, "zone": False} 3280 3281 3282class DatetimeAdd(Func, TimeUnit): 3283 arg_types = {"this": True, "expression": True, "unit": False} 3284 3285 3286class DatetimeSub(Func, TimeUnit): 3287 arg_types = {"this": True, "expression": True, "unit": False} 3288 3289 3290class DatetimeDiff(Func, TimeUnit): 3291 arg_types = {"this": True, "expression": True, "unit": False} 3292 3293 3294class DatetimeTrunc(Func, TimeUnit): 3295 arg_types = {"this": True, "unit": True, "zone": False} 3296 3297 3298class DayOfWeek(Func): 3299 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3300 3301 3302class DayOfMonth(Func): 3303 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3304 3305 3306class DayOfYear(Func): 3307 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3308 3309 3310class WeekOfYear(Func): 3311 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3312 3313 3314class LastDateOfMonth(Func): 3315 pass 3316 3317 3318class Extract(Func): 3319 arg_types = {"this": True, "expression": True} 3320 3321 3322class TimestampAdd(Func, TimeUnit): 3323 arg_types = {"this": True, "expression": True, "unit": False} 3324 3325 3326class TimestampSub(Func, TimeUnit): 3327 arg_types = {"this": True, "expression": True, "unit": False} 3328 3329 3330class TimestampDiff(Func, TimeUnit): 3331 arg_types = {"this": True, "expression": True, "unit": False} 3332 3333 3334class TimestampTrunc(Func, TimeUnit): 3335 arg_types = {"this": True, "unit": True, "zone": False} 3336 3337 3338class TimeAdd(Func, TimeUnit): 3339 arg_types = {"this": True, "expression": True, "unit": False} 3340 3341 3342class TimeSub(Func, TimeUnit): 3343 arg_types = {"this": True, "expression": True, "unit": False} 3344 3345 3346class TimeDiff(Func, TimeUnit): 3347 arg_types = {"this": True, "expression": True, "unit": False} 3348 3349 3350class TimeTrunc(Func, TimeUnit): 3351 arg_types = {"this": True, "unit": True, "zone": False} 3352 3353 3354class DateFromParts(Func): 3355 _sql_names = ["DATEFROMPARTS"] 3356 arg_types = {"year": True, "month": True, "day": True} 3357 3358 3359class DateStrToDate(Func): 3360 pass 3361 3362 3363class DateToDateStr(Func): 3364 pass 3365 3366 3367class DateToDi(Func): 3368 pass 3369 3370 3371class Day(Func): 3372 pass 3373 3374 3375class Decode(Func): 3376 arg_types = {"this": True, "charset": True, "replace": False} 3377 3378 3379class DiToDate(Func): 3380 pass 3381 3382 3383class Encode(Func): 3384 arg_types = {"this": True, "charset": True} 3385 3386 3387class Exp(Func): 3388 pass 3389 3390 3391class Explode(Func): 3392 pass 3393 3394 3395class Floor(Func): 3396 arg_types = {"this": True, "decimals": False} 3397 3398 3399class Greatest(Func): 3400 arg_types = {"this": True, "expressions": False} 3401 is_var_len_args = True 3402 3403 3404class GroupConcat(Func): 3405 arg_types = {"this": True, "separator": False} 3406 3407 3408class Hex(Func): 3409 pass 3410 3411 3412class If(Func): 3413 arg_types = {"this": True, "true": True, "false": False} 3414 3415 3416class IfNull(Func): 3417 arg_types = {"this": True, "expression": False} 3418 _sql_names = ["IFNULL", "NVL"] 3419 3420 3421class Initcap(Func): 3422 pass 3423 3424 3425class JSONBContains(Binary): 3426 _sql_names = ["JSONB_CONTAINS"] 3427 3428 3429class JSONExtract(Binary, Func): 3430 _sql_names = ["JSON_EXTRACT"] 3431 3432 3433class JSONExtractScalar(JSONExtract): 3434 _sql_names = ["JSON_EXTRACT_SCALAR"] 3435 3436 3437class JSONBExtract(JSONExtract): 3438 _sql_names = ["JSONB_EXTRACT"] 3439 3440 3441class JSONBExtractScalar(JSONExtract): 3442 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3443 3444 3445class Least(Func): 3446 arg_types = {"expressions": False} 3447 is_var_len_args = True 3448 3449 3450class Length(Func): 3451 pass 3452 3453 3454class Levenshtein(Func): 3455 arg_types = { 3456 "this": True, 3457 "expression": False, 3458 "ins_cost": False, 3459 "del_cost": False, 3460 "sub_cost": False, 3461 } 3462 3463 3464class Ln(Func): 3465 pass 3466 3467 3468class Log(Func): 3469 arg_types = {"this": True, "expression": False} 3470 3471 3472class Log2(Func): 3473 pass 3474 3475 3476class Log10(Func): 3477 pass 3478 3479 3480class LogicalOr(AggFunc): 3481 _sql_names = ["LOGICAL_OR", "BOOL_OR"] 3482 3483 3484class Lower(Func): 3485 _sql_names = ["LOWER", "LCASE"] 3486 3487 3488class Map(Func): 3489 arg_types = {"keys": False, "values": False} 3490 3491 3492class VarMap(Func): 3493 arg_types = {"keys": True, "values": True} 3494 is_var_len_args = True 3495 3496 3497class Matches(Func): 3498 """Oracle/Snowflake decode. 3499 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3500 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3501 """ 3502 3503 arg_types = {"this": True, "expressions": True} 3504 is_var_len_args = True 3505 3506 3507class Max(AggFunc): 3508 arg_types = {"this": True, "expressions": False} 3509 is_var_len_args = True 3510 3511 3512class Min(AggFunc): 3513 arg_types = {"this": True, "expressions": False} 3514 is_var_len_args = True 3515 3516 3517class Month(Func): 3518 pass 3519 3520 3521class Nvl2(Func): 3522 arg_types = {"this": True, "true": True, "false": False} 3523 3524 3525class Posexplode(Func): 3526 pass 3527 3528 3529class Pow(Binary, Func): 3530 _sql_names = ["POWER", "POW"] 3531 3532 3533class PercentileCont(AggFunc): 3534 pass 3535 3536 3537class PercentileDisc(AggFunc): 3538 pass 3539 3540 3541class Quantile(AggFunc): 3542 arg_types = {"this": True, "quantile": True} 3543 3544 3545# Clickhouse-specific: 3546# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles 3547class Quantiles(AggFunc): 3548 arg_types = {"parameters": True, "expressions": True} 3549 3550 3551class QuantileIf(AggFunc): 3552 arg_types = {"parameters": True, "expressions": True} 3553 3554 3555class ApproxQuantile(Quantile): 3556 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 3557 3558 3559class RangeN(Func): 3560 arg_types = {"this": True, "expressions": True, "each": False} 3561 3562 3563class ReadCSV(Func): 3564 _sql_names = ["READ_CSV"] 3565 is_var_len_args = True 3566 arg_types = {"this": True, "expressions": False} 3567 3568 3569class Reduce(Func): 3570 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 3571 3572 3573class RegexpExtract(Func): 3574 arg_types = { 3575 "this": True, 3576 "expression": True, 3577 "position": False, 3578 "occurrence": False, 3579 "group": False, 3580 } 3581 3582 3583class RegexpLike(Func): 3584 arg_types = {"this": True, "expression": True, "flag": False} 3585 3586 3587class RegexpILike(Func): 3588 arg_types = {"this": True, "expression": True, "flag": False} 3589 3590 3591class RegexpSplit(Func): 3592 arg_types = {"this": True, "expression": True} 3593 3594 3595class Repeat(Func): 3596 arg_types = {"this": True, "times": True} 3597 3598 3599class Round(Func): 3600 arg_types = {"this": True, "decimals": False} 3601 3602 3603class RowNumber(Func): 3604 arg_types: t.Dict[str, t.Any] = {} 3605 3606 3607class SafeDivide(Func): 3608 arg_types = {"this": True, "expression": True} 3609 3610 3611class SetAgg(AggFunc): 3612 pass 3613 3614 3615class SortArray(Func): 3616 arg_types = {"this": True, "asc": False} 3617 3618 3619class Split(Func): 3620 arg_types = {"this": True, "expression": True, "limit": False} 3621 3622 3623# Start may be omitted in the case of postgres 3624# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 3625class Substring(Func): 3626 arg_types = {"this": True, "start": False, "length": False} 3627 3628 3629class StrPosition(Func): 3630 arg_types = { 3631 "this": True, 3632 "substr": True, 3633 "position": False, 3634 "instance": False, 3635 } 3636 3637 3638class StrToDate(Func): 3639 arg_types = {"this": True, "format": True} 3640 3641 3642class StrToTime(Func): 3643 arg_types = {"this": True, "format": True} 3644 3645 3646# Spark allows unix_timestamp() 3647# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 3648class StrToUnix(Func): 3649 arg_types = {"this": False, "format": False} 3650 3651 3652class NumberToStr(Func): 3653 arg_types = {"this": True, "format": True} 3654 3655 3656class Struct(Func): 3657 arg_types = {"expressions": True} 3658 is_var_len_args = True 3659 3660 3661class StructExtract(Func): 3662 arg_types = {"this": True, "expression": True} 3663 3664 3665class Sum(AggFunc): 3666 pass 3667 3668 3669class Sqrt(Func): 3670 pass 3671 3672 3673class Stddev(AggFunc): 3674 pass 3675 3676 3677class StddevPop(AggFunc): 3678 pass 3679 3680 3681class StddevSamp(AggFunc): 3682 pass 3683 3684 3685class TimeToStr(Func): 3686 arg_types = {"this": True, "format": True} 3687 3688 3689class TimeToTimeStr(Func): 3690 pass 3691 3692 3693class TimeToUnix(Func): 3694 pass 3695 3696 3697class TimeStrToDate(Func): 3698 pass 3699 3700 3701class TimeStrToTime(Func): 3702 pass 3703 3704 3705class TimeStrToUnix(Func): 3706 pass 3707 3708 3709class Trim(Func): 3710 arg_types = { 3711 "this": True, 3712 "expression": False, 3713 "position": False, 3714 "collation": False, 3715 } 3716 3717 3718class TsOrDsAdd(Func, TimeUnit): 3719 arg_types = {"this": True, "expression": True, "unit": False} 3720 3721 3722class TsOrDsToDateStr(Func): 3723 pass 3724 3725 3726class TsOrDsToDate(Func): 3727 arg_types = {"this": True, "format": False} 3728 3729 3730class TsOrDiToDi(Func): 3731 pass 3732 3733 3734class Unhex(Func): 3735 pass 3736 3737 3738class UnixToStr(Func): 3739 arg_types = {"this": True, "format": False} 3740 3741 3742# https://prestodb.io/docs/current/functions/datetime.html 3743# presto has weird zone/hours/minutes 3744class UnixToTime(Func): 3745 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3746 3747 SECONDS = Literal.string("seconds") 3748 MILLIS = Literal.string("millis") 3749 MICROS = Literal.string("micros") 3750 3751 3752class UnixToTimeStr(Func): 3753 pass 3754 3755 3756class Upper(Func): 3757 _sql_names = ["UPPER", "UCASE"] 3758 3759 3760class Variance(AggFunc): 3761 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 3762 3763 3764class VariancePop(AggFunc): 3765 _sql_names = ["VARIANCE_POP", "VAR_POP"] 3766 3767 3768class Week(Func): 3769 arg_types = {"this": True, "mode": False} 3770 3771 3772class XMLTable(Func): 3773 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 3774 3775 3776class Year(Func): 3777 pass 3778 3779 3780class Use(Expression): 3781 arg_types = {"this": True, "kind": False} 3782 3783 3784class Merge(Expression): 3785 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 3786 3787 3788class When(Func): 3789 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 3790 3791 3792def _norm_args(expression): 3793 args = {} 3794 3795 for k, arg in expression.args.items(): 3796 if isinstance(arg, list): 3797 arg = [_norm_arg(a) for a in arg] 3798 if not arg: 3799 arg = None 3800 else: 3801 arg = _norm_arg(arg) 3802 3803 if arg is not None and arg is not False: 3804 args[k] = arg 3805 3806 return args 3807 3808 3809def _norm_arg(arg): 3810 return arg.lower() if isinstance(arg, str) else arg 3811 3812 3813ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 3814 3815 3816# Helpers 3817def maybe_parse( 3818 sql_or_expression: str | Expression, 3819 *, 3820 into: t.Optional[IntoType] = None, 3821 dialect: DialectType = None, 3822 prefix: t.Optional[str] = None, 3823 copy: bool = False, 3824 **opts, 3825) -> Expression: 3826 """Gracefully handle a possible string or expression. 3827 3828 Example: 3829 >>> maybe_parse("1") 3830 (LITERAL this: 1, is_string: False) 3831 >>> maybe_parse(to_identifier("x")) 3832 (IDENTIFIER this: x, quoted: False) 3833 3834 Args: 3835 sql_or_expression: the SQL code string or an expression 3836 into: the SQLGlot Expression to parse into 3837 dialect: the dialect used to parse the input expressions (in the case that an 3838 input expression is a SQL string). 3839 prefix: a string to prefix the sql with before it gets parsed 3840 (automatically includes a space) 3841 copy: whether or not to copy the expression. 3842 **opts: other options to use to parse the input expressions (again, in the case 3843 that an input expression is a SQL string). 3844 3845 Returns: 3846 Expression: the parsed or given expression. 3847 """ 3848 if isinstance(sql_or_expression, Expression): 3849 if copy: 3850 return sql_or_expression.copy() 3851 return sql_or_expression 3852 3853 import sqlglot 3854 3855 sql = str(sql_or_expression) 3856 if prefix: 3857 sql = f"{prefix} {sql}" 3858 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 3859 3860 3861def _maybe_copy(instance, copy=True): 3862 return instance.copy() if copy else instance 3863 3864 3865def _is_wrong_expression(expression, into): 3866 return isinstance(expression, Expression) and not isinstance(expression, into) 3867 3868 3869def _apply_builder( 3870 expression, 3871 instance, 3872 arg, 3873 copy=True, 3874 prefix=None, 3875 into=None, 3876 dialect=None, 3877 **opts, 3878): 3879 if _is_wrong_expression(expression, into): 3880 expression = into(this=expression) 3881 instance = _maybe_copy(instance, copy) 3882 expression = maybe_parse( 3883 sql_or_expression=expression, 3884 prefix=prefix, 3885 into=into, 3886 dialect=dialect, 3887 **opts, 3888 ) 3889 instance.set(arg, expression) 3890 return instance 3891 3892 3893def _apply_child_list_builder( 3894 *expressions, 3895 instance, 3896 arg, 3897 append=True, 3898 copy=True, 3899 prefix=None, 3900 into=None, 3901 dialect=None, 3902 properties=None, 3903 **opts, 3904): 3905 instance = _maybe_copy(instance, copy) 3906 parsed = [] 3907 for expression in expressions: 3908 if _is_wrong_expression(expression, into): 3909 expression = into(expressions=[expression]) 3910 expression = maybe_parse( 3911 expression, 3912 into=into, 3913 dialect=dialect, 3914 prefix=prefix, 3915 **opts, 3916 ) 3917 parsed.extend(expression.expressions) 3918 3919 existing = instance.args.get(arg) 3920 if append and existing: 3921 parsed = existing.expressions + parsed 3922 3923 child = into(expressions=parsed) 3924 for k, v in (properties or {}).items(): 3925 child.set(k, v) 3926 instance.set(arg, child) 3927 return instance 3928 3929 3930def _apply_list_builder( 3931 *expressions, 3932 instance, 3933 arg, 3934 append=True, 3935 copy=True, 3936 prefix=None, 3937 into=None, 3938 dialect=None, 3939 **opts, 3940): 3941 inst = _maybe_copy(instance, copy) 3942 3943 expressions = [ 3944 maybe_parse( 3945 sql_or_expression=expression, 3946 into=into, 3947 prefix=prefix, 3948 dialect=dialect, 3949 **opts, 3950 ) 3951 for expression in expressions 3952 ] 3953 3954 existing_expressions = inst.args.get(arg) 3955 if append and existing_expressions: 3956 expressions = existing_expressions + expressions 3957 3958 inst.set(arg, expressions) 3959 return inst 3960 3961 3962def _apply_conjunction_builder( 3963 *expressions, 3964 instance, 3965 arg, 3966 into=None, 3967 append=True, 3968 copy=True, 3969 dialect=None, 3970 **opts, 3971): 3972 expressions = [exp for exp in expressions if exp is not None and exp != ""] 3973 if not expressions: 3974 return instance 3975 3976 inst = _maybe_copy(instance, copy) 3977 3978 existing = inst.args.get(arg) 3979 if append and existing is not None: 3980 expressions = [existing.this if into else existing] + list(expressions) 3981 3982 node = and_(*expressions, dialect=dialect, **opts) 3983 3984 inst.set(arg, into(this=node) if into else node) 3985 return inst 3986 3987 3988def _combine(expressions, operator, dialect=None, **opts): 3989 expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions] 3990 this = expressions[0] 3991 if expressions[1:]: 3992 this = _wrap_operator(this) 3993 for expression in expressions[1:]: 3994 this = operator(this=this, expression=_wrap_operator(expression)) 3995 return this 3996 3997 3998def _wrap_operator(expression): 3999 if isinstance(expression, (And, Or, Not)): 4000 expression = Paren(this=expression) 4001 return expression 4002 4003 4004def union(left, right, distinct=True, dialect=None, **opts): 4005 """ 4006 Initializes a syntax tree from one UNION expression. 4007 4008 Example: 4009 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4010 'SELECT * FROM foo UNION SELECT * FROM bla' 4011 4012 Args: 4013 left (str | Expression): the SQL code string corresponding to the left-hand side. 4014 If an `Expression` instance is passed, it will be used as-is. 4015 right (str | Expression): the SQL code string corresponding to the right-hand side. 4016 If an `Expression` instance is passed, it will be used as-is. 4017 distinct (bool): set the DISTINCT flag if and only if this is true. 4018 dialect (str): the dialect used to parse the input expression. 4019 opts (kwargs): other options to use to parse the input expressions. 4020 Returns: 4021 Union: the syntax tree for the UNION expression. 4022 """ 4023 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4024 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4025 4026 return Union(this=left, expression=right, distinct=distinct) 4027 4028 4029def intersect(left, right, distinct=True, dialect=None, **opts): 4030 """ 4031 Initializes a syntax tree from one INTERSECT expression. 4032 4033 Example: 4034 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4035 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4036 4037 Args: 4038 left (str | Expression): the SQL code string corresponding to the left-hand side. 4039 If an `Expression` instance is passed, it will be used as-is. 4040 right (str | Expression): the SQL code string corresponding to the right-hand side. 4041 If an `Expression` instance is passed, it will be used as-is. 4042 distinct (bool): set the DISTINCT flag if and only if this is true. 4043 dialect (str): the dialect used to parse the input expression. 4044 opts (kwargs): other options to use to parse the input expressions. 4045 Returns: 4046 Intersect: the syntax tree for the INTERSECT expression. 4047 """ 4048 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4049 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4050 4051 return Intersect(this=left, expression=right, distinct=distinct) 4052 4053 4054def except_(left, right, distinct=True, dialect=None, **opts): 4055 """ 4056 Initializes a syntax tree from one EXCEPT expression. 4057 4058 Example: 4059 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4060 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4061 4062 Args: 4063 left (str | Expression): the SQL code string corresponding to the left-hand side. 4064 If an `Expression` instance is passed, it will be used as-is. 4065 right (str | Expression): the SQL code string corresponding to the right-hand side. 4066 If an `Expression` instance is passed, it will be used as-is. 4067 distinct (bool): set the DISTINCT flag if and only if this is true. 4068 dialect (str): the dialect used to parse the input expression. 4069 opts (kwargs): other options to use to parse the input expressions. 4070 Returns: 4071 Except: the syntax tree for the EXCEPT statement. 4072 """ 4073 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4074 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4075 4076 return Except(this=left, expression=right, distinct=distinct) 4077 4078 4079def select(*expressions: str | Expression, dialect: DialectType = None, **opts) -> Select: 4080 """ 4081 Initializes a syntax tree from one or multiple SELECT expressions. 4082 4083 Example: 4084 >>> select("col1", "col2").from_("tbl").sql() 4085 'SELECT col1, col2 FROM tbl' 4086 4087 Args: 4088 *expressions: the SQL code string to parse as the expressions of a 4089 SELECT statement. If an Expression instance is passed, this is used as-is. 4090 dialect: the dialect used to parse the input expressions (in the case that an 4091 input expression is a SQL string). 4092 **opts: other options to use to parse the input expressions (again, in the case 4093 that an input expression is a SQL string). 4094 4095 Returns: 4096 Select: the syntax tree for the SELECT statement. 4097 """ 4098 return Select().select(*expressions, dialect=dialect, **opts) 4099 4100 4101def from_(*expressions, dialect=None, **opts) -> Select: 4102 """ 4103 Initializes a syntax tree from a FROM expression. 4104 4105 Example: 4106 >>> from_("tbl").select("col1", "col2").sql() 4107 'SELECT col1, col2 FROM tbl' 4108 4109 Args: 4110 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4111 SELECT statement. If an Expression instance is passed, this is used as-is. 4112 dialect (str): the dialect used to parse the input expression (in the case that the 4113 input expression is a SQL string). 4114 **opts: other options to use to parse the input expressions (again, in the case 4115 that the input expression is a SQL string). 4116 4117 Returns: 4118 Select: the syntax tree for the SELECT statement. 4119 """ 4120 return Select().from_(*expressions, dialect=dialect, **opts) 4121 4122 4123def update(table, properties, where=None, from_=None, dialect=None, **opts) -> Update: 4124 """ 4125 Creates an update statement. 4126 4127 Example: 4128 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4129 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4130 4131 Args: 4132 *properties (Dict[str, Any]): dictionary of properties to set which are 4133 auto converted to sql objects eg None -> NULL 4134 where (str): sql conditional parsed into a WHERE statement 4135 from_ (str): sql statement parsed into a FROM statement 4136 dialect (str): the dialect used to parse the input expressions. 4137 **opts: other options to use to parse the input expressions. 4138 4139 Returns: 4140 Update: the syntax tree for the UPDATE statement. 4141 """ 4142 update = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4143 update.set( 4144 "expressions", 4145 [ 4146 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4147 for k, v in properties.items() 4148 ], 4149 ) 4150 if from_: 4151 update.set( 4152 "from", 4153 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4154 ) 4155 if isinstance(where, Condition): 4156 where = Where(this=where) 4157 if where: 4158 update.set( 4159 "where", 4160 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4161 ) 4162 return update 4163 4164 4165def delete(table, where=None, dialect=None, **opts) -> Delete: 4166 """ 4167 Builds a delete statement. 4168 4169 Example: 4170 >>> delete("my_table", where="id > 1").sql() 4171 'DELETE FROM my_table WHERE id > 1' 4172 4173 Args: 4174 where (str|Condition): sql conditional parsed into a WHERE statement 4175 dialect (str): the dialect used to parse the input expressions. 4176 **opts: other options to use to parse the input expressions. 4177 4178 Returns: 4179 Delete: the syntax tree for the DELETE statement. 4180 """ 4181 return Delete( 4182 this=maybe_parse(table, into=Table, dialect=dialect, **opts), 4183 where=Where(this=where) 4184 if isinstance(where, Condition) 4185 else maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4186 ) 4187 4188 4189def condition(expression, dialect=None, **opts) -> Condition: 4190 """ 4191 Initialize a logical condition expression. 4192 4193 Example: 4194 >>> condition("x=1").sql() 4195 'x = 1' 4196 4197 This is helpful for composing larger logical syntax trees: 4198 >>> where = condition("x=1") 4199 >>> where = where.and_("y=1") 4200 >>> Select().from_("tbl").select("*").where(where).sql() 4201 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4202 4203 Args: 4204 *expression (str | Expression): the SQL code string to parse. 4205 If an Expression instance is passed, this is used as-is. 4206 dialect (str): the dialect used to parse the input expression (in the case that the 4207 input expression is a SQL string). 4208 **opts: other options to use to parse the input expressions (again, in the case 4209 that the input expression is a SQL string). 4210 4211 Returns: 4212 Condition: the expression 4213 """ 4214 return maybe_parse( # type: ignore 4215 expression, 4216 into=Condition, 4217 dialect=dialect, 4218 **opts, 4219 ) 4220 4221 4222def and_(*expressions, dialect=None, **opts) -> And: 4223 """ 4224 Combine multiple conditions with an AND logical operator. 4225 4226 Example: 4227 >>> and_("x=1", and_("y=1", "z=1")).sql() 4228 'x = 1 AND (y = 1 AND z = 1)' 4229 4230 Args: 4231 *expressions (str | Expression): the SQL code strings to parse. 4232 If an Expression instance is passed, this is used as-is. 4233 dialect (str): the dialect used to parse the input expression. 4234 **opts: other options to use to parse the input expressions. 4235 4236 Returns: 4237 And: the new condition 4238 """ 4239 return _combine(expressions, And, dialect, **opts) 4240 4241 4242def or_(*expressions, dialect=None, **opts) -> Or: 4243 """ 4244 Combine multiple conditions with an OR logical operator. 4245 4246 Example: 4247 >>> or_("x=1", or_("y=1", "z=1")).sql() 4248 'x = 1 OR (y = 1 OR z = 1)' 4249 4250 Args: 4251 *expressions (str | Expression): the SQL code strings to parse. 4252 If an Expression instance is passed, this is used as-is. 4253 dialect (str): the dialect used to parse the input expression. 4254 **opts: other options to use to parse the input expressions. 4255 4256 Returns: 4257 Or: the new condition 4258 """ 4259 return _combine(expressions, Or, dialect, **opts) 4260 4261 4262def not_(expression, dialect=None, **opts) -> Not: 4263 """ 4264 Wrap a condition with a NOT operator. 4265 4266 Example: 4267 >>> not_("this_suit='black'").sql() 4268 "NOT this_suit = 'black'" 4269 4270 Args: 4271 expression (str | Expression): the SQL code strings to parse. 4272 If an Expression instance is passed, this is used as-is. 4273 dialect (str): the dialect used to parse the input expression. 4274 **opts: other options to use to parse the input expressions. 4275 4276 Returns: 4277 Not: the new condition 4278 """ 4279 this = condition( 4280 expression, 4281 dialect=dialect, 4282 **opts, 4283 ) 4284 return Not(this=_wrap_operator(this)) 4285 4286 4287def paren(expression) -> Paren: 4288 return Paren(this=expression) 4289 4290 4291SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4292 4293 4294@t.overload 4295def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None: 4296 ... 4297 4298 4299@t.overload 4300def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier: 4301 ... 4302 4303 4304def to_identifier(name, quoted=None): 4305 """Builds an identifier. 4306 4307 Args: 4308 name: The name to turn into an identifier. 4309 quoted: Whether or not force quote the identifier. 4310 4311 Returns: 4312 The identifier ast node. 4313 """ 4314 4315 if name is None: 4316 return None 4317 4318 if isinstance(name, Identifier): 4319 identifier = name 4320 elif isinstance(name, str): 4321 identifier = Identifier( 4322 this=name, 4323 quoted=not re.match(SAFE_IDENTIFIER_RE, name) if quoted is None else quoted, 4324 ) 4325 else: 4326 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4327 return identifier 4328 4329 4330INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4331 4332 4333def to_interval(interval: str | Literal) -> Interval: 4334 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4335 if isinstance(interval, Literal): 4336 if not interval.is_string: 4337 raise ValueError("Invalid interval string.") 4338 4339 interval = interval.this 4340 4341 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4342 4343 if not interval_parts: 4344 raise ValueError("Invalid interval string.") 4345 4346 return Interval( 4347 this=Literal.string(interval_parts.group(1)), 4348 unit=Var(this=interval_parts.group(2)), 4349 ) 4350 4351 4352@t.overload 4353def to_table(sql_path: str | Table, **kwargs) -> Table: 4354 ... 4355 4356 4357@t.overload 4358def to_table(sql_path: None, **kwargs) -> None: 4359 ... 4360 4361 4362def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4363 """ 4364 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4365 If a table is passed in then that table is returned. 4366 4367 Args: 4368 sql_path: a `[catalog].[schema].[table]` string. 4369 4370 Returns: 4371 A table expression. 4372 """ 4373 if sql_path is None or isinstance(sql_path, Table): 4374 return sql_path 4375 if not isinstance(sql_path, str): 4376 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4377 4378 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4379 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 4380 4381 4382def to_column(sql_path: str | Column, **kwargs) -> Column: 4383 """ 4384 Create a column from a `[table].[column]` sql path. Schema is optional. 4385 4386 If a column is passed in then that column is returned. 4387 4388 Args: 4389 sql_path: `[table].[column]` string 4390 Returns: 4391 Table: A column expression 4392 """ 4393 if sql_path is None or isinstance(sql_path, Column): 4394 return sql_path 4395 if not isinstance(sql_path, str): 4396 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4397 table_name, column_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 2)) 4398 return Column(this=column_name, table=table_name, **kwargs) 4399 4400 4401def alias_( 4402 expression: str | Expression, 4403 alias: str | Identifier, 4404 table: bool | t.Sequence[str | Identifier] = False, 4405 quoted: t.Optional[bool] = None, 4406 dialect: DialectType = None, 4407 **opts, 4408): 4409 """Create an Alias expression. 4410 4411 Example: 4412 >>> alias_('foo', 'bar').sql() 4413 'foo AS bar' 4414 4415 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4416 '(SELECT 1, 2) AS bar(a, b)' 4417 4418 Args: 4419 expression: the SQL code strings to parse. 4420 If an Expression instance is passed, this is used as-is. 4421 alias: the alias name to use. If the name has 4422 special characters it is quoted. 4423 table: Whether or not to create a table alias, can also be a list of columns. 4424 quoted: whether or not to quote the alias 4425 dialect: the dialect used to parse the input expression. 4426 **opts: other options to use to parse the input expressions. 4427 4428 Returns: 4429 Alias: the aliased expression 4430 """ 4431 exp = maybe_parse(expression, dialect=dialect, **opts) 4432 alias = to_identifier(alias, quoted=quoted) 4433 4434 if table: 4435 table_alias = TableAlias(this=alias) 4436 exp.set("alias", table_alias) 4437 4438 if not isinstance(table, bool): 4439 for column in table: 4440 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4441 4442 return exp 4443 4444 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4445 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4446 # for the complete Window expression. 4447 # 4448 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4449 4450 if "alias" in exp.arg_types and not isinstance(exp, Window): 4451 exp = exp.copy() 4452 exp.set("alias", alias) 4453 return exp 4454 return Alias(this=exp, alias=alias) 4455 4456 4457def subquery(expression, alias=None, dialect=None, **opts): 4458 """ 4459 Build a subquery expression. 4460 4461 Example: 4462 >>> subquery('select x from tbl', 'bar').select('x').sql() 4463 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4464 4465 Args: 4466 expression (str | Expression): the SQL code strings to parse. 4467 If an Expression instance is passed, this is used as-is. 4468 alias (str | Expression): the alias name to use. 4469 dialect (str): the dialect used to parse the input expression. 4470 **opts: other options to use to parse the input expressions. 4471 4472 Returns: 4473 Select: a new select with the subquery expression included 4474 """ 4475 4476 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4477 return Select().from_(expression, dialect=dialect, **opts) 4478 4479 4480def column( 4481 col: str | Identifier, 4482 table: t.Optional[str | Identifier] = None, 4483 schema: t.Optional[str | Identifier] = None, 4484 quoted: t.Optional[bool] = None, 4485) -> Column: 4486 """ 4487 Build a Column. 4488 4489 Args: 4490 col: column name 4491 table: table name 4492 schema: schema name 4493 quoted: whether or not to force quote each part 4494 Returns: 4495 Column: column instance 4496 """ 4497 return Column( 4498 this=to_identifier(col, quoted=quoted), 4499 table=to_identifier(table, quoted=quoted), 4500 schema=to_identifier(schema, quoted=quoted), 4501 ) 4502 4503 4504def cast(expression: str | Expression, to: str | DataType | DataType.Type, **opts) -> Cast: 4505 """Cast an expression to a data type. 4506 4507 Example: 4508 >>> cast('x + 1', 'int').sql() 4509 'CAST(x + 1 AS INT)' 4510 4511 Args: 4512 expression: The expression to cast. 4513 to: The datatype to cast to. 4514 4515 Returns: 4516 A cast node. 4517 """ 4518 expression = maybe_parse(expression, **opts) 4519 return Cast(this=expression, to=DataType.build(to, **opts)) 4520 4521 4522def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4523 """Build a Table. 4524 4525 Args: 4526 table (str | Expression): column name 4527 db (str | Expression): db name 4528 catalog (str | Expression): catalog name 4529 4530 Returns: 4531 Table: table instance 4532 """ 4533 return Table( 4534 this=to_identifier(table, quoted=quoted), 4535 db=to_identifier(db, quoted=quoted), 4536 catalog=to_identifier(catalog, quoted=quoted), 4537 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4538 ) 4539 4540 4541def values( 4542 values: t.Iterable[t.Tuple[t.Any, ...]], 4543 alias: t.Optional[str] = None, 4544 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4545) -> Values: 4546 """Build VALUES statement. 4547 4548 Example: 4549 >>> values([(1, '2')]).sql() 4550 "VALUES (1, '2')" 4551 4552 Args: 4553 values: values statements that will be converted to SQL 4554 alias: optional alias 4555 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4556 If either are provided then an alias is also required. 4557 If a dictionary is provided then the first column of the values will be casted to the expected type 4558 in order to help with type inference. 4559 4560 Returns: 4561 Values: the Values expression object 4562 """ 4563 if columns and not alias: 4564 raise ValueError("Alias is required when providing columns") 4565 table_alias = ( 4566 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4567 if columns 4568 else TableAlias(this=to_identifier(alias) if alias else None) 4569 ) 4570 expressions = [convert(tup) for tup in values] 4571 if columns and isinstance(columns, dict): 4572 types = list(columns.values()) 4573 expressions[0].set( 4574 "expressions", 4575 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4576 ) 4577 return Values( 4578 expressions=expressions, 4579 alias=table_alias, 4580 ) 4581 4582 4583def var(name: t.Optional[str | Expression]) -> Var: 4584 """Build a SQL variable. 4585 4586 Example: 4587 >>> repr(var('x')) 4588 '(VAR this: x)' 4589 4590 >>> repr(var(column('x', table='y'))) 4591 '(VAR this: x)' 4592 4593 Args: 4594 name: The name of the var or an expression who's name will become the var. 4595 4596 Returns: 4597 The new variable node. 4598 """ 4599 if not name: 4600 raise ValueError(f"Cannot convert empty name into var.") 4601 4602 if isinstance(name, Expression): 4603 name = name.name 4604 return Var(this=name) 4605 4606 4607def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4608 """Build ALTER TABLE... RENAME... expression 4609 4610 Args: 4611 old_name: The old name of the table 4612 new_name: The new name of the table 4613 4614 Returns: 4615 Alter table expression 4616 """ 4617 old_table = to_table(old_name) 4618 new_table = to_table(new_name) 4619 return AlterTable( 4620 this=old_table, 4621 actions=[ 4622 RenameTable(this=new_table), 4623 ], 4624 ) 4625 4626 4627def convert(value) -> Expression: 4628 """Convert a python value into an expression object. 4629 4630 Raises an error if a conversion is not possible. 4631 4632 Args: 4633 value (Any): a python object 4634 4635 Returns: 4636 Expression: the equivalent expression object 4637 """ 4638 if isinstance(value, Expression): 4639 return value 4640 if value is None: 4641 return NULL 4642 if isinstance(value, bool): 4643 return Boolean(this=value) 4644 if isinstance(value, str): 4645 return Literal.string(value) 4646 if isinstance(value, float) and math.isnan(value): 4647 return NULL 4648 if isinstance(value, numbers.Number): 4649 return Literal.number(value) 4650 if isinstance(value, tuple): 4651 return Tuple(expressions=[convert(v) for v in value]) 4652 if isinstance(value, list): 4653 return Array(expressions=[convert(v) for v in value]) 4654 if isinstance(value, dict): 4655 return Map( 4656 keys=[convert(k) for k in value], 4657 values=[convert(v) for v in value.values()], 4658 ) 4659 if isinstance(value, datetime.datetime): 4660 datetime_literal = Literal.string( 4661 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4662 ) 4663 return TimeStrToTime(this=datetime_literal) 4664 if isinstance(value, datetime.date): 4665 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4666 return DateStrToDate(this=date_literal) 4667 raise ValueError(f"Cannot convert {value}") 4668 4669 4670def replace_children(expression, fun): 4671 """ 4672 Replace children of an expression with the result of a lambda fun(child) -> exp. 4673 """ 4674 for k, v in expression.args.items(): 4675 is_list_arg = isinstance(v, list) 4676 4677 child_nodes = v if is_list_arg else [v] 4678 new_child_nodes = [] 4679 4680 for cn in child_nodes: 4681 if isinstance(cn, Expression): 4682 for child_node in ensure_collection(fun(cn)): 4683 new_child_nodes.append(child_node) 4684 child_node.parent = expression 4685 child_node.arg_key = k 4686 else: 4687 new_child_nodes.append(cn) 4688 4689 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 4690 4691 4692def column_table_names(expression): 4693 """ 4694 Return all table names referenced through columns in an expression. 4695 4696 Example: 4697 >>> import sqlglot 4698 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4699 ['c', 'a'] 4700 4701 Args: 4702 expression (sqlglot.Expression): expression to find table names 4703 4704 Returns: 4705 list: A list of unique names 4706 """ 4707 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 4708 4709 4710def table_name(table) -> str: 4711 """Get the full name of a table as a string. 4712 4713 Args: 4714 table (exp.Table | str): table expression node or string. 4715 4716 Examples: 4717 >>> from sqlglot import exp, parse_one 4718 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4719 'a.b.c' 4720 4721 Returns: 4722 The table name. 4723 """ 4724 4725 table = maybe_parse(table, into=Table) 4726 4727 if not table: 4728 raise ValueError(f"Cannot parse {table}") 4729 4730 return ".".join( 4731 part 4732 for part in ( 4733 table.text("catalog"), 4734 table.text("db"), 4735 table.name, 4736 ) 4737 if part 4738 ) 4739 4740 4741def replace_tables(expression, mapping): 4742 """Replace all tables in expression according to the mapping. 4743 4744 Args: 4745 expression (sqlglot.Expression): expression node to be transformed and replaced. 4746 mapping (Dict[str, str]): mapping of table names. 4747 4748 Examples: 4749 >>> from sqlglot import exp, parse_one 4750 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4751 'SELECT * FROM c' 4752 4753 Returns: 4754 The mapped expression. 4755 """ 4756 4757 def _replace_tables(node): 4758 if isinstance(node, Table): 4759 new_name = mapping.get(table_name(node)) 4760 if new_name: 4761 return to_table( 4762 new_name, 4763 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4764 ) 4765 return node 4766 4767 return expression.transform(_replace_tables) 4768 4769 4770def replace_placeholders(expression, *args, **kwargs): 4771 """Replace placeholders in an expression. 4772 4773 Args: 4774 expression (sqlglot.Expression): expression node to be transformed and replaced. 4775 args: positional names that will substitute unnamed placeholders in the given order. 4776 kwargs: keyword arguments that will substitute named placeholders. 4777 4778 Examples: 4779 >>> from sqlglot import exp, parse_one 4780 >>> replace_placeholders( 4781 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4782 ... ).sql() 4783 'SELECT * FROM foo WHERE a = b' 4784 4785 Returns: 4786 The mapped expression. 4787 """ 4788 4789 def _replace_placeholders(node, args, **kwargs): 4790 if isinstance(node, Placeholder): 4791 if node.name: 4792 new_name = kwargs.get(node.name) 4793 if new_name: 4794 return to_identifier(new_name) 4795 else: 4796 try: 4797 return to_identifier(next(args)) 4798 except StopIteration: 4799 pass 4800 return node 4801 4802 return expression.transform(_replace_placeholders, iter(args), **kwargs) 4803 4804 4805def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 4806 """Transforms an expression by expanding all referenced sources into subqueries. 4807 4808 Examples: 4809 >>> from sqlglot import parse_one 4810 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 4811 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 4812 4813 Args: 4814 expression: The expression to expand. 4815 sources: A dictionary of name to Subqueryables. 4816 copy: Whether or not to copy the expression during transformation. Defaults to True. 4817 4818 Returns: 4819 The transformed expression. 4820 """ 4821 4822 def _expand(node: Expression): 4823 if isinstance(node, Table): 4824 name = table_name(node) 4825 source = sources.get(name) 4826 if source: 4827 subquery = source.subquery(node.alias or name) 4828 subquery.comments = [f"source: {name}"] 4829 return subquery 4830 return node 4831 4832 return expression.transform(_expand, copy=copy) 4833 4834 4835def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 4836 """ 4837 Returns a Func expression. 4838 4839 Examples: 4840 >>> func("abs", 5).sql() 4841 'ABS(5)' 4842 4843 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 4844 'CAST(5 AS DOUBLE)' 4845 4846 Args: 4847 name: the name of the function to build. 4848 args: the args used to instantiate the function of interest. 4849 dialect: the source dialect. 4850 kwargs: the kwargs used to instantiate the function of interest. 4851 4852 Note: 4853 The arguments `args` and `kwargs` are mutually exclusive. 4854 4855 Returns: 4856 An instance of the function of interest, or an anonymous function, if `name` doesn't 4857 correspond to an existing `sqlglot.expressions.Func` class. 4858 """ 4859 if args and kwargs: 4860 raise ValueError("Can't use both args and kwargs to instantiate a function.") 4861 4862 from sqlglot.dialects.dialect import Dialect 4863 4864 args = tuple(convert(arg) for arg in args) 4865 kwargs = {key: convert(value) for key, value in kwargs.items()} 4866 4867 parser = Dialect.get_or_raise(dialect)().parser() 4868 from_args_list = parser.FUNCTIONS.get(name.upper()) 4869 4870 if from_args_list: 4871 function = from_args_list(args) if args else from_args_list.__self__(**kwargs) # type: ignore 4872 else: 4873 kwargs = kwargs or {"expressions": args} 4874 function = Anonymous(this=name, **kwargs) 4875 4876 for error_message in function.error_messages(args): 4877 raise ValueError(error_message) 4878 4879 return function 4880 4881 4882def true(): 4883 """ 4884 Returns a true Boolean expression. 4885 """ 4886 return Boolean(this=True) 4887 4888 4889def false(): 4890 """ 4891 Returns a false Boolean expression. 4892 """ 4893 return Boolean(this=False) 4894 4895 4896def null(): 4897 """ 4898 Returns a Null expression. 4899 """ 4900 return Null() 4901 4902 4903# TODO: deprecate this 4904TRUE = Boolean(this=True) 4905FALSE = Boolean(this=False) 4906NULL = Null()
56class Expression(metaclass=_Expression): 57 """ 58 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 59 context, such as its child expressions, their names (arg keys), and whether a given child expression 60 is optional or not. 61 62 Attributes: 63 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 64 and representing expressions as strings. 65 arg_types: determines what arguments (child nodes) are supported by an expression. It 66 maps arg keys to booleans that indicate whether the corresponding args are optional. 67 68 Example: 69 >>> class Foo(Expression): 70 ... arg_types = {"this": True, "expression": False} 71 72 The above definition informs us that Foo is an Expression that requires an argument called 73 "this" and may also optionally receive an argument called "expression". 74 75 Args: 76 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 77 parent: a reference to the parent expression (or None, in case of root expressions). 78 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 79 uses to refer to it. 80 comments: a list of comments that are associated with a given expression. This is used in 81 order to preserve comments when transpiling SQL code. 82 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 83 optimizer, in order to enable some transformations that require type information. 84 """ 85 86 key = "expression" 87 arg_types = {"this": True} 88 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta") 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 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value) 100 101 def __eq__(self, other) -> bool: 102 return type(self) is type(other) and _norm_args(self) == _norm_args(other) 103 104 def __hash__(self) -> int: 105 return hash( 106 ( 107 self.key, 108 tuple( 109 (k, tuple(v) if isinstance(v, list) else v) for k, v in _norm_args(self).items() 110 ), 111 ) 112 ) 113 114 @property 115 def this(self): 116 """ 117 Retrieves the argument with key "this". 118 """ 119 return self.args.get("this") 120 121 @property 122 def expression(self): 123 """ 124 Retrieves the argument with key "expression". 125 """ 126 return self.args.get("expression") 127 128 @property 129 def expressions(self): 130 """ 131 Retrieves the argument with key "expressions". 132 """ 133 return self.args.get("expressions") or [] 134 135 def text(self, key) -> str: 136 """ 137 Returns a textual representation of the argument corresponding to "key". This can only be used 138 for args that are strings or leaf Expression instances, such as identifiers and literals. 139 """ 140 field = self.args.get(key) 141 if isinstance(field, str): 142 return field 143 if isinstance(field, (Identifier, Literal, Var)): 144 return field.this 145 if isinstance(field, (Star, Null)): 146 return field.name 147 return "" 148 149 @property 150 def is_string(self) -> bool: 151 """ 152 Checks whether a Literal expression is a string. 153 """ 154 return isinstance(self, Literal) and self.args["is_string"] 155 156 @property 157 def is_number(self) -> bool: 158 """ 159 Checks whether a Literal expression is a number. 160 """ 161 return isinstance(self, Literal) and not self.args["is_string"] 162 163 @property 164 def is_int(self) -> bool: 165 """ 166 Checks whether a Literal expression is an integer. 167 """ 168 if self.is_number: 169 try: 170 int(self.name) 171 return True 172 except ValueError: 173 pass 174 return False 175 176 @property 177 def is_star(self) -> bool: 178 """Checks whether an expression is a star.""" 179 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 180 181 @property 182 def alias(self) -> str: 183 """ 184 Returns the alias of the expression, or an empty string if it's not aliased. 185 """ 186 if isinstance(self.args.get("alias"), TableAlias): 187 return self.args["alias"].name 188 return self.text("alias") 189 190 @property 191 def name(self) -> str: 192 return self.text("this") 193 194 @property 195 def alias_or_name(self): 196 return self.alias or self.name 197 198 @property 199 def output_name(self): 200 """ 201 Name of the output column if this expression is a selection. 202 203 If the Expression has no output name, an empty string is returned. 204 205 Example: 206 >>> from sqlglot import parse_one 207 >>> parse_one("SELECT a").expressions[0].output_name 208 'a' 209 >>> parse_one("SELECT b AS c").expressions[0].output_name 210 'c' 211 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 212 '' 213 """ 214 return "" 215 216 @property 217 def type(self) -> t.Optional[DataType]: 218 return self._type 219 220 @type.setter 221 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 222 if dtype and not isinstance(dtype, DataType): 223 dtype = DataType.build(dtype) 224 self._type = dtype # type: ignore 225 226 @property 227 def meta(self) -> t.Dict[str, t.Any]: 228 if self._meta is None: 229 self._meta = {} 230 return self._meta 231 232 def __deepcopy__(self, memo): 233 copy = self.__class__(**deepcopy(self.args)) 234 if self.comments is not None: 235 copy.comments = deepcopy(self.comments) 236 237 if self._type is not None: 238 copy._type = self._type.copy() 239 240 if self._meta is not None: 241 copy._meta = deepcopy(self._meta) 242 243 return copy 244 245 def copy(self): 246 """ 247 Returns a deep copy of the expression. 248 """ 249 new = deepcopy(self) 250 new.parent = self.parent 251 for item, parent, _ in new.bfs(): 252 if isinstance(item, Expression) and parent: 253 item.parent = parent 254 return new 255 256 def append(self, arg_key, value): 257 """ 258 Appends value to arg_key if it's a list or sets it as a new list. 259 260 Args: 261 arg_key (str): name of the list expression arg 262 value (Any): value to append to the list 263 """ 264 if not isinstance(self.args.get(arg_key), list): 265 self.args[arg_key] = [] 266 self.args[arg_key].append(value) 267 self._set_parent(arg_key, value) 268 269 def set(self, arg_key, value): 270 """ 271 Sets `arg_key` to `value`. 272 273 Args: 274 arg_key (str): name of the expression arg. 275 value: value to set the arg to. 276 """ 277 self.args[arg_key] = value 278 self._set_parent(arg_key, value) 279 280 def _set_parent(self, arg_key, value): 281 if isinstance(value, Expression): 282 value.parent = self 283 value.arg_key = arg_key 284 elif isinstance(value, list): 285 for v in value: 286 if isinstance(v, Expression): 287 v.parent = self 288 v.arg_key = arg_key 289 290 @property 291 def depth(self): 292 """ 293 Returns the depth of this tree. 294 """ 295 if self.parent: 296 return self.parent.depth + 1 297 return 0 298 299 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 300 """ 301 Returns the first node in this tree which matches at least one of 302 the specified types. 303 304 Args: 305 expression_types (type): the expression type(s) to match. 306 307 Returns: 308 The node which matches the criteria or None if no such node was found. 309 """ 310 return next(self.find_all(*expression_types, bfs=bfs), None) 311 312 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 313 """ 314 Returns a generator object which visits all nodes in this tree and only 315 yields those that match at least one of the specified expression types. 316 317 Args: 318 expression_types (type): the expression type(s) to match. 319 320 Returns: 321 The generator object. 322 """ 323 for expression, _, _ in self.walk(bfs=bfs): 324 if isinstance(expression, expression_types): 325 yield expression 326 327 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 328 """ 329 Returns a nearest parent matching expression_types. 330 331 Args: 332 expression_types (type): the expression type(s) to match. 333 334 Returns: 335 The parent node. 336 """ 337 ancestor = self.parent 338 while ancestor and not isinstance(ancestor, expression_types): 339 ancestor = ancestor.parent 340 # ignore type because mypy doesn't know that we're checking type in the loop 341 return ancestor # type: ignore[return-value] 342 343 @property 344 def parent_select(self): 345 """ 346 Returns the parent select statement. 347 """ 348 return self.find_ancestor(Select) 349 350 def root(self) -> Expression: 351 """ 352 Returns the root expression of this tree. 353 """ 354 expression = self 355 while expression.parent: 356 expression = expression.parent 357 return expression 358 359 def walk(self, bfs=True, prune=None): 360 """ 361 Returns a generator object which visits all nodes in this tree. 362 363 Args: 364 bfs (bool): if set to True the BFS traversal order will be applied, 365 otherwise the DFS traversal will be used instead. 366 prune ((node, parent, arg_key) -> bool): callable that returns True if 367 the generator should stop traversing this branch of the tree. 368 369 Returns: 370 the generator object. 371 """ 372 if bfs: 373 yield from self.bfs(prune=prune) 374 else: 375 yield from self.dfs(prune=prune) 376 377 def dfs(self, parent=None, key=None, prune=None): 378 """ 379 Returns a generator object which visits all nodes in this tree in 380 the DFS (Depth-first) order. 381 382 Returns: 383 The generator object. 384 """ 385 parent = parent or self.parent 386 yield self, parent, key 387 if prune and prune(self, parent, key): 388 return 389 390 for k, v in self.args.items(): 391 for node in ensure_collection(v): 392 if isinstance(node, Expression): 393 yield from node.dfs(self, k, prune) 394 395 def bfs(self, prune=None): 396 """ 397 Returns a generator object which visits all nodes in this tree in 398 the BFS (Breadth-first) order. 399 400 Returns: 401 The generator object. 402 """ 403 queue = deque([(self, self.parent, None)]) 404 405 while queue: 406 item, parent, key = queue.popleft() 407 408 yield item, parent, key 409 if prune and prune(item, parent, key): 410 continue 411 412 if isinstance(item, Expression): 413 for k, v in item.args.items(): 414 for node in ensure_collection(v): 415 if isinstance(node, Expression): 416 queue.append((node, item, k)) 417 418 def unnest(self): 419 """ 420 Returns the first non parenthesis child or self. 421 """ 422 expression = self 423 while isinstance(expression, Paren): 424 expression = expression.this 425 return expression 426 427 def unalias(self): 428 """ 429 Returns the inner expression if this is an Alias. 430 """ 431 if isinstance(self, Alias): 432 return self.this 433 return self 434 435 def unnest_operands(self): 436 """ 437 Returns unnested operands as a tuple. 438 """ 439 return tuple(arg.unnest() for arg in self.args.values() if arg) 440 441 def flatten(self, unnest=True): 442 """ 443 Returns a generator which yields child nodes who's parents are the same class. 444 445 A AND B AND C -> [A, B, C] 446 """ 447 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)): 448 if not isinstance(node, self.__class__): 449 yield node.unnest() if unnest else node 450 451 def __str__(self): 452 return self.sql() 453 454 def __repr__(self): 455 return self._to_s() 456 457 def sql(self, dialect: DialectType = None, **opts) -> str: 458 """ 459 Returns SQL string representation of this tree. 460 461 Args: 462 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 463 opts: other `sqlglot.generator.Generator` options. 464 465 Returns: 466 The SQL string. 467 """ 468 from sqlglot.dialects import Dialect 469 470 return Dialect.get_or_raise(dialect)().generate(self, **opts) 471 472 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 473 indent = "" if not level else "\n" 474 indent += "".join([" "] * level) 475 left = f"({self.key.upper()} " 476 477 args: t.Dict[str, t.Any] = { 478 k: ", ".join( 479 v._to_s(hide_missing=hide_missing, level=level + 1) 480 if hasattr(v, "_to_s") 481 else str(v) 482 for v in ensure_collection(vs) 483 if v is not None 484 ) 485 for k, vs in self.args.items() 486 } 487 args["comments"] = self.comments 488 args["type"] = self.type 489 args = {k: v for k, v in args.items() if v or not hide_missing} 490 491 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 492 right += ")" 493 494 return indent + left + right 495 496 def transform(self, fun, *args, copy=True, **kwargs): 497 """ 498 Recursively visits all tree nodes (excluding already transformed ones) 499 and applies the given transformation function to each node. 500 501 Args: 502 fun (function): a function which takes a node as an argument and returns a 503 new transformed node or the same node without modifications. If the function 504 returns None, then the corresponding node will be removed from the syntax tree. 505 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 506 modified in place. 507 508 Returns: 509 The transformed tree. 510 """ 511 node = self.copy() if copy else self 512 new_node = fun(node, *args, **kwargs) 513 514 if new_node is None or not isinstance(new_node, Expression): 515 return new_node 516 if new_node is not node: 517 new_node.parent = node.parent 518 return new_node 519 520 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 521 return new_node 522 523 def replace(self, expression): 524 """ 525 Swap out this expression with a new expression. 526 527 For example:: 528 529 >>> tree = Select().select("x").from_("tbl") 530 >>> tree.find(Column).replace(Column(this="y")) 531 (COLUMN this: y) 532 >>> tree.sql() 533 'SELECT y FROM tbl' 534 535 Args: 536 expression (Expression|None): new node 537 538 Returns: 539 The new expression or expressions. 540 """ 541 if not self.parent: 542 return expression 543 544 parent = self.parent 545 self.parent = None 546 547 replace_children(parent, lambda child: expression if child is self else child) 548 return expression 549 550 def pop(self): 551 """ 552 Remove this expression from its AST. 553 """ 554 self.replace(None) 555 556 def assert_is(self, type_): 557 """ 558 Assert that this `Expression` is an instance of `type_`. 559 560 If it is NOT an instance of `type_`, this raises an assertion error. 561 Otherwise, this returns this expression. 562 563 Examples: 564 This is useful for type security in chained expressions: 565 566 >>> import sqlglot 567 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 568 'SELECT x, z FROM y' 569 """ 570 assert isinstance(self, type_) 571 return self 572 573 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 574 """ 575 Checks if this expression is valid (e.g. all mandatory args are set). 576 577 Args: 578 args: a sequence of values that were used to instantiate a Func expression. This is used 579 to check that the provided arguments don't exceed the function argument limit. 580 581 Returns: 582 A list of error messages for all possible errors that were found. 583 """ 584 errors: t.List[str] = [] 585 586 for k in self.args: 587 if k not in self.arg_types: 588 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 589 for k, mandatory in self.arg_types.items(): 590 v = self.args.get(k) 591 if mandatory and (v is None or (isinstance(v, list) and not v)): 592 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 593 594 if ( 595 args 596 and isinstance(self, Func) 597 and len(args) > len(self.arg_types) 598 and not self.is_var_len_args 599 ): 600 errors.append( 601 f"The number of provided arguments ({len(args)}) is greater than " 602 f"the maximum number of supported arguments ({len(self.arg_types)})" 603 ) 604 605 return errors 606 607 def dump(self): 608 """ 609 Dump this Expression to a JSON-serializable dict. 610 """ 611 from sqlglot.serde import dump 612 613 return dump(self) 614 615 @classmethod 616 def load(cls, obj): 617 """ 618 Load a dict (as returned by `Expression.dump`) into an Expression instance. 619 """ 620 from sqlglot.serde import load 621 622 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataType
type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
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 98 for arg_key, value in self.args.items(): 99 self._set_parent(arg_key, value)
135 def text(self, key) -> str: 136 """ 137 Returns a textual representation of the argument corresponding to "key". This can only be used 138 for args that are strings or leaf Expression instances, such as identifiers and literals. 139 """ 140 field = self.args.get(key) 141 if isinstance(field, str): 142 return field 143 if isinstance(field, (Identifier, Literal, Var)): 144 return field.this 145 if isinstance(field, (Star, Null)): 146 return field.name 147 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 ''
245 def copy(self): 246 """ 247 Returns a deep copy of the expression. 248 """ 249 new = deepcopy(self) 250 new.parent = self.parent 251 for item, parent, _ in new.bfs(): 252 if isinstance(item, Expression) and parent: 253 item.parent = parent 254 return new
Returns a deep copy of the expression.
256 def append(self, arg_key, value): 257 """ 258 Appends value to arg_key if it's a list or sets it as a new list. 259 260 Args: 261 arg_key (str): name of the list expression arg 262 value (Any): value to append to the list 263 """ 264 if not isinstance(self.args.get(arg_key), list): 265 self.args[arg_key] = [] 266 self.args[arg_key].append(value) 267 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
269 def set(self, arg_key, value): 270 """ 271 Sets `arg_key` to `value`. 272 273 Args: 274 arg_key (str): name of the expression arg. 275 value: value to set the arg to. 276 """ 277 self.args[arg_key] = value 278 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.
299 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 300 """ 301 Returns the first node in this tree which matches at least one of 302 the specified types. 303 304 Args: 305 expression_types (type): the expression type(s) to match. 306 307 Returns: 308 The node which matches the criteria or None if no such node was found. 309 """ 310 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 (type): the expression type(s) to match.
Returns:
The node which matches the criteria or None if no such node was found.
312 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 313 """ 314 Returns a generator object which visits all nodes in this tree and only 315 yields those that match at least one of the specified expression types. 316 317 Args: 318 expression_types (type): the expression type(s) to match. 319 320 Returns: 321 The generator object. 322 """ 323 for expression, _, _ in self.walk(bfs=bfs): 324 if isinstance(expression, expression_types): 325 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 (type): the expression type(s) to match.
Returns:
The generator object.
327 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 328 """ 329 Returns a nearest parent matching expression_types. 330 331 Args: 332 expression_types (type): the expression type(s) to match. 333 334 Returns: 335 The parent node. 336 """ 337 ancestor = self.parent 338 while ancestor and not isinstance(ancestor, expression_types): 339 ancestor = ancestor.parent 340 # ignore type because mypy doesn't know that we're checking type in the loop 341 return ancestor # type: ignore[return-value]
Returns a nearest parent matching expression_types.
Arguments:
- expression_types (type): the expression type(s) to match.
Returns:
The parent node.
350 def root(self) -> Expression: 351 """ 352 Returns the root expression of this tree. 353 """ 354 expression = self 355 while expression.parent: 356 expression = expression.parent 357 return expression
Returns the root expression of this tree.
359 def walk(self, bfs=True, prune=None): 360 """ 361 Returns a generator object which visits all nodes in this tree. 362 363 Args: 364 bfs (bool): if set to True the BFS traversal order will be applied, 365 otherwise the DFS traversal will be used instead. 366 prune ((node, parent, arg_key) -> bool): callable that returns True if 367 the generator should stop traversing this branch of the tree. 368 369 Returns: 370 the generator object. 371 """ 372 if bfs: 373 yield from self.bfs(prune=prune) 374 else: 375 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.
377 def dfs(self, parent=None, key=None, prune=None): 378 """ 379 Returns a generator object which visits all nodes in this tree in 380 the DFS (Depth-first) order. 381 382 Returns: 383 The generator object. 384 """ 385 parent = parent or self.parent 386 yield self, parent, key 387 if prune and prune(self, parent, key): 388 return 389 390 for k, v in self.args.items(): 391 for node in ensure_collection(v): 392 if isinstance(node, Expression): 393 yield from node.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.
395 def bfs(self, prune=None): 396 """ 397 Returns a generator object which visits all nodes in this tree in 398 the BFS (Breadth-first) order. 399 400 Returns: 401 The generator object. 402 """ 403 queue = deque([(self, self.parent, None)]) 404 405 while queue: 406 item, parent, key = queue.popleft() 407 408 yield item, parent, key 409 if prune and prune(item, parent, key): 410 continue 411 412 if isinstance(item, Expression): 413 for k, v in item.args.items(): 414 for node in ensure_collection(v): 415 if isinstance(node, Expression): 416 queue.append((node, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
418 def unnest(self): 419 """ 420 Returns the first non parenthesis child or self. 421 """ 422 expression = self 423 while isinstance(expression, Paren): 424 expression = expression.this 425 return expression
Returns the first non parenthesis child or self.
427 def unalias(self): 428 """ 429 Returns the inner expression if this is an Alias. 430 """ 431 if isinstance(self, Alias): 432 return self.this 433 return self
Returns the inner expression if this is an Alias.
435 def unnest_operands(self): 436 """ 437 Returns unnested operands as a tuple. 438 """ 439 return tuple(arg.unnest() for arg in self.args.values() if arg)
Returns unnested operands as a tuple.
441 def flatten(self, unnest=True): 442 """ 443 Returns a generator which yields child nodes who's parents are the same class. 444 445 A AND B AND C -> [A, B, C] 446 """ 447 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)): 448 if not isinstance(node, self.__class__): 449 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]
457 def sql(self, dialect: DialectType = None, **opts) -> str: 458 """ 459 Returns SQL string representation of this tree. 460 461 Args: 462 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 463 opts: other `sqlglot.generator.Generator` options. 464 465 Returns: 466 The SQL string. 467 """ 468 from sqlglot.dialects import Dialect 469 470 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.
496 def transform(self, fun, *args, copy=True, **kwargs): 497 """ 498 Recursively visits all tree nodes (excluding already transformed ones) 499 and applies the given transformation function to each node. 500 501 Args: 502 fun (function): a function which takes a node as an argument and returns a 503 new transformed node or the same node without modifications. If the function 504 returns None, then the corresponding node will be removed from the syntax tree. 505 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 506 modified in place. 507 508 Returns: 509 The transformed tree. 510 """ 511 node = self.copy() if copy else self 512 new_node = fun(node, *args, **kwargs) 513 514 if new_node is None or not isinstance(new_node, Expression): 515 return new_node 516 if new_node is not node: 517 new_node.parent = node.parent 518 return new_node 519 520 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 521 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.
523 def replace(self, expression): 524 """ 525 Swap out this expression with a new expression. 526 527 For example:: 528 529 >>> tree = Select().select("x").from_("tbl") 530 >>> tree.find(Column).replace(Column(this="y")) 531 (COLUMN this: y) 532 >>> tree.sql() 533 'SELECT y FROM tbl' 534 535 Args: 536 expression (Expression|None): new node 537 538 Returns: 539 The new expression or expressions. 540 """ 541 if not self.parent: 542 return expression 543 544 parent = self.parent 545 self.parent = None 546 547 replace_children(parent, lambda child: expression if child is self else child) 548 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.
556 def assert_is(self, type_): 557 """ 558 Assert that this `Expression` is an instance of `type_`. 559 560 If it is NOT an instance of `type_`, this raises an assertion error. 561 Otherwise, this returns this expression. 562 563 Examples: 564 This is useful for type security in chained expressions: 565 566 >>> import sqlglot 567 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 568 'SELECT x, z FROM y' 569 """ 570 assert isinstance(self, type_) 571 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'
573 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 574 """ 575 Checks if this expression is valid (e.g. all mandatory args are set). 576 577 Args: 578 args: a sequence of values that were used to instantiate a Func expression. This is used 579 to check that the provided arguments don't exceed the function argument limit. 580 581 Returns: 582 A list of error messages for all possible errors that were found. 583 """ 584 errors: t.List[str] = [] 585 586 for k in self.args: 587 if k not in self.arg_types: 588 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 589 for k, mandatory in self.arg_types.items(): 590 v = self.args.get(k) 591 if mandatory and (v is None or (isinstance(v, list) and not v)): 592 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 593 594 if ( 595 args 596 and isinstance(self, Func) 597 and len(args) > len(self.arg_types) 598 and not self.is_var_len_args 599 ): 600 errors.append( 601 f"The number of provided arguments ({len(args)}) is greater than " 602 f"the maximum number of supported arguments ({len(self.arg_types)})" 603 ) 604 605 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.
607 def dump(self): 608 """ 609 Dump this Expression to a JSON-serializable dict. 610 """ 611 from sqlglot.serde import dump 612 613 return dump(self)
Dump this Expression to a JSON-serializable dict.
615 @classmethod 616 def load(cls, obj): 617 """ 618 Load a dict (as returned by `Expression.dump`) into an Expression instance. 619 """ 620 from sqlglot.serde import load 621 622 return load(obj)
Load a dict (as returned by Expression.dump
) into an Expression instance.
632class Condition(Expression): 633 def and_(self, *expressions, dialect=None, **opts): 634 """ 635 AND this condition with one or multiple expressions. 636 637 Example: 638 >>> condition("x=1").and_("y=1").sql() 639 'x = 1 AND y = 1' 640 641 Args: 642 *expressions (str | Expression): the SQL code strings to parse. 643 If an `Expression` instance is passed, it will be used as-is. 644 dialect (str): the dialect used to parse the input expression. 645 opts (kwargs): other options to use to parse the input expressions. 646 647 Returns: 648 And: the new condition. 649 """ 650 return and_(self, *expressions, dialect=dialect, **opts) 651 652 def or_(self, *expressions, dialect=None, **opts): 653 """ 654 OR this condition with one or multiple expressions. 655 656 Example: 657 >>> condition("x=1").or_("y=1").sql() 658 'x = 1 OR y = 1' 659 660 Args: 661 *expressions (str | Expression): the SQL code strings to parse. 662 If an `Expression` instance is passed, it will be used as-is. 663 dialect (str): the dialect used to parse the input expression. 664 opts (kwargs): other options to use to parse the input expressions. 665 666 Returns: 667 Or: the new condition. 668 """ 669 return or_(self, *expressions, dialect=dialect, **opts) 670 671 def not_(self): 672 """ 673 Wrap this condition with NOT. 674 675 Example: 676 >>> condition("x=1").not_().sql() 677 'NOT x = 1' 678 679 Returns: 680 Not: the new condition. 681 """ 682 return not_(self)
633 def and_(self, *expressions, dialect=None, **opts): 634 """ 635 AND this condition with one or multiple expressions. 636 637 Example: 638 >>> condition("x=1").and_("y=1").sql() 639 'x = 1 AND y = 1' 640 641 Args: 642 *expressions (str | Expression): the SQL code strings to parse. 643 If an `Expression` instance is passed, it will be used as-is. 644 dialect (str): the dialect used to parse the input expression. 645 opts (kwargs): other options to use to parse the input expressions. 646 647 Returns: 648 And: the new condition. 649 """ 650 return and_(self, *expressions, dialect=dialect, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
652 def or_(self, *expressions, dialect=None, **opts): 653 """ 654 OR this condition with one or multiple expressions. 655 656 Example: 657 >>> condition("x=1").or_("y=1").sql() 658 'x = 1 OR y = 1' 659 660 Args: 661 *expressions (str | Expression): the SQL code strings to parse. 662 If an `Expression` instance is passed, it will be used as-is. 663 dialect (str): the dialect used to parse the input expression. 664 opts (kwargs): other options to use to parse the input expressions. 665 666 Returns: 667 Or: the new condition. 668 """ 669 return or_(self, *expressions, dialect=dialect, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expression
instance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
671 def not_(self): 672 """ 673 Wrap this condition with NOT. 674 675 Example: 676 >>> condition("x=1").not_().sql() 677 'NOT x = 1' 678 679 Returns: 680 Not: the new condition. 681 """ 682 return not_(self)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Returns:
Not: the new condition.
Inherited Members
Relationships like x = y, x > 1, x >= y.
Inherited Members
689class DerivedTable(Expression): 690 @property 691 def alias_column_names(self): 692 table_alias = self.args.get("alias") 693 if not table_alias: 694 return [] 695 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 696 return [c.name for c in column_list] 697 698 @property 699 def selects(self): 700 alias = self.args.get("alias") 701 702 if alias: 703 return alias.columns 704 return [] 705 706 @property 707 def named_selects(self): 708 return [select.output_name for select in self.selects]
Inherited Members
711class Unionable(Expression): 712 def union(self, expression, distinct=True, dialect=None, **opts): 713 """ 714 Builds a UNION expression. 715 716 Example: 717 >>> import sqlglot 718 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 719 'SELECT * FROM foo UNION SELECT * FROM bla' 720 721 Args: 722 expression (str | Expression): the SQL code string. 723 If an `Expression` instance is passed, it will be used as-is. 724 distinct (bool): set the DISTINCT flag if and only if this is true. 725 dialect (str): the dialect used to parse the input expression. 726 opts (kwargs): other options to use to parse the input expressions. 727 Returns: 728 Union: the Union expression. 729 """ 730 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 731 732 def intersect(self, expression, distinct=True, dialect=None, **opts): 733 """ 734 Builds an INTERSECT expression. 735 736 Example: 737 >>> import sqlglot 738 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 739 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 740 741 Args: 742 expression (str | Expression): the SQL code string. 743 If an `Expression` instance is passed, it will be used as-is. 744 distinct (bool): set the DISTINCT flag if and only if this is true. 745 dialect (str): the dialect used to parse the input expression. 746 opts (kwargs): other options to use to parse the input expressions. 747 Returns: 748 Intersect: the Intersect expression 749 """ 750 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 751 752 def except_(self, expression, distinct=True, dialect=None, **opts): 753 """ 754 Builds an EXCEPT expression. 755 756 Example: 757 >>> import sqlglot 758 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 759 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 760 761 Args: 762 expression (str | Expression): the SQL code string. 763 If an `Expression` instance is passed, it will be used as-is. 764 distinct (bool): set the DISTINCT flag if and only if this is true. 765 dialect (str): the dialect used to parse the input expression. 766 opts (kwargs): other options to use to parse the input expressions. 767 Returns: 768 Except: the Except expression 769 """ 770 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
712 def union(self, expression, distinct=True, dialect=None, **opts): 713 """ 714 Builds a UNION expression. 715 716 Example: 717 >>> import sqlglot 718 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 719 'SELECT * FROM foo UNION SELECT * FROM bla' 720 721 Args: 722 expression (str | Expression): the SQL code string. 723 If an `Expression` instance is passed, it will be used as-is. 724 distinct (bool): set the DISTINCT flag if and only if this is true. 725 dialect (str): the dialect used to parse the input expression. 726 opts (kwargs): other options to use to parse the input expressions. 727 Returns: 728 Union: the Union expression. 729 """ 730 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.
732 def intersect(self, expression, distinct=True, dialect=None, **opts): 733 """ 734 Builds an INTERSECT expression. 735 736 Example: 737 >>> import sqlglot 738 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 739 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 740 741 Args: 742 expression (str | Expression): the SQL code string. 743 If an `Expression` instance is passed, it will be used as-is. 744 distinct (bool): set the DISTINCT flag if and only if this is true. 745 dialect (str): the dialect used to parse the input expression. 746 opts (kwargs): other options to use to parse the input expressions. 747 Returns: 748 Intersect: the Intersect expression 749 """ 750 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
752 def except_(self, expression, distinct=True, dialect=None, **opts): 753 """ 754 Builds an EXCEPT expression. 755 756 Example: 757 >>> import sqlglot 758 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 759 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 760 761 Args: 762 expression (str | Expression): the SQL code string. 763 If an `Expression` instance is passed, it will be used as-is. 764 distinct (bool): set the DISTINCT flag if and only if this is true. 765 dialect (str): the dialect used to parse the input expression. 766 opts (kwargs): other options to use to parse the input expressions. 767 Returns: 768 Except: the Except expression 769 """ 770 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
Inherited Members
777class Cache(Expression): 778 arg_types = { 779 "with": False, 780 "this": True, 781 "lazy": False, 782 "options": False, 783 "expression": False, 784 }
Inherited Members
Inherited Members
791class Create(Expression): 792 arg_types = { 793 "with": False, 794 "this": True, 795 "kind": True, 796 "expression": False, 797 "exists": False, 798 "properties": False, 799 "replace": False, 800 "unique": False, 801 "volatile": False, 802 "indexes": False, 803 "no_schema_binding": False, 804 "begin": False, 805 }
Inherited Members
Inherited Members
Inherited Members
816class SetItem(Expression): 817 arg_types = { 818 "this": False, 819 "expressions": False, 820 "kind": False, 821 "collate": False, # MySQL SET NAMES statement 822 "global": False, 823 }
Inherited Members
826class Show(Expression): 827 arg_types = { 828 "this": True, 829 "target": False, 830 "offset": False, 831 "limit": False, 832 "like": False, 833 "where": False, 834 "db": False, 835 "full": False, 836 "mutex": False, 837 "query": False, 838 "channel": False, 839 "global": False, 840 "log": False, 841 "position": False, 842 "types": False, 843 }
Inherited Members
846class UserDefinedFunction(Expression): 847 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
Inherited Members
854class With(Expression): 855 arg_types = {"expressions": True, "recursive": False} 856 857 @property 858 def recursive(self) -> bool: 859 return bool(self.args.get("recursive"))
Inherited Members
Inherited Members
Inherited Members
870class TableAlias(Expression): 871 arg_types = {"this": False, "columns": False} 872 873 @property 874 def columns(self): 875 return self.args.get("columns") or []
Inherited Members
Inherited Members
Inherited Members
Inherited Members
890class Column(Condition): 891 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 892 893 @property 894 def table(self) -> str: 895 return self.text("table") 896 897 @property 898 def db(self) -> str: 899 return self.text("db") 900 901 @property 902 def catalog(self) -> str: 903 return self.text("catalog") 904 905 @property 906 def output_name(self) -> str: 907 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
910class ColumnDef(Expression): 911 arg_types = { 912 "this": True, 913 "kind": False, 914 "constraints": False, 915 "exists": False, 916 }
Inherited Members
919class AlterColumn(Expression): 920 arg_types = { 921 "this": True, 922 "dtype": False, 923 "collate": False, 924 "using": False, 925 "default": False, 926 "drop": False, 927 }
Inherited Members
Inherited Members
Inherited Members
938class Comment(Expression): 939 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
990class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 991 # this: True -> ALWAYS, this: False -> BY DEFAULT 992 arg_types = { 993 "this": False, 994 "start": False, 995 "increment": False, 996 "minvalue": False, 997 "maxvalue": False, 998 "cycle": False, 999 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1034class Delete(Expression): 1035 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
Inherited Members
1038class Drop(Expression): 1039 arg_types = { 1040 "this": False, 1041 "kind": False, 1042 "exists": False, 1043 "temporary": False, 1044 "materialized": False, 1045 "cascade": False, 1046 }
Inherited Members
Inherited Members
Inherited Members
1057class Directory(Expression): 1058 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1059 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
1062class ForeignKey(Expression): 1063 arg_types = { 1064 "expressions": True, 1065 "reference": False, 1066 "delete": False, 1067 "update": False, 1068 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1101class Identifier(Expression): 1102 arg_types = {"this": True, "quoted": False} 1103 1104 @property 1105 def quoted(self): 1106 return bool(self.args.get("quoted")) 1107 1108 def __eq__(self, other): 1109 return isinstance(other, self.__class__) and _norm_arg(self.this) == _norm_arg(other.this) 1110 1111 def __hash__(self): 1112 return hash((self.key, self.this.lower())) 1113 1114 @property 1115 def output_name(self): 1116 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 ''
1119class Index(Expression): 1120 arg_types = { 1121 "this": False, 1122 "table": False, 1123 "where": False, 1124 "columns": False, 1125 "unique": False, 1126 "primary": False, 1127 "amp": False, # teradata 1128 }
Inherited Members
1131class Insert(Expression): 1132 arg_types = { 1133 "with": False, 1134 "this": True, 1135 "expression": False, 1136 "returning": False, 1137 "overwrite": False, 1138 "exists": False, 1139 "partition": False, 1140 "alternative": False, 1141 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1158class LoadData(Expression): 1159 arg_types = { 1160 "this": True, 1161 "local": False, 1162 "overwrite": False, 1163 "inpath": True, 1164 "partition": False, 1165 "input_format": False, 1166 "serde": False, 1167 }
Inherited Members
Inherited Members
Inherited Members
1178class Group(Expression): 1179 arg_types = { 1180 "expressions": False, 1181 "grouping_sets": False, 1182 "cube": False, 1183 "rollup": False, 1184 }
Inherited Members
Inherited Members
Inherited Members
1195class Literal(Condition): 1196 arg_types = {"this": True, "is_string": True} 1197 1198 def __eq__(self, other): 1199 return ( 1200 isinstance(other, Literal) 1201 and self.this == other.this 1202 and self.args["is_string"] == other.args["is_string"] 1203 ) 1204 1205 def __hash__(self): 1206 return hash((self.key, self.this, self.args["is_string"])) 1207 1208 @classmethod 1209 def number(cls, number) -> Literal: 1210 return cls(this=str(number), is_string=False) 1211 1212 @classmethod 1213 def string(cls, string) -> Literal: 1214 return cls(this=str(string), is_string=True) 1215 1216 @property 1217 def output_name(self): 1218 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
1221class Join(Expression): 1222 arg_types = { 1223 "this": True, 1224 "on": False, 1225 "side": False, 1226 "kind": False, 1227 "using": False, 1228 "natural": False, 1229 } 1230 1231 @property 1232 def kind(self): 1233 return self.text("kind").upper() 1234 1235 @property 1236 def side(self): 1237 return self.text("side").upper() 1238 1239 @property 1240 def alias_or_name(self): 1241 return self.this.alias_or_name 1242 1243 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1244 """ 1245 Append to or set the ON expressions. 1246 1247 Example: 1248 >>> import sqlglot 1249 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1250 'JOIN x ON y = 1' 1251 1252 Args: 1253 *expressions (str | Expression): the SQL code strings to parse. 1254 If an `Expression` instance is passed, it will be used as-is. 1255 Multiple expressions are combined with an AND operator. 1256 append (bool): if `True`, AND the new expressions to any existing expression. 1257 Otherwise, this resets the expression. 1258 dialect (str): the dialect used to parse the input expressions. 1259 copy (bool): if `False`, modify this expression instance in-place. 1260 opts (kwargs): other options to use to parse the input expressions. 1261 1262 Returns: 1263 Join: the modified join expression. 1264 """ 1265 join = _apply_conjunction_builder( 1266 *expressions, 1267 instance=self, 1268 arg="on", 1269 append=append, 1270 dialect=dialect, 1271 copy=copy, 1272 **opts, 1273 ) 1274 1275 if join.kind == "CROSS": 1276 join.set("kind", None) 1277 1278 return join 1279 1280 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1281 """ 1282 Append to or set the USING expressions. 1283 1284 Example: 1285 >>> import sqlglot 1286 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1287 'JOIN x USING (foo, bla)' 1288 1289 Args: 1290 *expressions (str | Expression): the SQL code strings to parse. 1291 If an `Expression` instance is passed, it will be used as-is. 1292 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1293 Otherwise, this resets the expression. 1294 dialect (str): the dialect used to parse the input expressions. 1295 copy (bool): if `False`, modify this expression instance in-place. 1296 opts (kwargs): other options to use to parse the input expressions. 1297 1298 Returns: 1299 Join: the modified join expression. 1300 """ 1301 join = _apply_list_builder( 1302 *expressions, 1303 instance=self, 1304 arg="using", 1305 append=append, 1306 dialect=dialect, 1307 copy=copy, 1308 **opts, 1309 ) 1310 1311 if join.kind == "CROSS": 1312 join.set("kind", None) 1313 1314 return join
1243 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1244 """ 1245 Append to or set the ON expressions. 1246 1247 Example: 1248 >>> import sqlglot 1249 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1250 'JOIN x ON y = 1' 1251 1252 Args: 1253 *expressions (str | Expression): the SQL code strings to parse. 1254 If an `Expression` instance is passed, it will be used as-is. 1255 Multiple expressions are combined with an AND operator. 1256 append (bool): if `True`, AND the new expressions to any existing expression. 1257 Otherwise, this resets the expression. 1258 dialect (str): the dialect used to parse the input expressions. 1259 copy (bool): if `False`, modify this expression instance in-place. 1260 opts (kwargs): other options to use to parse the input expressions. 1261 1262 Returns: 1263 Join: the modified join expression. 1264 """ 1265 join = _apply_conjunction_builder( 1266 *expressions, 1267 instance=self, 1268 arg="on", 1269 append=append, 1270 dialect=dialect, 1271 copy=copy, 1272 **opts, 1273 ) 1274 1275 if join.kind == "CROSS": 1276 join.set("kind", None) 1277 1278 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.
1280 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1281 """ 1282 Append to or set the USING expressions. 1283 1284 Example: 1285 >>> import sqlglot 1286 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1287 'JOIN x USING (foo, bla)' 1288 1289 Args: 1290 *expressions (str | Expression): the SQL code strings to parse. 1291 If an `Expression` instance is passed, it will be used as-is. 1292 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1293 Otherwise, this resets the expression. 1294 dialect (str): the dialect used to parse the input expressions. 1295 copy (bool): if `False`, modify this expression instance in-place. 1296 opts (kwargs): other options to use to parse the input expressions. 1297 1298 Returns: 1299 Join: the modified join expression. 1300 """ 1301 join = _apply_list_builder( 1302 *expressions, 1303 instance=self, 1304 arg="using", 1305 append=append, 1306 dialect=dialect, 1307 copy=copy, 1308 **opts, 1309 ) 1310 1311 if join.kind == "CROSS": 1312 join.set("kind", None) 1313 1314 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
1317class Lateral(UDTF): 1318 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
1321class MatchRecognize(Expression): 1322 arg_types = { 1323 "partition_by": False, 1324 "order": False, 1325 "measures": False, 1326 "rows": False, 1327 "after": False, 1328 "pattern": False, 1329 "define": False, 1330 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1369class AfterJournalProperty(Property): 1370 arg_types = {"no": True, "dual": False, "local": False}
Inherited Members
Inherited Members
Inherited Members
1381class BlockCompressionProperty(Property): 1382 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1397class DataBlocksizeProperty(Property): 1398 arg_types = {"size": False, "units": False, "min": False, "default": False}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1437class IsolatedLoadingProperty(Property): 1438 arg_types = { 1439 "no": True, 1440 "concurrent": True, 1441 "for_all": True, 1442 "for_insert": True, 1443 "for_none": True, 1444 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1463class LockingProperty(Property): 1464 arg_types = { 1465 "this": False, 1466 "kind": True, 1467 "for_or_in": True, 1468 "lock_type": True, 1469 "override": False, 1470 }
Inherited Members
Inherited Members
Inherited Members
1481class MergeBlockRatioProperty(Property): 1482 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1497class ReturnsProperty(Property): 1498 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
1501class RowFormatDelimitedProperty(Property): 1502 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1503 arg_types = { 1504 "fields": False, 1505 "escaped": False, 1506 "collection_items": False, 1507 "map_keys": False, 1508 "lines": False, 1509 "null": False, 1510 "serde": False, 1511 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1562class Properties(Expression): 1563 arg_types = {"expressions": True} 1564 1565 NAME_TO_PROPERTY = { 1566 "ALGORITHM": AlgorithmProperty, 1567 "AUTO_INCREMENT": AutoIncrementProperty, 1568 "CHARACTER SET": CharacterSetProperty, 1569 "COLLATE": CollateProperty, 1570 "COMMENT": SchemaCommentProperty, 1571 "DEFINER": DefinerProperty, 1572 "DISTKEY": DistKeyProperty, 1573 "DISTSTYLE": DistStyleProperty, 1574 "ENGINE": EngineProperty, 1575 "EXECUTE AS": ExecuteAsProperty, 1576 "FORMAT": FileFormatProperty, 1577 "LANGUAGE": LanguageProperty, 1578 "LOCATION": LocationProperty, 1579 "PARTITIONED_BY": PartitionedByProperty, 1580 "RETURNS": ReturnsProperty, 1581 "SORTKEY": SortKeyProperty, 1582 "TABLE_FORMAT": TableFormatProperty, 1583 } 1584 1585 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1586 1587 # CREATE property locations 1588 # Form: schema specified 1589 # create [POST_CREATE] 1590 # table a [POST_NAME] 1591 # (b int) [POST_SCHEMA] 1592 # with ([POST_WITH]) 1593 # index (b) [POST_INDEX] 1594 # 1595 # Form: alias selection 1596 # create [POST_CREATE] 1597 # table a [POST_NAME] 1598 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1599 # index (c) [POST_INDEX] 1600 class Location(AutoName): 1601 POST_CREATE = auto() 1602 POST_NAME = auto() 1603 POST_SCHEMA = auto() 1604 POST_WITH = auto() 1605 POST_ALIAS = auto() 1606 POST_EXPRESSION = auto() 1607 POST_INDEX = auto() 1608 UNSUPPORTED = auto() 1609 1610 @classmethod 1611 def from_dict(cls, properties_dict) -> Properties: 1612 expressions = [] 1613 for key, value in properties_dict.items(): 1614 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1615 if property_cls: 1616 expressions.append(property_cls(this=convert(value))) 1617 else: 1618 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1619 1620 return cls(expressions=expressions)
1610 @classmethod 1611 def from_dict(cls, properties_dict) -> Properties: 1612 expressions = [] 1613 for key, value in properties_dict.items(): 1614 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1615 if property_cls: 1616 expressions.append(property_cls(this=convert(value))) 1617 else: 1618 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1619 1620 return cls(expressions=expressions)
Inherited Members
1600 class Location(AutoName): 1601 POST_CREATE = auto() 1602 POST_NAME = auto() 1603 POST_SCHEMA = auto() 1604 POST_WITH = auto() 1605 POST_ALIAS = auto() 1606 POST_EXPRESSION = auto() 1607 POST_INDEX = auto() 1608 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
Inherited Members
1632class Reference(Expression): 1633 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
Inherited Members
1640class Subqueryable(Unionable): 1641 def subquery(self, alias=None, copy=True) -> Subquery: 1642 """ 1643 Convert this expression to an aliased expression that can be used as a Subquery. 1644 1645 Example: 1646 >>> subquery = Select().select("x").from_("tbl").subquery() 1647 >>> Select().select("x").from_(subquery).sql() 1648 'SELECT x FROM (SELECT x FROM tbl)' 1649 1650 Args: 1651 alias (str | Identifier): an optional alias for the subquery 1652 copy (bool): if `False`, modify this expression instance in-place. 1653 1654 Returns: 1655 Alias: the subquery 1656 """ 1657 instance = _maybe_copy(self, copy) 1658 return Subquery( 1659 this=instance, 1660 alias=TableAlias(this=to_identifier(alias)), 1661 ) 1662 1663 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1664 raise NotImplementedError 1665 1666 @property 1667 def ctes(self): 1668 with_ = self.args.get("with") 1669 if not with_: 1670 return [] 1671 return with_.expressions 1672 1673 @property 1674 def selects(self): 1675 raise NotImplementedError("Subqueryable objects must implement `selects`") 1676 1677 @property 1678 def named_selects(self): 1679 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1680 1681 def with_( 1682 self, 1683 alias, 1684 as_, 1685 recursive=None, 1686 append=True, 1687 dialect=None, 1688 copy=True, 1689 **opts, 1690 ): 1691 """ 1692 Append to or set the common table expressions. 1693 1694 Example: 1695 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1696 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1697 1698 Args: 1699 alias (str | Expression): the SQL code string to parse as the table name. 1700 If an `Expression` instance is passed, this is used as-is. 1701 as_ (str | Expression): the SQL code string to parse as the table expression. 1702 If an `Expression` instance is passed, it will be used as-is. 1703 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1704 append (bool): if `True`, add to any existing expressions. 1705 Otherwise, this resets the expressions. 1706 dialect (str): the dialect used to parse the input expression. 1707 copy (bool): if `False`, modify this expression instance in-place. 1708 opts (kwargs): other options to use to parse the input expressions. 1709 1710 Returns: 1711 Select: the modified expression. 1712 """ 1713 alias_expression = maybe_parse( 1714 alias, 1715 dialect=dialect, 1716 into=TableAlias, 1717 **opts, 1718 ) 1719 as_expression = maybe_parse( 1720 as_, 1721 dialect=dialect, 1722 **opts, 1723 ) 1724 cte = CTE( 1725 this=as_expression, 1726 alias=alias_expression, 1727 ) 1728 return _apply_child_list_builder( 1729 cte, 1730 instance=self, 1731 arg="with", 1732 append=append, 1733 copy=copy, 1734 into=With, 1735 properties={"recursive": recursive or False}, 1736 )
1641 def subquery(self, alias=None, copy=True) -> Subquery: 1642 """ 1643 Convert this expression to an aliased expression that can be used as a Subquery. 1644 1645 Example: 1646 >>> subquery = Select().select("x").from_("tbl").subquery() 1647 >>> Select().select("x").from_(subquery).sql() 1648 'SELECT x FROM (SELECT x FROM tbl)' 1649 1650 Args: 1651 alias (str | Identifier): an optional alias for the subquery 1652 copy (bool): if `False`, modify this expression instance in-place. 1653 1654 Returns: 1655 Alias: the subquery 1656 """ 1657 instance = _maybe_copy(self, copy) 1658 return Subquery( 1659 this=instance, 1660 alias=TableAlias(this=to_identifier(alias)), 1661 )
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
1681 def with_( 1682 self, 1683 alias, 1684 as_, 1685 recursive=None, 1686 append=True, 1687 dialect=None, 1688 copy=True, 1689 **opts, 1690 ): 1691 """ 1692 Append to or set the common table expressions. 1693 1694 Example: 1695 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1696 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1697 1698 Args: 1699 alias (str | Expression): the SQL code string to parse as the table name. 1700 If an `Expression` instance is passed, this is used as-is. 1701 as_ (str | Expression): the SQL code string to parse as the table expression. 1702 If an `Expression` instance is passed, it will be used as-is. 1703 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1704 append (bool): if `True`, add to any existing expressions. 1705 Otherwise, this resets the expressions. 1706 dialect (str): the dialect used to parse the input expression. 1707 copy (bool): if `False`, modify this expression instance in-place. 1708 opts (kwargs): other options to use to parse the input expressions. 1709 1710 Returns: 1711 Select: the modified expression. 1712 """ 1713 alias_expression = maybe_parse( 1714 alias, 1715 dialect=dialect, 1716 into=TableAlias, 1717 **opts, 1718 ) 1719 as_expression = maybe_parse( 1720 as_, 1721 dialect=dialect, 1722 **opts, 1723 ) 1724 cte = CTE( 1725 this=as_expression, 1726 alias=alias_expression, 1727 ) 1728 return _apply_child_list_builder( 1729 cte, 1730 instance=self, 1731 arg="with", 1732 append=append, 1733 copy=copy, 1734 into=With, 1735 properties={"recursive": recursive or False}, 1736 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias (str | Expression): the SQL code string to parse as the table name.
If an
Expression
instance is passed, this is used as-is. - as_ (str | Expression): the SQL code string to parse as the table expression.
If an
Expression
instance is passed, it will be used as-is. - recursive (bool): set the RECURSIVE part of the expression. Defaults to
False
. - append (bool): if
True
, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
Inherited Members
1760class Table(Expression): 1761 arg_types = { 1762 "this": True, 1763 "alias": False, 1764 "db": False, 1765 "catalog": False, 1766 "laterals": False, 1767 "joins": False, 1768 "pivots": False, 1769 "hints": False, 1770 "system_time": False, 1771 } 1772 1773 @property 1774 def db(self) -> str: 1775 return self.text("db") 1776 1777 @property 1778 def catalog(self) -> str: 1779 return self.text("catalog")
Inherited Members
1783class SystemTime(Expression): 1784 arg_types = { 1785 "this": False, 1786 "expression": False, 1787 "kind": True, 1788 }
Inherited Members
1791class Union(Subqueryable): 1792 arg_types = { 1793 "with": False, 1794 "this": True, 1795 "expression": True, 1796 "distinct": False, 1797 **QUERY_MODIFIERS, 1798 } 1799 1800 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1801 """ 1802 Set the LIMIT expression. 1803 1804 Example: 1805 >>> select("1").union(select("1")).limit(1).sql() 1806 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1807 1808 Args: 1809 expression (str | int | Expression): the SQL code string to parse. 1810 This can also be an integer. 1811 If a `Limit` instance is passed, this is used as-is. 1812 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1813 dialect (str): the dialect used to parse the input expression. 1814 copy (bool): if `False`, modify this expression instance in-place. 1815 opts (kwargs): other options to use to parse the input expressions. 1816 1817 Returns: 1818 Select: The limited subqueryable. 1819 """ 1820 return ( 1821 select("*") 1822 .from_(self.subquery(alias="_l_0", copy=copy)) 1823 .limit(expression, dialect=dialect, copy=False, **opts) 1824 ) 1825 1826 def select( 1827 self, 1828 *expressions: str | Expression, 1829 append: bool = True, 1830 dialect: DialectType = None, 1831 copy: bool = True, 1832 **opts, 1833 ) -> Union: 1834 """Append to or set the SELECT of the union recursively. 1835 1836 Example: 1837 >>> from sqlglot import parse_one 1838 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1839 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1840 1841 Args: 1842 *expressions: the SQL code strings to parse. 1843 If an `Expression` instance is passed, it will be used as-is. 1844 append: if `True`, add to any existing expressions. 1845 Otherwise, this resets the expressions. 1846 dialect: the dialect used to parse the input expressions. 1847 copy: if `False`, modify this expression instance in-place. 1848 opts: other options to use to parse the input expressions. 1849 1850 Returns: 1851 Union: the modified expression. 1852 """ 1853 this = self.copy() if copy else self 1854 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1855 this.expression.unnest().select( 1856 *expressions, append=append, dialect=dialect, copy=False, **opts 1857 ) 1858 return this 1859 1860 @property 1861 def named_selects(self): 1862 return self.this.unnest().named_selects 1863 1864 @property 1865 def is_star(self) -> bool: 1866 return self.this.is_star or self.expression.is_star 1867 1868 @property 1869 def selects(self): 1870 return self.this.unnest().selects 1871 1872 @property 1873 def left(self): 1874 return self.this 1875 1876 @property 1877 def right(self): 1878 return self.expression
1800 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1801 """ 1802 Set the LIMIT expression. 1803 1804 Example: 1805 >>> select("1").union(select("1")).limit(1).sql() 1806 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1807 1808 Args: 1809 expression (str | int | Expression): the SQL code string to parse. 1810 This can also be an integer. 1811 If a `Limit` instance is passed, this is used as-is. 1812 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1813 dialect (str): the dialect used to parse the input expression. 1814 copy (bool): if `False`, modify this expression instance in-place. 1815 opts (kwargs): other options to use to parse the input expressions. 1816 1817 Returns: 1818 Select: The limited subqueryable. 1819 """ 1820 return ( 1821 select("*") 1822 .from_(self.subquery(alias="_l_0", copy=copy)) 1823 .limit(expression, dialect=dialect, copy=False, **opts) 1824 )
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.
1826 def select( 1827 self, 1828 *expressions: str | Expression, 1829 append: bool = True, 1830 dialect: DialectType = None, 1831 copy: bool = True, 1832 **opts, 1833 ) -> Union: 1834 """Append to or set the SELECT of the union recursively. 1835 1836 Example: 1837 >>> from sqlglot import parse_one 1838 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1839 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1840 1841 Args: 1842 *expressions: the SQL code strings to parse. 1843 If an `Expression` instance is passed, it will be used as-is. 1844 append: if `True`, add to any existing expressions. 1845 Otherwise, this resets the expressions. 1846 dialect: the dialect used to parse the input expressions. 1847 copy: if `False`, modify this expression instance in-place. 1848 opts: other options to use to parse the input expressions. 1849 1850 Returns: 1851 Union: the modified expression. 1852 """ 1853 this = self.copy() if copy else self 1854 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1855 this.expression.unnest().select( 1856 *expressions, append=append, dialect=dialect, copy=False, **opts 1857 ) 1858 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
Inherited Members
Inherited Members
1889class Unnest(UDTF): 1890 arg_types = { 1891 "expressions": True, 1892 "ordinality": False, 1893 "alias": False, 1894 "offset": False, 1895 }
Inherited Members
1898class Update(Expression): 1899 arg_types = { 1900 "with": False, 1901 "this": False, 1902 "expressions": True, 1903 "from": False, 1904 "where": False, 1905 "returning": False, 1906 }
Inherited Members
1909class Values(UDTF): 1910 arg_types = { 1911 "expressions": True, 1912 "ordinality": False, 1913 "alias": False, 1914 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
1931class Select(Subqueryable): 1932 arg_types = { 1933 "with": False, 1934 "expressions": False, 1935 "hint": False, 1936 "distinct": False, 1937 "into": False, 1938 "from": False, 1939 **QUERY_MODIFIERS, 1940 } 1941 1942 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1943 """ 1944 Set the FROM expression. 1945 1946 Example: 1947 >>> Select().from_("tbl").select("x").sql() 1948 'SELECT x FROM tbl' 1949 1950 Args: 1951 *expressions (str | Expression): the SQL code strings to parse. 1952 If a `From` instance is passed, this is used as-is. 1953 If another `Expression` instance is passed, it will be wrapped in a `From`. 1954 append (bool): if `True`, add to any existing expressions. 1955 Otherwise, this flattens all the `From` expression into a single expression. 1956 dialect (str): the dialect used to parse the input expression. 1957 copy (bool): if `False`, modify this expression instance in-place. 1958 opts (kwargs): other options to use to parse the input expressions. 1959 1960 Returns: 1961 Select: the modified expression. 1962 """ 1963 return _apply_child_list_builder( 1964 *expressions, 1965 instance=self, 1966 arg="from", 1967 append=append, 1968 copy=copy, 1969 prefix="FROM", 1970 into=From, 1971 dialect=dialect, 1972 **opts, 1973 ) 1974 1975 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1976 """ 1977 Set the GROUP BY expression. 1978 1979 Example: 1980 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 1981 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 1982 1983 Args: 1984 *expressions (str | Expression): the SQL code strings to parse. 1985 If a `Group` instance is passed, this is used as-is. 1986 If another `Expression` instance is passed, it will be wrapped in a `Group`. 1987 If nothing is passed in then a group by is not applied to the expression 1988 append (bool): if `True`, add to any existing expressions. 1989 Otherwise, this flattens all the `Group` expression into a single expression. 1990 dialect (str): the dialect used to parse the input expression. 1991 copy (bool): if `False`, modify this expression instance in-place. 1992 opts (kwargs): other options to use to parse the input expressions. 1993 1994 Returns: 1995 Select: the modified expression. 1996 """ 1997 if not expressions: 1998 return self if not copy else self.copy() 1999 return _apply_child_list_builder( 2000 *expressions, 2001 instance=self, 2002 arg="group", 2003 append=append, 2004 copy=copy, 2005 prefix="GROUP BY", 2006 into=Group, 2007 dialect=dialect, 2008 **opts, 2009 ) 2010 2011 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2012 """ 2013 Set the ORDER BY expression. 2014 2015 Example: 2016 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2017 'SELECT x FROM tbl ORDER BY x DESC' 2018 2019 Args: 2020 *expressions (str | Expression): the SQL code strings to parse. 2021 If a `Group` instance is passed, this is used as-is. 2022 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2023 append (bool): if `True`, add to any existing expressions. 2024 Otherwise, this flattens all the `Order` expression into a single expression. 2025 dialect (str): the dialect used to parse the input expression. 2026 copy (bool): if `False`, modify this expression instance in-place. 2027 opts (kwargs): other options to use to parse the input expressions. 2028 2029 Returns: 2030 Select: the modified expression. 2031 """ 2032 return _apply_child_list_builder( 2033 *expressions, 2034 instance=self, 2035 arg="order", 2036 append=append, 2037 copy=copy, 2038 prefix="ORDER BY", 2039 into=Order, 2040 dialect=dialect, 2041 **opts, 2042 ) 2043 2044 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2045 """ 2046 Set the SORT BY expression. 2047 2048 Example: 2049 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2050 'SELECT x FROM tbl SORT BY x DESC' 2051 2052 Args: 2053 *expressions (str | Expression): the SQL code strings to parse. 2054 If a `Group` instance is passed, this is used as-is. 2055 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2056 append (bool): if `True`, add to any existing expressions. 2057 Otherwise, this flattens all the `Order` expression into a single expression. 2058 dialect (str): the dialect used to parse the input expression. 2059 copy (bool): if `False`, modify this expression instance in-place. 2060 opts (kwargs): other options to use to parse the input expressions. 2061 2062 Returns: 2063 Select: the modified expression. 2064 """ 2065 return _apply_child_list_builder( 2066 *expressions, 2067 instance=self, 2068 arg="sort", 2069 append=append, 2070 copy=copy, 2071 prefix="SORT BY", 2072 into=Sort, 2073 dialect=dialect, 2074 **opts, 2075 ) 2076 2077 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2078 """ 2079 Set the CLUSTER BY expression. 2080 2081 Example: 2082 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2083 'SELECT x FROM tbl CLUSTER BY x DESC' 2084 2085 Args: 2086 *expressions (str | Expression): the SQL code strings to parse. 2087 If a `Group` instance is passed, this is used as-is. 2088 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2089 append (bool): if `True`, add to any existing expressions. 2090 Otherwise, this flattens all the `Order` expression into a single expression. 2091 dialect (str): the dialect used to parse the input expression. 2092 copy (bool): if `False`, modify this expression instance in-place. 2093 opts (kwargs): other options to use to parse the input expressions. 2094 2095 Returns: 2096 Select: the modified expression. 2097 """ 2098 return _apply_child_list_builder( 2099 *expressions, 2100 instance=self, 2101 arg="cluster", 2102 append=append, 2103 copy=copy, 2104 prefix="CLUSTER BY", 2105 into=Cluster, 2106 dialect=dialect, 2107 **opts, 2108 ) 2109 2110 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2111 """ 2112 Set the LIMIT expression. 2113 2114 Example: 2115 >>> Select().from_("tbl").select("x").limit(10).sql() 2116 'SELECT x FROM tbl LIMIT 10' 2117 2118 Args: 2119 expression (str | int | Expression): the SQL code string to parse. 2120 This can also be an integer. 2121 If a `Limit` instance is passed, this is used as-is. 2122 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2123 dialect (str): the dialect used to parse the input expression. 2124 copy (bool): if `False`, modify this expression instance in-place. 2125 opts (kwargs): other options to use to parse the input expressions. 2126 2127 Returns: 2128 Select: the modified expression. 2129 """ 2130 return _apply_builder( 2131 expression=expression, 2132 instance=self, 2133 arg="limit", 2134 into=Limit, 2135 prefix="LIMIT", 2136 dialect=dialect, 2137 copy=copy, 2138 **opts, 2139 ) 2140 2141 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2142 """ 2143 Set the OFFSET expression. 2144 2145 Example: 2146 >>> Select().from_("tbl").select("x").offset(10).sql() 2147 'SELECT x FROM tbl OFFSET 10' 2148 2149 Args: 2150 expression (str | int | Expression): the SQL code string to parse. 2151 This can also be an integer. 2152 If a `Offset` instance is passed, this is used as-is. 2153 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2154 dialect (str): the dialect used to parse the input expression. 2155 copy (bool): if `False`, modify this expression instance in-place. 2156 opts (kwargs): other options to use to parse the input expressions. 2157 2158 Returns: 2159 Select: the modified expression. 2160 """ 2161 return _apply_builder( 2162 expression=expression, 2163 instance=self, 2164 arg="offset", 2165 into=Offset, 2166 prefix="OFFSET", 2167 dialect=dialect, 2168 copy=copy, 2169 **opts, 2170 ) 2171 2172 def select( 2173 self, 2174 *expressions: str | Expression, 2175 append: bool = True, 2176 dialect: DialectType = None, 2177 copy: bool = True, 2178 **opts, 2179 ) -> Select: 2180 """ 2181 Append to or set the SELECT expressions. 2182 2183 Example: 2184 >>> Select().select("x", "y").sql() 2185 'SELECT x, y' 2186 2187 Args: 2188 *expressions: the SQL code strings to parse. 2189 If an `Expression` instance is passed, it will be used as-is. 2190 append: if `True`, add to any existing expressions. 2191 Otherwise, this resets the expressions. 2192 dialect: the dialect used to parse the input expressions. 2193 copy: if `False`, modify this expression instance in-place. 2194 opts: other options to use to parse the input expressions. 2195 2196 Returns: 2197 Select: the modified expression. 2198 """ 2199 return _apply_list_builder( 2200 *expressions, 2201 instance=self, 2202 arg="expressions", 2203 append=append, 2204 dialect=dialect, 2205 copy=copy, 2206 **opts, 2207 ) 2208 2209 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2210 """ 2211 Append to or set the LATERAL expressions. 2212 2213 Example: 2214 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2215 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2216 2217 Args: 2218 *expressions (str | Expression): the SQL code strings to parse. 2219 If an `Expression` instance is passed, it will be used as-is. 2220 append (bool): if `True`, add to any existing expressions. 2221 Otherwise, this resets the expressions. 2222 dialect (str): the dialect used to parse the input expressions. 2223 copy (bool): if `False`, modify this expression instance in-place. 2224 opts (kwargs): other options to use to parse the input expressions. 2225 2226 Returns: 2227 Select: the modified expression. 2228 """ 2229 return _apply_list_builder( 2230 *expressions, 2231 instance=self, 2232 arg="laterals", 2233 append=append, 2234 into=Lateral, 2235 prefix="LATERAL VIEW", 2236 dialect=dialect, 2237 copy=copy, 2238 **opts, 2239 ) 2240 2241 def join( 2242 self, 2243 expression, 2244 on=None, 2245 using=None, 2246 append=True, 2247 join_type=None, 2248 join_alias=None, 2249 dialect=None, 2250 copy=True, 2251 **opts, 2252 ) -> Select: 2253 """ 2254 Append to or set the JOIN expressions. 2255 2256 Example: 2257 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2258 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2259 2260 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2261 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2262 2263 Use `join_type` to change the type of join: 2264 2265 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2266 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2267 2268 Args: 2269 expression (str | Expression): the SQL code string to parse. 2270 If an `Expression` instance is passed, it will be used as-is. 2271 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2272 If an `Expression` instance is passed, it will be used as-is. 2273 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2274 If an `Expression` instance is passed, it will be used as-is. 2275 append (bool): if `True`, add to any existing expressions. 2276 Otherwise, this resets the expressions. 2277 join_type (str): If set, alter the parsed join type 2278 dialect (str): the dialect used to parse the input expressions. 2279 copy (bool): if `False`, modify this expression instance in-place. 2280 opts (kwargs): other options to use to parse the input expressions. 2281 2282 Returns: 2283 Select: the modified expression. 2284 """ 2285 parse_args = {"dialect": dialect, **opts} 2286 2287 try: 2288 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2289 except ParseError: 2290 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2291 2292 join = expression if isinstance(expression, Join) else Join(this=expression) 2293 2294 if isinstance(join.this, Select): 2295 join.this.replace(join.this.subquery()) 2296 2297 if join_type: 2298 natural: t.Optional[Token] 2299 side: t.Optional[Token] 2300 kind: t.Optional[Token] 2301 2302 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2303 2304 if natural: 2305 join.set("natural", True) 2306 if side: 2307 join.set("side", side.text) 2308 if kind: 2309 join.set("kind", kind.text) 2310 2311 if on: 2312 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2313 join.set("on", on) 2314 2315 if using: 2316 join = _apply_list_builder( 2317 *ensure_collection(using), 2318 instance=join, 2319 arg="using", 2320 append=append, 2321 copy=copy, 2322 **opts, 2323 ) 2324 2325 if join_alias: 2326 join.set("this", alias_(join.this, join_alias, table=True)) 2327 return _apply_list_builder( 2328 join, 2329 instance=self, 2330 arg="joins", 2331 append=append, 2332 copy=copy, 2333 **opts, 2334 ) 2335 2336 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2337 """ 2338 Append to or set the WHERE expressions. 2339 2340 Example: 2341 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2342 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2343 2344 Args: 2345 *expressions (str | Expression): the SQL code strings to parse. 2346 If an `Expression` instance is passed, it will be used as-is. 2347 Multiple expressions are combined with an AND operator. 2348 append (bool): if `True`, AND the new expressions to any existing expression. 2349 Otherwise, this resets the expression. 2350 dialect (str): the dialect used to parse the input expressions. 2351 copy (bool): if `False`, modify this expression instance in-place. 2352 opts (kwargs): other options to use to parse the input expressions. 2353 2354 Returns: 2355 Select: the modified expression. 2356 """ 2357 return _apply_conjunction_builder( 2358 *expressions, 2359 instance=self, 2360 arg="where", 2361 append=append, 2362 into=Where, 2363 dialect=dialect, 2364 copy=copy, 2365 **opts, 2366 ) 2367 2368 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2369 """ 2370 Append to or set the HAVING expressions. 2371 2372 Example: 2373 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2374 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2375 2376 Args: 2377 *expressions (str | Expression): the SQL code strings to parse. 2378 If an `Expression` instance is passed, it will be used as-is. 2379 Multiple expressions are combined with an AND operator. 2380 append (bool): if `True`, AND the new expressions to any existing expression. 2381 Otherwise, this resets the expression. 2382 dialect (str): the dialect used to parse the input expressions. 2383 copy (bool): if `False`, modify this expression instance in-place. 2384 opts (kwargs): other options to use to parse the input expressions. 2385 2386 Returns: 2387 Select: the modified expression. 2388 """ 2389 return _apply_conjunction_builder( 2390 *expressions, 2391 instance=self, 2392 arg="having", 2393 append=append, 2394 into=Having, 2395 dialect=dialect, 2396 copy=copy, 2397 **opts, 2398 ) 2399 2400 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2401 return _apply_list_builder( 2402 *expressions, 2403 instance=self, 2404 arg="windows", 2405 append=append, 2406 into=Window, 2407 dialect=dialect, 2408 copy=copy, 2409 **opts, 2410 ) 2411 2412 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2413 return _apply_conjunction_builder( 2414 *expressions, 2415 instance=self, 2416 arg="qualify", 2417 append=append, 2418 into=Qualify, 2419 dialect=dialect, 2420 copy=copy, 2421 **opts, 2422 ) 2423 2424 def distinct(self, distinct=True, copy=True) -> Select: 2425 """ 2426 Set the OFFSET expression. 2427 2428 Example: 2429 >>> Select().from_("tbl").select("x").distinct().sql() 2430 'SELECT DISTINCT x FROM tbl' 2431 2432 Args: 2433 distinct (bool): whether the Select should be distinct 2434 copy (bool): if `False`, modify this expression instance in-place. 2435 2436 Returns: 2437 Select: the modified expression. 2438 """ 2439 instance = _maybe_copy(self, copy) 2440 instance.set("distinct", Distinct() if distinct else None) 2441 return instance 2442 2443 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2444 """ 2445 Convert this expression to a CREATE TABLE AS statement. 2446 2447 Example: 2448 >>> Select().select("*").from_("tbl").ctas("x").sql() 2449 'CREATE TABLE x AS SELECT * FROM tbl' 2450 2451 Args: 2452 table (str | Expression): the SQL code string to parse as the table name. 2453 If another `Expression` instance is passed, it will be used as-is. 2454 properties (dict): an optional mapping of table properties 2455 dialect (str): the dialect used to parse the input table. 2456 copy (bool): if `False`, modify this expression instance in-place. 2457 opts (kwargs): other options to use to parse the input table. 2458 2459 Returns: 2460 Create: the CREATE TABLE AS expression 2461 """ 2462 instance = _maybe_copy(self, copy) 2463 table_expression = maybe_parse( 2464 table, 2465 into=Table, 2466 dialect=dialect, 2467 **opts, 2468 ) 2469 properties_expression = None 2470 if properties: 2471 properties_expression = Properties.from_dict(properties) 2472 2473 return Create( 2474 this=table_expression, 2475 kind="table", 2476 expression=instance, 2477 properties=properties_expression, 2478 ) 2479 2480 def lock(self, update: bool = True, copy: bool = True) -> Select: 2481 """ 2482 Set the locking read mode for this expression. 2483 2484 Examples: 2485 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2486 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2487 2488 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2489 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2490 2491 Args: 2492 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2493 copy: if `False`, modify this expression instance in-place. 2494 2495 Returns: 2496 The modified expression. 2497 """ 2498 2499 inst = _maybe_copy(self, copy) 2500 inst.set("lock", Lock(update=update)) 2501 2502 return inst 2503 2504 @property 2505 def named_selects(self) -> t.List[str]: 2506 return [e.output_name for e in self.expressions if e.alias_or_name] 2507 2508 @property 2509 def is_star(self) -> bool: 2510 return any(expression.is_star for expression in self.expressions) 2511 2512 @property 2513 def selects(self) -> t.List[Expression]: 2514 return self.expressions
1942 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1943 """ 1944 Set the FROM expression. 1945 1946 Example: 1947 >>> Select().from_("tbl").select("x").sql() 1948 'SELECT x FROM tbl' 1949 1950 Args: 1951 *expressions (str | Expression): the SQL code strings to parse. 1952 If a `From` instance is passed, this is used as-is. 1953 If another `Expression` instance is passed, it will be wrapped in a `From`. 1954 append (bool): if `True`, add to any existing expressions. 1955 Otherwise, this flattens all the `From` expression into a single expression. 1956 dialect (str): the dialect used to parse the input expression. 1957 copy (bool): if `False`, modify this expression instance in-place. 1958 opts (kwargs): other options to use to parse the input expressions. 1959 1960 Returns: 1961 Select: the modified expression. 1962 """ 1963 return _apply_child_list_builder( 1964 *expressions, 1965 instance=self, 1966 arg="from", 1967 append=append, 1968 copy=copy, 1969 prefix="FROM", 1970 into=From, 1971 dialect=dialect, 1972 **opts, 1973 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
From
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aFrom
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theFrom
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
1975 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 1976 """ 1977 Set the GROUP BY expression. 1978 1979 Example: 1980 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 1981 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 1982 1983 Args: 1984 *expressions (str | Expression): the SQL code strings to parse. 1985 If a `Group` instance is passed, this is used as-is. 1986 If another `Expression` instance is passed, it will be wrapped in a `Group`. 1987 If nothing is passed in then a group by is not applied to the expression 1988 append (bool): if `True`, add to any existing expressions. 1989 Otherwise, this flattens all the `Group` expression into a single expression. 1990 dialect (str): the dialect used to parse the input expression. 1991 copy (bool): if `False`, modify this expression instance in-place. 1992 opts (kwargs): other options to use to parse the input expressions. 1993 1994 Returns: 1995 Select: the modified expression. 1996 """ 1997 if not expressions: 1998 return self if not copy else self.copy() 1999 return _apply_child_list_builder( 2000 *expressions, 2001 instance=self, 2002 arg="group", 2003 append=append, 2004 copy=copy, 2005 prefix="GROUP BY", 2006 into=Group, 2007 dialect=dialect, 2008 **opts, 2009 )
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.
2011 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2012 """ 2013 Set the ORDER BY expression. 2014 2015 Example: 2016 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2017 'SELECT x FROM tbl ORDER BY x DESC' 2018 2019 Args: 2020 *expressions (str | Expression): the SQL code strings to parse. 2021 If a `Group` instance is passed, this is used as-is. 2022 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2023 append (bool): if `True`, add to any existing expressions. 2024 Otherwise, this flattens all the `Order` expression into a single expression. 2025 dialect (str): the dialect used to parse the input expression. 2026 copy (bool): if `False`, modify this expression instance in-place. 2027 opts (kwargs): other options to use to parse the input expressions. 2028 2029 Returns: 2030 Select: the modified expression. 2031 """ 2032 return _apply_child_list_builder( 2033 *expressions, 2034 instance=self, 2035 arg="order", 2036 append=append, 2037 copy=copy, 2038 prefix="ORDER BY", 2039 into=Order, 2040 dialect=dialect, 2041 **opts, 2042 )
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.
2044 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2045 """ 2046 Set the SORT BY expression. 2047 2048 Example: 2049 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2050 'SELECT x FROM tbl SORT BY x DESC' 2051 2052 Args: 2053 *expressions (str | Expression): the SQL code strings to parse. 2054 If a `Group` instance is passed, this is used as-is. 2055 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2056 append (bool): if `True`, add to any existing expressions. 2057 Otherwise, this flattens all the `Order` expression into a single expression. 2058 dialect (str): the dialect used to parse the input expression. 2059 copy (bool): if `False`, modify this expression instance in-place. 2060 opts (kwargs): other options to use to parse the input expressions. 2061 2062 Returns: 2063 Select: the modified expression. 2064 """ 2065 return _apply_child_list_builder( 2066 *expressions, 2067 instance=self, 2068 arg="sort", 2069 append=append, 2070 copy=copy, 2071 prefix="SORT BY", 2072 into=Sort, 2073 dialect=dialect, 2074 **opts, 2075 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aSORT
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2077 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2078 """ 2079 Set the CLUSTER BY expression. 2080 2081 Example: 2082 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2083 'SELECT x FROM tbl CLUSTER BY x DESC' 2084 2085 Args: 2086 *expressions (str | Expression): the SQL code strings to parse. 2087 If a `Group` instance is passed, this is used as-is. 2088 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2089 append (bool): if `True`, add to any existing expressions. 2090 Otherwise, this flattens all the `Order` expression into a single expression. 2091 dialect (str): the dialect used to parse the input expression. 2092 copy (bool): if `False`, modify this expression instance in-place. 2093 opts (kwargs): other options to use to parse the input expressions. 2094 2095 Returns: 2096 Select: the modified expression. 2097 """ 2098 return _apply_child_list_builder( 2099 *expressions, 2100 instance=self, 2101 arg="cluster", 2102 append=append, 2103 copy=copy, 2104 prefix="CLUSTER BY", 2105 into=Cluster, 2106 dialect=dialect, 2107 **opts, 2108 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Group
instance is passed, this is used as-is. If anotherExpression
instance is passed, it will be wrapped in aCluster
. - append (bool): if
True
, add to any existing expressions. Otherwise, this flattens all theOrder
expression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False
, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2110 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2111 """ 2112 Set the LIMIT expression. 2113 2114 Example: 2115 >>> Select().from_("tbl").select("x").limit(10).sql() 2116 'SELECT x FROM tbl LIMIT 10' 2117 2118 Args: 2119 expression (str | int | Expression): the SQL code string to parse. 2120 This can also be an integer. 2121 If a `Limit` instance is passed, this is used as-is. 2122 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2123 dialect (str): the dialect used to parse the input expression. 2124 copy (bool): if `False`, modify this expression instance in-place. 2125 opts (kwargs): other options to use to parse the input expressions. 2126 2127 Returns: 2128 Select: the modified expression. 2129 """ 2130 return _apply_builder( 2131 expression=expression, 2132 instance=self, 2133 arg="limit", 2134 into=Limit, 2135 prefix="LIMIT", 2136 dialect=dialect, 2137 copy=copy, 2138 **opts, 2139 )
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.
2141 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2142 """ 2143 Set the OFFSET expression. 2144 2145 Example: 2146 >>> Select().from_("tbl").select("x").offset(10).sql() 2147 'SELECT x FROM tbl OFFSET 10' 2148 2149 Args: 2150 expression (str | int | Expression): the SQL code string to parse. 2151 This can also be an integer. 2152 If a `Offset` instance is passed, this is used as-is. 2153 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2154 dialect (str): the dialect used to parse the input expression. 2155 copy (bool): if `False`, modify this expression instance in-place. 2156 opts (kwargs): other options to use to parse the input expressions. 2157 2158 Returns: 2159 Select: the modified expression. 2160 """ 2161 return _apply_builder( 2162 expression=expression, 2163 instance=self, 2164 arg="offset", 2165 into=Offset, 2166 prefix="OFFSET", 2167 dialect=dialect, 2168 copy=copy, 2169 **opts, 2170 )
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.
2172 def select( 2173 self, 2174 *expressions: str | Expression, 2175 append: bool = True, 2176 dialect: DialectType = None, 2177 copy: bool = True, 2178 **opts, 2179 ) -> Select: 2180 """ 2181 Append to or set the SELECT expressions. 2182 2183 Example: 2184 >>> Select().select("x", "y").sql() 2185 'SELECT x, y' 2186 2187 Args: 2188 *expressions: the SQL code strings to parse. 2189 If an `Expression` instance is passed, it will be used as-is. 2190 append: if `True`, add to any existing expressions. 2191 Otherwise, this resets the expressions. 2192 dialect: the dialect used to parse the input expressions. 2193 copy: if `False`, modify this expression instance in-place. 2194 opts: other options to use to parse the input expressions. 2195 2196 Returns: 2197 Select: the modified expression. 2198 """ 2199 return _apply_list_builder( 2200 *expressions, 2201 instance=self, 2202 arg="expressions", 2203 append=append, 2204 dialect=dialect, 2205 copy=copy, 2206 **opts, 2207 )
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.
2209 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2210 """ 2211 Append to or set the LATERAL expressions. 2212 2213 Example: 2214 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2215 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2216 2217 Args: 2218 *expressions (str | Expression): the SQL code strings to parse. 2219 If an `Expression` instance is passed, it will be used as-is. 2220 append (bool): if `True`, add to any existing expressions. 2221 Otherwise, this resets the expressions. 2222 dialect (str): the dialect used to parse the input expressions. 2223 copy (bool): if `False`, modify this expression instance in-place. 2224 opts (kwargs): other options to use to parse the input expressions. 2225 2226 Returns: 2227 Select: the modified expression. 2228 """ 2229 return _apply_list_builder( 2230 *expressions, 2231 instance=self, 2232 arg="laterals", 2233 append=append, 2234 into=Lateral, 2235 prefix="LATERAL VIEW", 2236 dialect=dialect, 2237 copy=copy, 2238 **opts, 2239 )
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.
2241 def join( 2242 self, 2243 expression, 2244 on=None, 2245 using=None, 2246 append=True, 2247 join_type=None, 2248 join_alias=None, 2249 dialect=None, 2250 copy=True, 2251 **opts, 2252 ) -> Select: 2253 """ 2254 Append to or set the JOIN expressions. 2255 2256 Example: 2257 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2258 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2259 2260 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2261 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2262 2263 Use `join_type` to change the type of join: 2264 2265 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2266 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2267 2268 Args: 2269 expression (str | Expression): the SQL code string to parse. 2270 If an `Expression` instance is passed, it will be used as-is. 2271 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2272 If an `Expression` instance is passed, it will be used as-is. 2273 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2274 If an `Expression` instance is passed, it will be used as-is. 2275 append (bool): if `True`, add to any existing expressions. 2276 Otherwise, this resets the expressions. 2277 join_type (str): If set, alter the parsed join type 2278 dialect (str): the dialect used to parse the input expressions. 2279 copy (bool): if `False`, modify this expression instance in-place. 2280 opts (kwargs): other options to use to parse the input expressions. 2281 2282 Returns: 2283 Select: the modified expression. 2284 """ 2285 parse_args = {"dialect": dialect, **opts} 2286 2287 try: 2288 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2289 except ParseError: 2290 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2291 2292 join = expression if isinstance(expression, Join) else Join(this=expression) 2293 2294 if isinstance(join.this, Select): 2295 join.this.replace(join.this.subquery()) 2296 2297 if join_type: 2298 natural: t.Optional[Token] 2299 side: t.Optional[Token] 2300 kind: t.Optional[Token] 2301 2302 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2303 2304 if natural: 2305 join.set("natural", True) 2306 if side: 2307 join.set("side", side.text) 2308 if kind: 2309 join.set("kind", kind.text) 2310 2311 if on: 2312 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2313 join.set("on", on) 2314 2315 if using: 2316 join = _apply_list_builder( 2317 *ensure_collection(using), 2318 instance=join, 2319 arg="using", 2320 append=append, 2321 copy=copy, 2322 **opts, 2323 ) 2324 2325 if join_alias: 2326 join.set("this", alias_(join.this, join_alias, table=True)) 2327 return _apply_list_builder( 2328 join, 2329 instance=self, 2330 arg="joins", 2331 append=append, 2332 copy=copy, 2333 **opts, 2334 )
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.
2336 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2337 """ 2338 Append to or set the WHERE expressions. 2339 2340 Example: 2341 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2342 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2343 2344 Args: 2345 *expressions (str | Expression): the SQL code strings to parse. 2346 If an `Expression` instance is passed, it will be used as-is. 2347 Multiple expressions are combined with an AND operator. 2348 append (bool): if `True`, AND the new expressions to any existing expression. 2349 Otherwise, this resets the expression. 2350 dialect (str): the dialect used to parse the input expressions. 2351 copy (bool): if `False`, modify this expression instance in-place. 2352 opts (kwargs): other options to use to parse the input expressions. 2353 2354 Returns: 2355 Select: the modified expression. 2356 """ 2357 return _apply_conjunction_builder( 2358 *expressions, 2359 instance=self, 2360 arg="where", 2361 append=append, 2362 into=Where, 2363 dialect=dialect, 2364 copy=copy, 2365 **opts, 2366 )
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.
2368 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2369 """ 2370 Append to or set the HAVING expressions. 2371 2372 Example: 2373 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2374 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2375 2376 Args: 2377 *expressions (str | Expression): the SQL code strings to parse. 2378 If an `Expression` instance is passed, it will be used as-is. 2379 Multiple expressions are combined with an AND operator. 2380 append (bool): if `True`, AND the new expressions to any existing expression. 2381 Otherwise, this resets the expression. 2382 dialect (str): the dialect used to parse the input expressions. 2383 copy (bool): if `False`, modify this expression instance in-place. 2384 opts (kwargs): other options to use to parse the input expressions. 2385 2386 Returns: 2387 Select: the modified expression. 2388 """ 2389 return _apply_conjunction_builder( 2390 *expressions, 2391 instance=self, 2392 arg="having", 2393 append=append, 2394 into=Having, 2395 dialect=dialect, 2396 copy=copy, 2397 **opts, 2398 )
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.
2424 def distinct(self, distinct=True, copy=True) -> Select: 2425 """ 2426 Set the OFFSET expression. 2427 2428 Example: 2429 >>> Select().from_("tbl").select("x").distinct().sql() 2430 'SELECT DISTINCT x FROM tbl' 2431 2432 Args: 2433 distinct (bool): whether the Select should be distinct 2434 copy (bool): if `False`, modify this expression instance in-place. 2435 2436 Returns: 2437 Select: the modified expression. 2438 """ 2439 instance = _maybe_copy(self, copy) 2440 instance.set("distinct", Distinct() if distinct else None) 2441 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- distinct (bool): whether the Select should be distinct
- copy (bool): if
False
, modify this expression instance in-place.
Returns:
Select: the modified expression.
2443 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2444 """ 2445 Convert this expression to a CREATE TABLE AS statement. 2446 2447 Example: 2448 >>> Select().select("*").from_("tbl").ctas("x").sql() 2449 'CREATE TABLE x AS SELECT * FROM tbl' 2450 2451 Args: 2452 table (str | Expression): the SQL code string to parse as the table name. 2453 If another `Expression` instance is passed, it will be used as-is. 2454 properties (dict): an optional mapping of table properties 2455 dialect (str): the dialect used to parse the input table. 2456 copy (bool): if `False`, modify this expression instance in-place. 2457 opts (kwargs): other options to use to parse the input table. 2458 2459 Returns: 2460 Create: the CREATE TABLE AS expression 2461 """ 2462 instance = _maybe_copy(self, copy) 2463 table_expression = maybe_parse( 2464 table, 2465 into=Table, 2466 dialect=dialect, 2467 **opts, 2468 ) 2469 properties_expression = None 2470 if properties: 2471 properties_expression = Properties.from_dict(properties) 2472 2473 return Create( 2474 this=table_expression, 2475 kind="table", 2476 expression=instance, 2477 properties=properties_expression, 2478 )
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
2480 def lock(self, update: bool = True, copy: bool = True) -> Select: 2481 """ 2482 Set the locking read mode for this expression. 2483 2484 Examples: 2485 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2486 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2487 2488 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2489 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2490 2491 Args: 2492 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2493 copy: if `False`, modify this expression instance in-place. 2494 2495 Returns: 2496 The modified expression. 2497 """ 2498 2499 inst = _maybe_copy(self, copy) 2500 inst.set("lock", Lock(update=update)) 2501 2502 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
2517class Subquery(DerivedTable, Unionable): 2518 arg_types = { 2519 "this": True, 2520 "alias": False, 2521 "with": False, 2522 **QUERY_MODIFIERS, 2523 } 2524 2525 def unnest(self): 2526 """ 2527 Returns the first non subquery. 2528 """ 2529 expression = self 2530 while isinstance(expression, Subquery): 2531 expression = expression.this 2532 return expression 2533 2534 @property 2535 def is_star(self) -> bool: 2536 return self.this.is_star 2537 2538 @property 2539 def output_name(self): 2540 return self.alias
2525 def unnest(self): 2526 """ 2527 Returns the first non subquery. 2528 """ 2529 expression = self 2530 while isinstance(expression, Subquery): 2531 expression = expression.this 2532 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
2543class TableSample(Expression): 2544 arg_types = { 2545 "this": False, 2546 "method": False, 2547 "bucket_numerator": False, 2548 "bucket_denominator": False, 2549 "bucket_field": False, 2550 "percent": False, 2551 "rows": False, 2552 "size": False, 2553 "seed": False, 2554 "kind": False, 2555 }
Inherited Members
2558class Tag(Expression): 2559 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2560 2561 arg_types = { 2562 "this": False, 2563 "prefix": False, 2564 "postfix": False, 2565 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
2568class Pivot(Expression): 2569 arg_types = { 2570 "this": False, 2571 "alias": False, 2572 "expressions": True, 2573 "field": True, 2574 "unpivot": True, 2575 }
Inherited Members
2578class Window(Expression): 2579 arg_types = { 2580 "this": True, 2581 "partition_by": False, 2582 "order": False, 2583 "spec": False, 2584 "alias": False, 2585 }
Inherited Members
2588class WindowSpec(Expression): 2589 arg_types = { 2590 "kind": False, 2591 "start": False, 2592 "start_side": False, 2593 "end": False, 2594 "end_side": False, 2595 }
Inherited Members
Inherited Members
2602class Star(Expression): 2603 arg_types = {"except": False, "replace": False} 2604 2605 @property 2606 def name(self) -> str: 2607 return "*" 2608 2609 @property 2610 def output_name(self): 2611 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
Inherited Members
Inherited Members
2626class Null(Condition): 2627 arg_types: t.Dict[str, t.Any] = {} 2628 2629 @property 2630 def name(self) -> str: 2631 return "NULL"
Inherited Members
Inherited Members
2638class DataType(Expression): 2639 arg_types = { 2640 "this": True, 2641 "expressions": False, 2642 "nested": False, 2643 "values": False, 2644 "prefix": False, 2645 } 2646 2647 class Type(AutoName): 2648 CHAR = auto() 2649 NCHAR = auto() 2650 VARCHAR = auto() 2651 NVARCHAR = auto() 2652 TEXT = auto() 2653 MEDIUMTEXT = auto() 2654 LONGTEXT = auto() 2655 MEDIUMBLOB = auto() 2656 LONGBLOB = auto() 2657 BINARY = auto() 2658 VARBINARY = auto() 2659 INT = auto() 2660 TINYINT = auto() 2661 SMALLINT = auto() 2662 BIGINT = auto() 2663 FLOAT = auto() 2664 DOUBLE = auto() 2665 DECIMAL = auto() 2666 BOOLEAN = auto() 2667 JSON = auto() 2668 JSONB = auto() 2669 INTERVAL = auto() 2670 TIME = auto() 2671 TIMESTAMP = auto() 2672 TIMESTAMPTZ = auto() 2673 TIMESTAMPLTZ = auto() 2674 DATE = auto() 2675 DATETIME = auto() 2676 ARRAY = auto() 2677 MAP = auto() 2678 UUID = auto() 2679 GEOGRAPHY = auto() 2680 GEOMETRY = auto() 2681 STRUCT = auto() 2682 NULLABLE = auto() 2683 HLLSKETCH = auto() 2684 HSTORE = auto() 2685 SUPER = auto() 2686 SERIAL = auto() 2687 SMALLSERIAL = auto() 2688 BIGSERIAL = auto() 2689 XML = auto() 2690 UNIQUEIDENTIFIER = auto() 2691 MONEY = auto() 2692 SMALLMONEY = auto() 2693 ROWVERSION = auto() 2694 IMAGE = auto() 2695 VARIANT = auto() 2696 OBJECT = auto() 2697 INET = auto() 2698 NULL = auto() 2699 UNKNOWN = auto() # Sentinel value, useful for type annotation 2700 2701 TEXT_TYPES = { 2702 Type.CHAR, 2703 Type.NCHAR, 2704 Type.VARCHAR, 2705 Type.NVARCHAR, 2706 Type.TEXT, 2707 } 2708 2709 INTEGER_TYPES = { 2710 Type.INT, 2711 Type.TINYINT, 2712 Type.SMALLINT, 2713 Type.BIGINT, 2714 } 2715 2716 FLOAT_TYPES = { 2717 Type.FLOAT, 2718 Type.DOUBLE, 2719 } 2720 2721 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2722 2723 TEMPORAL_TYPES = { 2724 Type.TIMESTAMP, 2725 Type.TIMESTAMPTZ, 2726 Type.TIMESTAMPLTZ, 2727 Type.DATE, 2728 Type.DATETIME, 2729 } 2730 2731 @classmethod 2732 def build( 2733 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2734 ) -> DataType: 2735 from sqlglot import parse_one 2736 2737 if isinstance(dtype, str): 2738 if dtype.upper() in cls.Type.__members__: 2739 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2740 else: 2741 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2742 if data_type_exp is None: 2743 raise ValueError(f"Unparsable data type value: {dtype}") 2744 elif isinstance(dtype, DataType.Type): 2745 data_type_exp = DataType(this=dtype) 2746 elif isinstance(dtype, DataType): 2747 return dtype 2748 else: 2749 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2750 return DataType(**{**data_type_exp.args, **kwargs}) 2751 2752 def is_type(self, dtype: DataType.Type) -> bool: 2753 return self.this == dtype
2731 @classmethod 2732 def build( 2733 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2734 ) -> DataType: 2735 from sqlglot import parse_one 2736 2737 if isinstance(dtype, str): 2738 if dtype.upper() in cls.Type.__members__: 2739 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2740 else: 2741 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2742 if data_type_exp is None: 2743 raise ValueError(f"Unparsable data type value: {dtype}") 2744 elif isinstance(dtype, DataType.Type): 2745 data_type_exp = DataType(this=dtype) 2746 elif isinstance(dtype, DataType): 2747 return dtype 2748 else: 2749 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2750 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
2647 class Type(AutoName): 2648 CHAR = auto() 2649 NCHAR = auto() 2650 VARCHAR = auto() 2651 NVARCHAR = auto() 2652 TEXT = auto() 2653 MEDIUMTEXT = auto() 2654 LONGTEXT = auto() 2655 MEDIUMBLOB = auto() 2656 LONGBLOB = auto() 2657 BINARY = auto() 2658 VARBINARY = auto() 2659 INT = auto() 2660 TINYINT = auto() 2661 SMALLINT = auto() 2662 BIGINT = auto() 2663 FLOAT = auto() 2664 DOUBLE = auto() 2665 DECIMAL = auto() 2666 BOOLEAN = auto() 2667 JSON = auto() 2668 JSONB = auto() 2669 INTERVAL = auto() 2670 TIME = auto() 2671 TIMESTAMP = auto() 2672 TIMESTAMPTZ = auto() 2673 TIMESTAMPLTZ = auto() 2674 DATE = auto() 2675 DATETIME = auto() 2676 ARRAY = auto() 2677 MAP = auto() 2678 UUID = auto() 2679 GEOGRAPHY = auto() 2680 GEOMETRY = auto() 2681 STRUCT = auto() 2682 NULLABLE = auto() 2683 HLLSKETCH = auto() 2684 HSTORE = auto() 2685 SUPER = auto() 2686 SERIAL = auto() 2687 SMALLSERIAL = auto() 2688 BIGSERIAL = auto() 2689 XML = auto() 2690 UNIQUEIDENTIFIER = auto() 2691 MONEY = auto() 2692 SMALLMONEY = auto() 2693 ROWVERSION = auto() 2694 IMAGE = auto() 2695 VARIANT = auto() 2696 OBJECT = auto() 2697 INET = auto() 2698 NULL = auto() 2699 UNKNOWN = auto() # Sentinel value, useful for type annotation
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
2804class AddConstraint(Expression): 2805 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
Inherited Members
2813class Binary(Expression): 2814 arg_types = {"this": True, "expression": True} 2815 2816 @property 2817 def left(self): 2818 return self.this 2819 2820 @property 2821 def right(self): 2822 return self.expression
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Kwarg in special functions like func(kwarg => y).
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
2998class Alias(Expression): 2999 arg_types = {"this": True, "alias": False} 3000 3001 @property 3002 def output_name(self): 3003 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 ''
3006class Aliases(Expression): 3007 arg_types = {"this": True, "expressions": True} 3008 3009 @property 3010 def aliases(self): 3011 return self.expressions
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3030class In(Predicate): 3031 arg_types = { 3032 "this": True, 3033 "expressions": False, 3034 "query": False, 3035 "unnest": False, 3036 "field": False, 3037 "is_global": False, 3038 }
Inherited Members
3041class TimeUnit(Expression): 3042 """Automatically converts unit arg into a var.""" 3043 3044 arg_types = {"unit": False} 3045 3046 def __init__(self, **args): 3047 unit = args.get("unit") 3048 if isinstance(unit, Column): 3049 args["unit"] = Var(this=unit.name) 3050 elif isinstance(unit, Week): 3051 unit.set("this", Var(this=unit.this.name)) 3052 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
Inherited Members
Inherited Members
3068class Func(Condition): 3069 """ 3070 The base class for all function expressions. 3071 3072 Attributes: 3073 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3074 treated as a variable length argument and the argument's value will be stored as a list. 3075 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3076 for this function expression. These values are used to map this node to a name during parsing 3077 as well as to provide the function's name during SQL string generation. By default the SQL 3078 name is set to the expression's class name transformed to snake case. 3079 """ 3080 3081 is_var_len_args = False 3082 3083 @classmethod 3084 def from_arg_list(cls, args): 3085 if cls.is_var_len_args: 3086 all_arg_keys = list(cls.arg_types) 3087 # If this function supports variable length argument treat the last argument as such. 3088 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3089 num_non_var = len(non_var_len_arg_keys) 3090 3091 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3092 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3093 else: 3094 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3095 3096 return cls(**args_dict) 3097 3098 @classmethod 3099 def sql_names(cls): 3100 if cls is Func: 3101 raise NotImplementedError( 3102 "SQL name is only supported by concrete function implementations" 3103 ) 3104 if "_sql_names" not in cls.__dict__: 3105 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3106 return cls._sql_names 3107 3108 @classmethod 3109 def sql_name(cls): 3110 return cls.sql_names()[0] 3111 3112 @classmethod 3113 def default_parser_mappings(cls): 3114 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.
3083 @classmethod 3084 def from_arg_list(cls, args): 3085 if cls.is_var_len_args: 3086 all_arg_keys = list(cls.arg_types) 3087 # If this function supports variable length argument treat the last argument as such. 3088 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3089 num_non_var = len(non_var_len_arg_keys) 3090 3091 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3092 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3093 else: 3094 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3095 3096 return cls(**args_dict)
3098 @classmethod 3099 def sql_names(cls): 3100 if cls is Func: 3101 raise NotImplementedError( 3102 "SQL name is only supported by concrete function implementations" 3103 ) 3104 if "_sql_names" not in cls.__dict__: 3105 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3106 return cls._sql_names
Inherited Members
Inherited Members
Inherited Members
3125class Anonymous(Func): 3126 arg_types = {"this": True, "expressions": False} 3127 is_var_len_args = True
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3155class ArrayConcat(Func): 3156 arg_types = {"this": True, "expressions": False} 3157 is_var_len_args = True
Inherited Members
Inherited Members
3164class ArrayFilter(Func): 3165 arg_types = {"this": True, "expression": True} 3166 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3201class Cast(Func): 3202 arg_types = {"this": True, "to": True} 3203 3204 @property 3205 def name(self) -> str: 3206 return self.this.name 3207 3208 @property 3209 def to(self): 3210 return self.args["to"] 3211 3212 @property 3213 def output_name(self): 3214 return self.name 3215 3216 def is_type(self, dtype: DataType.Type) -> bool: 3217 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
Inherited Members
Inherited Members
3228class Ceil(Func): 3229 arg_types = {"this": True, "decimals": False} 3230 _sql_names = ["CEIL", "CEILING"]
Inherited Members
3233class Coalesce(Func): 3234 arg_types = {"this": True, "expressions": False} 3235 is_var_len_args = True
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3267class DateAdd(Func, TimeUnit): 3268 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3271class DateSub(Func, TimeUnit): 3272 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3275class DateDiff(Func, TimeUnit): 3276 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
Inherited Members
3283class DatetimeAdd(Func, TimeUnit): 3284 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3287class DatetimeSub(Func, TimeUnit): 3288 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3291class DatetimeDiff(Func, TimeUnit): 3292 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3295class DatetimeTrunc(Func, TimeUnit): 3296 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3323class TimestampAdd(Func, TimeUnit): 3324 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3327class TimestampSub(Func, TimeUnit): 3328 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3331class TimestampDiff(Func, TimeUnit): 3332 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3335class TimestampTrunc(Func, TimeUnit): 3336 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
3339class TimeAdd(Func, TimeUnit): 3340 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3343class TimeSub(Func, TimeUnit): 3344 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
3347class TimeDiff(Func, TimeUnit): 3348 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
Inherited Members
3355class DateFromParts(Func): 3356 _sql_names = ["DATEFROMPARTS"] 3357 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3400class Greatest(Func): 3401 arg_types = {"this": True, "expressions": False} 3402 is_var_len_args = True
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3417class IfNull(Func): 3418 arg_types = {"this": True, "expression": False} 3419 _sql_names = ["IFNULL", "NVL"]
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3455class Levenshtein(Func): 3456 arg_types = { 3457 "this": True, 3458 "expression": False, 3459 "ins_cost": False, 3460 "del_cost": False, 3461 "sub_cost": False, 3462 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3498class Matches(Func): 3499 """Oracle/Snowflake decode. 3500 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3501 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3502 """ 3503 3504 arg_types = {"this": True, "expressions": True} 3505 is_var_len_args = True
Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
Inherited Members
3508class Max(AggFunc): 3509 arg_types = {"this": True, "expressions": False} 3510 is_var_len_args = True
Inherited Members
3513class Min(AggFunc): 3514 arg_types = {"this": True, "expressions": False} 3515 is_var_len_args = True
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3556class ApproxQuantile(Quantile): 3557 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
Inherited Members
3564class ReadCSV(Func): 3565 _sql_names = ["READ_CSV"] 3566 is_var_len_args = True 3567 arg_types = {"this": True, "expressions": False}
Inherited Members
3570class Reduce(Func): 3571 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
3574class RegexpExtract(Func): 3575 arg_types = { 3576 "this": True, 3577 "expression": True, 3578 "position": False, 3579 "occurrence": False, 3580 "group": False, 3581 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3630class StrPosition(Func): 3631 arg_types = { 3632 "this": True, 3633 "substr": True, 3634 "position": False, 3635 "instance": False, 3636 }
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3710class Trim(Func): 3711 arg_types = { 3712 "this": True, 3713 "expression": False, 3714 "position": False, 3715 "collation": False, 3716 }
Inherited Members
3719class TsOrDsAdd(Func, TimeUnit): 3720 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3745class UnixToTime(Func): 3746 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3747 3748 SECONDS = Literal.string("seconds") 3749 MILLIS = Literal.string("millis") 3750 MICROS = Literal.string("micros")
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
Inherited Members
3773class XMLTable(Func): 3774 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
Inherited Members
Inherited Members
3785class Merge(Expression): 3786 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
3789class When(Func): 3790 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
3818def maybe_parse( 3819 sql_or_expression: str | Expression, 3820 *, 3821 into: t.Optional[IntoType] = None, 3822 dialect: DialectType = None, 3823 prefix: t.Optional[str] = None, 3824 copy: bool = False, 3825 **opts, 3826) -> Expression: 3827 """Gracefully handle a possible string or expression. 3828 3829 Example: 3830 >>> maybe_parse("1") 3831 (LITERAL this: 1, is_string: False) 3832 >>> maybe_parse(to_identifier("x")) 3833 (IDENTIFIER this: x, quoted: False) 3834 3835 Args: 3836 sql_or_expression: the SQL code string or an expression 3837 into: the SQLGlot Expression to parse into 3838 dialect: the dialect used to parse the input expressions (in the case that an 3839 input expression is a SQL string). 3840 prefix: a string to prefix the sql with before it gets parsed 3841 (automatically includes a space) 3842 copy: whether or not to copy the expression. 3843 **opts: other options to use to parse the input expressions (again, in the case 3844 that an input expression is a SQL string). 3845 3846 Returns: 3847 Expression: the parsed or given expression. 3848 """ 3849 if isinstance(sql_or_expression, Expression): 3850 if copy: 3851 return sql_or_expression.copy() 3852 return sql_or_expression 3853 3854 import sqlglot 3855 3856 sql = str(sql_or_expression) 3857 if prefix: 3858 sql = f"{prefix} {sql}" 3859 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.
4005def union(left, right, distinct=True, dialect=None, **opts): 4006 """ 4007 Initializes a syntax tree from one UNION expression. 4008 4009 Example: 4010 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4011 'SELECT * FROM foo UNION SELECT * FROM bla' 4012 4013 Args: 4014 left (str | Expression): the SQL code string corresponding to the left-hand side. 4015 If an `Expression` instance is passed, it will be used as-is. 4016 right (str | Expression): the SQL code string corresponding to the right-hand side. 4017 If an `Expression` instance is passed, it will be used as-is. 4018 distinct (bool): set the DISTINCT flag if and only if this is true. 4019 dialect (str): the dialect used to parse the input expression. 4020 opts (kwargs): other options to use to parse the input expressions. 4021 Returns: 4022 Union: the syntax tree for the UNION expression. 4023 """ 4024 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4025 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4026 4027 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.
4030def intersect(left, right, distinct=True, dialect=None, **opts): 4031 """ 4032 Initializes a syntax tree from one INTERSECT expression. 4033 4034 Example: 4035 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4036 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4037 4038 Args: 4039 left (str | Expression): the SQL code string corresponding to the left-hand side. 4040 If an `Expression` instance is passed, it will be used as-is. 4041 right (str | Expression): the SQL code string corresponding to the right-hand side. 4042 If an `Expression` instance is passed, it will be used as-is. 4043 distinct (bool): set the DISTINCT flag if and only if this is true. 4044 dialect (str): the dialect used to parse the input expression. 4045 opts (kwargs): other options to use to parse the input expressions. 4046 Returns: 4047 Intersect: the syntax tree for the INTERSECT expression. 4048 """ 4049 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4050 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4051 4052 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.
4055def except_(left, right, distinct=True, dialect=None, **opts): 4056 """ 4057 Initializes a syntax tree from one EXCEPT expression. 4058 4059 Example: 4060 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4061 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4062 4063 Args: 4064 left (str | Expression): the SQL code string corresponding to the left-hand side. 4065 If an `Expression` instance is passed, it will be used as-is. 4066 right (str | Expression): the SQL code string corresponding to the right-hand side. 4067 If an `Expression` instance is passed, it will be used as-is. 4068 distinct (bool): set the DISTINCT flag if and only if this is true. 4069 dialect (str): the dialect used to parse the input expression. 4070 opts (kwargs): other options to use to parse the input expressions. 4071 Returns: 4072 Except: the syntax tree for the EXCEPT statement. 4073 """ 4074 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4075 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4076 4077 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.
4080def select(*expressions: str | Expression, dialect: DialectType = None, **opts) -> Select: 4081 """ 4082 Initializes a syntax tree from one or multiple SELECT expressions. 4083 4084 Example: 4085 >>> select("col1", "col2").from_("tbl").sql() 4086 'SELECT col1, col2 FROM tbl' 4087 4088 Args: 4089 *expressions: the SQL code string to parse as the expressions of a 4090 SELECT statement. If an Expression instance is passed, this is used as-is. 4091 dialect: the dialect used to parse the input expressions (in the case that an 4092 input expression is a SQL string). 4093 **opts: other options to use to parse the input expressions (again, in the case 4094 that an input expression is a SQL string). 4095 4096 Returns: 4097 Select: the syntax tree for the SELECT statement. 4098 """ 4099 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.
4102def from_(*expressions, dialect=None, **opts) -> Select: 4103 """ 4104 Initializes a syntax tree from a FROM expression. 4105 4106 Example: 4107 >>> from_("tbl").select("col1", "col2").sql() 4108 'SELECT col1, col2 FROM tbl' 4109 4110 Args: 4111 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4112 SELECT statement. If an Expression instance is passed, this is used as-is. 4113 dialect (str): the dialect used to parse the input expression (in the case that the 4114 input expression is a SQL string). 4115 **opts: other options to use to parse the input expressions (again, in the case 4116 that the input expression is a SQL string). 4117 4118 Returns: 4119 Select: the syntax tree for the SELECT statement. 4120 """ 4121 return Select().from_(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4124def update(table, properties, where=None, from_=None, dialect=None, **opts) -> Update: 4125 """ 4126 Creates an update statement. 4127 4128 Example: 4129 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4130 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4131 4132 Args: 4133 *properties (Dict[str, Any]): dictionary of properties to set which are 4134 auto converted to sql objects eg None -> NULL 4135 where (str): sql conditional parsed into a WHERE statement 4136 from_ (str): sql statement parsed into a FROM statement 4137 dialect (str): the dialect used to parse the input expressions. 4138 **opts: other options to use to parse the input expressions. 4139 4140 Returns: 4141 Update: the syntax tree for the UPDATE statement. 4142 """ 4143 update = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4144 update.set( 4145 "expressions", 4146 [ 4147 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4148 for k, v in properties.items() 4149 ], 4150 ) 4151 if from_: 4152 update.set( 4153 "from", 4154 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4155 ) 4156 if isinstance(where, Condition): 4157 where = Where(this=where) 4158 if where: 4159 update.set( 4160 "where", 4161 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4162 ) 4163 return update
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 (Dict[str, Any]): dictionary of properties to set which are auto converted to sql objects eg None -> NULL
- where (str): sql conditional parsed into a WHERE statement
- from_ (str): sql statement parsed into a FROM statement
- dialect (str): 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.
4166def delete(table, where=None, dialect=None, **opts) -> Delete: 4167 """ 4168 Builds a delete statement. 4169 4170 Example: 4171 >>> delete("my_table", where="id > 1").sql() 4172 'DELETE FROM my_table WHERE id > 1' 4173 4174 Args: 4175 where (str|Condition): sql conditional parsed into a WHERE statement 4176 dialect (str): the dialect used to parse the input expressions. 4177 **opts: other options to use to parse the input expressions. 4178 4179 Returns: 4180 Delete: the syntax tree for the DELETE statement. 4181 """ 4182 return Delete( 4183 this=maybe_parse(table, into=Table, dialect=dialect, **opts), 4184 where=Where(this=where) 4185 if isinstance(where, Condition) 4186 else maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4187 )
Builds a delete statement.
Example:
>>> delete("my_table", where="id > 1").sql() 'DELETE FROM my_table WHERE id > 1'
Arguments:
- where (str|Condition): sql conditional parsed into a WHERE statement
- dialect (str): 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.
4190def condition(expression, dialect=None, **opts) -> Condition: 4191 """ 4192 Initialize a logical condition expression. 4193 4194 Example: 4195 >>> condition("x=1").sql() 4196 'x = 1' 4197 4198 This is helpful for composing larger logical syntax trees: 4199 >>> where = condition("x=1") 4200 >>> where = where.and_("y=1") 4201 >>> Select().from_("tbl").select("*").where(where).sql() 4202 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4203 4204 Args: 4205 *expression (str | Expression): the SQL code string to parse. 4206 If an Expression instance is passed, this is used as-is. 4207 dialect (str): the dialect used to parse the input expression (in the case that the 4208 input expression is a SQL string). 4209 **opts: other options to use to parse the input expressions (again, in the case 4210 that the input expression is a SQL string). 4211 4212 Returns: 4213 Condition: the expression 4214 """ 4215 return maybe_parse( # type: ignore 4216 expression, 4217 into=Condition, 4218 dialect=dialect, 4219 **opts, 4220 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'
This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4223def and_(*expressions, dialect=None, **opts) -> And: 4224 """ 4225 Combine multiple conditions with an AND logical operator. 4226 4227 Example: 4228 >>> and_("x=1", and_("y=1", "z=1")).sql() 4229 'x = 1 AND (y = 1 AND z = 1)' 4230 4231 Args: 4232 *expressions (str | Expression): the SQL code strings to parse. 4233 If an Expression instance is passed, this is used as-is. 4234 dialect (str): the dialect used to parse the input expression. 4235 **opts: other options to use to parse the input expressions. 4236 4237 Returns: 4238 And: the new condition 4239 """ 4240 return _combine(expressions, And, dialect, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4243def or_(*expressions, dialect=None, **opts) -> Or: 4244 """ 4245 Combine multiple conditions with an OR logical operator. 4246 4247 Example: 4248 >>> or_("x=1", or_("y=1", "z=1")).sql() 4249 'x = 1 OR (y = 1 OR z = 1)' 4250 4251 Args: 4252 *expressions (str | Expression): the SQL code strings to parse. 4253 If an Expression instance is passed, this is used as-is. 4254 dialect (str): the dialect used to parse the input expression. 4255 **opts: other options to use to parse the input expressions. 4256 4257 Returns: 4258 Or: the new condition 4259 """ 4260 return _combine(expressions, Or, dialect, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4263def not_(expression, dialect=None, **opts) -> Not: 4264 """ 4265 Wrap a condition with a NOT operator. 4266 4267 Example: 4268 >>> not_("this_suit='black'").sql() 4269 "NOT this_suit = 'black'" 4270 4271 Args: 4272 expression (str | Expression): the SQL code strings to parse. 4273 If an Expression instance is passed, this is used as-is. 4274 dialect (str): the dialect used to parse the input expression. 4275 **opts: other options to use to parse the input expressions. 4276 4277 Returns: 4278 Not: the new condition 4279 """ 4280 this = condition( 4281 expression, 4282 dialect=dialect, 4283 **opts, 4284 ) 4285 return Not(this=_wrap_operator(this))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Not: the new condition
4305def to_identifier(name, quoted=None): 4306 """Builds an identifier. 4307 4308 Args: 4309 name: The name to turn into an identifier. 4310 quoted: Whether or not force quote the identifier. 4311 4312 Returns: 4313 The identifier ast node. 4314 """ 4315 4316 if name is None: 4317 return None 4318 4319 if isinstance(name, Identifier): 4320 identifier = name 4321 elif isinstance(name, str): 4322 identifier = Identifier( 4323 this=name, 4324 quoted=not re.match(SAFE_IDENTIFIER_RE, name) if quoted is None else quoted, 4325 ) 4326 else: 4327 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4328 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
Returns:
The identifier ast node.
4334def to_interval(interval: str | Literal) -> Interval: 4335 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4336 if isinstance(interval, Literal): 4337 if not interval.is_string: 4338 raise ValueError("Invalid interval string.") 4339 4340 interval = interval.this 4341 4342 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4343 4344 if not interval_parts: 4345 raise ValueError("Invalid interval string.") 4346 4347 return Interval( 4348 this=Literal.string(interval_parts.group(1)), 4349 unit=Var(this=interval_parts.group(2)), 4350 )
Builds an interval expression from a string like '1 day' or '5 months'.
4363def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4364 """ 4365 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4366 If a table is passed in then that table is returned. 4367 4368 Args: 4369 sql_path: a `[catalog].[schema].[table]` string. 4370 4371 Returns: 4372 A table expression. 4373 """ 4374 if sql_path is None or isinstance(sql_path, Table): 4375 return sql_path 4376 if not isinstance(sql_path, str): 4377 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4378 4379 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4380 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.
4383def to_column(sql_path: str | Column, **kwargs) -> Column: 4384 """ 4385 Create a column from a `[table].[column]` sql path. Schema is optional. 4386 4387 If a column is passed in then that column is returned. 4388 4389 Args: 4390 sql_path: `[table].[column]` string 4391 Returns: 4392 Table: A column expression 4393 """ 4394 if sql_path is None or isinstance(sql_path, Column): 4395 return sql_path 4396 if not isinstance(sql_path, str): 4397 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4398 table_name, column_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 2)) 4399 return Column(this=column_name, table=table_name, **kwargs)
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
4402def alias_( 4403 expression: str | Expression, 4404 alias: str | Identifier, 4405 table: bool | t.Sequence[str | Identifier] = False, 4406 quoted: t.Optional[bool] = None, 4407 dialect: DialectType = None, 4408 **opts, 4409): 4410 """Create an Alias expression. 4411 4412 Example: 4413 >>> alias_('foo', 'bar').sql() 4414 'foo AS bar' 4415 4416 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4417 '(SELECT 1, 2) AS bar(a, b)' 4418 4419 Args: 4420 expression: the SQL code strings to parse. 4421 If an Expression instance is passed, this is used as-is. 4422 alias: the alias name to use. If the name has 4423 special characters it is quoted. 4424 table: Whether or not to create a table alias, can also be a list of columns. 4425 quoted: whether or not to quote the alias 4426 dialect: the dialect used to parse the input expression. 4427 **opts: other options to use to parse the input expressions. 4428 4429 Returns: 4430 Alias: the aliased expression 4431 """ 4432 exp = maybe_parse(expression, dialect=dialect, **opts) 4433 alias = to_identifier(alias, quoted=quoted) 4434 4435 if table: 4436 table_alias = TableAlias(this=alias) 4437 exp.set("alias", table_alias) 4438 4439 if not isinstance(table, bool): 4440 for column in table: 4441 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4442 4443 return exp 4444 4445 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4446 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4447 # for the complete Window expression. 4448 # 4449 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4450 4451 if "alias" in exp.arg_types and not isinstance(exp, Window): 4452 exp = exp.copy() 4453 exp.set("alias", alias) 4454 return exp 4455 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
4458def subquery(expression, alias=None, dialect=None, **opts): 4459 """ 4460 Build a subquery expression. 4461 4462 Example: 4463 >>> subquery('select x from tbl', 'bar').select('x').sql() 4464 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4465 4466 Args: 4467 expression (str | Expression): the SQL code strings to parse. 4468 If an Expression instance is passed, this is used as-is. 4469 alias (str | Expression): the alias name to use. 4470 dialect (str): the dialect used to parse the input expression. 4471 **opts: other options to use to parse the input expressions. 4472 4473 Returns: 4474 Select: a new select with the subquery expression included 4475 """ 4476 4477 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4478 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
4481def column( 4482 col: str | Identifier, 4483 table: t.Optional[str | Identifier] = None, 4484 schema: t.Optional[str | Identifier] = None, 4485 quoted: t.Optional[bool] = None, 4486) -> Column: 4487 """ 4488 Build a Column. 4489 4490 Args: 4491 col: column name 4492 table: table name 4493 schema: schema name 4494 quoted: whether or not to force quote each part 4495 Returns: 4496 Column: column instance 4497 """ 4498 return Column( 4499 this=to_identifier(col, quoted=quoted), 4500 table=to_identifier(table, quoted=quoted), 4501 schema=to_identifier(schema, quoted=quoted), 4502 )
Build a Column.
Arguments:
- col: column name
- table: table name
- schema: schema name
- quoted: whether or not to force quote each part
Returns:
Column: column instance
4505def cast(expression: str | Expression, to: str | DataType | DataType.Type, **opts) -> Cast: 4506 """Cast an expression to a data type. 4507 4508 Example: 4509 >>> cast('x + 1', 'int').sql() 4510 'CAST(x + 1 AS INT)' 4511 4512 Args: 4513 expression: The expression to cast. 4514 to: The datatype to cast to. 4515 4516 Returns: 4517 A cast node. 4518 """ 4519 expression = maybe_parse(expression, **opts) 4520 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.
4523def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4524 """Build a Table. 4525 4526 Args: 4527 table (str | Expression): column name 4528 db (str | Expression): db name 4529 catalog (str | Expression): catalog name 4530 4531 Returns: 4532 Table: table instance 4533 """ 4534 return Table( 4535 this=to_identifier(table, quoted=quoted), 4536 db=to_identifier(db, quoted=quoted), 4537 catalog=to_identifier(catalog, quoted=quoted), 4538 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4539 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
4542def values( 4543 values: t.Iterable[t.Tuple[t.Any, ...]], 4544 alias: t.Optional[str] = None, 4545 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4546) -> Values: 4547 """Build VALUES statement. 4548 4549 Example: 4550 >>> values([(1, '2')]).sql() 4551 "VALUES (1, '2')" 4552 4553 Args: 4554 values: values statements that will be converted to SQL 4555 alias: optional alias 4556 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4557 If either are provided then an alias is also required. 4558 If a dictionary is provided then the first column of the values will be casted to the expected type 4559 in order to help with type inference. 4560 4561 Returns: 4562 Values: the Values expression object 4563 """ 4564 if columns and not alias: 4565 raise ValueError("Alias is required when providing columns") 4566 table_alias = ( 4567 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4568 if columns 4569 else TableAlias(this=to_identifier(alias) if alias else None) 4570 ) 4571 expressions = [convert(tup) for tup in values] 4572 if columns and isinstance(columns, dict): 4573 types = list(columns.values()) 4574 expressions[0].set( 4575 "expressions", 4576 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4577 ) 4578 return Values( 4579 expressions=expressions, 4580 alias=table_alias, 4581 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:
Values: the Values expression object
4584def var(name: t.Optional[str | Expression]) -> Var: 4585 """Build a SQL variable. 4586 4587 Example: 4588 >>> repr(var('x')) 4589 '(VAR this: x)' 4590 4591 >>> repr(var(column('x', table='y'))) 4592 '(VAR this: x)' 4593 4594 Args: 4595 name: The name of the var or an expression who's name will become the var. 4596 4597 Returns: 4598 The new variable node. 4599 """ 4600 if not name: 4601 raise ValueError(f"Cannot convert empty name into var.") 4602 4603 if isinstance(name, Expression): 4604 name = name.name 4605 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.
4608def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4609 """Build ALTER TABLE... RENAME... expression 4610 4611 Args: 4612 old_name: The old name of the table 4613 new_name: The new name of the table 4614 4615 Returns: 4616 Alter table expression 4617 """ 4618 old_table = to_table(old_name) 4619 new_table = to_table(new_name) 4620 return AlterTable( 4621 this=old_table, 4622 actions=[ 4623 RenameTable(this=new_table), 4624 ], 4625 )
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
4628def convert(value) -> Expression: 4629 """Convert a python value into an expression object. 4630 4631 Raises an error if a conversion is not possible. 4632 4633 Args: 4634 value (Any): a python object 4635 4636 Returns: 4637 Expression: the equivalent expression object 4638 """ 4639 if isinstance(value, Expression): 4640 return value 4641 if value is None: 4642 return NULL 4643 if isinstance(value, bool): 4644 return Boolean(this=value) 4645 if isinstance(value, str): 4646 return Literal.string(value) 4647 if isinstance(value, float) and math.isnan(value): 4648 return NULL 4649 if isinstance(value, numbers.Number): 4650 return Literal.number(value) 4651 if isinstance(value, tuple): 4652 return Tuple(expressions=[convert(v) for v in value]) 4653 if isinstance(value, list): 4654 return Array(expressions=[convert(v) for v in value]) 4655 if isinstance(value, dict): 4656 return Map( 4657 keys=[convert(k) for k in value], 4658 values=[convert(v) for v in value.values()], 4659 ) 4660 if isinstance(value, datetime.datetime): 4661 datetime_literal = Literal.string( 4662 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4663 ) 4664 return TimeStrToTime(this=datetime_literal) 4665 if isinstance(value, datetime.date): 4666 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4667 return DateStrToDate(this=date_literal) 4668 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value (Any): a python object
Returns:
Expression: the equivalent expression object
4671def replace_children(expression, fun): 4672 """ 4673 Replace children of an expression with the result of a lambda fun(child) -> exp. 4674 """ 4675 for k, v in expression.args.items(): 4676 is_list_arg = isinstance(v, list) 4677 4678 child_nodes = v if is_list_arg else [v] 4679 new_child_nodes = [] 4680 4681 for cn in child_nodes: 4682 if isinstance(cn, Expression): 4683 for child_node in ensure_collection(fun(cn)): 4684 new_child_nodes.append(child_node) 4685 child_node.parent = expression 4686 child_node.arg_key = k 4687 else: 4688 new_child_nodes.append(cn) 4689 4690 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.
4693def column_table_names(expression): 4694 """ 4695 Return all table names referenced through columns in an expression. 4696 4697 Example: 4698 >>> import sqlglot 4699 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4700 ['c', 'a'] 4701 4702 Args: 4703 expression (sqlglot.Expression): expression to find table names 4704 4705 Returns: 4706 list: A list of unique names 4707 """ 4708 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
4711def table_name(table) -> str: 4712 """Get the full name of a table as a string. 4713 4714 Args: 4715 table (exp.Table | str): table expression node or string. 4716 4717 Examples: 4718 >>> from sqlglot import exp, parse_one 4719 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4720 'a.b.c' 4721 4722 Returns: 4723 The table name. 4724 """ 4725 4726 table = maybe_parse(table, into=Table) 4727 4728 if not table: 4729 raise ValueError(f"Cannot parse {table}") 4730 4731 return ".".join( 4732 part 4733 for part in ( 4734 table.text("catalog"), 4735 table.text("db"), 4736 table.name, 4737 ) 4738 if part 4739 )
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.
4742def replace_tables(expression, mapping): 4743 """Replace all tables in expression according to the mapping. 4744 4745 Args: 4746 expression (sqlglot.Expression): expression node to be transformed and replaced. 4747 mapping (Dict[str, str]): mapping of table names. 4748 4749 Examples: 4750 >>> from sqlglot import exp, parse_one 4751 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4752 'SELECT * FROM c' 4753 4754 Returns: 4755 The mapped expression. 4756 """ 4757 4758 def _replace_tables(node): 4759 if isinstance(node, Table): 4760 new_name = mapping.get(table_name(node)) 4761 if new_name: 4762 return to_table( 4763 new_name, 4764 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4765 ) 4766 return node 4767 4768 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.
4771def replace_placeholders(expression, *args, **kwargs): 4772 """Replace placeholders in an expression. 4773 4774 Args: 4775 expression (sqlglot.Expression): expression node to be transformed and replaced. 4776 args: positional names that will substitute unnamed placeholders in the given order. 4777 kwargs: keyword arguments that will substitute named placeholders. 4778 4779 Examples: 4780 >>> from sqlglot import exp, parse_one 4781 >>> replace_placeholders( 4782 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4783 ... ).sql() 4784 'SELECT * FROM foo WHERE a = b' 4785 4786 Returns: 4787 The mapped expression. 4788 """ 4789 4790 def _replace_placeholders(node, args, **kwargs): 4791 if isinstance(node, Placeholder): 4792 if node.name: 4793 new_name = kwargs.get(node.name) 4794 if new_name: 4795 return to_identifier(new_name) 4796 else: 4797 try: 4798 return to_identifier(next(args)) 4799 except StopIteration: 4800 pass 4801 return node 4802 4803 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" ... ).sql() 'SELECT * FROM foo WHERE a = b'
Returns:
The mapped expression.
4806def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 4807 """Transforms an expression by expanding all referenced sources into subqueries. 4808 4809 Examples: 4810 >>> from sqlglot import parse_one 4811 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 4812 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 4813 4814 Args: 4815 expression: The expression to expand. 4816 sources: A dictionary of name to Subqueryables. 4817 copy: Whether or not to copy the expression during transformation. Defaults to True. 4818 4819 Returns: 4820 The transformed expression. 4821 """ 4822 4823 def _expand(node: Expression): 4824 if isinstance(node, Table): 4825 name = table_name(node) 4826 source = sources.get(name) 4827 if source: 4828 subquery = source.subquery(node.alias or name) 4829 subquery.comments = [f"source: {name}"] 4830 return subquery 4831 return node 4832 4833 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
4836def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 4837 """ 4838 Returns a Func expression. 4839 4840 Examples: 4841 >>> func("abs", 5).sql() 4842 'ABS(5)' 4843 4844 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 4845 'CAST(5 AS DOUBLE)' 4846 4847 Args: 4848 name: the name of the function to build. 4849 args: the args used to instantiate the function of interest. 4850 dialect: the source dialect. 4851 kwargs: the kwargs used to instantiate the function of interest. 4852 4853 Note: 4854 The arguments `args` and `kwargs` are mutually exclusive. 4855 4856 Returns: 4857 An instance of the function of interest, or an anonymous function, if `name` doesn't 4858 correspond to an existing `sqlglot.expressions.Func` class. 4859 """ 4860 if args and kwargs: 4861 raise ValueError("Can't use both args and kwargs to instantiate a function.") 4862 4863 from sqlglot.dialects.dialect import Dialect 4864 4865 args = tuple(convert(arg) for arg in args) 4866 kwargs = {key: convert(value) for key, value in kwargs.items()} 4867 4868 parser = Dialect.get_or_raise(dialect)().parser() 4869 from_args_list = parser.FUNCTIONS.get(name.upper()) 4870 4871 if from_args_list: 4872 function = from_args_list(args) if args else from_args_list.__self__(**kwargs) # type: ignore 4873 else: 4874 kwargs = kwargs or {"expressions": args} 4875 function = Anonymous(this=name, **kwargs) 4876 4877 for error_message in function.error_messages(args): 4878 raise ValueError(error_message) 4879 4880 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.
4883def true(): 4884 """ 4885 Returns a true Boolean expression. 4886 """ 4887 return Boolean(this=True)
Returns a true Boolean expression.
4890def false(): 4891 """ 4892 Returns a false Boolean expression. 4893 """ 4894 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.