skifer-core 4.2.0__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.
- skifer/__init__.py +96 -0
- skifer/core/__init__.py +29 -0
- skifer/core/capability_matrix.py +136 -0
- skifer/core/connector.py +71 -0
- skifer/core/constants.py +66 -0
- skifer/core/dialect.py +47 -0
- skifer/core/ir.py +629 -0
- skifer/core/json_schema.py +708 -0
- skifer/core/op_catalog.py +393 -0
- skifer/core/registry.py +189 -0
- skifer/core/rule_analyzer.py +580 -0
- skifer/core/schema_loader.py +1944 -0
- skifer/core/sql_compiler.py +618 -0
- skifer_core-4.2.0.dist-info/METADATA +768 -0
- skifer_core-4.2.0.dist-info/RECORD +17 -0
- skifer_core-4.2.0.dist-info/WHEEL +4 -0
- skifer_core-4.2.0.dist-info/licenses/LICENSE +21 -0
skifer/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Skifer — declarative data engineering framework for Spark and Databricks."""
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version as _distribution_version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = _distribution_version("skifer")
|
|
9
|
+
except PackageNotFoundError: # running from an uninstalled source checkout
|
|
10
|
+
__version__ = "unknown"
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .core.core import SkiferEngine
|
|
14
|
+
from .core.spark_backend import SparkBackend
|
|
15
|
+
from .core.registry import RuleRegistry
|
|
16
|
+
from .core.config import ConfigurationManager
|
|
17
|
+
from .utils import safe_columns
|
|
18
|
+
from .utils import setup_notebook
|
|
19
|
+
from .utils import configure_logging
|
|
20
|
+
from .core.schema_loader import load_schema
|
|
21
|
+
from .core.schema_loader import parse_schema
|
|
22
|
+
from .core.rule_analyzer import RuleAnalyzer
|
|
23
|
+
from .core.rule_planner import RulePlanner
|
|
24
|
+
from .core.rule_planner import RuleCycleError
|
|
25
|
+
from .core.rule_executor import RuleExecutor
|
|
26
|
+
from .core.catalog_inspector import CatalogInspector
|
|
27
|
+
from .core.catalog_inspector import CatalogError
|
|
28
|
+
from .agentic.builder_agent import BuilderAgent
|
|
29
|
+
from .lineage import LineageTracker
|
|
30
|
+
from .lineage import LineageGraph
|
|
31
|
+
from .lineage import LineageEdge
|
|
32
|
+
from .lineage import DataDictionary
|
|
33
|
+
from .lineage import LineageRenderer
|
|
34
|
+
|
|
35
|
+
_EXPORTS = {
|
|
36
|
+
"SkiferEngine": "core.core",
|
|
37
|
+
"RuleRegistry": "core.registry",
|
|
38
|
+
"ConfigurationManager": "core.config",
|
|
39
|
+
"safe_columns": "utils",
|
|
40
|
+
"setup_notebook": "utils",
|
|
41
|
+
"configure_logging": "utils",
|
|
42
|
+
"load_schema": "core.schema_loader",
|
|
43
|
+
"parse_schema": "core.schema_loader",
|
|
44
|
+
"RuleAnalyzer": "core.rule_analyzer",
|
|
45
|
+
"RulePlanner": "core.rule_planner",
|
|
46
|
+
"RuleCycleError": "core.rule_planner",
|
|
47
|
+
"RuleExecutor": "core.rule_executor",
|
|
48
|
+
"CatalogInspector": "core.catalog_inspector",
|
|
49
|
+
"CatalogError": "core.catalog_inspector",
|
|
50
|
+
"BuilderAgent": "agentic.builder_agent",
|
|
51
|
+
"LineageTracker": "lineage",
|
|
52
|
+
"LineageGraph": "lineage",
|
|
53
|
+
"LineageEdge": "lineage",
|
|
54
|
+
"DataDictionary": "lineage",
|
|
55
|
+
"LineageRenderer": "lineage",
|
|
56
|
+
"SparkBackend": "core.spark_backend",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def __getattr__(name):
|
|
61
|
+
module = _EXPORTS.get(name)
|
|
62
|
+
if module is None:
|
|
63
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
64
|
+
obj = getattr(importlib.import_module(f"{__name__}.{module}"), name)
|
|
65
|
+
globals()[name] = obj
|
|
66
|
+
return obj
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def __dir__():
|
|
70
|
+
return sorted(__all__)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
__all__ = [
|
|
74
|
+
"__version__",
|
|
75
|
+
"SkiferEngine",
|
|
76
|
+
"SparkBackend",
|
|
77
|
+
"RuleRegistry",
|
|
78
|
+
"ConfigurationManager",
|
|
79
|
+
"safe_columns",
|
|
80
|
+
"setup_notebook",
|
|
81
|
+
"configure_logging",
|
|
82
|
+
"load_schema",
|
|
83
|
+
"parse_schema",
|
|
84
|
+
"RuleAnalyzer",
|
|
85
|
+
"RulePlanner",
|
|
86
|
+
"RuleCycleError",
|
|
87
|
+
"RuleExecutor",
|
|
88
|
+
"CatalogInspector",
|
|
89
|
+
"CatalogError",
|
|
90
|
+
"BuilderAgent",
|
|
91
|
+
"LineageTracker",
|
|
92
|
+
"LineageGraph",
|
|
93
|
+
"LineageEdge",
|
|
94
|
+
"DataDictionary",
|
|
95
|
+
"LineageRenderer",
|
|
96
|
+
]
|
skifer/core/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
from typing import TYPE_CHECKING
|
|
3
|
+
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from .core import SkiferEngine
|
|
6
|
+
from .registry import RuleRegistry
|
|
7
|
+
from .config import ConfigurationManager
|
|
8
|
+
|
|
9
|
+
_EXPORTS = {
|
|
10
|
+
"SkiferEngine": "core",
|
|
11
|
+
"RuleRegistry": "registry",
|
|
12
|
+
"ConfigurationManager": "config",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def __getattr__(name):
|
|
17
|
+
module = _EXPORTS.get(name)
|
|
18
|
+
if module is None:
|
|
19
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
20
|
+
obj = getattr(importlib.import_module(f"{__name__}.{module}"), name)
|
|
21
|
+
globals()[name] = obj
|
|
22
|
+
return obj
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def __dir__():
|
|
26
|
+
return sorted(__all__)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = ["SkiferEngine", "RuleRegistry", "ConfigurationManager"]
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""SQL capabilities default to conditional outside Databricks.
|
|
2
|
+
|
|
3
|
+
DuckDB support is explicitly promoted by executed parity (46.3); Snowflake
|
|
4
|
+
parity remains pending (46.6).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Supported:
|
|
14
|
+
kind: Literal["supported"] = field(default="supported", init=False)
|
|
15
|
+
reason: str = field(default="", init=False)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Conditional:
|
|
20
|
+
reason: str
|
|
21
|
+
kind: Literal["conditional"] = field(default="conditional", init=False)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Refused:
|
|
26
|
+
reason: str
|
|
27
|
+
kind: Literal["refused"] = field(default="refused", init=False)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
Status = Supported | Conditional | Refused
|
|
31
|
+
|
|
32
|
+
# Deliberately enumerated, not generated from op_catalog: adding a language
|
|
33
|
+
# operation must fail the drift guard until its capability is declared here.
|
|
34
|
+
_KEYS = frozenset({
|
|
35
|
+
"filter:is_null", "filter:is_not_null", "filter:equals", "filter:not_equals",
|
|
36
|
+
"filter:greater_than", "filter:less_than", "filter:greater_than_equal",
|
|
37
|
+
"filter:less_than_equal", "filter:in", "filter:not_in", "filter:between",
|
|
38
|
+
"filter:not_between", "filter:contains", "filter:not_contains",
|
|
39
|
+
"filter:starts_with", "filter:ends_with", "filter:like", "filter:not_like", "filter:sql",
|
|
40
|
+
"op:cast", "op:upper", "op:lower", "op:trim", "op:length", "op:split",
|
|
41
|
+
"op:substring", "op:round", "op:abs", "op:ceil", "op:to_date", "op:nvl",
|
|
42
|
+
"op:coalesce", "op:lit", "op:expr", "op:col", "op:when", "op:then", "op:else",
|
|
43
|
+
"agg:sum", "agg:avg", "agg:min", "agg:max", "agg:count", "agg:count_distinct",
|
|
44
|
+
"agg:sum_distinct", "agg:approx_count_distinct", "agg:stddev", "agg:variance",
|
|
45
|
+
"agg:first", "agg:last",
|
|
46
|
+
"join:inner", "join:left", "join:right", "join:full", "join:cross",
|
|
47
|
+
"join:left_semi", "join:left_anti",
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
# Only these explicitly named keys have unconditional executed parity evidence.
|
|
51
|
+
_DUCKDB_PROVEN = frozenset({
|
|
52
|
+
"filter:is_null", "filter:is_not_null", "filter:equals", "filter:not_equals",
|
|
53
|
+
"filter:greater_than", "filter:less_than", "filter:greater_than_equal",
|
|
54
|
+
"filter:less_than_equal", "filter:in", "filter:not_in", "filter:between",
|
|
55
|
+
"filter:not_between", "filter:contains", "filter:not_contains",
|
|
56
|
+
"filter:starts_with", "filter:ends_with", "filter:like", "filter:not_like",
|
|
57
|
+
"op:upper", "op:lower", "op:trim", "op:length", "op:substring", "op:round",
|
|
58
|
+
"op:abs", "op:ceil", "op:nvl", "op:coalesce", "op:lit", "op:col",
|
|
59
|
+
"op:when", "op:then", "op:else",
|
|
60
|
+
"agg:sum", "agg:min", "agg:max", "agg:count", "agg:count_distinct",
|
|
61
|
+
"agg:sum_distinct", "agg:stddev", "agg:variance",
|
|
62
|
+
"join:inner", "join:left", "join:right", "join:full", "join:cross",
|
|
63
|
+
"join:left_semi", "join:left_anti",
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
_matrix: dict[str, dict[str, Status]] = {
|
|
67
|
+
"databricks": {key: Supported() for key in _KEYS},
|
|
68
|
+
"duckdb": {key: Conditional("parity not executed for this key (Plan 46.3)") for key in _KEYS},
|
|
69
|
+
"snowflake": {key: Conditional("parity not executed against a Snowflake account") for key in _KEYS},
|
|
70
|
+
}
|
|
71
|
+
for _key in _DUCKDB_PROVEN:
|
|
72
|
+
_matrix["duckdb"][_key] = Supported()
|
|
73
|
+
for _target in ("duckdb", "snowflake"):
|
|
74
|
+
for _key in ("filter:sql", "op:expr"):
|
|
75
|
+
_matrix[_target][_key] = Refused(
|
|
76
|
+
"raw SQL fragments are authored in Spark SQL and are not rendered for another target"
|
|
77
|
+
)
|
|
78
|
+
_matrix[_target]["op:split"] = Conditional(
|
|
79
|
+
"Spark split() takes a regex, the target splits on a literal separator"
|
|
80
|
+
)
|
|
81
|
+
_matrix[_target]["op:to_date"] = Conditional(
|
|
82
|
+
"date format strings differ between Spark and the target"
|
|
83
|
+
)
|
|
84
|
+
_matrix[_target]["op:cast"] = Conditional(
|
|
85
|
+
"type names are rendered by sqlglot; cast failure semantics are unverified until parity (Plan 46.6)"
|
|
86
|
+
)
|
|
87
|
+
for _key in ("agg:first", "agg:last"):
|
|
88
|
+
_matrix["snowflake"][_key] = Refused(
|
|
89
|
+
"non-deterministic without ORDER BY; no portable equivalent"
|
|
90
|
+
)
|
|
91
|
+
for _key in ("join:left_semi", "join:left_anti"):
|
|
92
|
+
_matrix["snowflake"][_key] = Refused("no SEMI/ANTI JOIN syntax on this target")
|
|
93
|
+
|
|
94
|
+
_matrix["duckdb"]["op:cast"] = Conditional(
|
|
95
|
+
'TRY_CAST on DuckDB: a double->int cast truncates on Spark but rounds on DuckDB, and an '
|
|
96
|
+
'unconvertible value raises on Spark (ANSI) but yields NULL on DuckDB; parity proven for '
|
|
97
|
+
'casts only (numeric text->double, integer->string, decimal->double)'
|
|
98
|
+
)
|
|
99
|
+
_matrix["duckdb"]["op:split"] = Conditional(
|
|
100
|
+
'both engines split on a regex (Spark split, DuckDB str_split_regex) and sqlglot shifts the '
|
|
101
|
+
'0-based index; parity proven for a literal separator only, Java and RE2 regex syntax diverge '
|
|
102
|
+
'beyond that'
|
|
103
|
+
)
|
|
104
|
+
_matrix["duckdb"]["op:to_date"] = Conditional(
|
|
105
|
+
'sqlglot translates Java date tokens to strptime; parity proven for yyyy-MM-dd and dd/MM/yyyy '
|
|
106
|
+
'only'
|
|
107
|
+
)
|
|
108
|
+
_matrix["duckdb"]["agg:avg"] = Conditional(
|
|
109
|
+
'AVG over DECIMAL yields DECIMAL(p+4,s+4) on Spark and DOUBLE on DuckDB; parity proven over '
|
|
110
|
+
'DOUBLE inputs only'
|
|
111
|
+
)
|
|
112
|
+
_matrix["duckdb"]["agg:first"] = Conditional(
|
|
113
|
+
'order-dependent without ORDER BY; parity proven only when every group holds a single non-null '
|
|
114
|
+
'distinct value'
|
|
115
|
+
)
|
|
116
|
+
_matrix["duckdb"]["agg:last"] = Conditional(
|
|
117
|
+
'order-dependent without ORDER BY; parity proven only when every group holds a single non-null '
|
|
118
|
+
'distinct value'
|
|
119
|
+
)
|
|
120
|
+
_matrix["duckdb"]["agg:approx_count_distinct"] = Conditional(
|
|
121
|
+
'approximate algorithms differ by engine; parity proven exact on the canonical dataset '
|
|
122
|
+
'(at most 2 distinct values per group on the canonical dataset)'
|
|
123
|
+
)
|
|
124
|
+
MATRIX = MappingProxyType({
|
|
125
|
+
target: MappingProxyType(entries) for target, entries in _matrix.items()
|
|
126
|
+
})
|
|
127
|
+
del _matrix
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def capability(target: str, key: str) -> Status:
|
|
131
|
+
"""Look up a declared capability; unknown targets and keys never default."""
|
|
132
|
+
if target not in MATRIX:
|
|
133
|
+
raise KeyError(f"Unknown capability target: {target!r}")
|
|
134
|
+
if key not in MATRIX[target]:
|
|
135
|
+
raise KeyError(f"Unknown capability key {key!r} for target {target!r}")
|
|
136
|
+
return MATRIX[target][key]
|
skifer/core/connector.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Narrow SQL connector contracts; no runtime or DataFrame dependency."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Literal, Protocol, runtime_checkable
|
|
5
|
+
|
|
6
|
+
from skifer.core.dialect import TARGETS
|
|
7
|
+
|
|
8
|
+
WRITE_MODES = ("overwrite", "append")
|
|
9
|
+
WriteMode = Literal["overwrite", "append"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class ExecutionResult:
|
|
14
|
+
"""Optional backend hook result; ``execute_sql`` remains unchanged."""
|
|
15
|
+
|
|
16
|
+
dataframe: Any
|
|
17
|
+
statement_id: str | None = None
|
|
18
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class ColumnInfo:
|
|
23
|
+
"""A catalog column, with unknown nullability represented by None."""
|
|
24
|
+
|
|
25
|
+
name: str
|
|
26
|
+
type: str
|
|
27
|
+
nullable: bool | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class ConnectorCapabilities:
|
|
32
|
+
"""Declared dialect and supported write modes."""
|
|
33
|
+
|
|
34
|
+
dialect: str
|
|
35
|
+
writes: frozenset[str]
|
|
36
|
+
|
|
37
|
+
def __post_init__(self):
|
|
38
|
+
object.__setattr__(self, "writes", frozenset(self.writes))
|
|
39
|
+
if not self.writes.issubset(WRITE_MODES):
|
|
40
|
+
raise ValueError(f"Unsupported write modes {self.writes!r}; expected modes from {WRITE_MODES}.")
|
|
41
|
+
if self.dialect not in TARGETS:
|
|
42
|
+
raise ValueError(f"Unknown SQL dialect {self.dialect!r}; expected one of {TARGETS}.")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@runtime_checkable
|
|
46
|
+
class ExecutionContract(Protocol):
|
|
47
|
+
"""Execute SQL and return its result with optional execution metadata."""
|
|
48
|
+
|
|
49
|
+
def execute_sql_with_metadata(self, sql: str) -> ExecutionResult: ...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@runtime_checkable
|
|
53
|
+
class CatalogContract(Protocol):
|
|
54
|
+
"""Inspect tables and resolve logical names to fully qualified names."""
|
|
55
|
+
|
|
56
|
+
def table_exists(self, fqn: str) -> bool: ...
|
|
57
|
+
|
|
58
|
+
def columns(self, fqn: str) -> list[ColumnInfo]: ...
|
|
59
|
+
|
|
60
|
+
def resolve_fqn(self, name: str) -> str: ...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@runtime_checkable
|
|
64
|
+
class PublicationContract(Protocol):
|
|
65
|
+
"""Publish SQL results; callers must validate mode against WRITE_MODES
|
|
66
|
+
and the connector's declared writes before calling write_table.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def create_or_replace_view(self, fqn: str, select_sql: str) -> None: ...
|
|
70
|
+
|
|
71
|
+
def write_table(self, fqn: str, select_sql: str, mode: WriteMode) -> None: ...
|
skifer/core/constants.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Shared constants for the Skifer core."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
# Ordered from least to most sensitive — index = severity rank (Plan 31.3.1).
|
|
5
|
+
CLASSIFICATION_LEVELS: tuple[str, ...] = (
|
|
6
|
+
"public",
|
|
7
|
+
"internal",
|
|
8
|
+
"confidential",
|
|
9
|
+
"restricted",
|
|
10
|
+
"pii",
|
|
11
|
+
)
|
|
12
|
+
CLASSIFICATION_RANK: dict[str, int] = {
|
|
13
|
+
name: index for index, name in enumerate(CLASSIFICATION_LEVELS)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
# Restricted and PII filter values remain visible in governed audit evidence.
|
|
17
|
+
SENSITIVE_CLASSIFICATIONS: frozenset[str] = frozenset({"restricted", "pii"})
|
|
18
|
+
|
|
19
|
+
# Contract lifecycle statuses accepted in the ``contract:`` block (Plan 31.3.3).
|
|
20
|
+
VALID_CONTRACT_STATUSES: frozenset[str] = frozenset(
|
|
21
|
+
{"draft", "active", "deprecated"}
|
|
22
|
+
)
|
|
23
|
+
DEFAULT_CONTRACT_STATUS: str = "active"
|
|
24
|
+
|
|
25
|
+
#: Spark file formats supported by the declarative ``source:`` block (Plan 14).
|
|
26
|
+
VALID_SOURCE_TYPES: frozenset[str] = frozenset(
|
|
27
|
+
{"csv", "parquet", "json", "avro", "orc", "delta", "text"}
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
#: File formats readable via ``readStream`` without an explicit schema (Plan 27).
|
|
31
|
+
#: csv/json require a user schema; parquet/orc/avro require the global
|
|
32
|
+
#: ``spark.sql.streaming.schemaInference`` session conf — both deferred.
|
|
33
|
+
VALID_STREAMING_SOURCE_TYPES: frozenset[str] = frozenset({"delta", "text"})
|
|
34
|
+
|
|
35
|
+
#: Materialization types accepted by the top-level ``materialization:`` block
|
|
36
|
+
#: (Plan 27 for ``streaming_table``, Plan 28 for ``materialized_view``).
|
|
37
|
+
VALID_MATERIALIZATION_TYPES: frozenset[str] = frozenset(
|
|
38
|
+
{"table", "streaming_table", "materialized_view"}
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
#: Keys allowed in the ``materialization:`` block, per type. The allowlist is
|
|
42
|
+
#: type-dependent so streaming options cannot leak onto a materialized view
|
|
43
|
+
#: (and vice versa) — every other key is rejected at load time.
|
|
44
|
+
MATERIALIZATION_ALLOWED_KEYS: dict[str, frozenset[str]] = {
|
|
45
|
+
"table": frozenset({"type"}),
|
|
46
|
+
"streaming_table": frozenset({"type", "trigger", "checkpoint", "write_mode", "keys"}),
|
|
47
|
+
"materialized_view": frozenset(
|
|
48
|
+
{"type", "schedule", "comment", "cluster_by", "partition_by", "refresh"}
|
|
49
|
+
),
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
#: Default trigger for ``materialization: streaming_table``.
|
|
53
|
+
DEFAULT_STREAMING_TRIGGER: str = "available_now"
|
|
54
|
+
|
|
55
|
+
#: Refresh modes for ``materialization: materialized_view`` (Plan 28).
|
|
56
|
+
#: ``auto`` refreshes an already up-to-date view on each run; ``never`` leaves
|
|
57
|
+
#: refreshing to the declared ``schedule``.
|
|
58
|
+
VALID_MV_REFRESH_MODES: frozenset[str] = frozenset({"auto", "never"})
|
|
59
|
+
|
|
60
|
+
#: Accepted prefixes for the materialized-view ``schedule`` clause. The rest of
|
|
61
|
+
#: the string is passed through to Databricks, which validates it precisely.
|
|
62
|
+
VALID_MV_SCHEDULE_PREFIXES: tuple[str, ...] = ("EVERY ", "CRON ")
|
|
63
|
+
|
|
64
|
+
#: Table property carrying the hash of the compiled SELECT, so a changed YAML
|
|
65
|
+
#: triggers CREATE OR REPLACE instead of refreshing a stale definition (Plan 28).
|
|
66
|
+
MV_DEFINITION_HASH_PROPERTY: str = "skifer.definition_hash"
|
skifer/core/dialect.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Render common Spark SQL to a closed set of target dialects.
|
|
2
|
+
|
|
3
|
+
Snowflake always quotes identifiers and preserves their authored case. An unquoted
|
|
4
|
+
Snowflake table created as orders is named ORDERS: models must spell it ORDERS.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
TARGETS = ("databricks", "duckdb", "snowflake")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DialectError(ValueError):
|
|
13
|
+
"""SQL cannot be rendered for the requested target."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def render(sql: str, target: str) -> str:
|
|
17
|
+
"""Render one statement; Databricks preserves the source byte for byte."""
|
|
18
|
+
if target not in TARGETS:
|
|
19
|
+
raise DialectError(f"Unknown SQL dialect {target!r}; expected one of {TARGETS}.")
|
|
20
|
+
if target == "databricks":
|
|
21
|
+
return sql
|
|
22
|
+
try:
|
|
23
|
+
import sqlglot
|
|
24
|
+
from sqlglot.errors import ErrorLevel, SqlglotError
|
|
25
|
+
except ImportError as exc:
|
|
26
|
+
raise DialectError(
|
|
27
|
+
f"SQL rendering for '{target}' requires sqlglot: pip install skifer[dialects]"
|
|
28
|
+
) from exc
|
|
29
|
+
|
|
30
|
+
# Spark's reader interprets doubled quotes as adjacent literals. Normalize
|
|
31
|
+
# only literal interiors, leaving backticked identifiers untouched.
|
|
32
|
+
token = re.compile(r"`(?:[^`]|``)*`|'(?:[^']|'')*'")
|
|
33
|
+
source = token.sub(
|
|
34
|
+
lambda m: m.group(0) if m.group(0).startswith("`")
|
|
35
|
+
else "'" + m.group(0)[1:-1].replace("''", "\\'") + "'",
|
|
36
|
+
sql,
|
|
37
|
+
)
|
|
38
|
+
try:
|
|
39
|
+
statements = sqlglot.transpile(
|
|
40
|
+
source, read="spark", write=target, unsupported_level=ErrorLevel.RAISE,
|
|
41
|
+
identify=target == "snowflake",
|
|
42
|
+
)
|
|
43
|
+
except SqlglotError as exc:
|
|
44
|
+
raise DialectError(f"SQL cannot be rendered for '{target}'.") from exc
|
|
45
|
+
if len(statements) != 1 or not statements[0]:
|
|
46
|
+
raise DialectError("SQL must render to exactly one statement.")
|
|
47
|
+
return statements[0]
|