sqlleaf 0.0.4__py3-none-any.whl → 0.0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. sqlleaf/dialects/__init__.py +19 -0
  2. sqlleaf/dialects/athena/__init__.py +0 -0
  3. sqlleaf/dialects/athena/config.py +84 -0
  4. sqlleaf/{settings → dialects}/base.py +22 -2
  5. sqlleaf/dialects/loader.py +51 -0
  6. sqlleaf/dialects/postgres/__init__.py +0 -0
  7. sqlleaf/{settings/postgres.py → dialects/postgres/config.py} +10 -5
  8. sqlleaf/lineage.py +48 -3
  9. sqlleaf/mappings.py +148 -43
  10. sqlleaf/models/node/__init__.py +25 -0
  11. sqlleaf/models/node/column.py +38 -6
  12. sqlleaf/models/node/counter.py +16 -0
  13. sqlleaf/models/node/dynamodb.py +2 -2
  14. sqlleaf/models/node/function.py +2 -2
  15. sqlleaf/models/node/interval.py +2 -2
  16. sqlleaf/models/node/json.py +2 -2
  17. sqlleaf/models/node/literal.py +2 -2
  18. sqlleaf/models/node/null.py +2 -2
  19. sqlleaf/models/node/pivot.py +3 -3
  20. sqlleaf/models/node/program.py +2 -2
  21. sqlleaf/models/node/sequence.py +2 -2
  22. sqlleaf/models/node/star.py +2 -2
  23. sqlleaf/models/node/stream.py +2 -2
  24. sqlleaf/models/node/user_defined_function.py +2 -2
  25. sqlleaf/models/node/var.py +2 -2
  26. sqlleaf/models/node/variable.py +2 -2
  27. sqlleaf/models/node/window.py +2 -2
  28. sqlleaf/models/query/__init__.py +2 -0
  29. sqlleaf/models/query/base.py +1 -1
  30. sqlleaf/models/query/copy.py +2 -2
  31. sqlleaf/models/query/ctas.py +3 -0
  32. sqlleaf/models/query/open.py +1 -1
  33. sqlleaf/models/query/reset.py +30 -0
  34. sqlleaf/models/query/set.py +56 -6
  35. sqlleaf/models/query/table.py +26 -5
  36. sqlleaf/models/query/view.py +66 -0
  37. sqlleaf/path.py +21 -1
  38. sqlleaf/processors/collector/classify.py +22 -0
  39. sqlleaf/processors/collector/collector.py +95 -6
  40. sqlleaf/processors/generator/dialects/base.py +18 -7
  41. sqlleaf/processors/generator/generator.py +8 -1
  42. sqlleaf/processors/substitutor/substitute.py +39 -13
  43. sqlleaf/processors/transformer/base.py +112 -47
  44. sqlleaf/processors/transformer/copy.py +4 -4
  45. sqlleaf/processors/transformer/ctas.py +2 -3
  46. sqlleaf/processors/transformer/delete.py +2 -1
  47. sqlleaf/processors/transformer/expressions/__init__.py +3 -0
  48. sqlleaf/processors/transformer/expressions/functional_notation.py +1 -2
  49. sqlleaf/processors/transformer/expressions/operator.py +32 -0
  50. sqlleaf/processors/transformer/expressions/row.py +1 -2
  51. sqlleaf/processors/transformer/for_in.py +1 -1
  52. sqlleaf/processors/transformer/insert.py +3 -4
  53. sqlleaf/processors/transformer/merge.py +2 -1
  54. sqlleaf/processors/transformer/open.py +2 -2
  55. sqlleaf/processors/transformer/transformer.py +9 -9
  56. sqlleaf/processors/transformer/unload.py +1 -1
  57. sqlleaf/processors/transformer/update.py +4 -5
  58. sqlleaf/typing.py +7 -13
  59. sqlleaf/util/expression.py +3 -3
  60. {sqlleaf-0.0.4.dist-info → sqlleaf-0.0.7.dist-info}/METADATA +43 -5
  61. {sqlleaf-0.0.4.dist-info → sqlleaf-0.0.7.dist-info}/RECORD +64 -59
  62. sqlleaf/settings/__init__.py +0 -19
  63. sqlleaf/settings/athena.py +0 -23
  64. {sqlleaf-0.0.4.dist-info → sqlleaf-0.0.7.dist-info}/WHEEL +0 -0
  65. {sqlleaf-0.0.4.dist-info → sqlleaf-0.0.7.dist-info}/licenses/LICENSE +0 -0
  66. {sqlleaf-0.0.4.dist-info → sqlleaf-0.0.7.dist-info}/top_level.txt +0 -0
