sqlleaf 0.0.7__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 -20
- sqlleaf/dialects/athena/config.py +11 -3
- sqlleaf/dialects/base.py +41 -12
- sqlleaf/dialects/mysql/__init__.py +0 -0
- sqlleaf/dialects/mysql/config.py +33 -0
- sqlleaf/dialects/postgres/config.py +5 -5
- sqlleaf/dialects/redshift/__init__.py +0 -0
- sqlleaf/dialects/redshift/config.py +12 -0
- sqlleaf/exception.py +36 -9
- sqlleaf/lineage.py +7 -7
- sqlleaf/mappings.py +48 -20
- sqlleaf/models/context.py +2 -2
- sqlleaf/models/query/__init__.py +2 -0
- sqlleaf/models/query/base.py +9 -3
- sqlleaf/models/query/ctas.py +3 -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 +2 -2
- sqlleaf/models/query/select.py +13 -1
- sqlleaf/models/query/set.py +7 -7
- sqlleaf/models/query/table.py +6 -2
- sqlleaf/models/query/use.py +26 -0
- sqlleaf/models/query/user_defined_function.py +19 -1
- sqlleaf/path.py +6 -6
- sqlleaf/processors/collector/classify.py +62 -8
- sqlleaf/processors/collector/collector.py +25 -26
- sqlleaf/processors/generator/dialects/base.py +1 -1
- sqlleaf/processors/generator/generator.py +11 -8
- sqlleaf/processors/substitutor/substitute.py +37 -7
- sqlleaf/processors/transformer/base.py +30 -3
- sqlleaf/processors/transformer/transformer.py +8 -1
- sqlleaf/util/__init__.py +2 -0
- sqlleaf/util/expression.py +82 -5
- sqlleaf/util/graph.py +11 -10
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.8.dist-info}/METADATA +2 -2
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.8.dist-info}/RECORD +42 -37
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.8.dist-info}/WHEEL +0 -0
- {sqlleaf-0.0.7.dist-info → sqlleaf-0.0.8.dist-info}/licenses/LICENSE +0 -0
- {sqlleaf-0.0.7.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,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,9 +1,10 @@
|
|
|
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
|
DEFAULT_USER_CATALOG = "awsdatacatalog"
|
|
9
10
|
DEFAULT_SYSTEM_CATALOG = ""
|
|
@@ -77,8 +78,15 @@ class AthenaSettings(BaseDialectSettings):
|
|
|
77
78
|
}
|
|
78
79
|
|
|
79
80
|
@property
|
|
80
|
-
def
|
|
81
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
81
82
|
return [
|
|
82
83
|
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
83
84
|
for name, kind in self.PSEUDOCOLUMNS.items()
|
|
84
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
CHANGED
|
@@ -1,12 +1,35 @@
|
|
|
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
29
|
DEFAULT_USER_CATALOG = ""
|
|
9
30
|
DEFAULT_SYSTEM_CATALOG = ""
|
|
31
|
+
# The language of procedures that do not declare one explicitly
|
|
32
|
+
DEFAULT_PROCEDURE_LANGUAGE: str | None = None
|
|
10
33
|
# Metadata fields, keyed by their suffix (e.g. '$files' in 'my_table$files'), mapped to their column names and types
|
|
11
34
|
METADATA_FIELDS: dict[str, dict[str, str]] = {}
|
|
12
35
|
|
|
@@ -14,25 +37,23 @@ class BaseDialectSettings:
|
|
|
14
37
|
"""Automatically registers subclasses when they are defined."""
|
|
15
38
|
super().__init_subclass__(**kwargs)
|
|
16
39
|
if cls.DIALECT:
|
|
17
|
-
|
|
40
|
+
DialectConfig._dialects[cls.DIALECT] = cls
|
|
18
41
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
return BaseDialectSettings()
|
|
25
|
-
return target_class()
|
|
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))
|
|
26
47
|
|
|
27
48
|
@property
|
|
28
|
-
def
|
|
49
|
+
def SYSTEM_COLUMNS(self) -> list[exp.ColumnDef]:
|
|
29
50
|
"""
|
|
30
51
|
Represents system columns.
|
|
31
52
|
"""
|
|
32
53
|
return []
|
|
33
54
|
|
|
34
55
|
@property
|
|
35
|
-
def
|
|
56
|
+
def SYSTEM_FUNCTIONS(self) -> dict[str, list[str]]:
|
|
36
57
|
"""
|
|
37
58
|
Represents system functions.
|
|
38
59
|
"""
|
|
@@ -55,3 +76,11 @@ class BaseDialectSettings:
|
|
|
55
76
|
exp.ColumnDef(this=exp.to_identifier(name), kind=exp.DataType.build(kind, self.DIALECT))
|
|
56
77
|
for name, kind in self.METADATA_FIELDS[suffix].items()
|
|
57
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)
|
|
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,10 +1,10 @@
|
|
|
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
9
|
DEFAULT_USER_CATALOG = "public"
|
|
10
10
|
DEFAULT_SYSTEM_CATALOG = "pg_catalog"
|
|
@@ -19,14 +19,14 @@ 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
|
"""
|
|
@@ -48,7 +48,7 @@ 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
52
|
|
|
53
53
|
# Prevents pseudocolumns from being included in 'SELECT *' expansions
|
|
54
54
|
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,7 +2,7 @@ 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
|
|
@@ -25,13 +25,13 @@ 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
|
"""
|
|
@@ -58,7 +58,7 @@ class Lineage:
|
|
|
58
58
|
self.merge_graph(graph)
|
|
59
59
|
self.graph.graph["attrs"].add_query_to_graph(parent_holder)
|
|
60
60
|
|
|
61
|
-
def merge_graph(self, subgraph:
|
|
61
|
+
def merge_graph(self, subgraph: MultiDiGraph) -> None:
|
|
62
62
|
"""
|
|
63
63
|
Merge the subgraph into the main graph, and also track the individual subgraphs.
|
|
64
64
|
"""
|
|
@@ -224,7 +224,7 @@ class Lineage:
|
|
|
224
224
|
# Swap the parent and child
|
|
225
225
|
parent_name = edge_attrs.child.full_name
|
|
226
226
|
child_name = edge_attrs.parent.full_name
|
|
227
|
-
num_descendents_of_child = len(
|
|
227
|
+
num_descendents_of_child = len(descendants(g, child_name))
|
|
228
228
|
|
|
229
229
|
parent_node = g.nodes[parent_name]["attrs"]
|
|
230
230
|
child_node = g.nodes[child_name]["attrs"]
|
|
@@ -307,8 +307,8 @@ class Lineage:
|
|
|
307
307
|
self.object_mapping = mappings.ObjectMapping(dialect=dialect, object_loader=collector.SystemObjectLoader(dialect))
|
|
308
308
|
|
|
309
309
|
|
|
310
|
-
def new_graph() ->
|
|
310
|
+
def new_graph() -> MultiDiGraph:
|
|
311
311
|
"""
|
|
312
312
|
A graph has attributes along with its node and edges.
|
|
313
313
|
"""
|
|
314
|
-
return
|
|
314
|
+
return MultiDiGraph(attrs=GraphAttributes())
|
sqlleaf/mappings.py
CHANGED
|
@@ -11,8 +11,7 @@ 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
|
|
15
|
-
from sqlleaf.path import NodeIndex
|
|
14
|
+
from sqlleaf.dialects.base import DialectConfig
|
|
16
15
|
from sqlleaf.models.query import (
|
|
17
16
|
CallQuery,
|
|
18
17
|
CTASQuery,
|
|
@@ -30,6 +29,7 @@ from sqlleaf.models.query import (
|
|
|
30
29
|
UserDefinedFunctionQuery,
|
|
31
30
|
ViewQuery,
|
|
32
31
|
)
|
|
32
|
+
from sqlleaf.path import NodeIndex
|
|
33
33
|
|
|
34
34
|
ColumnMapping = t.Union[dict, str, list]
|
|
35
35
|
FunctionCallable = ProcedureQuery | UserDefinedFunctionQuery
|
|
@@ -37,25 +37,47 @@ FunctionCallable = ProcedureQuery | UserDefinedFunctionQuery
|
|
|
37
37
|
logger = logging.getLogger("sqlleaf")
|
|
38
38
|
|
|
39
39
|
|
|
40
|
+
ParamMode = t.Literal["IN", "OUT", "INOUT"]
|
|
41
|
+
|
|
42
|
+
|
|
40
43
|
@dataclass
|
|
41
44
|
class ParamBinding:
|
|
42
45
|
"""One parameter's binding for the lifetime of a single CALL."""
|
|
43
46
|
|
|
44
47
|
value: exp.Expr
|
|
48
|
+
mode: ParamMode
|
|
45
49
|
arg_name: str | None = None
|
|
46
50
|
|
|
51
|
+
@property
|
|
52
|
+
def is_input(self) -> bool:
|
|
53
|
+
return self.mode in ("IN", "INOUT")
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def is_output(self) -> bool:
|
|
57
|
+
return self.mode in ("OUT", "INOUT")
|
|
58
|
+
|
|
47
59
|
|
|
48
60
|
@dataclass
|
|
49
61
|
class VariableScope:
|
|
50
|
-
"""
|
|
62
|
+
"""Holds variables related to one CALL statement.
|
|
63
|
+
|
|
64
|
+
The two are separated because they have different lifetimes:
|
|
65
|
+
- blocks are created and destroyed along with a BEGIN block
|
|
66
|
+
- bindings are kept across all blocks at its level and below
|
|
67
|
+
"""
|
|
51
68
|
|
|
52
|
-
|
|
69
|
+
# A stack of DECLARE/BEGIN blocks. Holds variable names mapped to their current values.
|
|
70
|
+
blocks: list[dict[str, exp.Expr]] = field(default_factory=lambda: [{}])
|
|
71
|
+
# Parameters passed to a CALL(). Holds parameter names mapped to their bound values. Used for OUT/INOUT write-back
|
|
53
72
|
bindings: dict[str, ParamBinding] = field(default_factory=dict)
|
|
54
73
|
|
|
55
74
|
|
|
56
75
|
class Variables:
|
|
76
|
+
"""
|
|
77
|
+
Tracks the state of every variable currently available to SQL statements.
|
|
78
|
+
"""
|
|
57
79
|
def __init__(self):
|
|
58
|
-
#
|
|
80
|
+
# An initial scope exists for the top-level statements
|
|
59
81
|
self.scopes: list[VariableScope] = [VariableScope()]
|
|
60
82
|
|
|
61
83
|
@property
|
|
@@ -66,7 +88,6 @@ class Variables:
|
|
|
66
88
|
def _active_bindings(self) -> dict[str, ParamBinding]:
|
|
67
89
|
return self.scopes[-1].bindings
|
|
68
90
|
|
|
69
|
-
# ---- Block API ----
|
|
70
91
|
def push_block(self) -> None:
|
|
71
92
|
"""Enter a new DECLARE/BEGIN block."""
|
|
72
93
|
self._active_blocks.append({})
|
|
@@ -76,7 +97,6 @@ class Variables:
|
|
|
76
97
|
if self._active_blocks:
|
|
77
98
|
self._active_blocks.pop()
|
|
78
99
|
|
|
79
|
-
# ---- Scope API ----
|
|
80
100
|
def push_scope(self, bindings: dict[str, ParamBinding]) -> None:
|
|
81
101
|
"""Enter a CALL boundary."""
|
|
82
102
|
self.scopes.append(VariableScope(bindings=bindings))
|
|
@@ -88,7 +108,7 @@ class Variables:
|
|
|
88
108
|
scope = self.scopes.pop()
|
|
89
109
|
if write_back:
|
|
90
110
|
for binding in scope.bindings.values():
|
|
91
|
-
if binding.arg_name is not None:
|
|
111
|
+
if binding.is_output and binding.arg_name is not None:
|
|
92
112
|
self.set_variable(binding.arg_name, binding.value)
|
|
93
113
|
|
|
94
114
|
def declare_variable(self, name: str, value: exp.Expr | None = None) -> None:
|
|
@@ -97,8 +117,10 @@ class Variables:
|
|
|
97
117
|
self._active_blocks[-1][name] = val
|
|
98
118
|
logger.debug(f"Declared variable: {name} := {val}")
|
|
99
119
|
|
|
100
|
-
def set_variable(self, name: str, value: exp.Expr) -> None:
|
|
101
|
-
"""
|
|
120
|
+
def set_variable(self, name: str, value: exp.Expr, declare: bool = False) -> None:
|
|
121
|
+
"""
|
|
122
|
+
Assign a variable in the nearest block where it was declared.
|
|
123
|
+
"""
|
|
102
124
|
for block in reversed(self._active_blocks):
|
|
103
125
|
if name in block:
|
|
104
126
|
block[name] = value
|
|
@@ -110,6 +132,10 @@ class Variables:
|
|
|
110
132
|
binding.value = value
|
|
111
133
|
return
|
|
112
134
|
|
|
135
|
+
if declare:
|
|
136
|
+
self.declare_variable(name, value)
|
|
137
|
+
return
|
|
138
|
+
|
|
113
139
|
raise exception.MappingError(f'"{name}" is not a known variable')
|
|
114
140
|
|
|
115
141
|
def get_variable(self, name: str, raise_on_missing: bool = True) -> exp.Expr | None:
|
|
@@ -124,6 +150,10 @@ class Variables:
|
|
|
124
150
|
raise exception.MappingError(f"Could not find value for variable: {name}")
|
|
125
151
|
return None
|
|
126
152
|
|
|
153
|
+
def get_variables(self) -> dict[str, exp.Expr]:
|
|
154
|
+
"""Get all variables currently visible."""
|
|
155
|
+
return self.get_scope()
|
|
156
|
+
|
|
127
157
|
def get_variables_for(self, expressions: list[exp.Expr]) -> list[exp.Expr]:
|
|
128
158
|
"""
|
|
129
159
|
Given a list of expressions as keys, fetch their values from the variable scope if they exist.
|
|
@@ -168,14 +198,13 @@ class ObjectMapping(MappingSchema):
|
|
|
168
198
|
) # Set `normalize=False` to prevent an unnecessary second parse.
|
|
169
199
|
self.kind_mapping = {}
|
|
170
200
|
self.kind_mapping_trie = {}
|
|
171
|
-
|
|
201
|
+
config = DialectConfig(dialect)
|
|
172
202
|
# The catalog that unqualified user objects are created in, and the one holding system objects
|
|
173
|
-
self.current_user_catalog: str =
|
|
174
|
-
self.current_system_catalog: str =
|
|
203
|
+
self.current_user_catalog: str = config.DEFAULT_USER_CATALOG
|
|
204
|
+
self.current_system_catalog: str = config.DEFAULT_SYSTEM_CATALOG
|
|
205
|
+
self.current_database: str | None = None # For MySQL
|
|
175
206
|
# Load system objects lazily from disk
|
|
176
207
|
self.system_object_loader = object_loader
|
|
177
|
-
# Session/global variables (e.g., SET var = ...)
|
|
178
|
-
self.session_variables: dict[str, exp.Expr] = {}
|
|
179
208
|
self.variables = Variables()
|
|
180
209
|
# Nodes that have been added to the graph, indexed by class
|
|
181
210
|
self.node_index = NodeIndex()
|
|
@@ -392,8 +421,9 @@ class ObjectMapping(MappingSchema):
|
|
|
392
421
|
else:
|
|
393
422
|
knd = "CREATE " + {"udf": "FUNCTION"}.get(kind, kind).upper()
|
|
394
423
|
|
|
395
|
-
raise exception.
|
|
396
|
-
|
|
424
|
+
raise exception.raise_error(
|
|
425
|
+
exception.MappingError,
|
|
426
|
+
f"Could not find {kind} '{object.this}'. Did you forget to define a '{knd}' statement?",
|
|
397
427
|
)
|
|
398
428
|
return None
|
|
399
429
|
|
|
@@ -457,9 +487,7 @@ class ObjectMapping(MappingSchema):
|
|
|
457
487
|
|
|
458
488
|
return resolve_overloaded_function(node, candidates)
|
|
459
489
|
|
|
460
|
-
def lookup_procedure_call(
|
|
461
|
-
self, node: CallQuery, args: list[exp.Expr] | None = None
|
|
462
|
-
) -> ProcedureQuery | None:
|
|
490
|
+
def lookup_procedure_call(self, node: CallQuery, args: list[exp.Expr] | None = None) -> ProcedureQuery | None:
|
|
463
491
|
"""
|
|
464
492
|
Looks up the procedure definition for a CALL statement.
|
|
465
493
|
Returns the matched procedure definition, or None if no procedure with that name exists.
|
sqlleaf/models/context.py
CHANGED
|
@@ -5,7 +5,7 @@ import logging
|
|
|
5
5
|
import typing as t
|
|
6
6
|
from dataclasses import InitVar, dataclass
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
from networkx import MultiDiGraph
|
|
9
9
|
from sqlglot import exp
|
|
10
10
|
from sqlglot.optimizer import Scope, traverse_scope
|
|
11
11
|
|
|
@@ -65,7 +65,7 @@ Holds all the information required to generate lineage for an expression.
|
|
|
65
65
|
"""
|
|
66
66
|
@dataclass(frozen=True)
|
|
67
67
|
class GeneratorContext[Q, N]:
|
|
68
|
-
graph:
|
|
68
|
+
graph: MultiDiGraph
|
|
69
69
|
query: Q
|
|
70
70
|
expr: exp.Expr
|
|
71
71
|
scope: TableOrScopeType
|
sqlleaf/models/query/__init__.py
CHANGED
|
@@ -34,6 +34,7 @@ from sqlleaf.models.query.sequence import SequenceQuery as SequenceQuery
|
|
|
34
34
|
from sqlleaf.models.query.set import SetQuery as SetQuery
|
|
35
35
|
from sqlleaf.models.query.stage import StageQuery as StageQuery
|
|
36
36
|
from sqlleaf.models.query.table import TableQuery as TableQuery
|
|
37
|
+
from sqlleaf.models.query.use import UseQuery as UseQuery
|
|
37
38
|
from sqlleaf.models.query.trigger import TriggerQuery as TriggerQuery
|
|
38
39
|
from sqlleaf.models.query.type import TypeQuery as TypeQuery
|
|
39
40
|
from sqlleaf.models.query.unload import UnloadQuery as UnloadQuery
|
|
@@ -83,6 +84,7 @@ __all__ = [
|
|
|
83
84
|
"SetQuery",
|
|
84
85
|
"StageQuery",
|
|
85
86
|
"TableQuery",
|
|
87
|
+
"UseQuery",
|
|
86
88
|
"TriggerQuery",
|
|
87
89
|
"TypeQuery",
|
|
88
90
|
"UnloadQuery",
|
sqlleaf/models/query/base.py
CHANGED
|
@@ -134,8 +134,8 @@ class Query:
|
|
|
134
134
|
"""
|
|
135
135
|
Compute the source and target expressions for a query.
|
|
136
136
|
"""
|
|
137
|
-
source_exprs:
|
|
138
|
-
target_exprs:
|
|
137
|
+
source_exprs: t.Sequence[exp.Expr] = []
|
|
138
|
+
target_exprs: t.Sequence[exp.Expr] = []
|
|
139
139
|
|
|
140
140
|
if source_info and source_info.type == SqlObjectType.SET and isinstance(source_info.expression, list):
|
|
141
141
|
# UPDATE .. SET a = 1: the right-hand side is the source, the left-hand column is the target
|
|
@@ -166,12 +166,18 @@ class Query:
|
|
|
166
166
|
exp.ColumnDef(this=exp.to_identifier(col.alias_or_name), kind=col.unalias().type)
|
|
167
167
|
for col in source_exprs
|
|
168
168
|
]
|
|
169
|
+
elif target_info.type == SqlObjectType.TABLE and not target_exprs and source_info.type == SqlObjectType.SELECT:
|
|
170
|
+
# SELECT .. INTO <new table>: the new table's columns are the projections of the select
|
|
171
|
+
target_exprs = [
|
|
172
|
+
exp.ColumnDef(this=exp.to_identifier(col.alias_or_name), kind=col.unalias().type)
|
|
173
|
+
for col in source_exprs
|
|
174
|
+
]
|
|
169
175
|
|
|
170
176
|
source_info = dataclasses.replace(source_info, expressions=source_exprs) if source_info else None
|
|
171
177
|
target_info = dataclasses.replace(target_info, expressions=target_exprs) if target_info else None
|
|
172
178
|
return source_info, target_info
|
|
173
179
|
|
|
174
|
-
def _get_table_column_copies(self, table: exp.Table | exp.Var | exp.Schema) -> list[exp.
|
|
180
|
+
def _get_table_column_copies(self, table: exp.Table | exp.Var | exp.Schema) -> list[exp.ColumnDef]:
|
|
175
181
|
"""
|
|
176
182
|
Return copies of a table's columns, so that the object mapping is never aliased.
|
|
177
183
|
"""
|
sqlleaf/models/query/ctas.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
import typing as t
|
|
4
|
-
|
|
5
3
|
from sqlglot import exp
|
|
6
4
|
|
|
7
5
|
from sqlleaf import mappings, util
|
|
8
6
|
from sqlleaf.models.query.base import Query
|
|
9
7
|
from sqlleaf.models.query.table import TableQuery
|
|
10
8
|
from sqlleaf.typing import SourceInfo, TargetInfo
|
|
9
|
+
from sqlleaf.util import validate_athena_table_options
|
|
11
10
|
|
|
12
11
|
|
|
13
12
|
class CTASQuery(Query):
|
|
@@ -22,6 +21,8 @@ class CTASQuery(Query):
|
|
|
22
21
|
system_columns: list[exp.ColumnDef],
|
|
23
22
|
statement_index: int,
|
|
24
23
|
):
|
|
24
|
+
validate_athena_table_options(expr, dialect, is_ctas=True)
|
|
25
|
+
|
|
25
26
|
source = expr.expression
|
|
26
27
|
if source is None:
|
|
27
28
|
if exec_prop := expr.find(exp.ExecuteAsProperty):
|
|
@@ -12,7 +12,7 @@ class AssignmentQuery(Query):
|
|
|
12
12
|
|
|
13
13
|
def __init__(
|
|
14
14
|
self,
|
|
15
|
-
expr: pgexp.PGDeclareItem | exp.PropertyEQ,
|
|
15
|
+
expr: pgexp.PGDeclareItem | exp.PropertyEQ | exp.Declare,
|
|
16
16
|
dialect: str,
|
|
17
17
|
object_mapping: mappings.ObjectMapping,
|
|
18
18
|
statement_index: int,
|
|
@@ -28,10 +28,14 @@ class AssignmentQuery(Query):
|
|
|
28
28
|
|
|
29
29
|
@property
|
|
30
30
|
def is_declaration(self) -> bool:
|
|
31
|
-
return isinstance(self.statement, pgexp.PGDeclareItem)
|
|
31
|
+
return isinstance(self.statement, (pgexp.PGDeclareItem, exp.Declare))
|
|
32
32
|
|
|
33
33
|
def get_key(self) -> exp.Expr:
|
|
34
|
+
if isinstance(self.statement, exp.Declare):
|
|
35
|
+
return self.statement.expressions[0].this[0].name
|
|
34
36
|
return self.statement.this.name
|
|
35
37
|
|
|
36
38
|
def get_value(self)-> exp.Expr | None:
|
|
39
|
+
if isinstance(self.statement, exp.Declare):
|
|
40
|
+
return self.statement.expressions[0].args.get("default") or exp.Null()
|
|
37
41
|
return self.statement.args.get("expression") or self.statement.args.get("query") or exp.Null()
|
sqlleaf/models/query/execute.py
CHANGED
|
@@ -22,6 +22,12 @@ class ExecuteQueryProperties:
|
|
|
22
22
|
EXECUTE <name>(<arguments>);
|
|
23
23
|
"""
|
|
24
24
|
expression_name = expr.expression.name
|
|
25
|
+
if dialect == "mysql":
|
|
26
|
+
# EXECUTE stmt_name [USING @var [, @var] ...]
|
|
27
|
+
name, _, using = expression_name.partition(" USING ")
|
|
28
|
+
arguments = sqlglot.parse_one(f"SELECT {using}", read=dialect).expressions if using else []
|
|
29
|
+
return cls(name=name, arguments=arguments)
|
|
30
|
+
|
|
25
31
|
parsed = sqlglot.parse_one(expression_name, read=dialect)
|
|
26
32
|
|
|
27
33
|
if isinstance(parsed, exp.Anonymous):
|