graphmill 0.1.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.
- graphmill/__init__.py +8 -0
- graphmill/adapters/__init__.py +0 -0
- graphmill/adapters/clickhouse.py +96 -0
- graphmill/adapters/neo4j.py +199 -0
- graphmill/checks.py +209 -0
- graphmill/cli.py +222 -0
- graphmill/context.py +79 -0
- graphmill/cypher.py +111 -0
- graphmill/errors.py +2 -0
- graphmill/models.py +272 -0
- graphmill/planner.py +75 -0
- graphmill/project.py +96 -0
- graphmill/render.py +106 -0
- graphmill/runner.py +288 -0
- graphmill/values.py +111 -0
- graphmill-0.1.0.dist-info/METADATA +300 -0
- graphmill-0.1.0.dist-info/RECORD +21 -0
- graphmill-0.1.0.dist-info/WHEEL +5 -0
- graphmill-0.1.0.dist-info/entry_points.txt +2 -0
- graphmill-0.1.0.dist-info/licenses/LICENSE +21 -0
- graphmill-0.1.0.dist-info/top_level.txt +1 -0
graphmill/planner.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""`graphmill plan`: show what a run would change, without writing anything."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from .adapters.clickhouse import wrap
|
|
7
|
+
from .adapters.neo4j import q
|
|
8
|
+
from .context import Context
|
|
9
|
+
from .models import Model
|
|
10
|
+
from .render import quote_ch
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class PlanRow:
|
|
15
|
+
model: str
|
|
16
|
+
materialized: str
|
|
17
|
+
target: str
|
|
18
|
+
create: int | None = None
|
|
19
|
+
update: int | None = None
|
|
20
|
+
delete: int | None = None
|
|
21
|
+
note: str = ""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _source_keys(ctx: Context, m: Model, sql: str) -> set[str]:
|
|
25
|
+
cfg = m.config
|
|
26
|
+
if m.materialized == "node":
|
|
27
|
+
expr = f"toString({quote_ch(cfg['key'])})"
|
|
28
|
+
elif cfg.get("key"):
|
|
29
|
+
expr = f"toString({quote_ch(cfg['key'])})"
|
|
30
|
+
else:
|
|
31
|
+
expr = f"concat(toString({quote_ch(cfg['from_key'])}), '->', toString({quote_ch(cfg['to_key'])}))"
|
|
32
|
+
return {row[0] for row in ctx.ch.rows(f"SELECT DISTINCT {expr} FROM {wrap(sql)}")}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _graph_keys(ctx: Context, m: Model) -> set[str]:
|
|
36
|
+
cfg = m.config
|
|
37
|
+
if m.materialized == "node":
|
|
38
|
+
query = f"MATCH (n:{q(cfg['label'])}) WHERE n._model = $model RETURN toString(n.{q(cfg['key'])}) AS k"
|
|
39
|
+
elif cfg.get("key"):
|
|
40
|
+
query = f"MATCH ()-[r:{q(cfg['type'])}]->() WHERE r._model = $model RETURN toString(r.{q(cfg['key'])}) AS k"
|
|
41
|
+
else:
|
|
42
|
+
fp, tp = ctx.node_key_of(cfg["from_label"]), ctx.node_key_of(cfg["to_label"])
|
|
43
|
+
query = (
|
|
44
|
+
f"MATCH (a)-[r:{q(cfg['type'])}]->(b) WHERE r._model = $model "
|
|
45
|
+
f"RETURN toString(a.{q(fp)}) + '->' + toString(b.{q(tp)}) AS k"
|
|
46
|
+
)
|
|
47
|
+
return {row["k"] for row in ctx.neo.read(query, model=ctx.owner_id(m))}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def plan(ctx: Context, order: list[str], *, full_refresh: bool) -> list[PlanRow]:
|
|
51
|
+
rows: list[PlanRow] = []
|
|
52
|
+
for name in order:
|
|
53
|
+
m = ctx.models[name]
|
|
54
|
+
cfg = m.config
|
|
55
|
+
if m.is_load:
|
|
56
|
+
target = f":{cfg['label']}" if m.materialized == "node" else f"-[:{cfg['type']}]->"
|
|
57
|
+
incremental = False
|
|
58
|
+
watermark = None
|
|
59
|
+
if cfg.get("incremental") and not full_refresh:
|
|
60
|
+
watermark = ctx.neo.get_watermark(ctx.owner_id(m))
|
|
61
|
+
incremental = watermark is not None
|
|
62
|
+
source = _source_keys(ctx, m, ctx.compile(m, incremental=incremental, watermark=watermark))
|
|
63
|
+
graph = _graph_keys(ctx, m)
|
|
64
|
+
delete = 0 if incremental else len(graph - source)
|
|
65
|
+
note = f"incremental since {watermark['value']}" if incremental else ""
|
|
66
|
+
rows.append(PlanRow(name, m.materialized, target, len(source - graph), len(source & graph), delete, note))
|
|
67
|
+
elif m.materialized == "relationship":
|
|
68
|
+
current = sum(ctx.neo.count_rels(t, ctx.owner_id(m)) for t in cfg["types"])
|
|
69
|
+
target = " ".join(f"-[:{t}]->" for t in cfg["types"])
|
|
70
|
+
rows.append(PlanRow(name, m.materialized, target, note=f"recompute ({current:,} existing; stale ones swept)"))
|
|
71
|
+
elif m.materialized == "cypher":
|
|
72
|
+
rows.append(PlanRow(name, m.materialized, "graph", note="run statements"))
|
|
73
|
+
else:
|
|
74
|
+
rows.append(PlanRow(name, m.materialized, cfg["table"], note="replace table (atomic swap)"))
|
|
75
|
+
return rows
|
graphmill/project.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from jinja2 import Environment, StrictUndefined, TemplateError
|
|
10
|
+
|
|
11
|
+
from .errors import GraphmillError
|
|
12
|
+
|
|
13
|
+
PROJECT_FILE = "project.yml"
|
|
14
|
+
MISSING = object()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def load_dotenv(path: Path) -> None:
|
|
18
|
+
"""Minimal .env loader. Variables already set in the environment win."""
|
|
19
|
+
if not path.is_file():
|
|
20
|
+
return
|
|
21
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
22
|
+
line = raw.strip()
|
|
23
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
24
|
+
continue
|
|
25
|
+
key, value = line.split("=", 1)
|
|
26
|
+
key = key.strip().removeprefix("export ").strip()
|
|
27
|
+
value = value.strip()
|
|
28
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
|
29
|
+
value = value[1:-1]
|
|
30
|
+
os.environ.setdefault(key, value)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def env_var(name: str, default: Any = MISSING) -> Any:
|
|
34
|
+
if name in os.environ:
|
|
35
|
+
return os.environ[name]
|
|
36
|
+
if default is MISSING:
|
|
37
|
+
raise GraphmillError(f"Environment variable '{name}' is not set and has no default")
|
|
38
|
+
return default
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _as_bool(value: Any) -> bool:
|
|
42
|
+
if isinstance(value, bool):
|
|
43
|
+
return value
|
|
44
|
+
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Project:
|
|
49
|
+
root: Path
|
|
50
|
+
name: str
|
|
51
|
+
model_paths: list[Path]
|
|
52
|
+
test_paths: list[Path]
|
|
53
|
+
target_path: Path
|
|
54
|
+
vars: dict[str, Any] = field(default_factory=dict)
|
|
55
|
+
clickhouse: dict[str, Any] = field(default_factory=dict)
|
|
56
|
+
neo4j: dict[str, Any] = field(default_factory=dict)
|
|
57
|
+
batch_size: int = 5000
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def load(cls, project_dir: str | Path, cli_vars: dict[str, Any] | None = None) -> "Project":
|
|
61
|
+
root = Path(project_dir).resolve()
|
|
62
|
+
path = root / PROJECT_FILE
|
|
63
|
+
if not path.is_file():
|
|
64
|
+
raise GraphmillError(f"No {PROJECT_FILE} found in {root}")
|
|
65
|
+
load_dotenv(root / ".env")
|
|
66
|
+
|
|
67
|
+
env = Environment(undefined=StrictUndefined)
|
|
68
|
+
env.globals["env_var"] = env_var
|
|
69
|
+
try:
|
|
70
|
+
text = env.from_string(path.read_text(encoding="utf-8")).render()
|
|
71
|
+
except TemplateError as exc:
|
|
72
|
+
raise GraphmillError(f"{path}: {exc}") from exc
|
|
73
|
+
data = yaml.safe_load(text) or {}
|
|
74
|
+
|
|
75
|
+
connections = data.get("connections") or {}
|
|
76
|
+
clickhouse = dict(connections.get("clickhouse") or {})
|
|
77
|
+
neo4j = dict(connections.get("neo4j") or {})
|
|
78
|
+
if clickhouse.get("port") not in (None, ""):
|
|
79
|
+
clickhouse["port"] = int(clickhouse["port"])
|
|
80
|
+
if "secure" in clickhouse:
|
|
81
|
+
clickhouse["secure"] = _as_bool(clickhouse["secure"])
|
|
82
|
+
|
|
83
|
+
project_vars = dict(data.get("vars") or {})
|
|
84
|
+
project_vars.update(cli_vars or {})
|
|
85
|
+
|
|
86
|
+
return cls(
|
|
87
|
+
root=root,
|
|
88
|
+
name=str(data.get("name") or root.name),
|
|
89
|
+
model_paths=[root / p for p in data.get("model-paths", ["models"])],
|
|
90
|
+
test_paths=[root / p for p in data.get("test-paths", ["tests"])],
|
|
91
|
+
target_path=root / data.get("target-path", "target"),
|
|
92
|
+
vars=project_vars,
|
|
93
|
+
clickhouse=clickhouse,
|
|
94
|
+
neo4j=neo4j,
|
|
95
|
+
batch_size=int(data.get("batch-size", 5000)),
|
|
96
|
+
)
|
graphmill/render.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Jinja rendering for models and tests, with dbt-like context functions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any, Callable
|
|
6
|
+
|
|
7
|
+
from jinja2 import Environment, StrictUndefined, TemplateError
|
|
8
|
+
|
|
9
|
+
from .errors import GraphmillError
|
|
10
|
+
from .project import MISSING, Project, env_var
|
|
11
|
+
from .values import sql_literal
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def quote_ch(identifier: str) -> str:
|
|
15
|
+
"""Quote a ClickHouse identifier."""
|
|
16
|
+
return "`" + identifier.replace("\\", "\\\\").replace("`", "\\`") + "`"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def quote_table(qualified: str) -> str:
|
|
20
|
+
database, _, table = qualified.partition(".")
|
|
21
|
+
return f"{quote_ch(database)}.{quote_ch(table)}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def stamp(alias: str) -> str:
|
|
25
|
+
"""SET items that mark an element as written by the current model and run (used for sweeping)."""
|
|
26
|
+
return f"{alias}._run_id = $run_id, {alias}._model = $model, {alias}._loaded_at = datetime()"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Rendered:
|
|
31
|
+
text: str
|
|
32
|
+
config: dict[str, Any] = field(default_factory=dict)
|
|
33
|
+
refs: set[str] = field(default_factory=set)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Renderer:
|
|
37
|
+
def __init__(self, project: Project):
|
|
38
|
+
self.project = project
|
|
39
|
+
self.env = Environment(
|
|
40
|
+
undefined=StrictUndefined,
|
|
41
|
+
keep_trailing_newline=True,
|
|
42
|
+
extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def render(
|
|
46
|
+
self,
|
|
47
|
+
source: str,
|
|
48
|
+
*,
|
|
49
|
+
name: str,
|
|
50
|
+
origin: str,
|
|
51
|
+
ref_resolver: Callable[[str], str] | None = None,
|
|
52
|
+
incremental: bool = False,
|
|
53
|
+
watermark: dict[str, str] | None = None,
|
|
54
|
+
) -> Rendered:
|
|
55
|
+
config: dict[str, Any] = {}
|
|
56
|
+
refs: set[str] = set()
|
|
57
|
+
|
|
58
|
+
def _config(**kwargs: Any) -> str:
|
|
59
|
+
config.update(kwargs)
|
|
60
|
+
return ""
|
|
61
|
+
|
|
62
|
+
def _var(key: str, default: Any = MISSING) -> Any:
|
|
63
|
+
if key in self.project.vars:
|
|
64
|
+
return self.project.vars[key]
|
|
65
|
+
if default is MISSING:
|
|
66
|
+
raise GraphmillError(
|
|
67
|
+
f"{origin}: var '{key}' is not defined (set it under vars: in project.yml or pass --vars)"
|
|
68
|
+
)
|
|
69
|
+
return default
|
|
70
|
+
|
|
71
|
+
def _source(database: str, table: str) -> str:
|
|
72
|
+
return f"{quote_ch(database)}.{quote_ch(table)}"
|
|
73
|
+
|
|
74
|
+
def _ref(model_name: str) -> str:
|
|
75
|
+
refs.add(model_name)
|
|
76
|
+
if ref_resolver is None:
|
|
77
|
+
return f"__ref_{model_name}__"
|
|
78
|
+
return ref_resolver(model_name)
|
|
79
|
+
|
|
80
|
+
def _watermark() -> str:
|
|
81
|
+
if watermark is None:
|
|
82
|
+
raise GraphmillError(
|
|
83
|
+
f"{origin}: watermark() was called but there is no saved watermark; "
|
|
84
|
+
"wrap it in {% if is_incremental() %} ... {% endif %}"
|
|
85
|
+
)
|
|
86
|
+
return sql_literal(watermark)
|
|
87
|
+
|
|
88
|
+
context = {
|
|
89
|
+
"config": _config,
|
|
90
|
+
"var": _var,
|
|
91
|
+
"env_var": env_var,
|
|
92
|
+
"source": _source,
|
|
93
|
+
"ref": _ref,
|
|
94
|
+
"is_incremental": lambda: incremental,
|
|
95
|
+
"watermark": _watermark,
|
|
96
|
+
"stamp": stamp,
|
|
97
|
+
"this": name,
|
|
98
|
+
}
|
|
99
|
+
try:
|
|
100
|
+
text = self.env.from_string(source).render(**context)
|
|
101
|
+
except GraphmillError:
|
|
102
|
+
raise
|
|
103
|
+
except TemplateError as exc:
|
|
104
|
+
line = f":{exc.lineno}" if getattr(exc, "lineno", None) else ""
|
|
105
|
+
raise GraphmillError(f"{origin}{line}: {exc}") from exc
|
|
106
|
+
return Rendered(text=text, config=config, refs=refs)
|
graphmill/runner.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""`graphmill run`: execute models in dependency order."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import secrets
|
|
6
|
+
import time
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from dataclasses import asdict, dataclass, field
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
from .context import Context
|
|
13
|
+
from .cypher import split_statements
|
|
14
|
+
from .errors import GraphmillError
|
|
15
|
+
from .models import Model
|
|
16
|
+
from .values import WatermarkTracker, from_neo4j, to_neo4j, watermark_state
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Result:
|
|
21
|
+
model: str
|
|
22
|
+
materialized: str
|
|
23
|
+
status: str # success | warn | error | skipped
|
|
24
|
+
message: str = ""
|
|
25
|
+
seconds: float = 0.0
|
|
26
|
+
stats: dict[str, Any] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def new_run_id() -> str:
|
|
30
|
+
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(3)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _column_index(columns: list[str], column: str, model: Model, what: str) -> int:
|
|
34
|
+
try:
|
|
35
|
+
return columns.index(column)
|
|
36
|
+
except ValueError:
|
|
37
|
+
raise GraphmillError(
|
|
38
|
+
f"{model.rel_path}: {what} column '{column}' is not in the query result (columns: {', '.join(columns)})"
|
|
39
|
+
) from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Runner:
|
|
43
|
+
def __init__(self, ctx: Context, *, full_refresh: bool = False):
|
|
44
|
+
self.ctx = ctx
|
|
45
|
+
self.full_refresh = full_refresh
|
|
46
|
+
self.run_id = new_run_id()
|
|
47
|
+
|
|
48
|
+
# --- incremental state ---------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def _incremental(self, model: Model) -> tuple[bool, dict[str, str] | None]:
|
|
51
|
+
if not model.config.get("incremental") or self.full_refresh:
|
|
52
|
+
return False, None
|
|
53
|
+
state = self.ctx.neo.get_watermark(self.ctx.owner_id(model))
|
|
54
|
+
return state is not None, state
|
|
55
|
+
|
|
56
|
+
def _save_watermark(self, model: Model, tracker: WatermarkTracker, previous: dict[str, str] | None) -> None:
|
|
57
|
+
state = watermark_state(tracker.max) if tracker.max is not None else previous
|
|
58
|
+
self.ctx.neo.set_watermark(self.ctx.owner_id(model), state, self.run_id)
|
|
59
|
+
|
|
60
|
+
def _guard_empty(self, model: Model, rows_read: int, existing: Callable[[], int], what: str) -> None:
|
|
61
|
+
if rows_read or model.config.get("allow_empty"):
|
|
62
|
+
return
|
|
63
|
+
count = existing()
|
|
64
|
+
if count:
|
|
65
|
+
raise GraphmillError(
|
|
66
|
+
f"source query returned 0 rows; refusing to delete {count:,} existing {what} "
|
|
67
|
+
"(set allow_empty=True if an empty result is expected)"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# --- materializations ----------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
def node(self, m: Model) -> tuple[str, str, dict]:
|
|
73
|
+
cfg, neo = m.config, self.ctx.neo
|
|
74
|
+
label, key = cfg["label"], cfg["key"]
|
|
75
|
+
neo.ensure_node_key(label, key)
|
|
76
|
+
neo.await_indexes()
|
|
77
|
+
incremental, watermark = self._incremental(m)
|
|
78
|
+
sql = self.ctx.compile(m, incremental=incremental, watermark=watermark)
|
|
79
|
+
|
|
80
|
+
tracker = WatermarkTracker()
|
|
81
|
+
rows_read = written = 0
|
|
82
|
+
for columns, rows in self.ctx.ch.stream(sql, self.ctx.batch_size(m)):
|
|
83
|
+
ki = _column_index(columns, key, m, "key")
|
|
84
|
+
wi = _column_index(columns, cfg["incremental"], m, "incremental") if cfg.get("incremental") else None
|
|
85
|
+
nulls = sum(1 for r in rows if r[ki] is None)
|
|
86
|
+
if nulls:
|
|
87
|
+
raise GraphmillError(f"{m.rel_path}: key column '{key}' is NULL in {nulls} row(s)")
|
|
88
|
+
payload = []
|
|
89
|
+
for r in rows:
|
|
90
|
+
payload.append({"k": to_neo4j(r[ki]), "p": {c: to_neo4j(v) for i, (c, v) in enumerate(zip(columns, r)) if i != ki}})
|
|
91
|
+
if wi is not None:
|
|
92
|
+
tracker.update(r[wi])
|
|
93
|
+
rows_read += len(rows)
|
|
94
|
+
written += neo.upsert_nodes(label, key, cfg["labels"], payload, self.ctx.owner_id(m), self.run_id)
|
|
95
|
+
|
|
96
|
+
swept = 0
|
|
97
|
+
if not incremental:
|
|
98
|
+
self._guard_empty(m, rows_read, lambda: neo.count_nodes(label, self.ctx.owner_id(m)), f":{label} nodes")
|
|
99
|
+
swept = neo.sweep_nodes(label, self.ctx.owner_id(m), self.run_id)
|
|
100
|
+
if cfg.get("incremental"):
|
|
101
|
+
self._save_watermark(m, tracker, watermark)
|
|
102
|
+
mode = "incremental" if incremental else "full"
|
|
103
|
+
stats = {"rows_read": rows_read, "upserted": written, "swept": swept, "mode": mode}
|
|
104
|
+
return "success", f"{rows_read:,} rows -> {written:,} upserted, {swept:,} swept ({mode})", stats
|
|
105
|
+
|
|
106
|
+
def edge(self, m: Model) -> tuple[str, str, dict]:
|
|
107
|
+
cfg, neo = m.config, self.ctx.neo
|
|
108
|
+
rel_type, key = cfg["type"], cfg.get("key")
|
|
109
|
+
ends = dict(
|
|
110
|
+
from_label=cfg["from_label"], from_prop=self.ctx.node_key_of(cfg["from_label"]),
|
|
111
|
+
to_label=cfg["to_label"], to_prop=self.ctx.node_key_of(cfg["to_label"]),
|
|
112
|
+
)
|
|
113
|
+
if key:
|
|
114
|
+
neo.ensure_rel_index(rel_type, key)
|
|
115
|
+
neo.await_indexes()
|
|
116
|
+
incremental, watermark = self._incremental(m)
|
|
117
|
+
sql = self.ctx.compile(m, incremental=incremental, watermark=watermark)
|
|
118
|
+
|
|
119
|
+
tracker = WatermarkTracker()
|
|
120
|
+
rows_read = written = missing = 0
|
|
121
|
+
samples: list[dict] = []
|
|
122
|
+
for columns, rows in self.ctx.ch.stream(sql, self.ctx.batch_size(m)):
|
|
123
|
+
fi = _column_index(columns, cfg["from_key"], m, "from_key")
|
|
124
|
+
ti = _column_index(columns, cfg["to_key"], m, "to_key")
|
|
125
|
+
ki = _column_index(columns, key, m, "key") if key else None
|
|
126
|
+
wi = _column_index(columns, cfg["incremental"], m, "incremental") if cfg.get("incremental") else None
|
|
127
|
+
if ki is not None:
|
|
128
|
+
nulls = sum(1 for r in rows if r[ki] is None)
|
|
129
|
+
if nulls:
|
|
130
|
+
raise GraphmillError(f"{m.rel_path}: key column '{key}' is NULL in {nulls} row(s)")
|
|
131
|
+
skip = {fi, ti} | ({ki} if ki is not None else set())
|
|
132
|
+
payload = []
|
|
133
|
+
for n, r in enumerate(rows):
|
|
134
|
+
item = {
|
|
135
|
+
"i": n,
|
|
136
|
+
"f": to_neo4j(r[fi]),
|
|
137
|
+
"t": to_neo4j(r[ti]),
|
|
138
|
+
"p": {c: to_neo4j(v) for i, (c, v) in enumerate(zip(columns, r)) if i not in skip},
|
|
139
|
+
}
|
|
140
|
+
if ki is not None:
|
|
141
|
+
item["k"] = to_neo4j(r[ki])
|
|
142
|
+
payload.append(item)
|
|
143
|
+
if wi is not None:
|
|
144
|
+
tracker.update(r[wi])
|
|
145
|
+
rows_read += len(rows)
|
|
146
|
+
batch_written = neo.upsert_edges(rel_type=rel_type, key=key, rows=payload, model=self.ctx.owner_id(m), run_id=self.run_id, **ends)
|
|
147
|
+
written += batch_written
|
|
148
|
+
if batch_written < len(payload):
|
|
149
|
+
batch_missing, batch_samples = neo.missing_endpoints(rows=payload, **ends)
|
|
150
|
+
missing += batch_missing
|
|
151
|
+
samples.extend(batch_samples[: 5 - len(samples)])
|
|
152
|
+
if cfg["on_missing_endpoint"] == "fail":
|
|
153
|
+
raise GraphmillError(
|
|
154
|
+
f"{batch_missing:,} row(s) reference endpoint nodes that do not exist, e.g. {_fmt_missing(samples, ends)}. "
|
|
155
|
+
"Fix the data, or set on_missing_endpoint='warn' to skip such rows"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
swept = 0
|
|
159
|
+
if not incremental:
|
|
160
|
+
self._guard_empty(m, rows_read, lambda: neo.count_rels(rel_type, self.ctx.owner_id(m)), f":{rel_type} relationships")
|
|
161
|
+
swept = neo.sweep_rels(rel_type, self.ctx.owner_id(m), self.run_id)
|
|
162
|
+
if cfg.get("incremental"):
|
|
163
|
+
self._save_watermark(m, tracker, watermark)
|
|
164
|
+
mode = "incremental" if incremental else "full"
|
|
165
|
+
stats = {"rows_read": rows_read, "upserted": written, "missing_endpoints": missing, "swept": swept, "mode": mode}
|
|
166
|
+
message = f"{rows_read:,} rows -> {written:,} upserted, {swept:,} swept ({mode})"
|
|
167
|
+
if missing:
|
|
168
|
+
return "warn", message + f"; skipped {missing:,} with missing endpoints, e.g. {_fmt_missing(samples, ends)}", stats
|
|
169
|
+
return "success", message, stats
|
|
170
|
+
|
|
171
|
+
def _run_statements(self, m: Model, text: str) -> Counter:
|
|
172
|
+
totals: Counter = Counter()
|
|
173
|
+
for statement in split_statements(text):
|
|
174
|
+
_, counters = self.ctx.neo.auto(statement, run_id=self.run_id, model=self.ctx.owner_id(m))
|
|
175
|
+
totals.update(counters)
|
|
176
|
+
return totals
|
|
177
|
+
|
|
178
|
+
def relationship(self, m: Model) -> tuple[str, str, dict]:
|
|
179
|
+
text = self.ctx.compile(m)
|
|
180
|
+
if "$run_id" not in text:
|
|
181
|
+
raise GraphmillError(
|
|
182
|
+
f"{m.rel_path}: relationship models must stamp the relationships they write so stale ones can be "
|
|
183
|
+
"removed. Add {{ stamp('r') }} to the SET clause (r = your relationship variable)"
|
|
184
|
+
)
|
|
185
|
+
counters = self._run_statements(m, text)
|
|
186
|
+
swept = sum(self.ctx.neo.sweep_rels(t, self.ctx.owner_id(m), self.run_id) for t in m.config["types"])
|
|
187
|
+
current = sum(self.ctx.neo.count_rels(t, self.ctx.owner_id(m)) for t in m.config["types"])
|
|
188
|
+
stats = dict(counters, current=current, swept=swept)
|
|
189
|
+
return "success", f"{current:,} :{'|'.join(m.config['types'])} current, {swept:,} swept, {_fmt_counters(counters)}", stats
|
|
190
|
+
|
|
191
|
+
def cypher(self, m: Model) -> tuple[str, str, dict]:
|
|
192
|
+
counters = self._run_statements(m, self.ctx.compile(m))
|
|
193
|
+
return "success", _fmt_counters(counters), dict(counters)
|
|
194
|
+
|
|
195
|
+
def export(self, m: Model) -> tuple[str, str, dict]:
|
|
196
|
+
cfg = m.config
|
|
197
|
+
statements = split_statements(self.ctx.compile(m))
|
|
198
|
+
if not statements:
|
|
199
|
+
raise GraphmillError(f"{m.rel_path}: export model has no Cypher query")
|
|
200
|
+
for statement in statements[:-1]:
|
|
201
|
+
self.ctx.neo.auto(statement, run_id=self.run_id, model=self.ctx.owner_id(m))
|
|
202
|
+
columns = list(cfg["columns"])
|
|
203
|
+
size = self.ctx.batch_size(m)
|
|
204
|
+
|
|
205
|
+
def batches():
|
|
206
|
+
with self.ctx.neo.stream(statements[-1], run_id=self.run_id, model=self.ctx.owner_id(m)) as (keys, records):
|
|
207
|
+
absent = [c for c in columns if c not in keys]
|
|
208
|
+
if absent:
|
|
209
|
+
raise GraphmillError(f"{m.rel_path}: the query must RETURN column(s) {', '.join(absent)} (it returns {', '.join(keys)})")
|
|
210
|
+
batch: list[list[Any]] = []
|
|
211
|
+
for record in records:
|
|
212
|
+
batch.append([from_neo4j(record[c]) for c in columns])
|
|
213
|
+
if len(batch) >= size:
|
|
214
|
+
yield batch
|
|
215
|
+
batch = []
|
|
216
|
+
if batch:
|
|
217
|
+
yield batch
|
|
218
|
+
|
|
219
|
+
rows = self.ctx.ch.replace_table(cfg["table"], cfg["columns"], cfg["order_by"], cfg["engine"], batches())
|
|
220
|
+
return "success", f"{rows:,} rows -> {cfg['table']}", {"rows": rows}
|
|
221
|
+
|
|
222
|
+
# --- orchestration ----------------------------------------------------------
|
|
223
|
+
|
|
224
|
+
def run(self, order: list[str], echo: Callable[..., None]) -> list[Result]:
|
|
225
|
+
handlers = {
|
|
226
|
+
"node": self.node, "edge": self.edge, "relationship": self.relationship,
|
|
227
|
+
"cypher": self.cypher, "export": self.export,
|
|
228
|
+
}
|
|
229
|
+
if any(self.ctx.models[n].config.get("incremental") for n in order):
|
|
230
|
+
self.ctx.neo.ensure_state()
|
|
231
|
+
results: list[Result] = []
|
|
232
|
+
not_ok: set[str] = set()
|
|
233
|
+
total = len(order)
|
|
234
|
+
for index, name in enumerate(order, 1):
|
|
235
|
+
m = self.ctx.models[name]
|
|
236
|
+
blocked = m.depends_on & not_ok
|
|
237
|
+
if blocked:
|
|
238
|
+
result = Result(name, m.materialized, "skipped", f"upstream failed: {', '.join(sorted(blocked))}")
|
|
239
|
+
else:
|
|
240
|
+
started = time.perf_counter()
|
|
241
|
+
try:
|
|
242
|
+
status, message, stats = handlers[m.materialized](m)
|
|
243
|
+
result = Result(name, m.materialized, status, message, stats=stats)
|
|
244
|
+
except GraphmillError as exc:
|
|
245
|
+
result = Result(name, m.materialized, "error", str(exc))
|
|
246
|
+
except Exception as exc: # driver/database errors
|
|
247
|
+
result = Result(name, m.materialized, "error", f"{type(exc).__name__}: {exc}")
|
|
248
|
+
result.seconds = time.perf_counter() - started
|
|
249
|
+
if result.status in ("error", "skipped"):
|
|
250
|
+
not_ok.add(name)
|
|
251
|
+
echo(index, total, result)
|
|
252
|
+
results.append(result)
|
|
253
|
+
self._write_results(results)
|
|
254
|
+
return results
|
|
255
|
+
|
|
256
|
+
def _write_results(self, results: list[Result]) -> None:
|
|
257
|
+
target = self.ctx.project.target_path
|
|
258
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
259
|
+
payload = {
|
|
260
|
+
"run_id": self.run_id,
|
|
261
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
262
|
+
"full_refresh": self.full_refresh,
|
|
263
|
+
"results": [asdict(r) for r in results],
|
|
264
|
+
}
|
|
265
|
+
(target / "run_results.json").write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _fmt_missing(samples: list[dict], ends: dict[str, str]) -> str:
|
|
269
|
+
parts = []
|
|
270
|
+
for s in samples[:3]:
|
|
271
|
+
gone = []
|
|
272
|
+
if s["from_missing"]:
|
|
273
|
+
gone.append(f"(:{ends['from_label']} {{{ends['from_prop']}: {s['from_key']!r}}})")
|
|
274
|
+
if s["to_missing"]:
|
|
275
|
+
gone.append(f"(:{ends['to_label']} {{{ends['to_prop']}: {s['to_key']!r}}})")
|
|
276
|
+
parts.append(" and ".join(gone))
|
|
277
|
+
return "; ".join(parts) or "n/a"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _fmt_counters(counters: Counter | dict) -> str:
|
|
281
|
+
if not counters:
|
|
282
|
+
return "no changes"
|
|
283
|
+
short = {
|
|
284
|
+
"nodes_created": "nodes+", "nodes_deleted": "nodes-", "relationships_created": "rels+",
|
|
285
|
+
"relationships_deleted": "rels-", "properties_set": "props set", "labels_added": "labels+",
|
|
286
|
+
"labels_removed": "labels-",
|
|
287
|
+
}
|
|
288
|
+
return ", ".join(f"{v:,} {short.get(k, k)}" for k, v in counters.items())
|
graphmill/values.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Value conversion between ClickHouse rows, Neo4j properties and watermarks."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from datetime import date, datetime, time, timedelta, timezone
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
INT64_MIN, INT64_MAX = -(2**63), 2**63 - 1
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _json(value: Any) -> str:
|
|
13
|
+
return json.dumps(value, default=str, ensure_ascii=False)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def to_neo4j(value: Any) -> Any:
|
|
17
|
+
"""Convert a ClickHouse value into something Neo4j can store as a property.
|
|
18
|
+
|
|
19
|
+
Neo4j properties are scalars or homogeneous lists of scalars without nulls.
|
|
20
|
+
Anything else (maps, nested arrays, mixed arrays) is stored as a JSON string.
|
|
21
|
+
None is kept: `SET n += {x: null}` removes the property, which is the right
|
|
22
|
+
upsert behavior when a source value became NULL.
|
|
23
|
+
"""
|
|
24
|
+
if value is None or isinstance(value, (bool, str, float)):
|
|
25
|
+
return value
|
|
26
|
+
if isinstance(value, int):
|
|
27
|
+
return value if INT64_MIN <= value <= INT64_MAX else str(value)
|
|
28
|
+
if isinstance(value, Decimal):
|
|
29
|
+
return float(value)
|
|
30
|
+
if isinstance(value, (datetime, date, time, timedelta)):
|
|
31
|
+
return value
|
|
32
|
+
if isinstance(value, (bytes, bytearray)):
|
|
33
|
+
try:
|
|
34
|
+
return bytes(value).decode("utf-8")
|
|
35
|
+
except UnicodeDecodeError:
|
|
36
|
+
return bytes(value).hex()
|
|
37
|
+
if isinstance(value, (list, tuple)):
|
|
38
|
+
items = [to_neo4j(v) for v in value]
|
|
39
|
+
kinds = {type(v) for v in items}
|
|
40
|
+
if None in items or len(kinds) > 1 or kinds & {list, dict}:
|
|
41
|
+
return _json(list(value))
|
|
42
|
+
return items
|
|
43
|
+
if isinstance(value, dict):
|
|
44
|
+
return _json(value)
|
|
45
|
+
return str(value) # UUID, IP addresses, enums, ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def from_neo4j(value: Any) -> Any:
|
|
49
|
+
"""Convert a value returned by the Neo4j driver into a plain Python value for ClickHouse."""
|
|
50
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
51
|
+
return value
|
|
52
|
+
to_native = getattr(value, "to_native", None)
|
|
53
|
+
if callable(to_native):
|
|
54
|
+
try:
|
|
55
|
+
return to_native()
|
|
56
|
+
except (ValueError, OverflowError):
|
|
57
|
+
return str(value)
|
|
58
|
+
if isinstance(value, (list, tuple)):
|
|
59
|
+
return [from_neo4j(v) for v in value]
|
|
60
|
+
if isinstance(value, dict):
|
|
61
|
+
return _json({k: from_neo4j(v) for k, v in value.items()})
|
|
62
|
+
return str(value)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# --- watermarks -------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
def watermark_state(value: Any) -> dict[str, str] | None:
|
|
68
|
+
"""Serialize a watermark value for storage in the graph."""
|
|
69
|
+
if value is None:
|
|
70
|
+
return None
|
|
71
|
+
if isinstance(value, datetime):
|
|
72
|
+
if value.tzinfo is not None:
|
|
73
|
+
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
|
74
|
+
return {"type": "datetime", "value": value.isoformat(sep=" ")}
|
|
75
|
+
if isinstance(value, date):
|
|
76
|
+
return {"type": "date", "value": value.isoformat()}
|
|
77
|
+
if isinstance(value, bool):
|
|
78
|
+
return {"type": "int", "value": str(int(value))}
|
|
79
|
+
if isinstance(value, (int, Decimal)):
|
|
80
|
+
return {"type": "int", "value": str(value)}
|
|
81
|
+
if isinstance(value, float):
|
|
82
|
+
return {"type": "float", "value": repr(value)}
|
|
83
|
+
return {"type": "str", "value": str(value)}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def sql_literal(state: dict[str, str]) -> str:
|
|
87
|
+
"""Render a stored watermark as a ClickHouse literal. Datetimes are stored in UTC."""
|
|
88
|
+
kind, value = state["type"], state["value"]
|
|
89
|
+
if kind == "datetime":
|
|
90
|
+
return f"toDateTime64('{value}', 6, 'UTC')"
|
|
91
|
+
if kind == "date":
|
|
92
|
+
return f"toDate('{value}')"
|
|
93
|
+
if kind in ("int", "float"):
|
|
94
|
+
return value
|
|
95
|
+
escaped = value.replace("\\", "\\\\").replace("'", "\\'")
|
|
96
|
+
return f"'{escaped}'"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class WatermarkTracker:
|
|
100
|
+
"""Tracks the maximum value of the incremental column across streamed rows."""
|
|
101
|
+
|
|
102
|
+
def __init__(self) -> None:
|
|
103
|
+
self.max: Any = None
|
|
104
|
+
|
|
105
|
+
def update(self, value: Any) -> None:
|
|
106
|
+
if value is None:
|
|
107
|
+
return
|
|
108
|
+
if isinstance(value, datetime) and value.tzinfo is not None:
|
|
109
|
+
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
|
110
|
+
if self.max is None or value > self.max:
|
|
111
|
+
self.max = value
|