@@ -1 +1,20 @@
1
1
  from sqlleaf.dialects.plpgsql.p_dialect import PlPgSQL
2
+
3
+ from functools import cache
4
+
5
+ from sqlglot import exp
6
+
7
+ from sqlleaf.dialects.athena.config import AthenaSettings as AthenaSettings
8
+ from sqlleaf.dialects.base import BaseDialectSettings as BaseDialectSettings
9
+ from sqlleaf.dialects.postgres.config import PostgresSettings as PostgresSettings
10
+
11
+
12
+ @cache
13
+ def system_columns(dialect: str) -> list[exp.ColumnDef]:
14
+ return BaseDialectSettings.from_dialect(dialect).system_columns
15
+
16
+
17
+ @cache
18
+ def system_functions(dialect: str) -> dict[str, list[str]]:
19
+ # TODO: refactor this into a set of objects that can be loaded into the mapping
20
+ return BaseDialectSettings.from_dialect(dialect).system_functions
File without changes
@@ -0,0 +1,84 @@
1
+ from sqlglot import exp
2
+
3
+ from sqlleaf.dialects.base import BaseDialectSettings
4
+
5
+
6
+ class AthenaSettings(BaseDialectSettings):
7
+ DIALECT = "athena"
8
+ DEFAULT_USER_CATALOG = "awsdatacatalog"
9
+ DEFAULT_SYSTEM_CATALOG = ""
10
+ PSEUDOCOLUMNS = {
11
+ "$bucket": "BIGINT",
12
+ "$file_modified_time": "TIMESTAMP",
13
+ "$file_size": "BIGINT",
14
+ "$partition": "VARCHAR",
15
+ "$path": "VARCHAR",
16
+ }
17
+ # Iceberg metadata fields
18
+ METADATA_FIELDS = {
19
+ "$files": {
20
+ "content": "INTEGER",
21
+ "file_path": "VARCHAR",
22
+ "file_format": "VARCHAR",
23
+ "record_count": "BIGINT",
24
+ "file_size_in_bytes": "BIGINT",
25
+ "column_sizes": "MAP(INTEGER, BIGINT)",
26
+ "value_counts": "MAP(INTEGER, BIGINT)",
27
+ "null_value_counts": "MAP(INTEGER, BIGINT)",
28
+ "nan_value_counts": "MAP(INTEGER, BIGINT)",
29
+ "lower_bounds": "MAP(INTEGER, VARCHAR)",
30
+ "upper_bounds": "MAP(INTEGER, VARCHAR)",
31
+ "key_metadata": "VARBINARY",
32
+ "split_offsets": "ARRAY(BIGINT)",
33
+ "equality_ids": "ARRAY(INTEGER)",
34
+ },
35
+ "$manifests": {
36
+ "path": "VARCHAR",
37
+ "length": "BIGINT",
38
+ "partition_spec_id": "INTEGER",
39
+ "added_snapshot_id": "BIGINT",
40
+ "added_data_files_count": "INTEGER",
41
+ "added_rows_count": "BIGINT",
42
+ "existing_data_files_count": "INTEGER",
43
+ "existing_rows_count": "BIGINT",
44
+ "deleted_data_files_count": "INTEGER",
45
+ "deleted_rows_count": "BIGINT",
46
+ "partitions": "ARRAY(STRUCT(contains_null BOOLEAN, contains_nan BOOLEAN, lower_bound VARCHAR, upper_bound VARCHAR))",
47
+ },
48
+ "$history": {
49
+ "made_current_at": "TIMESTAMP WITH TIME ZONE",
50
+ "snapshot_id": "BIGINT",
51
+ "parent_id": "BIGINT",
52
+ "is_current_ancestor": "BOOLEAN",
53
+ },
54
+ "$partitions": {
55
+ "partition": "STRUCT(category VARCHAR)",
56
+ "record_count": "BIGINT",
57
+ "file_count": "BIGINT",
58
+ "total_size": "BIGINT",
59
+ "data": "STRUCT(id STRUCT(min BIGINT, max BIGINT, null_count BIGINT, nan_count BIGINT), data STRUCT(min VARCHAR, max VARCHAR, null_count BIGINT, nan_count BIGINT))",
60
+ },
61
+ "$snapshots": {
62
+ "committed_at": "TIMESTAMP WITH TIME ZONE",
63
+ "snapshot_id": "BIGINT",
64
+ "parent_id": "BIGINT",
65
+ "operation": "VARCHAR",
66
+ "manifest_list": "VARCHAR",
67
+ "summary": "MAP(VARCHAR, VARCHAR)",
68
+ },
69
+ "$refs": {
70
+ "name": "VARCHAR",
71
+ "type": "VARCHAR",
72
+ "snapshot_id": "BIGINT",
73
+ "max_reference_age_in_ms": "BIGINT",
74
+ "min_snapshots_to_keep": "INTEGER",
75
+ "max_snapshot_age_in_ms": "BIGINT",
76
+ },
77
+ }
78
+
79
+ @property
80
+ def system_columns(self) -> list[exp.ColumnDef]:
81
+ return [
82
+ exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
83
+ for name, kind in self.PSEUDOCOLUMNS.items()
84
+ ]
@@ -1,5 +1,3 @@
1
- import typing as t
2
-
3
1
  from sqlglot import exp
