sqlleaf 0.0.5__py3-none-any.whl → 0.0.8__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/__init__.py +0 -1
- sqlleaf/dialects/__init__.py +8 -1
- sqlleaf/dialects/athena/__init__.py +0 -0
- sqlleaf/dialects/athena/config.py +92 -0
- sqlleaf/dialects/base.py +86 -0
- sqlleaf/dialects/loader.py +51 -0
- sqlleaf/dialects/mysql/__init__.py +0 -0
- sqlleaf/dialects/mysql/config.py +33 -0
- sqlleaf/dialects/postgres/__init__.py +0 -0
- sqlleaf/{settings/postgres.py → dialects/postgres/config.py} +14 -9
- sqlleaf/dialects/redshift/__init__.py +0 -0
- sqlleaf/dialects/redshift/config.py +12 -0
- sqlleaf/exception.py +36 -9
- sqlleaf/lineage.py +55 -10
- sqlleaf/mappings.py +92 -16
- sqlleaf/models/context.py +2 -2
- 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 +4 -0
- sqlleaf/models/query/base.py +9 -3
- sqlleaf/models/query/ctas.py +6 -2
- sqlleaf/models/query/declare_item.py +6 -2
- sqlleaf/models/query/execute.py +6 -0
- sqlleaf/models/query/prepare.py +48 -6
- sqlleaf/models/query/procedure.py +9 -8
- sqlleaf/models/query/reset.py +30 -0
- sqlleaf/models/query/select.py +13 -1
- sqlleaf/models/query/set.py +61 -11
- sqlleaf/models/query/table.py +30 -5
- sqlleaf/models/query/use.py +26 -0
- sqlleaf/models/query/user_defined_function.py +19 -1
- sqlleaf/models/query/view.py +66 -0
- sqlleaf/path.py +27 -7
- sqlleaf/processors/collector/classify.py +84 -8
- sqlleaf/processors/collector/collector.py +104 -23
- sqlleaf/processors/generator/dialects/base.py +16 -5
- sqlleaf/processors/generator/generator.py +19 -9
- sqlleaf/processors/substitutor/substitute.py +37 -7
- sqlleaf/processors/transformer/base.py +108 -4
- sqlleaf/processors/transformer/expressions/__init__.py +3 -0
- sqlleaf/processors/transformer/expressions/operator.py +32 -0
- sqlleaf/processors/transformer/transformer.py +8 -1
- sqlleaf/typing.py +5 -0
- sqlleaf/util/__init__.py +2 -0
- sqlleaf/util/expression.py +82 -5
- sqlleaf/util/graph.py +11 -10
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.8.dist-info}/METADATA +43 -5
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.8.dist-info}/RECORD +67 -57
- sqlleaf/settings/__init__.py +0 -19
- sqlleaf/settings/athena.py +0 -23
- sqlleaf/settings/base.py +0 -37
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.8.dist-info}/WHEEL +0 -0
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.8.dist-info}/licenses/LICENSE +0 -0
- {sqlleaf-0.0.5.dist-info → sqlleaf-0.0.8.dist-info}/top_level.txt +0 -0
sqlleaf/__init__.py
CHANGED
|
@@ -2,4 +2,3 @@ from sqlleaf.lineage import Lineage as Lineage
|
|
|
2
2
|
from sqlleaf.processors.collector.collector import collect_queries as collect_queries
|
|
3
3
|
from sqlleaf.processors.generator.generator import generate_lineage_for_query as generate_lineage_for_query
|
|
4
4
|
from sqlleaf.processors.transformer.transformer import transform_query as transform_query
|
|
5
|
-
from sqlleaf.dialects import PlPgSQL
|
sqlleaf/dialects/__init__.py
CHANGED
|
@@ -1 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
# Maps each dialect name to the module that registers its config or parser. Lazily imported for performance.
|
|
2
|
+
DIALECT_MODULES = {
|
|
3
|
+
"athena": "sqlleaf.dialects.athena.config",
|
|
4
|
+
"mysql": "sqlleaf.dialects.mysql.config",
|
|
5
|
+
"plpgsql": "sqlleaf.dialects.plpgsql.p_dialect",
|
|
6
|
+
"postgres": "sqlleaf.dialects.postgres.config",
|
|
7
|
+
"redshift": "sqlleaf.dialects.redshift.config",
|
|
8
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from sqlglot import exp
|
|
2
|
+
from sqlglot.dialects import athena
|
|
3
|
+
|
|
4
|
+
from sqlleaf.dialects.base import DialectConfig
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AthenaConfig(DialectConfig):
|
|
8
|
+
DIALECT = "athena"
|
|
9
|
+
DEFAULT_USER_CATALOG = "awsdatacatalog"
|
|
10
|
+
DEFAULT_SYSTEM_CATALOG = ""
|
|
11
|
+
PSEUDOCOLUMNS = {
|
|
12
|
+
"$bucket": "BIGINT",
|
|
13
|
+
"$file_modified_time": "TIMESTAMP",
|
|
14
|
+
"$file_size": "BIGINT",
|
|
15
|
+
"$partition": "VARCHAR",
|
|
16
|
+
"$path": "VARCHAR",
|
|
17
|
+
}
|
|
18
|
+
# Iceberg metadata fields
|
|
19
|
+
METADATA_FIELDS = {
|
|
20
|
+
"$files": {
|
|
21
|
+
"content": "INTEGER",
|
|
22
|
+
"file_path": "VARCHAR",
|
|
23
|
+
"file_format": "VARCHAR",
|
|
24
|
+
"record_count": "BIGINT",
|
|
25
|
+
"file_size_in_bytes": "BIGINT",
|
|
26
|
+
"column_sizes": "MAP(INTEGER, BIGINT)",
|
|
27
|
+
"value_counts": "MAP(INTEGER, BIGINT)",
|
|
28
|
+
"null_value_counts": "MAP(INTEGER, BIGINT)",
|
|
29
|
+
"nan_value_counts": "MAP(INTEGER, BIGINT)",
|
|
30
|
+
"lower_bounds": "MAP(INTEGER, VARCHAR)",
|
|
31
|
+
"upper_bounds": "MAP(INTEGER, VARCHAR)",
|
|
32
|
+
"key_metadata": "VARBINARY",
|
|
33
|
+
"split_offsets": "ARRAY(BIGINT)",
|
|
34
|
+
"equality_ids": "ARRAY(INTEGER)",
|
|
35
|
+
},
|
|
36
|
+
"$manifests": {
|
|
37
|
+
"path": "VARCHAR",
|
|
38
|
+
"length": "BIGINT",
|
|
39
|
+
"partition_spec_id": "INTEGER",
|
|
40
|
+
"added_snapshot_id": "BIGINT",
|
|
41
|
+
"added_data_files_count": "INTEGER",
|
|
42
|
+
"added_rows_count": "BIGINT",
|
|
43
|
+
"existing_data_files_count": "INTEGER",
|
|
44
|
+
"existing_rows_count": "BIGINT",
|
|
45
|
+
"deleted_data_files_count": "INTEGER",
|
|
46
|
+
"deleted_rows_count": "BIGINT",
|
|
47
|
+
"partitions": "ARRAY(STRUCT(contains_null BOOLEAN, contains_nan BOOLEAN, lower_bound VARCHAR, upper_bound VARCHAR))",
|
|
48
|
+
},
|
|
49
|
+
"$history": {
|
|
50
|
+
"made_current_at": "TIMESTAMP WITH TIME ZONE",
|
|
51
|
+
"snapshot_id": "BIGINT",
|
|
52
|
+
"parent_id": "BIGINT",
|
|
53
|
+
"is_current_ancestor": "BOOLEAN",
|
|
54
|
+
},
|
|
55
|
+
"$partitions": {
|
|
56
|
+
"partition": "STRUCT(category VARCHAR)",
|
|
57
|
+
"record_count": "BIGINT",
|
|
58
|
+
"file_count": "BIGINT",
|
|
59
|
+
"total_size": "BIGINT",
|
|
60
|
+
"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))",
|
|
61
|
+
},
|
|
62
|
+
"$snapshots": {
|
|
63
|
+
"committed_at": "TIMESTAMP WITH TIME ZONE",
|
|
64
|
+
"snapshot_id": "BIGINT",
|
|
65
|
+
"parent_id": "BIGINT",
|
|
66
|
+
"operation": "VARCHAR",
|
|
67
|
+
"manifest_list": "VARCHAR",
|
|
68
|
+
"summary": "MAP(VARCHAR, VARCHAR)",
|
|
69
|
+
},
|
|
70
|
+
"$refs": {
|
|
71
|
+
"name": "VARCHAR",
|
|
72
|
+
"type": "VARCHAR",
|
|
73
|
+
"snapshot_id": "BIGINT",
|
|
74
|
+
"max_reference_age_in_ms": "BIGINT",
|
|
75
|
+
"min_snapshots_to_keep": "INTEGER",
|
|
76
|
+
"max_snapshot_age_in_ms": "BIGINT",
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
82
|
+
return [
|
|
83
|
+
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
84
|
+
for name, kind in self.PSEUDOCOLUMNS.items()
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# sqlglot is missing pseudocolumns for Athena
|
|
89
|
+
athena.Athena.PSEUDOCOLUMNS = {c.upper() for c in AthenaConfig.PSEUDOCOLUMNS.keys()}
|
|
90
|
+
|
|
91
|
+
# Prevents pseudocolumns from being included in 'SELECT *' expansions
|
|
92
|
+
athena.Athena.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR = True
|
sqlleaf/dialects/base.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import typing as t
|
|
3
|
+
|
|
4
|
+
import sqlglot
|
|
5
|
+
from sqlglot import Dialect, exp
|
|
6
|
+
|
|
7
|
+
from sqlleaf.dialects import DIALECT_MODULES
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# Wrap a function parameter parser so that it also accepts IN, OUT, and INOUT parameter modes
|
|
11
|
+
def with_parameter_modes(parse_function_parameter: t.Callable) -> t.Callable:
|
|
12
|
+
def _parse_function_parameter(self) -> exp.Expr | None:
|
|
13
|
+
mode = self._match_texts(("INOUT", "IN", "OUT")) and self._prev.text.upper()
|
|
14
|
+
parameter = parse_function_parameter(self)
|
|
15
|
+
if mode and parameter:
|
|
16
|
+
parameter.append(
|
|
17
|
+
"constraints",
|
|
18
|
+
exp.InOutColumnConstraint(input_=mode in ("IN", "INOUT"), output=mode in ("OUT", "INOUT")),
|
|
19
|
+
)
|
|
20
|
+
return parameter
|
|
21
|
+
|
|
22
|
+
return _parse_function_parameter
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DialectConfig:
|
|
26
|
+
# A registry to store subclasses
|
|
27
|
+
_dialects = {}
|
|
28
|
+
DIALECT = ""
|
|
29
|
+
DEFAULT_USER_CATALOG = ""
|
|
30
|
+
DEFAULT_SYSTEM_CATALOG = ""
|
|
31
|
+
# The language of procedures that do not declare one explicitly
|
|
32
|
+
DEFAULT_PROCEDURE_LANGUAGE: str | None = None
|
|
33
|
+
# Metadata fields, keyed by their suffix (e.g. '$files' in 'my_table$files'), mapped to their column names and types
|
|
34
|
+
METADATA_FIELDS: dict[str, dict[str, str]] = {}
|
|
35
|
+
|
|
36
|
+
def __init_subclass__(cls, **kwargs):
|
|
37
|
+
"""Automatically registers subclasses when they are defined."""
|
|
38
|
+
super().__init_subclass__(**kwargs)
|
|
39
|
+
if cls.DIALECT:
|
|
40
|
+
DialectConfig._dialects[cls.DIALECT] = cls
|
|
41
|
+
|
|
42
|
+
def __new__(cls, dialect: str) -> DialectConfig:
|
|
43
|
+
"""Returns the config registered for the dialect name, or the base config if none is registered."""
|
|
44
|
+
if dialect in DIALECT_MODULES:
|
|
45
|
+
importlib.import_module(DIALECT_MODULES[dialect])
|
|
46
|
+
return super().__new__(DialectConfig._dialects.get(dialect, DialectConfig))
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
50
|
+
"""
|
|
51
|
+
Represents system columns.
|
|
52
|
+
"""
|
|
53
|
+
return []
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def SYSTEM_FUNCTIONS(self) -> dict[str, list[str]]:
|
|
57
|
+
"""
|
|
58
|
+
Represents system functions.
|
|
59
|
+
"""
|
|
60
|
+
return {}
|
|
61
|
+
|
|
62
|
+
def get_metadata_field(self, table_name: str) -> str | None:
|
|
63
|
+
"""
|
|
64
|
+
Returns the metadata field of a table name (e.g. '$files' for 'my_table$files').
|
|
65
|
+
"""
|
|
66
|
+
for suffix in self.METADATA_FIELDS:
|
|
67
|
+
if table_name.lower().endswith(suffix):
|
|
68
|
+
return suffix
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
def get_metadata_field_column_defs(self, suffix: str) -> list[exp.ColumnDef]:
|
|
72
|
+
"""
|
|
73
|
+
Returns the column definitions of the metadata table with the given field (e.g. '$files').
|
|
74
|
+
"""
|
|
75
|
+
return [
|
|
76
|
+
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
77
|
+
for name, kind in self.METADATA_FIELDS[suffix].items()
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
class ParameterModeDialect(Dialect):
|
|
81
|
+
"""
|
|
82
|
+
The generic dialect, which also accepts IN, OUT, and INOUT parameter modes in procedure parameters.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
class Parser(sqlglot.Parser):
|
|
86
|
+
_parse_function_parameter = with_parameter_modes(sqlglot.Parser._parse_function_parameter)
|
|
@@ -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
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from sqlglot import TokenType
|
|
2
|
+
from sqlglot.dialects.mysql import MySQL
|
|
3
|
+
|
|
4
|
+
from sqlleaf.dialects.base import DialectConfig, with_parameter_modes
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MySQLConfig(DialectConfig):
|
|
8
|
+
DIALECT = "mysql"
|
|
9
|
+
DEFAULT_PROCEDURE_LANGUAGE = "SQL"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Monkeypatch sqlglot's MySQL parser so that MySQL procedure parameters also accept parameter modes
|
|
13
|
+
MySQL.Parser._parse_function_parameter = with_parameter_modes(MySQL.Parser._parse_function_parameter)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_user_defined_function_expression(self):
|
|
17
|
+
"""
|
|
18
|
+
Parse a MySQL function body that starts with BEGIN as a block, so that every statement is kept inside the function
|
|
19
|
+
rather than only the first one.
|
|
20
|
+
"""
|
|
21
|
+
if self._prev.token_type == TokenType.BEGIN:
|
|
22
|
+
return self._parse_block()
|
|
23
|
+
return _parse_user_defined_function_expression_default(self)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_parse_user_defined_function_expression_default = MySQL.Parser._parse_user_defined_function_expression
|
|
27
|
+
MySQL.Parser._parse_user_defined_function_expression = _parse_user_defined_function_expression
|
|
28
|
+
|
|
29
|
+
# Tokenize 'DECLARE' as a keyword so procedure variable declarations are parsed by sqlglot's declare parser rather than an exp.Column
|
|
30
|
+
MySQL.Tokenizer.KEYWORDS["DECLARE"] = TokenType.DECLARE
|
|
31
|
+
|
|
32
|
+
# MySQL supports 'SELECT ... INTO @var', so keep it as a SELECT rather than rewriting it to 'CREATE TABLE AS'
|
|
33
|
+
MySQL.Generator.SUPPORTS_SELECT_INTO = True
|
|
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 DialectConfig
|
|
7
5
|
|
|
8
6
|
|
|
9
|
-
class
|
|
7
|
+
class PostgresConfig(DialectConfig):
|
|
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",
|
|
@@ -19,19 +19,19 @@ class PostgresSettings(BaseDialectSettings):
|
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
@property
|
|
22
|
-
def
|
|
22
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
23
23
|
return [
|
|
24
24
|
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
25
25
|
for name, kind in self.PSEUDOCOLUMNS.items()
|
|
26
26
|
]
|
|
27
27
|
|
|
28
28
|
@property
|
|
29
|
-
def
|
|
29
|
+
def SYSTEM_FUNCTIONS(self) -> dict[str, list[str]]:
|
|
30
30
|
"""
|
|
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"],
|
|
@@ -48,5 +48,10 @@ class PostgresSettings(BaseDialectSettings):
|
|
|
48
48
|
|
|
49
49
|
|
|
50
50
|
# sqlglot is missing pseudocolumns for Postgres
|
|
51
|
-
postgres.Postgres.PSEUDOCOLUMNS = {c.upper() for c in
|
|
51
|
+
postgres.Postgres.PSEUDOCOLUMNS = {c.upper() for c in PostgresConfig.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
|
|
File without changes
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from sqlglot.dialects.redshift import Redshift
|
|
2
|
+
|
|
3
|
+
from sqlleaf.dialects.base import DialectConfig
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RedshiftConfig(DialectConfig):
|
|
7
|
+
DIALECT = "redshift"
|
|
8
|
+
DEFAULT_PROCEDURE_LANGUAGE = "PLPGSQL"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# Redshift supports 'SELECT ... INTO', so keep it as a SELECT rather than rewriting it to 'CREATE TABLE AS'
|
|
12
|
+
Redshift.Generator.SUPPORTS_SELECT_INTO = True
|
sqlleaf/exception.py
CHANGED
|
@@ -1,30 +1,36 @@
|
|
|
1
1
|
import logging
|
|
2
|
+
import sys
|
|
3
|
+
from enum import StrEnum, auto
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
logger = logging.getLogger("sqlleaf")
|
|
4
6
|
|
|
7
|
+
class ErrorLevel(StrEnum):
|
|
8
|
+
ERROR = auto()
|
|
9
|
+
WARN = auto()
|
|
5
10
|
|
|
6
|
-
|
|
11
|
+
|
|
12
|
+
ERROR_LEVEL = ErrorLevel.ERROR
|
|
7
13
|
|
|
8
14
|
|
|
9
15
|
def raise_error(cls: type, message: str):
|
|
10
16
|
"""
|
|
11
17
|
Raise a custom exception based on the error level.
|
|
12
18
|
"""
|
|
13
|
-
if ERROR_LEVEL ==
|
|
14
|
-
raise cls(message)
|
|
15
|
-
elif ERROR_LEVEL ==
|
|
19
|
+
if ERROR_LEVEL == ErrorLevel.ERROR:
|
|
20
|
+
raise cls(message).with_traceback(None)
|
|
21
|
+
elif ERROR_LEVEL == ErrorLevel.WARN:
|
|
16
22
|
logger.error(message)
|
|
17
23
|
|
|
18
24
|
|
|
19
25
|
def set_error_action(action: str) -> None:
|
|
20
26
|
"""
|
|
21
|
-
Set the error level for exceptions.
|
|
27
|
+
Set the error level for exceptions ('error' or 'warn').
|
|
22
28
|
"""
|
|
23
|
-
if action not in
|
|
24
|
-
raise ValueError("The error action must be '
|
|
29
|
+
if action not in {level.value for level in ErrorLevel}:
|
|
30
|
+
raise ValueError("The error action must be 'error' or 'warn'.")
|
|
25
31
|
|
|
26
32
|
global ERROR_LEVEL
|
|
27
|
-
ERROR_LEVEL = action
|
|
33
|
+
ERROR_LEVEL = ErrorLevel(action)
|
|
28
34
|
|
|
29
35
|
|
|
30
36
|
class SqlGlotException(Exception):
|
|
@@ -65,3 +71,24 @@ class GeneratorError(SqlLeafException):
|
|
|
65
71
|
|
|
66
72
|
class GraphError(SqlLeafException):
|
|
67
73
|
pass
|
|
74
|
+
|
|
75
|
+
PRINT_FULL_EXCEPTION = False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def set_print_full_exception(enabled: bool) -> None:
|
|
79
|
+
"""
|
|
80
|
+
Set whether uncaught exceptions print the full traceback instead of only the error type and message.
|
|
81
|
+
"""
|
|
82
|
+
global PRINT_FULL_EXCEPTION
|
|
83
|
+
PRINT_FULL_EXCEPTION = enabled
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def suppress_exception_message(kind, message, traceback):
|
|
87
|
+
if not PRINT_FULL_EXCEPTION and SqlLeafException in kind.__bases__:
|
|
88
|
+
# Short form
|
|
89
|
+
print('{0}: {1}'.format(kind.__name__, message))
|
|
90
|
+
else:
|
|
91
|
+
# Regular form
|
|
92
|
+
sys.__excepthook__(kind, message, traceback)
|
|
93
|
+
|
|
94
|
+
sys.excepthook = suppress_exception_message
|
sqlleaf/lineage.py
CHANGED
|
@@ -2,11 +2,11 @@ import json
|
|
|
2
2
|
import logging
|
|
3
3
|
import typing as t
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
from networkx import MultiDiGraph, descendants
|
|
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
|
)
|
|
@@ -25,20 +25,19 @@ class Lineage:
|
|
|
25
25
|
|
|
26
26
|
def __init__(self):
|
|
27
27
|
self.graph = new_graph() # The graph that contains all lineage
|
|
28
|
-
self.subgraphs: list[
|
|
28
|
+
self.subgraphs: list[MultiDiGraph] = [] # The subgraphs that make up the main graph
|
|
29
29
|
self.paths: dict[str, list[LineagePath]] = {} # The paths throughout the graph
|
|
30
30
|
self.collected_queries: collector.CollectQueryResult | None = None
|
|
31
31
|
self.user_defined_hooks: list[Hook] = []
|
|
32
32
|
self.object_mapping: mappings.ObjectMapping | None = None
|
|
33
33
|
|
|
34
|
-
def generate(self, sql: str, dialect: str, on_error: str = "
|
|
34
|
+
def generate(self, sql: str, dialect: str, on_error: str = "error") -> None:
|
|
35
35
|
"""
|
|
36
36
|
Generate lineage for one or more SQL statements.
|
|
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
|
|
@@ -59,7 +58,7 @@ class Lineage:
|
|
|
59
58
|
self.merge_graph(graph)
|
|
60
59
|
self.graph.graph["attrs"].add_query_to_graph(parent_holder)
|
|
61
60
|
|
|
62
|
-
def merge_graph(self, subgraph:
|
|
61
|
+
def merge_graph(self, subgraph: MultiDiGraph) -> None:
|
|
63
62
|
"""
|
|
64
63
|
Merge the subgraph into the main graph, and also track the individual subgraphs.
|
|
65
64
|
"""
|
|
@@ -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.
|
|
@@ -184,7 +224,7 @@ class Lineage:
|
|
|
184
224
|
# Swap the parent and child
|
|
185
225
|
parent_name = edge_attrs.child.full_name
|
|
186
226
|
child_name = edge_attrs.parent.full_name
|
|
187
|
-
num_descendents_of_child = len(
|
|
227
|
+
num_descendents_of_child = len(descendants(g, child_name))
|
|
188
228
|
|
|
189
229
|
parent_node = g.nodes[parent_name]["attrs"]
|
|
190
230
|
child_node = g.nodes[child_name]["attrs"]
|
|
@@ -262,8 +302,13 @@ 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
|
|
|
265
|
-
def
|
|
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
|
+
|
|
310
|
+
def new_graph() -> MultiDiGraph:
|
|
266
311
|
"""
|
|
267
312
|
A graph has attributes along with its node and edges.
|
|
268
313
|
"""
|
|
269
|
-
return
|
|
314
|
+
return MultiDiGraph(attrs=GraphAttributes())
|