sqlglot.schema
1from __future__ import annotations 2 3import abc 4import typing as t 5 6from sqlglot import expressions as exp 7from sqlglot.dialects.dialect import Dialect 8from sqlglot.errors import SchemaError 9from sqlglot.helper import dict_depth, first 10from sqlglot.trie import TrieResult, in_trie, new_trie 11 12 13if t.TYPE_CHECKING: 14 from sqlglot._typing import SchemaArgs 15 from sqlglot.dialects.dialect import DialectType 16 from collections.abc import Sequence 17 from typing_extensions import Unpack 18 19 ColumnMapping = t.Union[dict[str, t.Any], str, list[str]] 20 21 22class Schema(abc.ABC): 23 """Abstract base class for database schemas""" 24 25 @property 26 def dialect(self) -> Dialect | None: 27 """ 28 Returns None by default. Subclasses that require dialect-specific 29 behavior should override this property. 30 """ 31 return None 32 33 @abc.abstractmethod 34 def add_table( 35 self, 36 table: exp.Table | str, 37 column_mapping: ColumnMapping | None = None, 38 dialect: DialectType = None, 39 normalize: bool | None = None, 40 match_depth: bool = True, 41 ) -> None: 42 """ 43 Register or update a table. Some implementing classes may require column information to also be provided. 44 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 45 46 Args: 47 table: the `Table` expression instance or string representing the table. 48 column_mapping: a column mapping that describes the structure of the table. 49 dialect: the SQL dialect that will be used to parse `table` if it's a string. 50 normalize: whether to normalize identifiers according to the dialect of interest. 51 match_depth: whether to enforce that the table must match the schema's depth or not. 52 """ 53 54 @abc.abstractmethod 55 def column_names( 56 self, 57 table: exp.Table | str, 58 only_visible: bool = False, 59 dialect: DialectType = None, 60 normalize: bool | None = None, 61 ) -> Sequence[str]: 62 """ 63 Get the column names for a table. 64 65 Args: 66 table: the `Table` expression instance. 67 only_visible: whether to include invisible columns. 68 dialect: the SQL dialect that will be used to parse `table` if it's a string. 69 normalize: whether to normalize identifiers according to the dialect of interest. 70 71 Returns: 72 The sequence of column names. 73 """ 74 75 @abc.abstractmethod 76 def get_column_type( 77 self, 78 table: exp.Table | str, 79 column: exp.Column | str, 80 dialect: DialectType = None, 81 normalize: bool | None = None, 82 ) -> exp.DataType: 83 """ 84 Get the `sqlglot.exp.DataType` type of a column in the schema. 85 86 Args: 87 table: the source table. 88 column: the target column. 89 dialect: the SQL dialect that will be used to parse `table` if it's a string. 90 normalize: whether to normalize identifiers according to the dialect of interest. 91 92 Returns: 93 The resulting column type. 94 """ 95 96 def has_column( 97 self, 98 table: exp.Table | str, 99 column: exp.Column | str, 100 dialect: DialectType = None, 101 normalize: bool | None = None, 102 ) -> bool: 103 """ 104 Returns whether `column` appears in `table`'s schema. 105 106 Args: 107 table: the source table. 108 column: the target column. 109 dialect: the SQL dialect that will be used to parse `table` if it's a string. 110 normalize: whether to normalize identifiers according to the dialect of interest. 111 112 Returns: 113 True if the column appears in the schema, False otherwise. 114 """ 115 name = column if isinstance(column, str) else column.name 116 return name in self.column_names(table, dialect=dialect, normalize=normalize) 117 118 def get_udf_type( 119 self, 120 udf: exp.Anonymous | str, 121 dialect: DialectType = None, 122 normalize: bool | None = None, 123 ) -> exp.DataType: 124 """ 125 Get the return type of a UDF. 126 127 Args: 128 udf: the UDF expression or string. 129 dialect: the SQL dialect for parsing string arguments. 130 normalize: whether to normalize identifiers. 131 132 Returns: 133 The return type as a DataType, or UNKNOWN if not found. 134 """ 135 return exp.DType.UNKNOWN.into_expr() 136 137 @property 138 @abc.abstractmethod 139 def supported_table_args(self) -> tuple[str, ...]: 140 """ 141 Table arguments this schema support, e.g. `("this", "db", "catalog")` 142 """ 143 144 @property 145 def empty(self) -> bool: 146 """Returns whether the schema is empty.""" 147 return True 148 149 150class AbstractMappingSchema: 151 def __init__( 152 self, 153 mapping: dict[str, object] | None = None, 154 udf_mapping: dict[str, object] | None = None, 155 ) -> None: 156 self.mapping: dict[str, object] = mapping or {} 157 self.mapping_trie: dict[str, object] = new_trie( 158 tuple(reversed(t)) for t in flatten_schema(self.mapping, depth=self.depth()) 159 ) 160 self.udf_mapping: dict[str, object] = udf_mapping or {} 161 self.udf_trie: dict[str, object] = new_trie( 162 tuple(reversed(t)) for t in flatten_schema(self.udf_mapping, depth=self.udf_depth()) 163 ) 164 165 self._supported_table_args: tuple[str, ...] = tuple() 166 167 @property 168 def empty(self) -> bool: 169 return not self.mapping 170 171 def depth(self) -> int: 172 return dict_depth(self.mapping) 173 174 def udf_depth(self) -> int: 175 return dict_depth(self.udf_mapping) 176 177 @property 178 def supported_table_args(self) -> tuple[str, ...]: 179 if not self._supported_table_args and self.mapping: 180 depth = self.depth() 181 182 if not depth: # None 183 self._supported_table_args = tuple() 184 elif 1 <= depth <= 3: 185 self._supported_table_args = exp.TABLE_PARTS[:depth] 186 else: 187 raise SchemaError(f"Invalid mapping shape. Depth: {depth}") 188 189 return self._supported_table_args 190 191 def table_parts(self, table: exp.Table) -> list[str]: 192 return [p.name for p in reversed(table.parts)] 193 194 def udf_parts(self, udf: exp.Anonymous) -> list[str]: 195 # a.b.c(...) is represented as Dot(Dot(a, b), Anonymous(c, ...)) 196 parent = udf.parent 197 parts = [p.name for p in parent.flatten()] if isinstance(parent, exp.Dot) else [udf.name] 198 return list(reversed(parts))[0 : self.udf_depth()] 199 200 def _find_in_trie( 201 self, 202 parts: list[str], 203 trie: dict[str, object], 204 raise_on_missing: bool, 205 ) -> list[str] | None: 206 value, trie = in_trie(trie, parts) 207 208 if value == TrieResult.FAILED: 209 return None 210 211 if value == TrieResult.PREFIX: 212 possibilities = flatten_schema(trie) 213 214 if len(possibilities) == 1: 215 parts.extend(possibilities[0]) 216 else: 217 if raise_on_missing: 218 joined_parts = ".".join(parts) 219 message = ", ".join(".".join(p) for p in possibilities) 220 raise SchemaError(f"Ambiguous mapping for {joined_parts}: {message}.") 221 222 return None 223 224 return parts 225 226 def find( 227 self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False 228 ) -> t.Any | None: 229 """ 230 Returns the schema of a given table. 231 232 Args: 233 table: the target table. 234 raise_on_missing: whether to raise in case the schema is not found. 235 ensure_data_types: whether to convert `str` types to their `DataType` equivalents. 236 237 Returns: 238 The schema of the target table. 239 """ 240 return self._find( 241 self.table_parts(table), 242 raise_on_missing=raise_on_missing, 243 ensure_data_types=ensure_data_types, 244 ) 245 246 def _find( 247 self, parts: Sequence[str], raise_on_missing: bool = True, ensure_data_types: bool = False 248 ) -> t.Any | None: 249 parts = list(parts[0 : len(self.supported_table_args)]) 250 resolved_parts = self._find_in_trie(parts, self.mapping_trie, raise_on_missing) 251 252 if resolved_parts is None: 253 return None 254 255 return self.nested_get(resolved_parts, raise_on_missing=raise_on_missing) 256 257 def find_udf(self, udf: exp.Anonymous, raise_on_missing: bool = False) -> t.Any | None: 258 """ 259 Returns the return type of a given UDF. 260 261 Args: 262 udf: the target UDF expression. 263 raise_on_missing: whether to raise if the UDF is not found. 264 265 Returns: 266 The return type of the UDF, or None if not found. 267 """ 268 parts = self.udf_parts(udf) 269 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing) 270 271 if resolved_parts is None: 272 return None 273 274 return nested_get( 275 self.udf_mapping, 276 *zip(resolved_parts, reversed(resolved_parts)), 277 raise_on_missing=raise_on_missing, 278 ) 279 280 def nested_get( 281 self, 282 parts: Sequence[str], 283 d: dict[str, object] | None = None, 284 raise_on_missing: bool = True, 285 ) -> t.Any | None: 286 return nested_get( 287 d or self.mapping, 288 *zip(self.supported_table_args, reversed(parts)), 289 raise_on_missing=raise_on_missing, 290 ) 291 292 293class MappingSchema(AbstractMappingSchema, Schema): 294 """ 295 Schema based on a nested mapping. 296 297 Args: 298 schema: Mapping in one of the following forms: 299 1. {table: {col: type}} 300 2. {db: {table: {col: type}}} 301 3. {catalog: {db: {table: {col: type}}}} 302 4. None - Tables will be added later 303 visible: Optional mapping of which columns in the schema are visible. If not provided, all columns 304 are assumed to be visible. The nesting should mirror that of the schema: 305 1. {table: set(*cols)}} 306 2. {db: {table: set(*cols)}}} 307 3. {catalog: {db: {table: set(*cols)}}}} 308 dialect: The dialect to be used for custom type mappings & parsing string arguments. 309 normalize: Whether to normalize identifier names according to the given dialect or not. 310 """ 311 312 def __init__( 313 self, 314 schema: dict[str, object] | None = None, 315 visible: dict[str, object] | None = None, 316 dialect: DialectType = None, 317 normalize: bool = True, 318 udf_mapping: dict[str, object] | None = None, 319 ) -> None: 320 self.visible: dict[str, object] = {} if visible is None else visible 321 self.normalize: bool = normalize 322 self._dialect: Dialect = Dialect.get_or_raise(dialect) 323 self._type_mapping_cache: dict[str, exp.DataType] = {} 324 self._normalized_table_cache: dict[ 325 tuple[tuple[tuple[str, bool | None], ...], DialectType, bool], tuple[str, ...] 326 ] = {} 327 self._normalized_name_cache: dict[tuple[str, DialectType, bool, bool], str] = {} 328 self._find_cache: dict[tuple[tuple[str, ...], bool], dict[str, object] | None] = {} 329 self._depth: int = 0 330 schema = {} if schema is None else schema 331 udf_mapping = {} if udf_mapping is None else udf_mapping 332 333 super().__init__( 334 self._normalize(schema) if self.normalize else schema, 335 self._normalize_udfs(udf_mapping) if self.normalize else udf_mapping, 336 ) 337 338 @property 339 def dialect(self) -> Dialect: 340 """Returns the dialect for this mapping schema.""" 341 return self._dialect 342 343 @classmethod 344 def from_mapping_schema(cls, mapping_schema: MappingSchema) -> MappingSchema: 345 return MappingSchema( 346 schema=mapping_schema.mapping, 347 visible=mapping_schema.visible, 348 dialect=mapping_schema.dialect, 349 normalize=mapping_schema.normalize, 350 udf_mapping=mapping_schema.udf_mapping, 351 ) 352 353 def _find( 354 self, parts: Sequence[str], raise_on_missing: bool = True, ensure_data_types: bool = False 355 ) -> t.Any | None: 356 cache_key = (tuple(parts), ensure_data_types) 357 schema = self._find_cache.get(cache_key) 358 359 if schema is None: 360 schema = super()._find(parts, raise_on_missing=raise_on_missing) 361 if ensure_data_types and isinstance(schema, dict): 362 schema = { 363 col: self._to_data_type(dtype) if isinstance(dtype, str) else dtype 364 for col, dtype in schema.items() 365 } 366 self._find_cache[cache_key] = schema 367 368 return schema 369 370 def copy( 371 self, schema: dict[str, object] | None = None, **kwargs: Unpack[SchemaArgs] 372 ) -> MappingSchema: 373 mapping_kwargs: SchemaArgs = { 374 "visible": self.visible.copy(), 375 "dialect": self.dialect, 376 "normalize": self.normalize, 377 "udf_mapping": self.udf_mapping.copy(), 378 **kwargs, 379 } 380 return MappingSchema(self.mapping.copy() if schema is None else schema, **mapping_kwargs) 381 382 def add_table( 383 self, 384 table: exp.Table | str, 385 column_mapping: ColumnMapping | None = None, 386 dialect: DialectType = None, 387 normalize: bool | None = None, 388 match_depth: bool = True, 389 ) -> None: 390 """ 391 Register or update a table. Updates are only performed if a new column mapping is provided. 392 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 393 394 Args: 395 table: the `Table` expression instance or string representing the table. 396 column_mapping: a column mapping that describes the structure of the table. 397 dialect: the SQL dialect that will be used to parse `table` if it's a string. 398 normalize: whether to normalize identifiers according to the dialect of interest. 399 match_depth: whether to enforce that the table must match the schema's depth or not. 400 """ 401 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 402 403 if match_depth and not self.empty and len(parts) != self.depth(): 404 table = exp.maybe_parse( 405 table, into=exp.Table, dialect=dialect or self.dialect, copy=True 406 ) 407 for part, name in zip(reversed(table.parts), parts): 408 if isinstance(part, exp.Identifier): 409 part.set("this", name) 410 raise SchemaError( 411 f"Table {table.sql(dialect=self.dialect)} must match the " 412 f"schema's nesting level: {self.depth()}." 413 ) 414 415 normalized_column_mapping = { 416 self._normalize_name(key, dialect=dialect, normalize=normalize): value 417 for key, value in ensure_column_mapping(column_mapping).items() 418 } 419 420 schema = self._find(parts, raise_on_missing=False) 421 if schema and not normalized_column_mapping: 422 return 423 424 nested_set(self.mapping, tuple(reversed(parts)), normalized_column_mapping) 425 new_trie([parts], self.mapping_trie) 426 427 # A new table can change how partially-qualified names resolve (or make them ambiguous), 428 # so any cached lookup may be stale, not just the one for this table's full path 429 self._find_cache.clear() 430 431 def column_names( 432 self, 433 table: exp.Table | str, 434 only_visible: bool = False, 435 dialect: DialectType = None, 436 normalize: bool | None = None, 437 ) -> list[str]: 438 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 439 440 schema: dict[str, object] | None = self._find(parts) 441 if schema is None: 442 return [] 443 444 if not only_visible or not self.visible: 445 return list(schema) 446 447 visible = self.nested_get(parts, self.visible) or [] 448 return [col for col in schema if col in visible] 449 450 def get_column_type( 451 self, 452 table: exp.Table | str, 453 column: exp.Column | str, 454 dialect: DialectType = None, 455 normalize: bool | None = None, 456 ) -> exp.DataType: 457 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 458 459 normalized_column_name = self._normalize_name( 460 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 461 ) 462 463 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 464 if table_schema: 465 column_type = table_schema.get(normalized_column_name) 466 467 if isinstance(column_type, exp.DataType): 468 return column_type 469 elif isinstance(column_type, str): 470 return self._to_data_type(column_type, dialect=dialect) 471 472 return exp.DType.UNKNOWN.into_expr() 473 474 def get_udf_type( 475 self, 476 udf: exp.Anonymous | str, 477 dialect: DialectType = None, 478 normalize: bool | None = None, 479 ) -> exp.DataType: 480 """ 481 Get the return type of a UDF. 482 483 Args: 484 udf: the UDF expression or string (e.g., "db.my_func()"). 485 dialect: the SQL dialect for parsing string arguments. 486 normalize: whether to normalize identifiers. 487 488 Returns: 489 The return type as a DataType, or UNKNOWN if not found. 490 """ 491 parts = self._normalize_udf(udf, dialect=dialect, normalize=normalize) 492 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing=False) 493 494 if resolved_parts is None: 495 return exp.DType.UNKNOWN.into_expr() 496 497 udf_type = nested_get( 498 self.udf_mapping, 499 *zip(resolved_parts, reversed(resolved_parts)), 500 raise_on_missing=False, 501 ) 502 503 if isinstance(udf_type, exp.DataType): 504 return udf_type 505 elif isinstance(udf_type, str): 506 return self._to_data_type(udf_type, dialect=dialect) 507 508 return exp.DType.UNKNOWN.into_expr() 509 510 def has_column( 511 self, 512 table: exp.Table | str, 513 column: exp.Column | str, 514 dialect: DialectType = None, 515 normalize: bool | None = None, 516 ) -> bool: 517 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 518 519 normalized_column_name = self._normalize_name( 520 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 521 ) 522 523 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 524 return normalized_column_name in table_schema if table_schema else False 525 526 def _normalize(self, schema: dict[str, object]) -> dict[str, object]: 527 """ 528 Normalizes all identifiers in the schema. 529 530 Args: 531 schema: the schema to normalize. 532 533 Returns: 534 The normalized schema mapping. 535 """ 536 normalized_mapping: dict[str, object] = {} 537 flattened_schema = flatten_schema(schema) 538 error_msg = "Table {} must match the schema's nesting level: {}." 539 540 for keys in flattened_schema: 541 columns = nested_get(schema, *zip(keys, keys)) 542 543 if not isinstance(columns, dict): 544 raise SchemaError(error_msg.format(".".join(keys[:-1]), len(flattened_schema[0]))) 545 if not columns: 546 raise SchemaError(f"Table {'.'.join(keys[:-1])} must have at least one column") 547 if isinstance(first(columns.values()), dict): 548 raise SchemaError( 549 error_msg.format( 550 ".".join(keys + flatten_schema(columns)[0]), len(flattened_schema[0]) 551 ), 552 ) 553 554 normalized_keys = [self._normalize_name(key, is_table=True) for key in keys] 555 for column_name, column_type in columns.items(): 556 nested_set( 557 normalized_mapping, 558 normalized_keys + [self._normalize_name(column_name)], 559 column_type, 560 ) 561 562 return normalized_mapping 563 564 def _normalize_udfs(self, udfs: dict[str, object]) -> dict[str, object]: 565 """ 566 Normalizes all identifiers in the UDF mapping. 567 568 Args: 569 udfs: the UDF mapping to normalize. 570 571 Returns: 572 The normalized UDF mapping. 573 """ 574 normalized_mapping: dict[str, object] = {} 575 576 for keys in flatten_schema(udfs, depth=dict_depth(udfs)): 577 udf_type = nested_get(udfs, *zip(keys, keys)) 578 normalized_keys = [self._normalize_name(key, is_table=True) for key in keys] 579 nested_set(normalized_mapping, normalized_keys, udf_type) 580 581 return normalized_mapping 582 583 def _normalize_udf( 584 self, 585 udf: exp.Anonymous | str, 586 dialect: DialectType = None, 587 normalize: bool | None = None, 588 ) -> list[str]: 589 """ 590 Extract and normalize UDF parts for lookup. 591 592 Args: 593 udf: the UDF expression or qualified string (e.g., "db.my_func()"). 594 dialect: the SQL dialect for parsing. 595 normalize: whether to normalize identifiers. 596 597 Returns: 598 A list of normalized UDF parts (reversed for trie lookup). 599 """ 600 dialect = dialect or self.dialect 601 normalize = self.normalize if normalize is None else normalize 602 603 if isinstance(udf, str): 604 parsed: exp.Expr = exp.maybe_parse(udf, dialect=dialect) 605 606 if isinstance(parsed, exp.Anonymous): 607 udf = parsed 608 elif isinstance(parsed, exp.Dot) and isinstance(parsed.expression, exp.Anonymous): 609 udf = parsed.expression 610 else: 611 raise SchemaError(f"Unable to parse UDF from: {udf!r}") 612 parts = self.udf_parts(udf) 613 614 if normalize: 615 parts = [self._normalize_name(part, dialect=dialect, is_table=True) for part in parts] 616 617 return parts 618 619 def _normalize_table_parts( 620 self, 621 table: exp.Table | str, 622 dialect: DialectType = None, 623 normalize: bool | None = None, 624 ) -> tuple[str, ...]: 625 dialect = dialect or self.dialect 626 normalize = self.normalize if normalize is None else normalize 627 628 table = exp.maybe_parse(table, into=exp.Table, dialect=dialect, copy=False) 629 parts = table.parts 630 cache_key = ( 631 tuple( 632 (part.name, part.quoted if isinstance(part, exp.Identifier) else None) 633 for part in parts 634 ), 635 dialect, 636 normalize, 637 ) 638 if (cached := self._normalized_table_cache.get(cache_key)) is not None: 639 return cached 640 641 normalized_parts = tuple( 642 normalize_name(part, dialect=dialect, is_table=True).name 643 if normalize and isinstance(part, exp.Identifier) 644 else part.name 645 for part in reversed(parts) 646 ) 647 self._normalized_table_cache[cache_key] = normalized_parts 648 return normalized_parts 649 650 def _normalize_name( 651 self, 652 name: str | exp.Identifier, 653 dialect: DialectType = None, 654 is_table: bool = False, 655 normalize: bool | None = None, 656 ) -> str: 657 normalize = self.normalize if normalize is None else normalize 658 659 dialect = dialect or self.dialect 660 name_str = name if isinstance(name, str) else name.name 661 cache_key = (name_str, dialect, is_table, normalize) 662 663 if cached := self._normalized_name_cache.get(cache_key): 664 return cached 665 666 result = normalize_name( 667 name, 668 dialect=dialect, 669 is_table=is_table, 670 normalize=normalize, 671 ).name 672 673 self._normalized_name_cache[cache_key] = result 674 return result 675 676 def depth(self) -> int: 677 if not self.empty and not self._depth: 678 # The columns themselves are a mapping, but we don't want to include those 679 self._depth = super().depth() - 1 680 return self._depth 681 682 def _to_data_type(self, schema_type: str, dialect: DialectType = None) -> exp.DataType: 683 """ 684 Convert a type represented as a string to the corresponding `sqlglot.exp.DataType` object. 685 686 Args: 687 schema_type: the type we want to convert. 688 dialect: the SQL dialect that will be used to parse `schema_type`, if needed. 689 690 Returns: 691 The resulting expression type. 692 """ 693 if schema_type not in self._type_mapping_cache: 694 dialect = Dialect.get_or_raise(dialect) if dialect else self.dialect 695 udt = dialect.SUPPORTS_USER_DEFINED_TYPES 696 697 try: 698 expression = exp.DataType.from_str(schema_type, dialect=dialect, udt=udt) 699 expression.transform(dialect.normalize_identifier, copy=False) 700 self._type_mapping_cache[schema_type] = expression 701 except AttributeError: 702 in_dialect = f" in dialect {dialect}" if dialect else "" 703 raise SchemaError(f"Failed to build type '{schema_type}'{in_dialect}.") 704 705 return self._type_mapping_cache[schema_type] 706 707 708def normalize_name( 709 identifier: str | exp.Identifier, 710 dialect: DialectType = None, 711 is_table: bool = False, 712 normalize: bool | None = True, 713) -> exp.Identifier: 714 if isinstance(identifier, str): 715 identifier = exp.parse_identifier(identifier, dialect=dialect) 716 elif normalize: 717 identifier = identifier.copy() 718 719 if not normalize: 720 return identifier 721 722 # this is used for normalize_identifier, bigquery has special rules pertaining tables 723 identifier.meta["is_table"] = is_table 724 return Dialect.get_or_raise(dialect).normalize_identifier(identifier) 725 726 727def ensure_schema( 728 schema: Schema | dict[str, object] | None, **kwargs: Unpack[SchemaArgs] 729) -> Schema: 730 if isinstance(schema, Schema): 731 return schema 732 733 return MappingSchema(schema, **kwargs) 734 735 736def ensure_column_mapping(mapping: ColumnMapping | None) -> dict[str, t.Any]: 737 if mapping is None: 738 return {} 739 elif isinstance(mapping, dict): 740 return mapping 741 elif isinstance(mapping, str): 742 col_name_type_strs = [x.strip() for x in mapping.split(",")] 743 return { 744 name_type_str.split(":")[0].strip(): name_type_str.split(":")[1].strip() 745 for name_type_str in col_name_type_strs 746 } 747 elif isinstance(mapping, list): 748 return {x.strip(): None for x in mapping} 749 750 raise ValueError(f"Invalid mapping provided: {type(mapping)}") 751 752 753def flatten_schema( 754 schema: dict[str, object], depth: int | None = None, keys: list[str] | None = None 755) -> list[list[str]]: 756 tables: list[list[str]] = [] 757 keys = keys or [] 758 depth = dict_depth(schema) - 1 if depth is None else depth 759 760 for k, v in schema.items(): 761 if depth == 1 or not isinstance(v, dict): 762 tables.append(keys + [k]) 763 elif depth >= 2: 764 tables.extend(flatten_schema(v, depth - 1, keys + [k])) 765 766 return tables 767 768 769def nested_get( 770 d: dict[str, object], *path: tuple[str, str], raise_on_missing: bool = True 771) -> t.Any | None: 772 """ 773 Get a value for a nested dictionary. 774 775 Args: 776 d: the dictionary to search. 777 *path: tuples of (name, key), where: 778 `key` is the key in the dictionary to get. 779 `name` is a string to use in the error if `key` isn't found. 780 781 Returns: 782 The value or None if it doesn't exist. 783 """ 784 result: t.Any = d 785 for name, key in path: 786 result = result.get(key) 787 if result is None: 788 if raise_on_missing: 789 name = "table" if name == "this" else name 790 raise ValueError(f"Unknown {name}: {key}") 791 return None 792 793 return result 794 795 796def nested_set(d: dict[str, t.Any], keys: Sequence[str], value: t.Any) -> dict[str, t.Any]: 797 """ 798 In-place set a value for a nested dictionary 799 800 Example: 801 >>> nested_set({}, ["top_key", "second_key"], "value") 802 {'top_key': {'second_key': 'value'}} 803 804 >>> nested_set({"top_key": {"third_key": "third_value"}}, ["top_key", "second_key"], "value") 805 {'top_key': {'third_key': 'third_value', 'second_key': 'value'}} 806 807 Args: 808 d: dictionary to update. 809 keys: the keys that makeup the path to `value`. 810 value: the value to set in the dictionary for the given key path. 811 812 Returns: 813 The (possibly) updated dictionary. 814 """ 815 if not keys: 816 return d 817 818 if len(keys) == 1: 819 d[keys[0]] = value 820 return d 821 822 subd = d 823 for key in keys[:-1]: 824 if key not in subd: 825 subd = subd.setdefault(key, {}) 826 else: 827 subd = subd[key] 828 829 subd[keys[-1]] = value 830 return d
23class Schema(abc.ABC): 24 """Abstract base class for database schemas""" 25 26 @property 27 def dialect(self) -> Dialect | None: 28 """ 29 Returns None by default. Subclasses that require dialect-specific 30 behavior should override this property. 31 """ 32 return None 33 34 @abc.abstractmethod 35 def add_table( 36 self, 37 table: exp.Table | str, 38 column_mapping: ColumnMapping | None = None, 39 dialect: DialectType = None, 40 normalize: bool | None = None, 41 match_depth: bool = True, 42 ) -> None: 43 """ 44 Register or update a table. Some implementing classes may require column information to also be provided. 45 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 46 47 Args: 48 table: the `Table` expression instance or string representing the table. 49 column_mapping: a column mapping that describes the structure of the table. 50 dialect: the SQL dialect that will be used to parse `table` if it's a string. 51 normalize: whether to normalize identifiers according to the dialect of interest. 52 match_depth: whether to enforce that the table must match the schema's depth or not. 53 """ 54 55 @abc.abstractmethod 56 def column_names( 57 self, 58 table: exp.Table | str, 59 only_visible: bool = False, 60 dialect: DialectType = None, 61 normalize: bool | None = None, 62 ) -> Sequence[str]: 63 """ 64 Get the column names for a table. 65 66 Args: 67 table: the `Table` expression instance. 68 only_visible: whether to include invisible columns. 69 dialect: the SQL dialect that will be used to parse `table` if it's a string. 70 normalize: whether to normalize identifiers according to the dialect of interest. 71 72 Returns: 73 The sequence of column names. 74 """ 75 76 @abc.abstractmethod 77 def get_column_type( 78 self, 79 table: exp.Table | str, 80 column: exp.Column | str, 81 dialect: DialectType = None, 82 normalize: bool | None = None, 83 ) -> exp.DataType: 84 """ 85 Get the `sqlglot.exp.DataType` type of a column in the schema. 86 87 Args: 88 table: the source table. 89 column: the target column. 90 dialect: the SQL dialect that will be used to parse `table` if it's a string. 91 normalize: whether to normalize identifiers according to the dialect of interest. 92 93 Returns: 94 The resulting column type. 95 """ 96 97 def has_column( 98 self, 99 table: exp.Table | str, 100 column: exp.Column | str, 101 dialect: DialectType = None, 102 normalize: bool | None = None, 103 ) -> bool: 104 """ 105 Returns whether `column` appears in `table`'s schema. 106 107 Args: 108 table: the source table. 109 column: the target column. 110 dialect: the SQL dialect that will be used to parse `table` if it's a string. 111 normalize: whether to normalize identifiers according to the dialect of interest. 112 113 Returns: 114 True if the column appears in the schema, False otherwise. 115 """ 116 name = column if isinstance(column, str) else column.name 117 return name in self.column_names(table, dialect=dialect, normalize=normalize) 118 119 def get_udf_type( 120 self, 121 udf: exp.Anonymous | str, 122 dialect: DialectType = None, 123 normalize: bool | None = None, 124 ) -> exp.DataType: 125 """ 126 Get the return type of a UDF. 127 128 Args: 129 udf: the UDF expression or string. 130 dialect: the SQL dialect for parsing string arguments. 131 normalize: whether to normalize identifiers. 132 133 Returns: 134 The return type as a DataType, or UNKNOWN if not found. 135 """ 136 return exp.DType.UNKNOWN.into_expr() 137 138 @property 139 @abc.abstractmethod 140 def supported_table_args(self) -> tuple[str, ...]: 141 """ 142 Table arguments this schema support, e.g. `("this", "db", "catalog")` 143 """ 144 145 @property 146 def empty(self) -> bool: 147 """Returns whether the schema is empty.""" 148 return True
Abstract base class for database schemas
26 @property 27 def dialect(self) -> Dialect | None: 28 """ 29 Returns None by default. Subclasses that require dialect-specific 30 behavior should override this property. 31 """ 32 return None
Returns None by default. Subclasses that require dialect-specific behavior should override this property.
34 @abc.abstractmethod 35 def add_table( 36 self, 37 table: exp.Table | str, 38 column_mapping: ColumnMapping | None = None, 39 dialect: DialectType = None, 40 normalize: bool | None = None, 41 match_depth: bool = True, 42 ) -> None: 43 """ 44 Register or update a table. Some implementing classes may require column information to also be provided. 45 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 46 47 Args: 48 table: the `Table` expression instance or string representing the table. 49 column_mapping: a column mapping that describes the structure of the table. 50 dialect: the SQL dialect that will be used to parse `table` if it's a string. 51 normalize: whether to normalize identifiers according to the dialect of interest. 52 match_depth: whether to enforce that the table must match the schema's depth or not. 53 """
Register or update a table. Some implementing classes may require column information to also be provided. The added table must have the necessary number of qualifiers in its path to match the schema's nesting level.
Arguments:
- table: the
Tableexpression instance or string representing the table. - column_mapping: a column mapping that describes the structure of the table.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
- match_depth: whether to enforce that the table must match the schema's depth or not.
55 @abc.abstractmethod 56 def column_names( 57 self, 58 table: exp.Table | str, 59 only_visible: bool = False, 60 dialect: DialectType = None, 61 normalize: bool | None = None, 62 ) -> Sequence[str]: 63 """ 64 Get the column names for a table. 65 66 Args: 67 table: the `Table` expression instance. 68 only_visible: whether to include invisible columns. 69 dialect: the SQL dialect that will be used to parse `table` if it's a string. 70 normalize: whether to normalize identifiers according to the dialect of interest. 71 72 Returns: 73 The sequence of column names. 74 """
Get the column names for a table.
Arguments:
- table: the
Tableexpression instance. - only_visible: whether to include invisible columns.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
The sequence of column names.
76 @abc.abstractmethod 77 def get_column_type( 78 self, 79 table: exp.Table | str, 80 column: exp.Column | str, 81 dialect: DialectType = None, 82 normalize: bool | None = None, 83 ) -> exp.DataType: 84 """ 85 Get the `sqlglot.exp.DataType` type of a column in the schema. 86 87 Args: 88 table: the source table. 89 column: the target column. 90 dialect: the SQL dialect that will be used to parse `table` if it's a string. 91 normalize: whether to normalize identifiers according to the dialect of interest. 92 93 Returns: 94 The resulting column type. 95 """
Get the sqlglot.exp.DataType type of a column in the schema.
Arguments:
- table: the source table.
- column: the target column.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
The resulting column type.
97 def has_column( 98 self, 99 table: exp.Table | str, 100 column: exp.Column | str, 101 dialect: DialectType = None, 102 normalize: bool | None = None, 103 ) -> bool: 104 """ 105 Returns whether `column` appears in `table`'s schema. 106 107 Args: 108 table: the source table. 109 column: the target column. 110 dialect: the SQL dialect that will be used to parse `table` if it's a string. 111 normalize: whether to normalize identifiers according to the dialect of interest. 112 113 Returns: 114 True if the column appears in the schema, False otherwise. 115 """ 116 name = column if isinstance(column, str) else column.name 117 return name in self.column_names(table, dialect=dialect, normalize=normalize)
Returns whether column appears in table's schema.
Arguments:
- table: the source table.
- column: the target column.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
True if the column appears in the schema, False otherwise.
119 def get_udf_type( 120 self, 121 udf: exp.Anonymous | str, 122 dialect: DialectType = None, 123 normalize: bool | None = None, 124 ) -> exp.DataType: 125 """ 126 Get the return type of a UDF. 127 128 Args: 129 udf: the UDF expression or string. 130 dialect: the SQL dialect for parsing string arguments. 131 normalize: whether to normalize identifiers. 132 133 Returns: 134 The return type as a DataType, or UNKNOWN if not found. 135 """ 136 return exp.DType.UNKNOWN.into_expr()
Get the return type of a UDF.
Arguments:
- udf: the UDF expression or string.
- dialect: the SQL dialect for parsing string arguments.
- normalize: whether to normalize identifiers.
Returns:
The return type as a DataType, or UNKNOWN if not found.
151class AbstractMappingSchema: 152 def __init__( 153 self, 154 mapping: dict[str, object] | None = None, 155 udf_mapping: dict[str, object] | None = None, 156 ) -> None: 157 self.mapping: dict[str, object] = mapping or {} 158 self.mapping_trie: dict[str, object] = new_trie( 159 tuple(reversed(t)) for t in flatten_schema(self.mapping, depth=self.depth()) 160 ) 161 self.udf_mapping: dict[str, object] = udf_mapping or {} 162 self.udf_trie: dict[str, object] = new_trie( 163 tuple(reversed(t)) for t in flatten_schema(self.udf_mapping, depth=self.udf_depth()) 164 ) 165 166 self._supported_table_args: tuple[str, ...] = tuple() 167 168 @property 169 def empty(self) -> bool: 170 return not self.mapping 171 172 def depth(self) -> int: 173 return dict_depth(self.mapping) 174 175 def udf_depth(self) -> int: 176 return dict_depth(self.udf_mapping) 177 178 @property 179 def supported_table_args(self) -> tuple[str, ...]: 180 if not self._supported_table_args and self.mapping: 181 depth = self.depth() 182 183 if not depth: # None 184 self._supported_table_args = tuple() 185 elif 1 <= depth <= 3: 186 self._supported_table_args = exp.TABLE_PARTS[:depth] 187 else: 188 raise SchemaError(f"Invalid mapping shape. Depth: {depth}") 189 190 return self._supported_table_args 191 192 def table_parts(self, table: exp.Table) -> list[str]: 193 return [p.name for p in reversed(table.parts)] 194 195 def udf_parts(self, udf: exp.Anonymous) -> list[str]: 196 # a.b.c(...) is represented as Dot(Dot(a, b), Anonymous(c, ...)) 197 parent = udf.parent 198 parts = [p.name for p in parent.flatten()] if isinstance(parent, exp.Dot) else [udf.name] 199 return list(reversed(parts))[0 : self.udf_depth()] 200 201 def _find_in_trie( 202 self, 203 parts: list[str], 204 trie: dict[str, object], 205 raise_on_missing: bool, 206 ) -> list[str] | None: 207 value, trie = in_trie(trie, parts) 208 209 if value == TrieResult.FAILED: 210 return None 211 212 if value == TrieResult.PREFIX: 213 possibilities = flatten_schema(trie) 214 215 if len(possibilities) == 1: 216 parts.extend(possibilities[0]) 217 else: 218 if raise_on_missing: 219 joined_parts = ".".join(parts) 220 message = ", ".join(".".join(p) for p in possibilities) 221 raise SchemaError(f"Ambiguous mapping for {joined_parts}: {message}.") 222 223 return None 224 225 return parts 226 227 def find( 228 self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False 229 ) -> t.Any | None: 230 """ 231 Returns the schema of a given table. 232 233 Args: 234 table: the target table. 235 raise_on_missing: whether to raise in case the schema is not found. 236 ensure_data_types: whether to convert `str` types to their `DataType` equivalents. 237 238 Returns: 239 The schema of the target table. 240 """ 241 return self._find( 242 self.table_parts(table), 243 raise_on_missing=raise_on_missing, 244 ensure_data_types=ensure_data_types, 245 ) 246 247 def _find( 248 self, parts: Sequence[str], raise_on_missing: bool = True, ensure_data_types: bool = False 249 ) -> t.Any | None: 250 parts = list(parts[0 : len(self.supported_table_args)]) 251 resolved_parts = self._find_in_trie(parts, self.mapping_trie, raise_on_missing) 252 253 if resolved_parts is None: 254 return None 255 256 return self.nested_get(resolved_parts, raise_on_missing=raise_on_missing) 257 258 def find_udf(self, udf: exp.Anonymous, raise_on_missing: bool = False) -> t.Any | None: 259 """ 260 Returns the return type of a given UDF. 261 262 Args: 263 udf: the target UDF expression. 264 raise_on_missing: whether to raise if the UDF is not found. 265 266 Returns: 267 The return type of the UDF, or None if not found. 268 """ 269 parts = self.udf_parts(udf) 270 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing) 271 272 if resolved_parts is None: 273 return None 274 275 return nested_get( 276 self.udf_mapping, 277 *zip(resolved_parts, reversed(resolved_parts)), 278 raise_on_missing=raise_on_missing, 279 ) 280 281 def nested_get( 282 self, 283 parts: Sequence[str], 284 d: dict[str, object] | None = None, 285 raise_on_missing: bool = True, 286 ) -> t.Any | None: 287 return nested_get( 288 d or self.mapping, 289 *zip(self.supported_table_args, reversed(parts)), 290 raise_on_missing=raise_on_missing, 291 )
152 def __init__( 153 self, 154 mapping: dict[str, object] | None = None, 155 udf_mapping: dict[str, object] | None = None, 156 ) -> None: 157 self.mapping: dict[str, object] = mapping or {} 158 self.mapping_trie: dict[str, object] = new_trie( 159 tuple(reversed(t)) for t in flatten_schema(self.mapping, depth=self.depth()) 160 ) 161 self.udf_mapping: dict[str, object] = udf_mapping or {} 162 self.udf_trie: dict[str, object] = new_trie( 163 tuple(reversed(t)) for t in flatten_schema(self.udf_mapping, depth=self.udf_depth()) 164 ) 165 166 self._supported_table_args: tuple[str, ...] = tuple()
178 @property 179 def supported_table_args(self) -> tuple[str, ...]: 180 if not self._supported_table_args and self.mapping: 181 depth = self.depth() 182 183 if not depth: # None 184 self._supported_table_args = tuple() 185 elif 1 <= depth <= 3: 186 self._supported_table_args = exp.TABLE_PARTS[:depth] 187 else: 188 raise SchemaError(f"Invalid mapping shape. Depth: {depth}") 189 190 return self._supported_table_args
227 def find( 228 self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False 229 ) -> t.Any | None: 230 """ 231 Returns the schema of a given table. 232 233 Args: 234 table: the target table. 235 raise_on_missing: whether to raise in case the schema is not found. 236 ensure_data_types: whether to convert `str` types to their `DataType` equivalents. 237 238 Returns: 239 The schema of the target table. 240 """ 241 return self._find( 242 self.table_parts(table), 243 raise_on_missing=raise_on_missing, 244 ensure_data_types=ensure_data_types, 245 )
Returns the schema of a given table.
Arguments:
- table: the target table.
- raise_on_missing: whether to raise in case the schema is not found.
- ensure_data_types: whether to convert
strtypes to theirDataTypeequivalents.
Returns:
The schema of the target table.
258 def find_udf(self, udf: exp.Anonymous, raise_on_missing: bool = False) -> t.Any | None: 259 """ 260 Returns the return type of a given UDF. 261 262 Args: 263 udf: the target UDF expression. 264 raise_on_missing: whether to raise if the UDF is not found. 265 266 Returns: 267 The return type of the UDF, or None if not found. 268 """ 269 parts = self.udf_parts(udf) 270 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing) 271 272 if resolved_parts is None: 273 return None 274 275 return nested_get( 276 self.udf_mapping, 277 *zip(resolved_parts, reversed(resolved_parts)), 278 raise_on_missing=raise_on_missing, 279 )
Returns the return type of a given UDF.
Arguments:
- udf: the target UDF expression.
- raise_on_missing: whether to raise if the UDF is not found.
Returns:
The return type of the UDF, or None if not found.
294class MappingSchema(AbstractMappingSchema, Schema): 295 """ 296 Schema based on a nested mapping. 297 298 Args: 299 schema: Mapping in one of the following forms: 300 1. {table: {col: type}} 301 2. {db: {table: {col: type}}} 302 3. {catalog: {db: {table: {col: type}}}} 303 4. None - Tables will be added later 304 visible: Optional mapping of which columns in the schema are visible. If not provided, all columns 305 are assumed to be visible. The nesting should mirror that of the schema: 306 1. {table: set(*cols)}} 307 2. {db: {table: set(*cols)}}} 308 3. {catalog: {db: {table: set(*cols)}}}} 309 dialect: The dialect to be used for custom type mappings & parsing string arguments. 310 normalize: Whether to normalize identifier names according to the given dialect or not. 311 """ 312 313 def __init__( 314 self, 315 schema: dict[str, object] | None = None, 316 visible: dict[str, object] | None = None, 317 dialect: DialectType = None, 318 normalize: bool = True, 319 udf_mapping: dict[str, object] | None = None, 320 ) -> None: 321 self.visible: dict[str, object] = {} if visible is None else visible 322 self.normalize: bool = normalize 323 self._dialect: Dialect = Dialect.get_or_raise(dialect) 324 self._type_mapping_cache: dict[str, exp.DataType] = {} 325 self._normalized_table_cache: dict[ 326 tuple[tuple[tuple[str, bool | None], ...], DialectType, bool], tuple[str, ...] 327 ] = {} 328 self._normalized_name_cache: dict[tuple[str, DialectType, bool, bool], str] = {} 329 self._find_cache: dict[tuple[tuple[str, ...], bool], dict[str, object] | None] = {} 330 self._depth: int = 0 331 schema = {} if schema is None else schema 332 udf_mapping = {} if udf_mapping is None else udf_mapping 333 334 super().__init__( 335 self._normalize(schema) if self.normalize else schema, 336 self._normalize_udfs(udf_mapping) if self.normalize else udf_mapping, 337 ) 338 339 @property 340 def dialect(self) -> Dialect: 341 """Returns the dialect for this mapping schema.""" 342 return self._dialect 343 344 @classmethod 345 def from_mapping_schema(cls, mapping_schema: MappingSchema) -> MappingSchema: 346 return MappingSchema( 347 schema=mapping_schema.mapping, 348 visible=mapping_schema.visible, 349 dialect=mapping_schema.dialect, 350 normalize=mapping_schema.normalize, 351 udf_mapping=mapping_schema.udf_mapping, 352 ) 353 354 def _find( 355 self, parts: Sequence[str], raise_on_missing: bool = True, ensure_data_types: bool = False 356 ) -> t.Any | None: 357 cache_key = (tuple(parts), ensure_data_types) 358 schema = self._find_cache.get(cache_key) 359 360 if schema is None: 361 schema = super()._find(parts, raise_on_missing=raise_on_missing) 362 if ensure_data_types and isinstance(schema, dict): 363 schema = { 364 col: self._to_data_type(dtype) if isinstance(dtype, str) else dtype 365 for col, dtype in schema.items() 366 } 367 self._find_cache[cache_key] = schema 368 369 return schema 370 371 def copy( 372 self, schema: dict[str, object] | None = None, **kwargs: Unpack[SchemaArgs] 373 ) -> MappingSchema: 374 mapping_kwargs: SchemaArgs = { 375 "visible": self.visible.copy(), 376 "dialect": self.dialect, 377 "normalize": self.normalize, 378 "udf_mapping": self.udf_mapping.copy(), 379 **kwargs, 380 } 381 return MappingSchema(self.mapping.copy() if schema is None else schema, **mapping_kwargs) 382 383 def add_table( 384 self, 385 table: exp.Table | str, 386 column_mapping: ColumnMapping | None = None, 387 dialect: DialectType = None, 388 normalize: bool | None = None, 389 match_depth: bool = True, 390 ) -> None: 391 """ 392 Register or update a table. Updates are only performed if a new column mapping is provided. 393 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 394 395 Args: 396 table: the `Table` expression instance or string representing the table. 397 column_mapping: a column mapping that describes the structure of the table. 398 dialect: the SQL dialect that will be used to parse `table` if it's a string. 399 normalize: whether to normalize identifiers according to the dialect of interest. 400 match_depth: whether to enforce that the table must match the schema's depth or not. 401 """ 402 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 403 404 if match_depth and not self.empty and len(parts) != self.depth(): 405 table = exp.maybe_parse( 406 table, into=exp.Table, dialect=dialect or self.dialect, copy=True 407 ) 408 for part, name in zip(reversed(table.parts), parts): 409 if isinstance(part, exp.Identifier): 410 part.set("this", name) 411 raise SchemaError( 412 f"Table {table.sql(dialect=self.dialect)} must match the " 413 f"schema's nesting level: {self.depth()}." 414 ) 415 416 normalized_column_mapping = { 417 self._normalize_name(key, dialect=dialect, normalize=normalize): value 418 for key, value in ensure_column_mapping(column_mapping).items() 419 } 420 421 schema = self._find(parts, raise_on_missing=False) 422 if schema and not normalized_column_mapping: 423 return 424 425 nested_set(self.mapping, tuple(reversed(parts)), normalized_column_mapping) 426 new_trie([parts], self.mapping_trie) 427 428 # A new table can change how partially-qualified names resolve (or make them ambiguous), 429 # so any cached lookup may be stale, not just the one for this table's full path 430 self._find_cache.clear() 431 432 def column_names( 433 self, 434 table: exp.Table | str, 435 only_visible: bool = False, 436 dialect: DialectType = None, 437 normalize: bool | None = None, 438 ) -> list[str]: 439 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 440 441 schema: dict[str, object] | None = self._find(parts) 442 if schema is None: 443 return [] 444 445 if not only_visible or not self.visible: 446 return list(schema) 447 448 visible = self.nested_get(parts, self.visible) or [] 449 return [col for col in schema if col in visible] 450 451 def get_column_type( 452 self, 453 table: exp.Table | str, 454 column: exp.Column | str, 455 dialect: DialectType = None, 456 normalize: bool | None = None, 457 ) -> exp.DataType: 458 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 459 460 normalized_column_name = self._normalize_name( 461 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 462 ) 463 464 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 465 if table_schema: 466 column_type = table_schema.get(normalized_column_name) 467 468 if isinstance(column_type, exp.DataType): 469 return column_type 470 elif isinstance(column_type, str): 471 return self._to_data_type(column_type, dialect=dialect) 472 473 return exp.DType.UNKNOWN.into_expr() 474 475 def get_udf_type( 476 self, 477 udf: exp.Anonymous | str, 478 dialect: DialectType = None, 479 normalize: bool | None = None, 480 ) -> exp.DataType: 481 """ 482 Get the return type of a UDF. 483 484 Args: 485 udf: the UDF expression or string (e.g., "db.my_func()"). 486 dialect: the SQL dialect for parsing string arguments. 487 normalize: whether to normalize identifiers. 488 489 Returns: 490 The return type as a DataType, or UNKNOWN if not found. 491 """ 492 parts = self._normalize_udf(udf, dialect=dialect, normalize=normalize) 493 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing=False) 494 495 if resolved_parts is None: 496 return exp.DType.UNKNOWN.into_expr() 497 498 udf_type = nested_get( 499 self.udf_mapping, 500 *zip(resolved_parts, reversed(resolved_parts)), 501 raise_on_missing=False, 502 ) 503 504 if isinstance(udf_type, exp.DataType): 505 return udf_type 506 elif isinstance(udf_type, str): 507 return self._to_data_type(udf_type, dialect=dialect) 508 509 return exp.DType.UNKNOWN.into_expr() 510 511 def has_column( 512 self, 513 table: exp.Table | str, 514 column: exp.Column | str, 515 dialect: DialectType = None, 516 normalize: bool | None = None, 517 ) -> bool: 518 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 519 520 normalized_column_name = self._normalize_name( 521 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 522 ) 523 524 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 525 return normalized_column_name in table_schema if table_schema else False 526 527 def _normalize(self, schema: dict[str, object]) -> dict[str, object]: 528 """ 529 Normalizes all identifiers in the schema. 530 531 Args: 532 schema: the schema to normalize. 533 534 Returns: 535 The normalized schema mapping. 536 """ 537 normalized_mapping: dict[str, object] = {} 538 flattened_schema = flatten_schema(schema) 539 error_msg = "Table {} must match the schema's nesting level: {}." 540 541 for keys in flattened_schema: 542 columns = nested_get(schema, *zip(keys, keys)) 543 544 if not isinstance(columns, dict): 545 raise SchemaError(error_msg.format(".".join(keys[:-1]), len(flattened_schema[0]))) 546 if not columns: 547 raise SchemaError(f"Table {'.'.join(keys[:-1])} must have at least one column") 548 if isinstance(first(columns.values()), dict): 549 raise SchemaError( 550 error_msg.format( 551 ".".join(keys + flatten_schema(columns)[0]), len(flattened_schema[0]) 552 ), 553 ) 554 555 normalized_keys = [self._normalize_name(key, is_table=True) for key in keys] 556 for column_name, column_type in columns.items(): 557 nested_set( 558 normalized_mapping, 559 normalized_keys + [self._normalize_name(column_name)], 560 column_type, 561 ) 562 563 return normalized_mapping 564 565 def _normalize_udfs(self, udfs: dict[str, object]) -> dict[str, object]: 566 """ 567 Normalizes all identifiers in the UDF mapping. 568 569 Args: 570 udfs: the UDF mapping to normalize. 571 572 Returns: 573 The normalized UDF mapping. 574 """ 575 normalized_mapping: dict[str, object] = {} 576 577 for keys in flatten_schema(udfs, depth=dict_depth(udfs)): 578 udf_type = nested_get(udfs, *zip(keys, keys)) 579 normalized_keys = [self._normalize_name(key, is_table=True) for key in keys] 580 nested_set(normalized_mapping, normalized_keys, udf_type) 581 582 return normalized_mapping 583 584 def _normalize_udf( 585 self, 586 udf: exp.Anonymous | str, 587 dialect: DialectType = None, 588 normalize: bool | None = None, 589 ) -> list[str]: 590 """ 591 Extract and normalize UDF parts for lookup. 592 593 Args: 594 udf: the UDF expression or qualified string (e.g., "db.my_func()"). 595 dialect: the SQL dialect for parsing. 596 normalize: whether to normalize identifiers. 597 598 Returns: 599 A list of normalized UDF parts (reversed for trie lookup). 600 """ 601 dialect = dialect or self.dialect 602 normalize = self.normalize if normalize is None else normalize 603 604 if isinstance(udf, str): 605 parsed: exp.Expr = exp.maybe_parse(udf, dialect=dialect) 606 607 if isinstance(parsed, exp.Anonymous): 608 udf = parsed 609 elif isinstance(parsed, exp.Dot) and isinstance(parsed.expression, exp.Anonymous): 610 udf = parsed.expression 611 else: 612 raise SchemaError(f"Unable to parse UDF from: {udf!r}") 613 parts = self.udf_parts(udf) 614 615 if normalize: 616 parts = [self._normalize_name(part, dialect=dialect, is_table=True) for part in parts] 617 618 return parts 619 620 def _normalize_table_parts( 621 self, 622 table: exp.Table | str, 623 dialect: DialectType = None, 624 normalize: bool | None = None, 625 ) -> tuple[str, ...]: 626 dialect = dialect or self.dialect 627 normalize = self.normalize if normalize is None else normalize 628 629 table = exp.maybe_parse(table, into=exp.Table, dialect=dialect, copy=False) 630 parts = table.parts 631 cache_key = ( 632 tuple( 633 (part.name, part.quoted if isinstance(part, exp.Identifier) else None) 634 for part in parts 635 ), 636 dialect, 637 normalize, 638 ) 639 if (cached := self._normalized_table_cache.get(cache_key)) is not None: 640 return cached 641 642 normalized_parts = tuple( 643 normalize_name(part, dialect=dialect, is_table=True).name 644 if normalize and isinstance(part, exp.Identifier) 645 else part.name 646 for part in reversed(parts) 647 ) 648 self._normalized_table_cache[cache_key] = normalized_parts 649 return normalized_parts 650 651 def _normalize_name( 652 self, 653 name: str | exp.Identifier, 654 dialect: DialectType = None, 655 is_table: bool = False, 656 normalize: bool | None = None, 657 ) -> str: 658 normalize = self.normalize if normalize is None else normalize 659 660 dialect = dialect or self.dialect 661 name_str = name if isinstance(name, str) else name.name 662 cache_key = (name_str, dialect, is_table, normalize) 663 664 if cached := self._normalized_name_cache.get(cache_key): 665 return cached 666 667 result = normalize_name( 668 name, 669 dialect=dialect, 670 is_table=is_table, 671 normalize=normalize, 672 ).name 673 674 self._normalized_name_cache[cache_key] = result 675 return result 676 677 def depth(self) -> int: 678 if not self.empty and not self._depth: 679 # The columns themselves are a mapping, but we don't want to include those 680 self._depth = super().depth() - 1 681 return self._depth 682 683 def _to_data_type(self, schema_type: str, dialect: DialectType = None) -> exp.DataType: 684 """ 685 Convert a type represented as a string to the corresponding `sqlglot.exp.DataType` object. 686 687 Args: 688 schema_type: the type we want to convert. 689 dialect: the SQL dialect that will be used to parse `schema_type`, if needed. 690 691 Returns: 692 The resulting expression type. 693 """ 694 if schema_type not in self._type_mapping_cache: 695 dialect = Dialect.get_or_raise(dialect) if dialect else self.dialect 696 udt = dialect.SUPPORTS_USER_DEFINED_TYPES 697 698 try: 699 expression = exp.DataType.from_str(schema_type, dialect=dialect, udt=udt) 700 expression.transform(dialect.normalize_identifier, copy=False) 701 self._type_mapping_cache[schema_type] = expression 702 except AttributeError: 703 in_dialect = f" in dialect {dialect}" if dialect else "" 704 raise SchemaError(f"Failed to build type '{schema_type}'{in_dialect}.") 705 706 return self._type_mapping_cache[schema_type]
Schema based on a nested mapping.
Arguments:
- schema: Mapping in one of the following forms:
- {table: {col: type}}
- {db: {table: {col: type}}}
- {catalog: {db: {table: {col: type}}}}
- None - Tables will be added later
- visible: Optional mapping of which columns in the schema are visible. If not provided, all columns
are assumed to be visible. The nesting should mirror that of the schema:
- {table: set(*cols)}}
- {db: {table: set(*cols)}}}
- {catalog: {db: {table: set(*cols)}}}}
- dialect: The dialect to be used for custom type mappings & parsing string arguments.
- normalize: Whether to normalize identifier names according to the given dialect or not.
313 def __init__( 314 self, 315 schema: dict[str, object] | None = None, 316 visible: dict[str, object] | None = None, 317 dialect: DialectType = None, 318 normalize: bool = True, 319 udf_mapping: dict[str, object] | None = None, 320 ) -> None: 321 self.visible: dict[str, object] = {} if visible is None else visible 322 self.normalize: bool = normalize 323 self._dialect: Dialect = Dialect.get_or_raise(dialect) 324 self._type_mapping_cache: dict[str, exp.DataType] = {} 325 self._normalized_table_cache: dict[ 326 tuple[tuple[tuple[str, bool | None], ...], DialectType, bool], tuple[str, ...] 327 ] = {} 328 self._normalized_name_cache: dict[tuple[str, DialectType, bool, bool], str] = {} 329 self._find_cache: dict[tuple[tuple[str, ...], bool], dict[str, object] | None] = {} 330 self._depth: int = 0 331 schema = {} if schema is None else schema 332 udf_mapping = {} if udf_mapping is None else udf_mapping 333 334 super().__init__( 335 self._normalize(schema) if self.normalize else schema, 336 self._normalize_udfs(udf_mapping) if self.normalize else udf_mapping, 337 )
339 @property 340 def dialect(self) -> Dialect: 341 """Returns the dialect for this mapping schema.""" 342 return self._dialect
Returns the dialect for this mapping schema.
344 @classmethod 345 def from_mapping_schema(cls, mapping_schema: MappingSchema) -> MappingSchema: 346 return MappingSchema( 347 schema=mapping_schema.mapping, 348 visible=mapping_schema.visible, 349 dialect=mapping_schema.dialect, 350 normalize=mapping_schema.normalize, 351 udf_mapping=mapping_schema.udf_mapping, 352 )
371 def copy( 372 self, schema: dict[str, object] | None = None, **kwargs: Unpack[SchemaArgs] 373 ) -> MappingSchema: 374 mapping_kwargs: SchemaArgs = { 375 "visible": self.visible.copy(), 376 "dialect": self.dialect, 377 "normalize": self.normalize, 378 "udf_mapping": self.udf_mapping.copy(), 379 **kwargs, 380 } 381 return MappingSchema(self.mapping.copy() if schema is None else schema, **mapping_kwargs)
383 def add_table( 384 self, 385 table: exp.Table | str, 386 column_mapping: ColumnMapping | None = None, 387 dialect: DialectType = None, 388 normalize: bool | None = None, 389 match_depth: bool = True, 390 ) -> None: 391 """ 392 Register or update a table. Updates are only performed if a new column mapping is provided. 393 The added table must have the necessary number of qualifiers in its path to match the schema's nesting level. 394 395 Args: 396 table: the `Table` expression instance or string representing the table. 397 column_mapping: a column mapping that describes the structure of the table. 398 dialect: the SQL dialect that will be used to parse `table` if it's a string. 399 normalize: whether to normalize identifiers according to the dialect of interest. 400 match_depth: whether to enforce that the table must match the schema's depth or not. 401 """ 402 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 403 404 if match_depth and not self.empty and len(parts) != self.depth(): 405 table = exp.maybe_parse( 406 table, into=exp.Table, dialect=dialect or self.dialect, copy=True 407 ) 408 for part, name in zip(reversed(table.parts), parts): 409 if isinstance(part, exp.Identifier): 410 part.set("this", name) 411 raise SchemaError( 412 f"Table {table.sql(dialect=self.dialect)} must match the " 413 f"schema's nesting level: {self.depth()}." 414 ) 415 416 normalized_column_mapping = { 417 self._normalize_name(key, dialect=dialect, normalize=normalize): value 418 for key, value in ensure_column_mapping(column_mapping).items() 419 } 420 421 schema = self._find(parts, raise_on_missing=False) 422 if schema and not normalized_column_mapping: 423 return 424 425 nested_set(self.mapping, tuple(reversed(parts)), normalized_column_mapping) 426 new_trie([parts], self.mapping_trie) 427 428 # A new table can change how partially-qualified names resolve (or make them ambiguous), 429 # so any cached lookup may be stale, not just the one for this table's full path 430 self._find_cache.clear()
Register or update a table. Updates are only performed if a new column mapping is provided. The added table must have the necessary number of qualifiers in its path to match the schema's nesting level.
Arguments:
- table: the
Tableexpression instance or string representing the table. - column_mapping: a column mapping that describes the structure of the table.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
- match_depth: whether to enforce that the table must match the schema's depth or not.
432 def column_names( 433 self, 434 table: exp.Table | str, 435 only_visible: bool = False, 436 dialect: DialectType = None, 437 normalize: bool | None = None, 438 ) -> list[str]: 439 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 440 441 schema: dict[str, object] | None = self._find(parts) 442 if schema is None: 443 return [] 444 445 if not only_visible or not self.visible: 446 return list(schema) 447 448 visible = self.nested_get(parts, self.visible) or [] 449 return [col for col in schema if col in visible]
Get the column names for a table.
Arguments:
- table: the
Tableexpression instance. - only_visible: whether to include invisible columns.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
The sequence of column names.
451 def get_column_type( 452 self, 453 table: exp.Table | str, 454 column: exp.Column | str, 455 dialect: DialectType = None, 456 normalize: bool | None = None, 457 ) -> exp.DataType: 458 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 459 460 normalized_column_name = self._normalize_name( 461 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 462 ) 463 464 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 465 if table_schema: 466 column_type = table_schema.get(normalized_column_name) 467 468 if isinstance(column_type, exp.DataType): 469 return column_type 470 elif isinstance(column_type, str): 471 return self._to_data_type(column_type, dialect=dialect) 472 473 return exp.DType.UNKNOWN.into_expr()
Get the sqlglot.exp.DataType type of a column in the schema.
Arguments:
- table: the source table.
- column: the target column.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
The resulting column type.
475 def get_udf_type( 476 self, 477 udf: exp.Anonymous | str, 478 dialect: DialectType = None, 479 normalize: bool | None = None, 480 ) -> exp.DataType: 481 """ 482 Get the return type of a UDF. 483 484 Args: 485 udf: the UDF expression or string (e.g., "db.my_func()"). 486 dialect: the SQL dialect for parsing string arguments. 487 normalize: whether to normalize identifiers. 488 489 Returns: 490 The return type as a DataType, or UNKNOWN if not found. 491 """ 492 parts = self._normalize_udf(udf, dialect=dialect, normalize=normalize) 493 resolved_parts = self._find_in_trie(parts, self.udf_trie, raise_on_missing=False) 494 495 if resolved_parts is None: 496 return exp.DType.UNKNOWN.into_expr() 497 498 udf_type = nested_get( 499 self.udf_mapping, 500 *zip(resolved_parts, reversed(resolved_parts)), 501 raise_on_missing=False, 502 ) 503 504 if isinstance(udf_type, exp.DataType): 505 return udf_type 506 elif isinstance(udf_type, str): 507 return self._to_data_type(udf_type, dialect=dialect) 508 509 return exp.DType.UNKNOWN.into_expr()
Get the return type of a UDF.
Arguments:
- udf: the UDF expression or string (e.g., "db.my_func()").
- dialect: the SQL dialect for parsing string arguments.
- normalize: whether to normalize identifiers.
Returns:
The return type as a DataType, or UNKNOWN if not found.
511 def has_column( 512 self, 513 table: exp.Table | str, 514 column: exp.Column | str, 515 dialect: DialectType = None, 516 normalize: bool | None = None, 517 ) -> bool: 518 parts = self._normalize_table_parts(table, dialect=dialect, normalize=normalize) 519 520 normalized_column_name = self._normalize_name( 521 column if isinstance(column, str) else column.this, dialect=dialect, normalize=normalize 522 ) 523 524 table_schema: dict[str, object] | None = self._find(parts, raise_on_missing=False) 525 return normalized_column_name in table_schema if table_schema else False
Returns whether column appears in table's schema.
Arguments:
- table: the source table.
- column: the target column.
- dialect: the SQL dialect that will be used to parse
tableif it's a string. - normalize: whether to normalize identifiers according to the dialect of interest.
Returns:
True if the column appears in the schema, False otherwise.
709def normalize_name( 710 identifier: str | exp.Identifier, 711 dialect: DialectType = None, 712 is_table: bool = False, 713 normalize: bool | None = True, 714) -> exp.Identifier: 715 if isinstance(identifier, str): 716 identifier = exp.parse_identifier(identifier, dialect=dialect) 717 elif normalize: 718 identifier = identifier.copy() 719 720 if not normalize: 721 return identifier 722 723 # this is used for normalize_identifier, bigquery has special rules pertaining tables 724 identifier.meta["is_table"] = is_table 725 return Dialect.get_or_raise(dialect).normalize_identifier(identifier)
737def ensure_column_mapping(mapping: ColumnMapping | None) -> dict[str, t.Any]: 738 if mapping is None: 739 return {} 740 elif isinstance(mapping, dict): 741 return mapping 742 elif isinstance(mapping, str): 743 col_name_type_strs = [x.strip() for x in mapping.split(",")] 744 return { 745 name_type_str.split(":")[0].strip(): name_type_str.split(":")[1].strip() 746 for name_type_str in col_name_type_strs 747 } 748 elif isinstance(mapping, list): 749 return {x.strip(): None for x in mapping} 750 751 raise ValueError(f"Invalid mapping provided: {type(mapping)}")
754def flatten_schema( 755 schema: dict[str, object], depth: int | None = None, keys: list[str] | None = None 756) -> list[list[str]]: 757 tables: list[list[str]] = [] 758 keys = keys or [] 759 depth = dict_depth(schema) - 1 if depth is None else depth 760 761 for k, v in schema.items(): 762 if depth == 1 or not isinstance(v, dict): 763 tables.append(keys + [k]) 764 elif depth >= 2: 765 tables.extend(flatten_schema(v, depth - 1, keys + [k])) 766 767 return tables
770def nested_get( 771 d: dict[str, object], *path: tuple[str, str], raise_on_missing: bool = True 772) -> t.Any | None: 773 """ 774 Get a value for a nested dictionary. 775 776 Args: 777 d: the dictionary to search. 778 *path: tuples of (name, key), where: 779 `key` is the key in the dictionary to get. 780 `name` is a string to use in the error if `key` isn't found. 781 782 Returns: 783 The value or None if it doesn't exist. 784 """ 785 result: t.Any = d 786 for name, key in path: 787 result = result.get(key) 788 if result is None: 789 if raise_on_missing: 790 name = "table" if name == "this" else name 791 raise ValueError(f"Unknown {name}: {key}") 792 return None 793 794 return result
Get a value for a nested dictionary.
Arguments:
- d: the dictionary to search.
- *path: tuples of (name, key), where:
keyis the key in the dictionary to get.nameis a string to use in the error ifkeyisn't found.
Returns:
The value or None if it doesn't exist.
797def nested_set(d: dict[str, t.Any], keys: Sequence[str], value: t.Any) -> dict[str, t.Any]: 798 """ 799 In-place set a value for a nested dictionary 800 801 Example: 802 >>> nested_set({}, ["top_key", "second_key"], "value") 803 {'top_key': {'second_key': 'value'}} 804 805 >>> nested_set({"top_key": {"third_key": "third_value"}}, ["top_key", "second_key"], "value") 806 {'top_key': {'third_key': 'third_value', 'second_key': 'value'}} 807 808 Args: 809 d: dictionary to update. 810 keys: the keys that makeup the path to `value`. 811 value: the value to set in the dictionary for the given key path. 812 813 Returns: 814 The (possibly) updated dictionary. 815 """ 816 if not keys: 817 return d 818 819 if len(keys) == 1: 820 d[keys[0]] = value 821 return d 822 823 subd = d 824 for key in keys[:-1]: 825 if key not in subd: 826 subd = subd.setdefault(key, {}) 827 else: 828 subd = subd[key] 829 830 subd[keys[-1]] = value 831 return d
In-place set a value for a nested dictionary
Example:
>>> nested_set({}, ["top_key", "second_key"], "value") {'top_key': {'second_key': 'value'}}>>> nested_set({"top_key": {"third_key": "third_value"}}, ["top_key", "second_key"], "value") {'top_key': {'third_key': 'third_value', 'second_key': 'value'}}
Arguments:
- d: dictionary to update.
- keys: the keys that makeup the path to
value. - value: the value to set in the dictionary for the given key path.
Returns:
The (possibly) updated dictionary.