4
2
 
5
3
 
@@ -7,6 +5,10 @@ class BaseDialectSettings:
7
5
  # A registry to store subclasses
8
6
  _dialects = {}
9
7
  DIALECT = ""
8
+ DEFAULT_USER_CATALOG = ""
9
+ DEFAULT_SYSTEM_CATALOG = ""
10
+ # Metadata fields, keyed by their suffix (e.g. '$files' in 'my_table$files'), mapped to their column names and types
11
+ METADATA_FIELDS: dict[str, dict[str, str]] = {}
10
12
 
11
13
  def __init_subclass__(cls, **kwargs):
12
14
  """Automatically registers subclasses when they are defined."""
@@ -35,3 +37,21 @@ class BaseDialectSettings:
35
37
  Represents system functions.
36
38
  """
37
39
  return {}
40
+
41
+ def get_metadata_field(self, table_name: str) -> str | None:
42
+ """
43
+ Returns the metadata field of a table name (e.g. '$files' for 'my_table$files').
44
+ """
45
+ for suffix in self.METADATA_FIELDS:
46
+ if table_name.lower().endswith(suffix):
47
+ return suffix
48
+ return None
49
+
50
+ def get_metadata_field_column_defs(self, suffix: str) -> list[exp.ColumnDef]:
51
+ """
52
+ Returns the column definitions of the metadata table with the given field (e.g. '$files').
53
+ """
54
+ return [
55
+ exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
56
+ for name, kind in self.METADATA_FIELDS[suffix].items()
57
+ ]
@@ -0,0 +1,51 @@
1
+ import re
2
+ from functools import cache
3
+ from pathlib import Path
4
+
5
+ TABLE_HEADER = re.compile(r"^CREATE TABLE (\w+)\.(\w+) \(", re.MULTILINE)
6
+ VIEW_HEADER = re.compile(r"^CREATE VIEW (\w+)\.(\w+) AS", re.MULTILINE)
7
+ SCHEMA_HEADER = re.compile(r"^CREATE SCHEMA (\w+);", re.MULTILINE)
8
+
9
+ KINDS = {
10
+ "tables": (TABLE_HEADER, "\n);"),
11
+ "views": (VIEW_HEADER, ";\n"),
12
+ "schemas": (SCHEMA_HEADER, ";\n"),
13
+ }
14
+
15
+
16
+ @cache
17
+ def _read_system_objects(dialect: str, kind: str) -> tuple[str, dict[tuple[str, ...], tuple[int, int]]]:
18
+ """
19
+ Read the system objects from disk.
20
+ """
21
+ path = Path(__file__).parent / dialect / "system_objects" / f"{kind}.sql"
22
+ if not path.exists():
23
+ return "", {}
24
+
25
+ header, statement_end = KINDS[kind]
26
+ text = path.read_text()
27
+ if kind in ("tables", "views"):
28
+ # sqlglot fails when parsing 'oid[]'
29
+ text = text.replace("oid[]", "array<oid>")
30
+ index = {}
31
+ for match in header.finditer(text):
32
+ end = text.index(statement_end, match.start()) + len(statement_end)
33
+ index[tuple(group.lower() for group in match.groups())] = (match.start(), end)
34
+ return text, index
35
+
36
+
37
+ def _lookup(dialect: str, kind: str, key: tuple[str, ...]) -> str | None:
38
+ text, index = _read_system_objects(dialect, kind)
39
+ span = index.get(key)
40
+ if span is None:
41
+ return None
42
+ return text[span[0] : span[1]]
43
+
44
+
45
+ def get_object_ddl(schema: str, table: str, dialect: str) -> str | None:
46
+ key = (schema.lower(), table.lower())
47
+ return _lookup(dialect, "tables", key) or _lookup(dialect, "views", key)
48
+
49
+
50
+ def get_schema_ddl(schema: str, dialect: str) -> str | None:
51
+ return _lookup(dialect, "schemas", (schema.lower(),))
File without changes
@@ -1,13 +1,13 @@
1
- import typing as t
2
-
3
1
  from sqlglot import exp
4
2
  from sqlglot.dialects import postgres
5
3
 
6
- from sqlleaf.settings.base import BaseDialectSettings
4
+ from sqlleaf.dialects.base import BaseDialectSettings
7
5
 
8
6
 
9
7
  class PostgresSettings(BaseDialectSettings):
10
8
  DIALECT = "postgres"
9
+ DEFAULT_USER_CATALOG = "public"
10
+ DEFAULT_SYSTEM_CATALOG = "pg_catalog"
11
11
  PSEUDOCOLUMNS = {
12
12
  "cmax": "OID",
13
13
  "cmin": "OID",
@@ -31,7 +31,7 @@ class PostgresSettings(BaseDialectSettings):
31
31
  Map function names to their returned column names.
32
32
  """
