sqlleaf 0.0.7__py3-none-any.whl → 0.0.9__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 -20
- sqlleaf/dialects/athena/config.py +14 -5
- sqlleaf/dialects/base.py +39 -14
- sqlleaf/dialects/mysql/__init__.py +0 -0
- sqlleaf/dialects/mysql/config.py +33 -0
- sqlleaf/dialects/postgres/config.py +8 -7
- sqlleaf/dialects/redshift/__init__.py +0 -0
- sqlleaf/dialects/redshift/config.py +12 -0
- sqlleaf/exception.py +36 -9
- sqlleaf/lineage.py +110 -70
- sqlleaf/mappings.py +70 -26
- sqlleaf/models/context.py +2 -2
- sqlleaf/models/node/__init__.py +2 -2
- sqlleaf/models/node/column.py +3 -2
- sqlleaf/models/node/json.py +29 -2
- sqlleaf/models/node/{counter.py → series.py} +3 -3
- sqlleaf/models/node/window.py +3 -1
- sqlleaf/models/query/__init__.py +2 -0
- sqlleaf/models/query/base.py +27 -6
- sqlleaf/models/query/ctas.py +21 -7
- 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 +4 -4
- sqlleaf/models/query/select.py +13 -1
- sqlleaf/models/query/sequence.py +4 -0
- sqlleaf/models/query/set.py +10 -10
- sqlleaf/models/query/table.py +26 -8
- sqlleaf/models/query/type.py +4 -0
- sqlleaf/models/query/use.py +26 -0
- sqlleaf/models/query/user_defined_function.py +19 -1
- sqlleaf/models/query/view.py +3 -2
- sqlleaf/path.py +77 -19
- sqlleaf/processors/collector/classify.py +62 -8
- sqlleaf/processors/collector/collector.py +30 -29
- sqlleaf/processors/generator/dialects/base.py +119 -9
- sqlleaf/processors/generator/dialects/postgres.py +7 -10
- sqlleaf/processors/generator/generator.py +12 -9
- sqlleaf/processors/substitutor/substitute.py +40 -10
- sqlleaf/processors/transformer/base.py +131 -50
- sqlleaf/processors/transformer/copy.py +0 -1
- sqlleaf/processors/transformer/expressions/operator.py +4 -4
- sqlleaf/processors/transformer/insert.py +0 -2
- sqlleaf/processors/transformer/transformer.py +8 -1
- sqlleaf/util/__init__.py +2 -6
- sqlleaf/util/expression.py +85 -6
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.9.dist-info}/METADATA +2 -2
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.9.dist-info}/RECORD +53 -49
- sqlleaf/util/graph.py +0 -116
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.9.dist-info}/WHEEL +0 -0
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.9.dist-info}/licenses/LICENSE +0 -0
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.9.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,20 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
|
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
|
+
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
from sqlglot import exp
|
|
2
|
+
from sqlglot.dialects import athena
|
|
2
3
|
|
|
3
|
-
from sqlleaf.dialects.base import
|
|
4
|
+
from sqlleaf.dialects.base import DialectConfig
|
|
4
5
|
|
|
5
6
|
|
|
6
|
-
class
|
|
7
|
+
class AthenaConfig(DialectConfig):
|
|
7
8
|
DIALECT = "athena"
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
DEFAULT_CATALOG = "awsdatacatalog"
|
|
10
|
+
DEFAULT_USER_SCHEMA = "default"
|
|
11
|
+
DEFAULT_SYSTEM_SCHEMA = ""
|
|
10
12
|
PSEUDOCOLUMNS = {
|
|
11
13
|
"$bucket": "BIGINT",
|
|
12
14
|
"$file_modified_time": "TIMESTAMP",
|
|
@@ -77,8 +79,15 @@ class AthenaSettings(BaseDialectSettings):
|
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
@property
|
|
80
|
-
def
|
|
82
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
81
83
|
return [
|
|
82
84
|
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
83
85
|
for name, kind in self.PSEUDOCOLUMNS.items()
|
|
84
86
|
]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# sqlglot is missing pseudocolumns for Athena
|
|
90
|
+
athena.Athena.PSEUDOCOLUMNS = {c.upper() for c in AthenaConfig.PSEUDOCOLUMNS.keys()}
|
|
91
|
+
|
|
92
|
+
# Prevents pseudocolumns from being included in 'SELECT *' expansions
|
|
93
|
+
athena.Athena.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR = True
|
sqlleaf/dialects/base.py
CHANGED
|
@@ -1,12 +1,39 @@
|
|
|
1
|
-
|
|
1
|
+
import importlib
|
|
2
|
+
import typing as t
|
|
2
3
|
|
|
4
|
+
import sqlglot
|
|
5
|
+
from sqlglot import Dialect, exp
|
|
3
6
|
|
|
4
|
-
|
|
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:
|
|
5
26
|
# A registry to store subclasses
|
|
6
27
|
_dialects = {}
|
|
7
28
|
DIALECT = ""
|
|
8
|
-
|
|
9
|
-
|
|
29
|
+
# The catalog that the dialect's objects belong to, if the dialect has a catalog level above schemas
|
|
30
|
+
DEFAULT_CATALOG = ""
|
|
31
|
+
DEFAULT_USER_SCHEMA = ""
|
|
32
|
+
DEFAULT_SYSTEM_SCHEMA = ""
|
|
33
|
+
# The schema that temporary objects are created in, if the dialect has one
|
|
34
|
+
DEFAULT_TEMPORARY_SCHEMA: str = ""
|
|
35
|
+
# The language of procedures that do not declare one explicitly
|
|
36
|
+
DEFAULT_PROCEDURE_LANGUAGE: str = ""
|
|
10
37
|
# Metadata fields, keyed by their suffix (e.g. '$files' in 'my_table$files'), mapped to their column names and types
|
|
11
38
|
METADATA_FIELDS: dict[str, dict[str, str]] = {}
|
|
12
39
|
|
|
@@ -14,25 +41,23 @@ class BaseDialectSettings:
|
|
|
14
41
|
"""Automatically registers subclasses when they are defined."""
|
|
15
42
|
super().__init_subclass__(**kwargs)
|
|
16
43
|
if cls.DIALECT:
|
|
17
|
-
|
|
44
|
+
DialectConfig._dialects[cls.DIALECT] = cls
|
|
18
45
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
return BaseDialectSettings()
|
|
25
|
-
return target_class()
|
|
46
|
+
def __new__(cls, dialect: str) -> DialectConfig:
|
|
47
|
+
"""Returns the config registered for the dialect name, or the base config if none is registered."""
|
|
48
|
+
if dialect in DIALECT_MODULES:
|
|
49
|
+
importlib.import_module(DIALECT_MODULES[dialect])
|
|
50
|
+
return super().__new__(DialectConfig._dialects.get(dialect, DialectConfig))
|
|
26
51
|
|
|
27
52
|
@property
|
|
28
|
-
def
|
|
53
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
29
54
|
"""
|
|
30
55
|
Represents system columns.
|
|
31
56
|
"""
|
|
32
57
|
return []
|
|
33
58
|
|
|
34
59
|
@property
|
|
35
|
-
def
|
|
60
|
+
def SYSTEM_FUNCTIONS(self) -> dict[str, list[str]]:
|
|
36
61
|
"""
|
|
37
62
|
Represents system functions.
|
|
38
63
|
"""
|
|
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
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
from sqlglot import exp
|
|
2
2
|
from sqlglot.dialects import postgres
|
|
3
3
|
|
|
4
|
-
from sqlleaf.dialects.base import
|
|
4
|
+
from sqlleaf.dialects.base import DialectConfig
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
class
|
|
7
|
+
class PostgresConfig(DialectConfig):
|
|
8
8
|
DIALECT = "postgres"
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
DEFAULT_USER_SCHEMA = "public"
|
|
10
|
+
DEFAULT_SYSTEM_SCHEMA = "pg_catalog"
|
|
11
|
+
DEFAULT_TEMPORARY_SCHEMA = "pg_temp"
|
|
11
12
|
PSEUDOCOLUMNS = {
|
|
12
13
|
"cmax": "OID",
|
|
13
14
|
"cmin": "OID",
|
|
@@ -19,14 +20,14 @@ class PostgresSettings(BaseDialectSettings):
|
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
@property
|
|
22
|
-
def
|
|
23
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
23
24
|
return [
|
|
24
25
|
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
25
26
|
for name, kind in self.PSEUDOCOLUMNS.items()
|
|
26
27
|
]
|
|
27
28
|
|
|
28
29
|
@property
|
|
29
|
-
def
|
|
30
|
+
def SYSTEM_FUNCTIONS(self) -> dict[str, list[str]]:
|
|
30
31
|
"""
|
|
31
32
|
Map function names to their returned column names.
|
|
32
33
|
"""
|
|
@@ -48,7 +49,7 @@ class PostgresSettings(BaseDialectSettings):
|
|
|
48
49
|
|
|
49
50
|
|
|
50
51
|
# sqlglot is missing pseudocolumns for Postgres
|
|
51
|
-
postgres.Postgres.PSEUDOCOLUMNS = {c.upper() for c in
|
|
52
|
+
postgres.Postgres.PSEUDOCOLUMNS = {c.upper() for c in PostgresConfig.PSEUDOCOLUMNS.keys()}
|
|
52
53
|
|
|
53
54
|
# Prevents pseudocolumns from being included in 'SELECT *' expansions
|
|
54
55
|
postgres.Postgres.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR = True
|
|
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,15 +2,12 @@ import json
|
|
|
2
2
|
import logging
|
|
3
3
|
import typing as t
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
from networkx import MultiDiGraph
|
|
6
6
|
|
|
7
|
-
from sqlleaf import exception, mappings, path
|
|
7
|
+
from sqlleaf import exception, mappings, path
|
|
8
8
|
from sqlleaf.models.hook import Hook
|
|
9
9
|
from sqlleaf.models.node import EdgeAttributes, GraphAttributes, N, NodeAttributes
|
|
10
|
-
from sqlleaf.models.query import
|
|
11
|
-
Q,
|
|
12
|
-
)
|
|
13
|
-
from sqlleaf.path import LineagePath
|
|
10
|
+
from sqlleaf.models.query import Q
|
|
14
11
|
from sqlleaf.processors.collector import collector
|
|
15
12
|
from sqlleaf.processors.generator import generator
|
|
16
13
|
|
|
@@ -25,13 +22,12 @@ class Lineage:
|
|
|
25
22
|
|
|
26
23
|
def __init__(self):
|
|
27
24
|
self.graph = new_graph() # The graph that contains all lineage
|
|
28
|
-
self.subgraphs: list[
|
|
29
|
-
self.
|
|
30
|
-
self.collected_queries: collector.CollectQueryResult | None = None
|
|
25
|
+
self.subgraphs: list[MultiDiGraph] = [] # The subgraphs that make up the main graph
|
|
26
|
+
self.collected_queries = collector.CollectQueryResult()
|
|
31
27
|
self.user_defined_hooks: list[Hook] = []
|
|
32
28
|
self.object_mapping: mappings.ObjectMapping | None = None
|
|
33
29
|
|
|
34
|
-
def generate(self, sql: str, dialect: str, on_error: str = "
|
|
30
|
+
def generate(self, sql: str, dialect: str, on_error: str = "error") -> None:
|
|
35
31
|
"""
|
|
36
32
|
Generate lineage for one or more SQL statements.
|
|
37
33
|
"""
|
|
@@ -58,7 +54,7 @@ class Lineage:
|
|
|
58
54
|
self.merge_graph(graph)
|
|
59
55
|
self.graph.graph["attrs"].add_query_to_graph(parent_holder)
|
|
60
56
|
|
|
61
|
-
def merge_graph(self, subgraph:
|
|
57
|
+
def merge_graph(self, subgraph: MultiDiGraph) -> None:
|
|
62
58
|
"""
|
|
63
59
|
Merge the subgraph into the main graph, and also track the individual subgraphs.
|
|
64
60
|
"""
|
|
@@ -110,13 +106,13 @@ class Lineage:
|
|
|
110
106
|
|
|
111
107
|
Examples:
|
|
112
108
|
# Find all columns whose name is 'price'
|
|
113
|
-
|
|
109
|
+
find_nodes(ColumnNode(column="price"))
|
|
114
110
|
|
|
115
111
|
# Find two columns: one unqualified, another fully qualified
|
|
116
|
-
|
|
112
|
+
find_nodes(ColumnNode(column="age"), ColumnNode(schema="fruit", table="raw", column="name"))
|
|
117
113
|
|
|
118
114
|
# Find all functions
|
|
119
|
-
|
|
115
|
+
find_nodes(FunctionNode())
|
|
120
116
|
"""
|
|
121
117
|
if self.object_mapping is None:
|
|
122
118
|
return []
|
|
@@ -137,6 +133,68 @@ class Lineage:
|
|
|
137
133
|
|
|
138
134
|
return found
|
|
139
135
|
|
|
136
|
+
def paths_downstream_from(self, node: NodeAttributes) -> t.Generator[path.LineagePath]:
|
|
137
|
+
"""
|
|
138
|
+
Find all the paths that begin with the given node.
|
|
139
|
+
|
|
140
|
+
The node is looked up with `find_nodes()`, so a partial node matches every node with the same name.
|
|
141
|
+
|
|
142
|
+
Examples:
|
|
143
|
+
# Find every path downward from a column
|
|
144
|
+
paths_downstream_from(ColumnNode(column="price"))
|
|
145
|
+
"""
|
|
146
|
+
for start in self.find_nodes(node):
|
|
147
|
+
for hops in path.find_edges_from_root(self.graph, start.full_name):
|
|
148
|
+
if hops:
|
|
149
|
+
yield path.LineagePath(hops=hops)
|
|
150
|
+
|
|
151
|
+
def paths_upstream_from(self, node: NodeAttributes) -> t.Generator[path.LineagePath]:
|
|
152
|
+
"""
|
|
153
|
+
Find all the paths that end with the given node as their leaf.
|
|
154
|
+
|
|
155
|
+
The reverse of `paths_downstream_from()`. The node is looked up with `find_nodes()`, so a partial node
|
|
156
|
+
matches every node with the same name.
|
|
157
|
+
|
|
158
|
+
Examples:
|
|
159
|
+
# Find every path upward from a column
|
|
160
|
+
paths_upstream_from(ColumnNode(column="total"))
|
|
161
|
+
"""
|
|
162
|
+
reversed_graph = self.graph.reverse(copy=False)
|
|
163
|
+
for end in self.find_nodes(node):
|
|
164
|
+
for hops in path.find_edges_from_root(reversed_graph, end.full_name):
|
|
165
|
+
if hops:
|
|
166
|
+
yield path.LineagePath(hops=list(reversed(hops)))
|
|
167
|
+
|
|
168
|
+
def has_path(self, src: NodeAttributes, dst: NodeAttributes) -> bool:
|
|
169
|
+
"""
|
|
170
|
+
Check whether there is a path from any node matching the first node to any node matching the second.
|
|
171
|
+
|
|
172
|
+
Examples:
|
|
173
|
+
# Check whether price flows into total
|
|
174
|
+
has_path(ColumnNode(column="price"), ColumnNode(column="total"))
|
|
175
|
+
"""
|
|
176
|
+
from networkx import has_path as nx_has_path
|
|
177
|
+
|
|
178
|
+
return any(
|
|
179
|
+
nx_has_path(self.graph, s.full_name, d.full_name)
|
|
180
|
+
for s in self.find_nodes(src)
|
|
181
|
+
for d in self.find_nodes(dst)
|
|
182
|
+
if self.graph.has_node(s.full_name) and self.graph.has_node(d.full_name)
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
def paths_between_nodes(self, src: NodeAttributes, dst: NodeAttributes) -> t.Generator[path.LineagePath]:
|
|
186
|
+
"""
|
|
187
|
+
Find all the paths that begin with a node matching the first node and end with a node matching the second.
|
|
188
|
+
|
|
189
|
+
Examples:
|
|
190
|
+
# Find every path from price to total
|
|
191
|
+
paths_between_nodes(ColumnNode(column="price"), ColumnNode(column="total"))
|
|
192
|
+
"""
|
|
193
|
+
dst_names = {d.full_name for d in self.find_nodes(dst)}
|
|
194
|
+
|
|
195
|
+
for p in self.paths_downstream_from(src):
|
|
196
|
+
if p.hops[-1].child.full_name in dst_names:
|
|
197
|
+
yield p
|
|
140
198
|
|
|
141
199
|
def get_original_queries(self) -> list[Q]:
|
|
142
200
|
"""
|
|
@@ -150,7 +208,7 @@ class Lineage:
|
|
|
150
208
|
"""
|
|
151
209
|
return [q.transformed for q in self.graph.graph["attrs"].queries]
|
|
152
210
|
|
|
153
|
-
def get_paths(self) -> t.Generator[LineagePath]:
|
|
211
|
+
def get_paths(self) -> t.Generator[path.LineagePath]:
|
|
154
212
|
"""
|
|
155
213
|
paths: [
|
|
156
214
|
{
|
|
@@ -166,7 +224,7 @@ class Lineage:
|
|
|
166
224
|
for p in path.find_all_paths(graph=self.graph):
|
|
167
225
|
yield p
|
|
168
226
|
|
|
169
|
-
def print_json(self):
|
|
227
|
+
def print_json(self) -> None:
|
|
170
228
|
"""
|
|
171
229
|
Print the graph as JSON.
|
|
172
230
|
"""
|
|
@@ -192,65 +250,45 @@ class Lineage:
|
|
|
192
250
|
)
|
|
193
251
|
)
|
|
194
252
|
|
|
195
|
-
def print_tree(self, full_name=False):
|
|
253
|
+
def print_tree(self, full_name: bool = False) -> None:
|
|
196
254
|
"""
|
|
197
255
|
Print from the leaves to the root (as left to right) so that the tree is displayed correctly.
|
|
198
|
-
|
|
256
|
+
Mimics the `tree` utility on Linux.
|
|
199
257
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
258
|
+
For example, given query:
|
|
259
|
+
INSERT INTO fruit.processed
|
|
260
|
+
SELECT SUBSTRING(name, 2, 4) AS name
|
|
261
|
+
FROM fruit.raw
|
|
203
262
|
|
|
204
263
|
Output:
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
264
|
+
.
|
|
265
|
+
└── column[fruit.processed.name]
|
|
266
|
+
└── function[SUBSTRING]
|
|
267
|
+
├── column[fruit.raw.name]
|
|
268
|
+
├── literal[2]
|
|
269
|
+
└── literal[4]
|
|
211
270
|
"""
|
|
212
|
-
g = self.graph.reverse() # We print from the leaves to the roots
|
|
213
|
-
root_columns = util.get_root_nodes(g)
|
|
214
|
-
seen = set()
|
|
215
|
-
symbol = "└──"
|
|
216
|
-
|
|
271
|
+
g = self.graph.reverse(copy=False) # We print from the leaves to the roots
|
|
217
272
|
attr = "full_name" if full_name else "friendly_name"
|
|
218
273
|
|
|
219
|
-
|
|
274
|
+
def print_entry(name: str, prefix: str, is_last: bool, ancestors: frozenset[str]) -> None:
|
|
275
|
+
connector = "└── " if is_last else "├── "
|
|
276
|
+
print(prefix + connector + getattr(g.nodes[name]["attrs"], attr))
|
|
277
|
+
# A last entry has no siblings below it, so its children are indented instead of guided
|
|
278
|
+
child_prefix = prefix + (" " if is_last else "│ ")
|
|
279
|
+
print_children(name, child_prefix, ancestors | {name})
|
|
280
|
+
|
|
281
|
+
def print_children(name: str, prefix: str, ancestors: frozenset[str]) -> None:
|
|
282
|
+
children = sorted(n for n in g.successors(name) if n != name and n not in ancestors)
|
|
283
|
+
for i, child in enumerate(children):
|
|
284
|
+
print_entry(child, prefix, i == len(children) - 1, ancestors)
|
|
285
|
+
|
|
286
|
+
root_columns = path.get_root_nodes(g)
|
|
287
|
+
print(".")
|
|
220
288
|
for i, root in enumerate(root_columns):
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
# Swap the parent and child
|
|
225
|
-
parent_name = edge_attrs.child.full_name
|
|
226
|
-
child_name = edge_attrs.parent.full_name
|
|
227
|
-
num_descendents_of_child = len(nx.descendants(g, child_name))
|
|
228
|
-
|
|
229
|
-
parent_node = g.nodes[parent_name]["attrs"]
|
|
230
|
-
child_node = g.nodes[child_name]["attrs"]
|
|
231
|
-
|
|
232
|
-
if parent_name not in seen:
|
|
233
|
-
symbol = "└──"
|
|
234
|
-
|
|
235
|
-
# Print arrows
|
|
236
|
-
if depth > 0:
|
|
237
|
-
prefix = ((depth - 1) * 4 * " ") + f"{symbol} "
|
|
238
|
-
else:
|
|
239
|
-
prefix = ""
|
|
240
|
-
print("%s%s" % (prefix, getattr(parent_node, attr)))
|
|
241
|
-
seen.add(parent_name)
|
|
242
|
-
|
|
243
|
-
# Print the child if we're at the end of the path
|
|
244
|
-
if num_descendents_of_child == 0:
|
|
245
|
-
if depth == 0:
|
|
246
|
-
# Direct load (source -> target)
|
|
247
|
-
prefix = "└── "
|
|
248
|
-
else:
|
|
249
|
-
prefix = (depth * 4 * " ") + f"{symbol} "
|
|
250
|
-
print("%s%s" % (prefix, getattr(child_node, attr)))
|
|
251
|
-
seen.add(child_name)
|
|
252
|
-
|
|
253
|
-
def print_paths(self):
|
|
289
|
+
print_entry(root, "", i == len(root_columns) - 1, frozenset())
|
|
290
|
+
|
|
291
|
+
def print_paths(self) -> None:
|
|
254
292
|
"""
|
|
255
293
|
Iterate over all the paths in the graph and print each one.
|
|
256
294
|
|
|
@@ -302,13 +340,15 @@ class Lineage:
|
|
|
302
340
|
"""
|
|
303
341
|
self.user_defined_hooks = [udh for udh in self.user_defined_hooks if udh not in hooks]
|
|
304
342
|
|
|
305
|
-
def init_object_mapping(self, dialect: str):
|
|
343
|
+
def init_object_mapping(self, dialect: str) -> None:
|
|
306
344
|
if not self.object_mapping:
|
|
307
|
-
self.object_mapping = mappings.ObjectMapping(
|
|
345
|
+
self.object_mapping = mappings.ObjectMapping(
|
|
346
|
+
dialect=dialect, object_loader=collector.SystemObjectLoader(dialect)
|
|
347
|
+
)
|
|
308
348
|
|
|
309
349
|
|
|
310
|
-
def new_graph() ->
|
|
350
|
+
def new_graph() -> MultiDiGraph:
|
|
311
351
|
"""
|
|
312
352
|
A graph has attributes along with its node and edges.
|
|
313
353
|
"""
|
|
314
|
-
return
|
|
354
|
+
return MultiDiGraph(attrs=GraphAttributes())
|