sqlleaf 0.0.5__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.
- sqlleaf/dialects/__init__.py +19 -0
- sqlleaf/dialects/athena/__init__.py +0 -0
- sqlleaf/dialects/athena/config.py +84 -0
- sqlleaf/{settings → dialects}/base.py +22 -2
- sqlleaf/dialects/loader.py +51 -0
- sqlleaf/dialects/postgres/__init__.py +0 -0
- sqlleaf/{settings/postgres.py → dialects/postgres/config.py} +10 -5
- sqlleaf/lineage.py +48 -3
- sqlleaf/mappings.py +49 -1
- sqlleaf/models/node/__init__.py +25 -0
- sqlleaf/models/node/column.py +38 -6
- sqlleaf/models/node/counter.py +16 -0
- sqlleaf/models/node/dynamodb.py +2 -2
- sqlleaf/models/node/function.py +2 -2
- sqlleaf/models/node/interval.py +2 -2
- sqlleaf/models/node/json.py +2 -2
- sqlleaf/models/node/literal.py +2 -2
- sqlleaf/models/node/null.py +2 -2
- sqlleaf/models/node/pivot.py +3 -3
- sqlleaf/models/node/program.py +2 -2
- sqlleaf/models/node/sequence.py +2 -2
- sqlleaf/models/node/star.py +2 -2
- sqlleaf/models/node/stream.py +2 -2
- sqlleaf/models/node/user_defined_function.py +2 -2
- sqlleaf/models/node/var.py +2 -2
- sqlleaf/models/node/variable.py +2 -2
- sqlleaf/models/node/window.py +2 -2
- sqlleaf/models/query/__init__.py +2 -0
- sqlleaf/models/query/ctas.py +3 -0
- sqlleaf/models/query/reset.py +30 -0
- sqlleaf/models/query/set.py +56 -6
- sqlleaf/models/query/table.py +26 -5
- sqlleaf/models/query/view.py +66 -0
- sqlleaf/path.py +21 -1
- sqlleaf/processors/collector/classify.py +22 -0
- sqlleaf/processors/collector/collector.py +84 -2
- sqlleaf/processors/generator/dialects/base.py +15 -4
- sqlleaf/processors/generator/generator.py +8 -1
- sqlleaf/processors/transformer/base.py +80 -3
- sqlleaf/processors/transformer/expressions/__init__.py +3 -0
- sqlleaf/processors/transformer/expressions/operator.py +32 -0
- sqlleaf/typing.py +5 -0
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.7.dist-info}/METADATA +43 -5
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.7.dist-info}/RECORD +47 -42
- sqlleaf/settings/__init__.py +0 -19
- sqlleaf/settings/athena.py +0 -23
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.7.dist-info}/WHEEL +0 -0
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.7.dist-info}/licenses/LICENSE +0 -0
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.7.dist-info}/top_level.txt +0 -0
sqlleaf/dialects/__init__.py
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
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
|
@@ -11,6 +11,8 @@ from sqlglot.schema import nested_set
|
|
|
11
11
|
from sqlglot.trie import new_trie
|
|
12
12
|
|
|
13
13
|
from sqlleaf import exception, util
|
|
14
|
+
from sqlleaf.dialects.base import BaseDialectSettings
|
|
15
|
+
from sqlleaf.path import NodeIndex
|
|
14
16
|
from sqlleaf.models.query import (
|
|
15
17
|
CallQuery,
|
|
16
18
|
CTASQuery,
|
|
@@ -156,15 +158,27 @@ class ObjectMapping(MappingSchema):
|
|
|
156
158
|
like qualification and simplification).
|
|
157
159
|
"""
|
|
158
160
|
|
|
159
|
-
def __init__(
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
dialect: str,
|
|
164
|
+
object_loader: t.Callable[[ObjectMapping, exp.Table, str], None] | None = None,
|
|
165
|
+
):
|
|
160
166
|
super().__init__(
|
|
161
167
|
dialect=dialect, normalize=False
|
|
162
168
|
) # Set `normalize=False` to prevent an unnecessary second parse.
|
|
163
169
|
self.kind_mapping = {}
|
|
164
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
|
|
165
177
|
# Session/global variables (e.g., SET var = ...)
|
|
166
178
|
self.session_variables: dict[str, exp.Expr] = {}
|
|
167
179
|
self.variables = Variables()
|
|
180
|
+
# Nodes that have been added to the graph, indexed by class
|
|
181
|
+
self.node_index = NodeIndex()
|
|
168
182
|
|
|
169
183
|
def add_database_query(self, query: DatabaseQuery) -> None:
|
|
170
184
|
self._add_query(query=query, dialect=query.dialect)
|
|
@@ -187,6 +201,26 @@ class ObjectMapping(MappingSchema):
|
|
|
187
201
|
def add_table_query(
|
|
188
202
|
self, query: TableQuery | ViewQuery | CTASQuery, column_mapping: ColumnMapping | None = None
|
|
189
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
|
+
|
|
190
224
|
self._add_query(query=query, column_mapping=column_mapping, dialect=query.dialect, kind="table")
|
|
191
225
|
|
|
192
226
|
def add_trigger_query(self, query: TriggerQuery) -> None:
|
|
@@ -274,6 +308,14 @@ class ObjectMapping(MappingSchema):
|
|
|
274
308
|
match_depth=match_depth,
|
|
275
309
|
)
|
|
276
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
|
+
|
|
277
319
|
def find_columns_for_table(
|
|
278
320
|
self,
|
|
279
321
|
table: exp.Table,
|
|
@@ -296,6 +338,9 @@ class ObjectMapping(MappingSchema):
|
|
|
296
338
|
# A procedure can be overloaded with different parameters, thus we return a list
|
|
297
339
|
return self._lookup_query(kind="procedure", object=table, raise_on_missing=raise_on_missing)
|
|
298
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
|
+
|
|
299
344
|
def lookup_sequence_query(self, table: exp.Table, raise_on_missing: bool = True) -> SequenceQuery | None:
|
|
300
345
|
return self._lookup_query(kind="sequence", object=table, raise_on_missing=raise_on_missing)
|
|
301
346
|
|
|
@@ -337,6 +382,9 @@ class ObjectMapping(MappingSchema):
|
|
|
337
382
|
Returns:
|
|
338
383
|
The schema of the target object.
|
|
339
384
|
"""
|
|
385
|
+
if kind in ("table", "schema"):
|
|
386
|
+
self.handle_missing_object(object, kind=kind)
|
|
387
|
+
|
|
340
388
|
if kind not in self.kind_mapping:
|
|
341
389
|
if raise_on_missing:
|
|
342
390
|
if kind == "prepare":
|
sqlleaf/models/node/__init__.py
CHANGED
|
@@ -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
|
sqlleaf/models/node/column.py
CHANGED
|
@@ -8,15 +8,15 @@ from sqlglot.optimizer import Scope
|
|
|
8
8
|
from sqlglot.optimizer.scope import ScopeType
|
|
9
9
|
|
|
10
10
|
from sqlleaf import exception
|
|
11
|
-
from sqlleaf.models.context import GeneratorContext
|
|
12
|
-
from sqlleaf.models.node import NodeAttributes
|
|
11
|
+
from sqlleaf.models.context import GeneratorContext
|
|
12
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
13
13
|
from sqlleaf.typing import TableOrScopeType, TableSubtype, TableType
|
|
14
14
|
|
|
15
15
|
logger = logging.getLogger("sqlleaf")
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
class ColumnNode(NodeAttributes):
|
|
19
|
-
KIND =
|
|
19
|
+
KIND = NodeKind.COLUMN
|
|
20
20
|
|
|
21
21
|
def __init__(
|
|
22
22
|
self,
|
|
@@ -37,6 +37,7 @@ class ColumnNode(NodeAttributes):
|
|
|
37
37
|
|
|
38
38
|
self.parent_kind: str = kind
|
|
39
39
|
self.parent_subkind: str = subkind
|
|
40
|
+
self.metadata_field: str | None = None
|
|
40
41
|
self.source_scope: TableOrScopeType | None = None
|
|
41
42
|
self._source = source
|
|
42
43
|
|
|
@@ -59,8 +60,32 @@ class ColumnNode(NodeAttributes):
|
|
|
59
60
|
"schema": self.schema,
|
|
60
61
|
"table": self.table,
|
|
61
62
|
})
|
|
63
|
+
if self.metadata_field:
|
|
64
|
+
d["metadata"] = self.metadata_field
|
|
62
65
|
return d
|
|
63
66
|
|
|
67
|
+
def is_ordinality_column(self) -> bool:
|
|
68
|
+
"""
|
|
69
|
+
The column appended by 'WITH ORDINALITY' is the last alias column, or 'ordinality' if unaliased.
|
|
70
|
+
"""
|
|
71
|
+
source = self.source_scope
|
|
72
|
+
if isinstance(source, Scope):
|
|
73
|
+
source = source.expression
|
|
74
|
+
|
|
75
|
+
if isinstance(source, exp.Lateral):
|
|
76
|
+
source = source.this
|
|
77
|
+
|
|
78
|
+
if isinstance(source, exp.Unnest):
|
|
79
|
+
offset = source.args.get("offset")
|
|
80
|
+
return isinstance(offset, exp.Identifier) and self.name == offset.name
|
|
81
|
+
|
|
82
|
+
if not isinstance(source, exp.Table) or not source.args.get("ordinality"):
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
alias = source.args.get("alias")
|
|
86
|
+
ordinal_name = alias.columns[-1].name if alias and alias.columns else "ordinality"
|
|
87
|
+
return self.name == ordinal_name
|
|
88
|
+
|
|
64
89
|
def _apply_rename(self, source: exp.Table | exp.Select | exp.Lateral, dialect: str) -> None:
|
|
65
90
|
"""
|
|
66
91
|
Change the column's source table to be its fully qualified name, not its alias,
|
|
@@ -238,6 +263,9 @@ class ColumnNode(NodeAttributes):
|
|
|
238
263
|
if query and query.property:
|
|
239
264
|
self.parent_subkind = TableSubtype(query.property)
|
|
240
265
|
|
|
266
|
+
if query and query.kind == "table":
|
|
267
|
+
self.metadata_field = query.metadata_field
|
|
268
|
+
|
|
241
269
|
@property
|
|
242
270
|
def friendly_name(self) -> str:
|
|
243
271
|
tokens = [self.catalog, self.schema, self.table, self.name]
|
|
@@ -263,12 +291,16 @@ class ColumnNode(NodeAttributes):
|
|
|
263
291
|
if self.parent_subkind:
|
|
264
292
|
f["subkind"] = self.parent_subkind
|
|
265
293
|
|
|
294
|
+
table = self.table.removesuffix(self.metadata_field) if self.metadata_field else self.table
|
|
266
295
|
f |= {
|
|
267
|
-
"table":
|
|
296
|
+
"table": table,
|
|
268
297
|
"schema": self.schema,
|
|
269
298
|
"type": self.data_type,
|
|
270
299
|
}
|
|
271
300
|
|
|
301
|
+
if self.metadata_field:
|
|
302
|
+
f["metadata"] = self.metadata_field
|
|
303
|
+
|
|
272
304
|
if self.parent_kind == TableType.CTE and self.parent_subkind == TableSubtype.RECURSIVE:
|
|
273
305
|
f["member"] = self.member
|
|
274
306
|
|
|
@@ -279,7 +311,7 @@ class ColumnNode(NodeAttributes):
|
|
|
279
311
|
|
|
280
312
|
|
|
281
313
|
class FileColumnNode(NodeAttributes):
|
|
282
|
-
KIND =
|
|
314
|
+
KIND = NodeKind.COLUMN
|
|
283
315
|
|
|
284
316
|
def __init__(
|
|
285
317
|
self,
|
|
@@ -313,7 +345,7 @@ class FileColumnNode(NodeAttributes):
|
|
|
313
345
|
|
|
314
346
|
|
|
315
347
|
class StageColumnNode(NodeAttributes):
|
|
316
|
-
KIND =
|
|
348
|
+
KIND = NodeKind.COLUMN
|
|
317
349
|
|
|
318
350
|
def __init__(
|
|
319
351
|
self,
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# Represents the source of a 'WITH ORDINALITY' column
|
|
7
|
+
class CounterNode(NodeAttributes):
|
|
8
|
+
KIND = NodeKind.COUNTER
|
|
9
|
+
WITH_POSITIONS = True
|
|
10
|
+
|
|
11
|
+
def fields(self) -> dict[str, str]:
|
|
12
|
+
return {}
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def full_name(self) -> str:
|
|
16
|
+
return self.wrap(f"position[{self.ctx.as_str()}]")
|
sqlleaf/models/node/dynamodb.py
CHANGED
|
@@ -4,13 +4,13 @@ import logging
|
|
|
4
4
|
import typing as t
|
|
5
5
|
|
|
6
6
|
from sqlleaf.models.context import GeneratorContext
|
|
7
|
-
from sqlleaf.models.node import NodeAttributes
|
|
7
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
8
8
|
|
|
9
9
|
logger = logging.getLogger("sqlleaf")
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
class DynamoDbNode(NodeAttributes):
|
|
13
|
-
KIND =
|
|
13
|
+
KIND = NodeKind.COLUMN
|
|
14
14
|
|
|
15
15
|
def __init__(
|
|
16
16
|
self,
|
sqlleaf/models/node/function.py
CHANGED
|
@@ -6,11 +6,11 @@ from sqlglot import exp
|
|
|
6
6
|
|
|
7
7
|
from sqlleaf import util
|
|
8
8
|
from sqlleaf.models.context import GeneratorContext
|
|
9
|
-
from sqlleaf.models.node import NodeAttributes
|
|
9
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
class FunctionNode(NodeAttributes):
|
|
13
|
-
KIND =
|
|
13
|
+
KIND = NodeKind.FUNCTION
|
|
14
14
|
WITH_POSITIONS = True
|
|
15
15
|
|
|
16
16
|
def with_context(self, gen_ctx: GeneratorContext) -> t.Self:
|
sqlleaf/models/node/interval.py
CHANGED
|
@@ -5,11 +5,11 @@ import typing as t
|
|
|
5
5
|
from sqlglot import exp
|
|
6
6
|
|
|
7
7
|
from sqlleaf.models.context import GeneratorContext
|
|
8
|
-
from sqlleaf.models.node import NodeAttributes
|
|
8
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class IntervalNode(NodeAttributes):
|
|
12
|
-
KIND =
|
|
12
|
+
KIND = NodeKind.INTERVAL
|
|
13
13
|
WITH_POSITIONS = True
|
|
14
14
|
|
|
15
15
|
def with_context(self, gen_ctx: GeneratorContext) -> t.Self:
|
sqlleaf/models/node/json.py
CHANGED
|
@@ -6,13 +6,13 @@ import typing as t
|
|
|
6
6
|
from sqlglot import exp
|
|
7
7
|
|
|
8
8
|
from sqlleaf.models.context import GeneratorContext
|
|
9
|
-
from sqlleaf.models.node import NodeAttributes
|
|
9
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
10
10
|
|
|
11
11
|
logger = logging.getLogger("sqlleaf")
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
class JsonPathNode(NodeAttributes):
|
|
15
|
-
KIND =
|
|
15
|
+
KIND = NodeKind.JSONPATH
|
|
16
16
|
|
|
17
17
|
def __init__(self, selector: str = "", selector_depth: int = 0, data_type: str = ""):
|
|
18
18
|
super().__init__(name=selector, data_type=data_type)
|
sqlleaf/models/node/literal.py
CHANGED
|
@@ -3,11 +3,11 @@ from __future__ import annotations
|
|
|
3
3
|
import typing as t
|
|
4
4
|
|
|
5
5
|
from sqlleaf.models.context import GeneratorContext
|
|
6
|
-
from sqlleaf.models.node import NodeAttributes
|
|
6
|
+
from sqlleaf.models.node import NodeAttributes, NodeKind
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
class LiteralNode(NodeAttributes):
|
|
10
|
-
KIND =
|
|
10
|
+
KIND = NodeKind.LITERAL
|
|
11
11
|
WITH_POSITIONS = True
|
|
12
12
|
|
|
13
13
|
def __init__(self, name: t.Any = "", data_type: str = ""):
|