33
33
  return {
34
- "aclexplode": ["grantor, grantee, privilege_type, is_grantable"],
34
+ "aclexplode": ["grantor", "grantee", "privilege_type", "is_grantable"],
35
35
  "json_array_elements": ["value"],
36
36
  "json_array_elements_text": ["value"],
37
37
  "json_each": ["key", "value"],
@@ -40,7 +40,7 @@ class PostgresSettings(BaseDialectSettings):
40
40
  "jsonb_array_elements_text": ["value"],
41
41
  "jsonb_each": ["key", "value"],
42
42
  "jsonb_each_text": ["key", "value"],
43
- "ts_debug": ["alias, description, token, dictionaries, dictionary, lexemes"],
43
+ "ts_debug": ["alias", "description", "token", "dictionaries", "dictionary", "lexemes"],
44
44
  "ts_parse": ["tokid", "token"],
45
45
  "ts_stat": ["word", "ndoc", "nentry"],
46
46
  "ts_token_type": ["tokid", "alias", "description"],
@@ -49,4 +49,9 @@ class PostgresSettings(BaseDialectSettings):
49
49
 
50
50
  # sqlglot is missing pseudocolumns for Postgres
51
51
  postgres.Postgres.PSEUDOCOLUMNS = {c.upper() for c in PostgresSettings.PSEUDOCOLUMNS.keys()}
52
+
53
+ # Prevents pseudocolumns from being included in 'SELECT *' expansions
52
54
  postgres.Postgres.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR = True
55
+
56
+ # Prevents sqlglot's optimizer from assigning [n+1] to arrays of [n]
57
+ postgres.Postgres.INDEX_OFFSET = 0
sqlleaf/lineage.py CHANGED
@@ -6,7 +6,7 @@ import networkx as nx
6
6
 
7
7
  from sqlleaf import exception, mappings, path, util
8
8
  from sqlleaf.models.hook import Hook
9
- from sqlleaf.models.node import EdgeAttributes, GraphAttributes, N
9
+ from sqlleaf.models.node import EdgeAttributes, GraphAttributes, N, NodeAttributes
10
10
  from sqlleaf.models.query import (
11
11
  Q,
12
12
  )
@@ -37,8 +37,7 @@ class Lineage:
37
37
  """
38
38
  exception.set_error_action(action=on_error)
39
39
 
40
- if not self.object_mapping:
41
- self.object_mapping = mappings.ObjectMapping(dialect=dialect)
40
+ self.init_object_mapping(dialect)
42
41
 
43
42
  self.collected_queries = collector.collect_queries(
44
43
  text=sql, dialect=dialect, object_mapping=self.object_mapping
@@ -80,6 +79,7 @@ class Lineage:
80
79
  edge_data["attrs"].child = old_node_attrs
81
80
  else:
82
81
  self.graph.add_node(n, **data)
82
+ self.object_mapping.node_index.add(data["attrs"])
83
83
 
84
84
  self.graph.add_edges_from(subgraph.edges(data=True))
85
85
 
@@ -98,6 +98,46 @@ class Lineage:
98
98
  )
99
99
  return nodes
100
100
 
101
+ def find_nodes(self, *nodes: NodeAttributes) -> list[NodeAttributes]:
102
+ """
103
+ Find a set of nodes in the graph matching the given node instances.
104
+
105
+ This allows nodes to be found without knowing their positions.
106
+
107
+ This uses an index/map structure because the keys of the full node names contain
108
+ the positions of each node to identify them uniquely. For example, two literal
109
+ expressions for "abc" are assigned their own positions to distinguish them from each other.
110
+
111
+ Examples:
112
+ # Find all columns whose name is 'price'
113
+ find_node(ColumnNode(column="price"))
114
+
115
+ # Find two columns: one unqualified, another fully qualified
116
+ find_node(ColumnNode(column="age"), ColumnNode(schema="fruit", table="raw", column="name"))
117
+
118
+ # Find all functions
119
+ find_node(FunctionNode())
120
+ """
121
+ if self.object_mapping is None:
122
+ return []
123
+
124
+ found: list[NodeAttributes] = []
125
+ seen: set[str] = set()
126
+
127
+ for query in nodes:
128
+ candidates = self.object_mapping.node_index.get(type(query))
129
+ if query.name != "":
130
+ query_name = query.get_name()
131
+ candidates = [node for node in candidates if node.get_name() == query_name]
132
+
133
+ for node in candidates:
134
+ if node.full_name not in seen:
135
+ seen.add(node.full_name)
136
+ found.append(node)
137
+
138
+ return found
139
+
140
+
101
141
  def get_original_queries(self) -> list[Q]:
102
142
  """
103
143
  Get the original queries from the graph.
@@ -262,6 +302,11 @@ class Lineage:
262
302
  """
263
303
  self.user_defined_hooks = [udh for udh in self.user_defined_hooks if udh not in hooks]
264
304
 
305
+ def init_object_mapping(self, dialect: str):
306
+ if not self.object_mapping:
307
+ self.object_mapping = mappings.ObjectMapping(dialect=dialect, object_loader=collector.SystemObjectLoader(dialect))
308
+
309
+
265
310
  def new_graph() -> nx.MultiDiGraph:
266
311
  """
267
312
  A graph has attributes along with its node and edges.
sqlleaf/mappings.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import logging
4
4
  import typing as t
5
+ from dataclasses import dataclass, field
5
6
 
6
7
  from sqlglot import MappingSchema, exp
7
8
  from sqlglot.dialects.dialect import DialectType
@@ -10,6 +11,8 @@ from sqlglot.schema import nested_set
10
11
  from sqlglot.trie import new_trie
11
12
 
12
13
  from sqlleaf import exception, util
14
+ from sqlleaf.dialects.base import BaseDialectSettings
15
+ from sqlleaf.path import NodeIndex
13
16
  from sqlleaf.models.query import (
14
17
  CallQuery,
15
18
  CTASQuery,
@@ -34,57 +37,89 @@ FunctionCallable = ProcedureQuery | UserDefinedFunctionQuery
34
37
  logger = logging.getLogger("sqlleaf")
35
38
 
36
39
 
37
- class ObjectMapping(MappingSchema):
38
- """
39
- Contains all the objects that get created, such as tables, procedures, functions, and sequences.
40
+ @dataclass
41
+ class ParamBinding:
42
+ """One parameter's binding for the lifetime of a single CALL."""
40
43
 
41
- We extends sqlglot.MappingSchema to provide additional functionality related to tracking these objects,
42
- while still allowing optimizer inside sqlglot to work (as it needs a mapping of objects to perform functions
43
- like qualification and simplification).
44
- """
44
+ value: exp.Expr
45
+ arg_name: str | None = None
45
46
 
46
- def __init__(self, dialect: str):
47
- super().__init__(
48
- dialect=dialect, normalize=False
49
- ) # Set `normalize=False` to prevent an unnecessary second parse.
50
- self.kind_mapping = {}
51
- self.kind_mapping_trie = {}
52
- # Session/global variables (e.g., SET var = ...)
53
- self.session_variables: dict[str, exp.Expr] = {}
54
- # Block-scoped variables: one dict per active block, innermost scope at the end
55
- self.variable_scopes: list[dict[str, exp.Expr]] = []
56
47
 
57
- # ---- Variable scope API ----
58
- def push_variable_scope(self) -> None:
59
- """Enter a new block scope."""
60
- self.variable_scopes.append({})
48
+ @dataclass
49
+ class VariableScope:
50
+ """One CALL boundary: its block stack and parameter bindings."""
51
+
52
+ blocks: list[dict[str, exp.Expr]] = field(default_factory=list)
53
+ bindings: dict[str, ParamBinding] = field(default_factory=dict)
54
+
55
+
56
+ class Variables:
57
+ def __init__(self):
58
+ # The base scope runs DO / top-level code and is never popped
59
+ self.scopes: list[VariableScope] = [VariableScope()]
60
+
61
+ @property
62
+ def _active_blocks(self) -> list[dict[str, exp.Expr]]:
63
+ return self.scopes[-1].blocks
61
64
 
62
- def pop_variable_scope(self) -> None:
63
- """Leave the current block scope."""
64
- if self.variable_scopes:
65
- self.variable_scopes.pop()
65
+ @property
66
+ def _active_bindings(self) -> dict[str, ParamBinding]:
67
+ return self.scopes[-1].bindings
68
+
69
+ # ---- Block API ----
70
+ def push_block(self) -> None:
71
+ """Enter a new DECLARE/BEGIN block."""
72
+ self._active_blocks.append({})
73
+
74
+ def pop_block(self) -> None:
75
+ """Leave the current DECLARE/BEGIN block."""
76
+ if self._active_blocks:
77
+ self._active_blocks.pop()
78
+
79
+ # ---- Scope API ----
80
+ def push_scope(self, bindings: dict[str, ParamBinding]) -> None:
81
+ """Enter a CALL boundary."""
82
+ self.scopes.append(VariableScope(bindings=bindings))
83
+
84
+ def pop_scope(self, write_back: bool = True) -> None:
85
+ """Leave the current CALL boundary, optionally writing OUT/INOUT values back to the caller."""
86
+ if len(self.scopes) == 1:
87
+ raise exception.MappingError("Cannot pop the base variable scope")
88
+ scope = self.scopes.pop()
89
+ if write_back:
90
+ for binding in scope.bindings.values():
91
+ if binding.arg_name is not None:
92
+ self.set_variable(binding.arg_name, binding.value)
66
93
 
67
94
  def declare_variable(self, name: str, value: exp.Expr | None = None) -> None:
68
- """Declare a variable in the current (innermost) scope."""
95
+ """Declare a variable in the current (innermost) block."""
69
96
  val = value if value is not None else exp.Null()
70
- self.variable_scopes[-1][name] = val
71
- logger.debug(f"Declared variable: {name} := {val.sql(dialect=self.dialect)}")
97
+ self._active_blocks[-1][name] = val
98
+ logger.debug(f"Declared variable: {name} := {val}")
72
99
 
73
100
  def set_variable(self, name: str, value: exp.Expr) -> None:
74
- """Assign a variable in the nearest scope where it was declared."""
75
- for scope in reversed(self.variable_scopes):
76
- if name in scope:
77
- scope[name] = value
78
- logger.debug(f"Set variable value: {name} := {value.sql(dialect=self.dialect)}")
101
+ """Assign a variable in the nearest block where it was declared."""
102
+ for block in reversed(self._active_blocks):
103
+ if name in block:
104
+ block[name] = value
105
+ logger.debug(f"Set variable value: {name} := {value}")
79
106
  return
80
107
 
108
+ binding = self._active_bindings.get(name)
109
+ if binding is not None:
110
+ binding.value = value
111
+ return
112
+
81
113
  raise exception.MappingError(f'"{name}" is not a known variable')
82
114
 
83
115
  def get_variable(self, name: str, raise_on_missing: bool = True) -> exp.Expr | None:
84
- """Resolve a variable by searching from innermost to outermost scopes."""
85
- for scope in reversed(self.variable_scopes):
86
- if name in scope:
87
- return scope[name]
116
+ """Resolve a variable by searching from innermost block outward, then the call's bindings."""
117
+ for block in reversed(self._active_blocks):
118
+ if name in block:
119
+ return block[name]
120
+ binding = self._active_bindings.get(name)
121
+ if binding is not None:
122
+ return binding.value
88
123
  if raise_on_missing:
89
124
  raise exception.MappingError(f"Could not find value for variable: {name}")
90
125
  return None
@@ -110,8 +145,40 @@ class ObjectMapping(MappingSchema):
110
145
  return resolved
111
146
 
112
147
  def get_scope(self) -> dict[str, exp.Expr]:
113
- """Return the current scope dict (innermost)."""
114
- return self.variable_scopes[-1]
148
+ """Return the current block dict (innermost)."""
149
+ return self._active_blocks[-1]
150
+
151
+
152
+ class ObjectMapping(MappingSchema):
153
+ """
154
+ Contains all the objects that get created, such as tables, procedures, functions, and sequences.
155
+
156
+ We extends sqlglot.MappingSchema to provide additional functionality related to tracking these objects,
157
+ while still allowing optimizer inside sqlglot to work (as it needs a mapping of objects to perform functions
158
+ like qualification and simplification).
159
+ """
160
+
161
+ def __init__(
162
+ self,
163
+ dialect: str,
164
+ object_loader: t.Callable[[ObjectMapping, exp.Table, str], None] | None = None,
165
+ ):
166
+ super().__init__(
167
+ dialect=dialect, normalize=False
168
+ ) # Set `normalize=False` to prevent an unnecessary second parse.
169
+ self.kind_mapping = {}
170
+ self.kind_mapping_trie = {}
171
+ settings = BaseDialectSettings.from_dialect(dialect)
172
+ # The catalog that unqualified user objects are created in, and the one holding system objects
173
+ self.current_user_catalog: str = settings.DEFAULT_USER_CATALOG
174
+ self.current_system_catalog: str = settings.DEFAULT_SYSTEM_CATALOG
175
+ # Load system objects lazily from disk
176
+ self.system_object_loader = object_loader
177
+ # Session/global variables (e.g., SET var = ...)
178
+ self.session_variables: dict[str, exp.Expr] = {}
179
+ self.variables = Variables()
180
+ # Nodes that have been added to the graph, indexed by class
181
+ self.node_index = NodeIndex()
115
182
 
116
183
  def add_database_query(self, query: DatabaseQuery) -> None:
117
184
  self._add_query(query=query, dialect=query.dialect)
@@ -134,6 +201,26 @@ class ObjectMapping(MappingSchema):
134
201
  def add_table_query(
135
202
  self, query: TableQuery | ViewQuery | CTASQuery, column_mapping: ColumnMapping | None = None
136
203
  ) -> None:
204
+ if isinstance(query, TableQuery):
205
+ table = query.get_target_as_table()
206
+ if self._lookup_query(kind="table", object=table, raise_on_missing=False) is not None:
207
+ # A repeated 'CREATE TABLE' keeps the original definition; 'IF NOT EXISTS' prevents an error
208
+ if not query.statement.args.get("exists"):
209
+ exception.raise_error(
210
+ exception.MappingError,
211
+ f"Table '{table.sql()}' already exists.",
212
+ )
213
+ return
214
+ elif isinstance(query, ViewQuery) and not query.statement.args.get("replace"):
215
+ table = query.get_target_as_table()
216
+ if self._lookup_query(kind="table", object=table, raise_on_missing=False) is not None:
217
+ # A repeated 'CREATE VIEW' keeps the original definition; 'CREATE OR REPLACE VIEW' overwrites it
218
+ exception.raise_error(
219
+ exception.MappingError,
220
+ f"View '{table.sql()}' already exists.",
221
+ )
222
+ return
223
+
137
224
  self._add_query(query=query, column_mapping=column_mapping, dialect=query.dialect, kind="table")
138
225
 
139
226
  def add_trigger_query(self, query: TriggerQuery) -> None:
@@ -221,6 +308,14 @@ class ObjectMapping(MappingSchema):
221
308
  match_depth=match_depth,
222
309
  )
223
310
 
311
+ def handle_missing_object(self, object: exp.Table, kind: str = "table") -> None:
312
+ if self.system_object_loader is not None:
313
+ self.system_object_loader(self, object, kind)
314
+
315
+ def find(self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False) -> t.Any | None:
316
+ self.handle_missing_object(table)
317
+ return super().find(table, raise_on_missing=raise_on_missing, ensure_data_types=ensure_data_types)
318
+
224
319
  def find_columns_for_table(
225
320
  self,
226
321
  table: exp.Table,
@@ -243,6 +338,9 @@ class ObjectMapping(MappingSchema):
243
338
  # A procedure can be overloaded with different parameters, thus we return a list
244
339
  return self._lookup_query(kind="procedure", object=table, raise_on_missing=raise_on_missing)
245
340
 
341
+ def lookup_schema_query(self, schema: exp.Table, raise_on_missing: bool = True) -> SchemaQuery | None:
342
+ return self._lookup_query(kind="schema", object=schema, raise_on_missing=raise_on_missing)
343
+
246
344
  def lookup_sequence_query(self, table: exp.Table, raise_on_missing: bool = True) -> SequenceQuery | None:
247
345
  return self._lookup_query(kind="sequence", object=table, raise_on_missing=raise_on_missing)
248
346
 
@@ -284,6 +382,9 @@ class ObjectMapping(MappingSchema):
284
382
  Returns:
285
383
  The schema of the target object.
286
384
  """
385
+ if kind in ("table", "schema"):
386
+ self.handle_missing_object(object, kind=kind)
387
+
287
388
  if kind not in self.kind_mapping:
288
389
  if raise_on_missing:
289
390
  if kind == "prepare":
@@ -356,7 +457,9 @@ class ObjectMapping(MappingSchema):
356
457
 
357
458
  return resolve_overloaded_function(node, candidates)
358
459
 
359
- def lookup_procedure_call(self, node: CallQuery) -> ProcedureQuery | None:
460
+ def lookup_procedure_call(
461
+ self, node: CallQuery, args: list[exp.Expr] | None = None
462
+ ) -> ProcedureQuery | None:
360
463
  """
361
464
  Looks up the procedure definition for a CALL statement.
362
465
  Returns the matched procedure definition, or None if no procedure with that name exists.
@@ -367,11 +470,11 @@ class ObjectMapping(MappingSchema):
367
470
  return None
368
471
 
369
472
  # Annotate copies so the call's own expressions are left untouched
370
- args = [arg.copy() for arg in node.args]
371
- for arg in args:
473
+ call_args = [arg.copy() for arg in (args if args is not None else node.args)]
474
+ for arg in call_args:
372
475
  annotate_types(_get_call_arg_value(arg), dialect=self.dialect, schema=self)
373
476
 
374
- return resolve_overloaded_procedure(args, candidates)
477
+ return resolve_overloaded_procedure(call_args, candidates)
375
478
 
376
479
 
377
480
  def resolve_overloaded_function(
@@ -504,6 +607,8 @@ def match_callable_arguments(args: list[exp.Expr], params: list[FunctionParam])
504
607
  if param.default is None and not param.is_variadic:
505
608
  return False
506
609
  elif param.is_input and not isinstance(bound[i], exp.Null):
610
+ if param.is_output and isinstance(bound[i], exp.Column) and not bound[i].table:
611
+ continue
507
612
  if not _match_argument(bound[i], param.type):
508
613
  return False
509
614
 
@@ -1,11 +1,36 @@
1
1
  import typing as t
2
2
 
3
+ from enum import StrEnum, auto
4
+
5
+ class NodeKind(StrEnum):
6
+ COLUMN = auto()
7
+ COUNTER = auto()
8
+ DYNAMODB = auto()
9
+ FUNCTION = auto()
10
+ INTERVAL = auto()
11
+ JSONPATH = auto()
12
+ LITERAL = auto()
13
+ NULL = auto()
14
+ PIVOT = auto()
15
+ UNPIVOT = auto()
16
+ PROGRAM = auto()
17
+ SEQUENCE = auto()
18
+ STAR = auto()
19
+ STREAM = auto()
20
+ UDF = auto()
21
+ VAR = auto()
22
+ VARIABLE = auto()
23
+ WINDOW = auto()
24
+
25
+ # Base classes
3
26
  from sqlleaf.models.node.base import EdgeAttributes as EdgeAttributes
4
27
  from sqlleaf.models.node.base import GraphAttributes as GraphAttributes
5
28
  from sqlleaf.models.node.base import NodeAttributes as NodeAttributes
29
+ # Node classes
6
30
  from sqlleaf.models.node.column import ColumnNode as ColumnNode
7
31
  from sqlleaf.models.node.column import FileColumnNode as FileColumnNode
8
32
  from sqlleaf.models.node.column import StageColumnNode as StageColumnNode
33
+ from sqlleaf.models.node.counter import CounterNode as CounterNode
9
34
  from sqlleaf.models.node.dynamodb import DynamoDbNode as DynamoDbNode
10
35
  from sqlleaf.models.node.function import FunctionNode as FunctionNode
11
36
  from sqlleaf.models.node.interval import IntervalNode as IntervalNode