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/cli.py ADDED
@@ -0,0 +1,222 @@
1
+ """Command line interface."""
2
+ from __future__ import annotations
3
+
4
+ import functools
5
+ import os
6
+ import sys
7
+ from collections import Counter
8
+ from typing import Any, Callable
9
+
10
+ import click
11
+ import yaml
12
+
13
+ from . import __version__
14
+ from .checks import TestResult, collect, run_checks
15
+ from .context import Context
16
+ from .errors import GraphmillError
17
+ from .models import discover_models, resolve_dependencies, select, topological_order
18
+ from .planner import plan as make_plan
19
+ from .project import Project
20
+ from .render import Renderer
21
+ from .runner import Result, Runner
22
+
23
+ STATUS_COLORS = {
24
+ "success": "green", "pass": "green", "warn": "yellow",
25
+ "error": "red", "fail": "red", "skipped": "bright_black",
26
+ }
27
+
28
+
29
+ def _load(project_dir: str, vars_: str | None) -> Context:
30
+ cli_vars: dict[str, Any] = {}
31
+ if vars_:
32
+ cli_vars = yaml.safe_load(vars_)
33
+ if not isinstance(cli_vars, dict):
34
+ raise GraphmillError("--vars must be a YAML mapping, e.g. --vars \"{regions: [eu, us]}\"")
35
+ project = Project.load(project_dir, cli_vars)
36
+ renderer = Renderer(project)
37
+ models = discover_models(project, renderer)
38
+ if not models:
39
+ raise GraphmillError(f"No models found under {', '.join(str(p) for p in project.model_paths)}")
40
+ resolve_dependencies(models)
41
+ return Context(project, renderer, models)
42
+
43
+
44
+ def _command(fn: Callable) -> Callable:
45
+ """Shared options + friendly error handling."""
46
+
47
+ @click.option("--project-dir", "-p", default=".", show_default=True, type=click.Path(file_okay=False), help="Directory containing project.yml.")
48
+ @click.option("--vars", "vars_", default=None, help='Override vars as YAML, e.g. "{regions: [eu, us]}".')
49
+ @functools.wraps(fn)
50
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
51
+ try:
52
+ return fn(*args, **kwargs)
53
+ except GraphmillError as exc:
54
+ click.secho(f"Error: {exc}", fg="red", err=True)
55
+ sys.exit(2)
56
+ except Exception as exc: # database/driver errors outside a model run
57
+ if os.environ.get("GRAPHMILL_DEBUG"):
58
+ raise
59
+ click.secho(f"Error: {type(exc).__name__}: {exc}", fg="red", err=True)
60
+ click.secho("(set GRAPHMILL_DEBUG=1 for a traceback)", fg="bright_black", err=True)
61
+ sys.exit(2)
62
+
63
+ return wrapper
64
+
65
+
66
+ _select = click.option("--select", "-s", multiple=True, help="Models to include: name, glob, +name (with upstream), name+ (with downstream).")
67
+
68
+
69
+ def _status(status: str) -> str:
70
+ return click.style(f"{status.upper():<7}", fg=STATUS_COLORS.get(status, None))
71
+
72
+
73
+ def _line(index: int, total: int, kind: str, name: str, status: str, detail: str, seconds: float) -> None:
74
+ width = len(str(total))
75
+ label = f"{kind:<12} {name}"
76
+ click.echo(f"{index:>{width}}/{total} {label:<44} {_status(status)} {detail} [{seconds:.1f}s]")
77
+
78
+
79
+ def _summary(statuses: list[str]) -> str:
80
+ counts = Counter(statuses)
81
+ return " ".join(click.style(f"{k.upper()}={v}", fg=STATUS_COLORS.get(k)) for k, v in sorted(counts.items()))
82
+
83
+
84
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
85
+ @click.version_option(__version__, prog_name="graphmill")
86
+ def main() -> None:
87
+ """dbt-style modeling for graphs: ClickHouse -> Neo4j -> derived relationships -> ClickHouse."""
88
+
89
+
90
+ @main.command()
91
+ @_command
92
+ def debug(project_dir: str, vars_: str | None) -> None:
93
+ """Check the project and both connections."""
94
+ ctx = _load(project_dir, vars_)
95
+ p = ctx.project
96
+ click.echo(f"project {p.name} ({p.root})")
97
+ click.echo(f"models {len(ctx.models)}")
98
+ ok = True
99
+ with ctx:
100
+ for label, probe in (("clickhouse", lambda: ctx.ch.version()), ("neo4j", lambda: ctx.neo.version())):
101
+ try:
102
+ click.echo(f"{label:<10}{click.style('OK', fg='green')} {probe()}")
103
+ except Exception as exc:
104
+ ok = False
105
+ click.echo(f"{label:<10}{click.style('FAIL', fg='red')} {exc}")
106
+ sys.exit(0 if ok else 1)
107
+
108
+
109
+ @main.command(name="ls")
110
+ @_select
111
+ @_command
112
+ def ls_(project_dir: str, vars_: str | None, select: tuple[str, ...]) -> None:
113
+ """List models in run order with their dependencies, and the graph schema."""
114
+ ctx = _load(project_dir, vars_)
115
+ chosen = select_models(ctx, select)
116
+ for name in topological_order(ctx.models, chosen):
117
+ m = ctx.models[name]
118
+ produces = ", ".join([f":{x}" for x in m.produced_labels()] + [f"[:{x}]" for x in sorted(m.produced_types())])
119
+ if m.materialized == "export":
120
+ produces = m.config["table"]
121
+ deps = ", ".join(sorted(m.depends_on)) or "-"
122
+ click.echo(f"{m.materialized:<12} {name:<28} {produces:<32} <- {deps}")
123
+ click.echo("\nGraph schema:")
124
+ for m in ctx.models.values():
125
+ if m.materialized == "node":
126
+ click.echo(f" (:{m.config['label']} {{{m.config['key']}}})")
127
+ for m in ctx.models.values():
128
+ if m.materialized == "edge":
129
+ click.echo(f" (:{m.config['from_label']})-[:{m.config['type']}]->(:{m.config['to_label']})")
130
+ if m.materialized == "relationship":
131
+ for t in m.config["types"]:
132
+ click.echo(f" ()-[:{t}]->() derived by {m.name}")
133
+
134
+
135
+ def select_models(ctx: Context, selectors: tuple[str, ...]) -> set[str]:
136
+ return select(ctx.models, list(selectors))
137
+
138
+
139
+ @main.command(name="compile")
140
+ @_select
141
+ @click.option("--show", is_flag=True, help="Print compiled text instead of only writing files.")
142
+ @_command
143
+ def compile_(project_dir: str, vars_: str | None, select: tuple[str, ...], show: bool) -> None:
144
+ """Render models to target/compiled/ (full-refresh form)."""
145
+ ctx = _load(project_dir, vars_)
146
+ out = ctx.project.target_path / "compiled"
147
+ for name in topological_order(ctx.models, select_models(ctx, select)):
148
+ m = ctx.models[name]
149
+ text = ctx.compile(m)
150
+ dest = out / m.rel_path
151
+ dest.parent.mkdir(parents=True, exist_ok=True)
152
+ dest.write_text(text, encoding="utf-8")
153
+ if show:
154
+ click.secho(f"-- {m.rel_path}", fg="cyan")
155
+ click.echo(text.strip() + "\n")
156
+ else:
157
+ click.echo(f"compiled {m.rel_path}")
158
+
159
+
160
+ @main.command()
161
+ @_select
162
+ @click.option("--full-refresh", is_flag=True, help="Plan as a full refresh (ignore incremental watermarks).")
163
+ @_command
164
+ def plan(project_dir: str, vars_: str | None, select: tuple[str, ...], full_refresh: bool) -> None:
165
+ """Show what `run` would create, update and delete. Writes nothing."""
166
+ ctx = _load(project_dir, vars_)
167
+ order = topological_order(ctx.models, select_models(ctx, select))
168
+ with ctx:
169
+ rows = make_plan(ctx, order, full_refresh=full_refresh)
170
+ fmt = "{:<12} {:<28} {:<24} {:>9} {:>9} {:>9} {}"
171
+ click.echo(fmt.format("kind", "model", "target", "create", "update", "delete", "note"))
172
+ for r in rows:
173
+ cells = ["" if v is None else f"{v:,}" for v in (r.create, r.update, r.delete)]
174
+ line = fmt.format(r.materialized, r.model, r.target, *cells, r.note)
175
+ if r.delete:
176
+ line = click.style(line, fg="yellow")
177
+ click.echo(line)
178
+
179
+
180
+ @main.command()
181
+ @_select
182
+ @click.option("--full-refresh", is_flag=True, help="Ignore incremental watermarks: reload everything and sweep stale elements.")
183
+ @_command
184
+ def run(project_dir: str, vars_: str | None, select: tuple[str, ...], full_refresh: bool) -> None:
185
+ """Load node/edge models, derive relationships, run exports."""
186
+ ctx = _load(project_dir, vars_)
187
+ order = topological_order(ctx.models, select_models(ctx, select))
188
+ with ctx:
189
+ runner = Runner(ctx, full_refresh=full_refresh)
190
+ click.echo(f"graphmill run project={ctx.project.name} run_id={runner.run_id} models={len(order)}\n")
191
+
192
+ def echo(index: int, total: int, r: Result) -> None:
193
+ _line(index, total, r.materialized, r.model, r.status, r.message, r.seconds)
194
+
195
+ results = runner.run(order, echo)
196
+ click.echo("\n" + _summary([r.status for r in results]))
197
+ sys.exit(1 if any(r.status in ("error", "skipped") for r in results) else 0)
198
+
199
+
200
+ @main.command()
201
+ @_select
202
+ @_command
203
+ def test(project_dir: str, vars_: str | None, select: tuple[str, ...]) -> None:
204
+ """Run data tests: key uniqueness, source/graph reconciliation, generic and singular tests."""
205
+ ctx = _load(project_dir, vars_)
206
+ chosen = select_models(ctx, select)
207
+ with ctx:
208
+ checks = collect(ctx, chosen, selection_given=bool(select))
209
+
210
+ def echo(index: int, total: int, r: TestResult) -> None:
211
+ detail = "" if r.status == "pass" else r.message
212
+ _line(index, total, "test", r.name, r.status, detail, r.seconds)
213
+ for sample in r.samples:
214
+ click.echo(f"{'':>8}{click.style(sample, fg='bright_black')}")
215
+
216
+ results = run_checks(checks, echo)
217
+ click.echo("\n" + _summary([r.status for r in results]))
218
+ sys.exit(1 if any(r.status in ("fail", "error") for r in results) else 0)
219
+
220
+
221
+ if __name__ == "__main__":
222
+ main()
graphmill/context.py ADDED
@@ -0,0 +1,79 @@
1
+ """Shared state for a command: project, models, renderer and lazily opened connections."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from .adapters.clickhouse import ClickHouseSource
7
+ from .adapters.neo4j import Neo4jTarget
8
+ from .errors import GraphmillError
9
+ from .models import Model, owners
10
+ from .project import Project
11
+ from .render import Renderer, quote_table
12
+
13
+
14
+ class Context:
15
+ def __init__(self, project: Project, renderer: Renderer, models: dict[str, Model]):
16
+ self.project = project
17
+ self.renderer = renderer
18
+ self.models = models
19
+ self.label_owner, self.type_owner = owners(models)
20
+ self._ch: ClickHouseSource | None = None
21
+ self._neo: Neo4jTarget | None = None
22
+
23
+ @property
24
+ def ch(self) -> ClickHouseSource:
25
+ if self._ch is None:
26
+ self._ch = ClickHouseSource(self.project.clickhouse)
27
+ return self._ch
28
+
29
+ @property
30
+ def neo(self) -> Neo4jTarget:
31
+ if self._neo is None:
32
+ target = Neo4jTarget(self.project.neo4j)
33
+ target.verify()
34
+ self._neo = target
35
+ return self._neo
36
+
37
+ def close(self) -> None:
38
+ if self._ch is not None:
39
+ self._ch.close()
40
+ if self._neo is not None:
41
+ self._neo.close()
42
+
43
+ def __enter__(self) -> "Context":
44
+ return self
45
+
46
+ def __exit__(self, *exc: Any) -> None:
47
+ self.close()
48
+
49
+ # --- helpers -----------------------------------------------------------------
50
+
51
+ def compile(self, model: Model, *, incremental: bool = False, watermark: dict[str, str] | None = None) -> str:
52
+ def resolve(name: str) -> str:
53
+ return quote_table(self.models[name].config["table"])
54
+
55
+ return self.renderer.render(
56
+ model.source,
57
+ name=model.name,
58
+ origin=model.rel_path,
59
+ ref_resolver=resolve,
60
+ incremental=incremental,
61
+ watermark=watermark,
62
+ ).text
63
+
64
+ def owner_id(self, model: Model) -> str:
65
+ """Value stamped into `_model` and used to scope sweeps, counts and watermarks.
66
+
67
+ Qualified with the project name so several projects can share one database
68
+ without sweeping each other's data.
69
+ """
70
+ return f"{self.project.name}.{model.name}"
71
+
72
+ def node_key_of(self, label: str) -> str:
73
+ owner = self.label_owner.get(label)
74
+ if owner is None:
75
+ raise GraphmillError(f"No node model produces label '{label}'")
76
+ return self.models[owner].config["key"]
77
+
78
+ def batch_size(self, model: Model) -> int:
79
+ return int(model.config.get("batch_size") or self.project.batch_size)
graphmill/cypher.py ADDED
@@ -0,0 +1,111 @@
1
+ """Lightweight Cypher text utilities: statement splitting and label/type reference extraction.
2
+
3
+ This is deliberately not a full parser. It understands strings, backtick identifiers and
4
+ comments well enough to split on ';' safely and to find the labels and relationship types
5
+ used in node and relationship patterns, which is what dependency inference needs.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ _SPECIAL = "/\"'`"
12
+
13
+
14
+ def _tokens(text: str) -> list[tuple[str, str]]:
15
+ """Split text into (kind, chunk) with kind in code | string | ident | comment."""
16
+ out: list[tuple[str, str]] = []
17
+ i, n = 0, len(text)
18
+ while i < n:
19
+ c = text[i]
20
+ nxt = text[i + 1] if i + 1 < n else ""
21
+ if c == "/" and nxt == "/":
22
+ j = text.find("\n", i)
23
+ j = n if j == -1 else j
24
+ out.append(("comment", text[i:j]))
25
+ i = j
26
+ continue
27
+ if c == "/" and nxt == "*":
28
+ j = text.find("*/", i + 2)
29
+ j = n if j == -1 else j + 2
30
+ out.append(("comment", text[i:j]))
31
+ i = j
32
+ continue
33
+ if c in "\"'`":
34
+ j = i + 1
35
+ while j < n:
36
+ if c != "`" and text[j] == "\\":
37
+ j += 2
38
+ continue
39
+ if text[j] == c:
40
+ if c == "`" and j + 1 < n and text[j + 1] == "`": # escaped backtick
41
+ j += 2
42
+ continue
43
+ break
44
+ j += 1
45
+ j = min(j + 1, n)
46
+ out.append(("ident" if c == "`" else "string", text[i:j]))
47
+ i = j
48
+ continue
49
+ j = i
50
+ while j < n and text[j] not in _SPECIAL:
51
+ j += 1
52
+ if j == i: # a lone '/'
53
+ j = i + 1
54
+ out.append(("code", text[i:j]))
55
+ i = j
56
+ return out
57
+
58
+
59
+ def split_statements(text: str) -> list[str]:
60
+ """Split a Cypher script on top-level ';'. Empty and comment-only statements are dropped."""
61
+ statements: list[list[tuple[str, str]]] = [[]]
62
+ for kind, chunk in _tokens(text):
63
+ if kind != "code":
64
+ statements[-1].append((kind, chunk))
65
+ continue
66
+ parts = chunk.split(";")
67
+ statements[-1].append((kind, parts[0]))
68
+ for part in parts[1:]:
69
+ statements.append([(kind, part)])
70
+ result = []
71
+ for toks in statements:
72
+ if "".join(c for k, c in toks if k != "comment").strip():
73
+ result.append("".join(c for _, c in toks).strip())
74
+ return result
75
+
76
+
77
+ def code_only(text: str) -> str:
78
+ """Text with comments removed, strings blanked and backtick identifiers unquoted."""
79
+ parts = []
80
+ for kind, chunk in _tokens(text):
81
+ if kind == "code":
82
+ parts.append(chunk)
83
+ elif kind == "ident":
84
+ parts.append(chunk[1:-1].replace("``", "`").replace(" ", "_"))
85
+ elif kind == "string":
86
+ parts.append("''")
87
+ else:
88
+ parts.append(" ")
89
+ return "".join(parts)
90
+
91
+
92
+ _NODE = re.compile(r"\(\s*(?:[A-Za-z_]\w*)?\s*:([^(){}]*)")
93
+ _REL = re.compile(r"\[\s*(?:[A-Za-z_]\w*)?\s*:([^\[\]{}*]*)")
94
+ _WORD = re.compile(r"[A-Za-z_]\w*")
95
+ _WHERE = re.compile(r"\bWHERE\b", re.IGNORECASE)
96
+
97
+
98
+ def _names(fragment: str) -> set[str]:
99
+ return set(_WORD.findall(_WHERE.split(fragment)[0]))
100
+
101
+
102
+ def references(text: str) -> tuple[set[str], set[str]]:
103
+ """Labels and relationship types used in node / relationship patterns."""
104
+ code = code_only(text)
105
+ labels: set[str] = set()
106
+ types: set[str] = set()
107
+ for match in _NODE.finditer(code):
108
+ labels |= _names(match.group(1))
109
+ for match in _REL.finditer(code):
110
+ types |= _names(match.group(1))
111
+ return labels, types
graphmill/errors.py ADDED
@@ -0,0 +1,2 @@
1
+ class GraphmillError(Exception):
2
+ """A user-facing error. The CLI prints it without a traceback."""
graphmill/models.py ADDED
@@ -0,0 +1,272 @@
1
+ """Model discovery, config validation and dependency resolution."""
2
+ from __future__ import annotations
3
+
4
+ import fnmatch
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from graphlib import CycleError, TopologicalSorter
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .cypher import references
12
+ from .errors import GraphmillError
13
+ from .project import Project
14
+ from .render import Renderer
15
+
16
+ IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
17
+ LANGUAGE_BY_EXT = {".sql": "sql", ".cypher": "cypher", ".cql": "cypher"}
18
+ FOLDER_DEFAULTS = {"nodes": "node", "edges": "edge", "derived": "cypher", "exports": "export"}
19
+ LANGUAGE_OF = {
20
+ "node": "sql",
21
+ "edge": "sql",
22
+ "relationship": "cypher",
23
+ "cypher": "cypher",
24
+ "export": "cypher",
25
+ }
26
+ COMMON_KEYS = {"materialized", "depends_on", "enabled", "batch_size", "tests", "description"}
27
+ ALLOWED_KEYS = {
28
+ "node": COMMON_KEYS | {"label", "key", "labels", "incremental", "allow_empty", "reconcile"},
29
+ "edge": COMMON_KEYS
30
+ | {"type", "from_label", "from_key", "to_label", "to_key", "key", "on_missing_endpoint",
31
+ "incremental", "allow_empty", "reconcile"},
32
+ "relationship": COMMON_KEYS | {"type"},
33
+ "cypher": COMMON_KEYS,
34
+ "export": COMMON_KEYS | {"table", "columns", "order_by", "engine"},
35
+ }
36
+
37
+
38
+ @dataclass
39
+ class Model:
40
+ name: str
41
+ path: Path
42
+ rel_path: str
43
+ language: str
44
+ source: str
45
+ config: dict[str, Any]
46
+ refs: set[str]
47
+ parsed_text: str
48
+ depends_on: set[str] = field(default_factory=set)
49
+
50
+ @property
51
+ def materialized(self) -> str:
52
+ return self.config["materialized"]
53
+
54
+ @property
55
+ def is_load(self) -> bool:
56
+ return self.materialized in ("node", "edge")
57
+
58
+ def produced_labels(self) -> set[str]:
59
+ return {self.config["label"]} if self.materialized == "node" else set()
60
+
61
+ def produced_types(self) -> set[str]:
62
+ if self.materialized == "edge":
63
+ return {self.config["type"]}
64
+ if self.materialized == "relationship":
65
+ return set(self.config["types"])
66
+ return set()
67
+
68
+
69
+ def _fail(model_path: str, message: str) -> GraphmillError:
70
+ return GraphmillError(f"{model_path}: {message}")
71
+
72
+
73
+ def _ident(cfg: dict, key: str, origin: str, required: bool = True) -> None:
74
+ value = cfg.get(key)
75
+ if value is None:
76
+ if required:
77
+ raise _fail(origin, f"config '{key}' is required for materialized='{cfg['materialized']}'")
78
+ return
79
+ if not isinstance(value, str) or not IDENT.match(value):
80
+ raise _fail(origin, f"config '{key}' must be a plain identifier (letters, digits, _), got {value!r}")
81
+
82
+
83
+ def _string(cfg: dict, key: str, origin: str) -> None:
84
+ value = cfg.get(key)
85
+ if not isinstance(value, str) or not value.strip():
86
+ raise _fail(origin, f"config '{key}' is required for materialized='{cfg['materialized']}'")
87
+
88
+
89
+ def validate_config(cfg: dict[str, Any], origin: str) -> dict[str, Any]:
90
+ kind = cfg["materialized"]
91
+ unknown = set(cfg) - ALLOWED_KEYS[kind]
92
+ if unknown:
93
+ raise _fail(origin, f"unknown config key(s) for {kind} models: {', '.join(sorted(unknown))}")
94
+
95
+ if kind == "node":
96
+ _ident(cfg, "label", origin)
97
+ _ident(cfg, "key", origin)
98
+ cfg.setdefault("labels", [])
99
+ if not isinstance(cfg["labels"], list) or not all(isinstance(x, str) and IDENT.match(x) for x in cfg["labels"]):
100
+ raise _fail(origin, "config 'labels' must be a list of identifiers")
101
+ _ident(cfg, "incremental", origin, required=False)
102
+ elif kind == "edge":
103
+ _ident(cfg, "type", origin)
104
+ _ident(cfg, "from_label", origin)
105
+ _ident(cfg, "to_label", origin)
106
+ _string(cfg, "from_key", origin)
107
+ _string(cfg, "to_key", origin)
108
+ _ident(cfg, "key", origin, required=False)
109
+ _ident(cfg, "incremental", origin, required=False)
110
+ cfg.setdefault("on_missing_endpoint", "fail")
111
+ if cfg["on_missing_endpoint"] not in ("fail", "warn"):
112
+ raise _fail(origin, "config 'on_missing_endpoint' must be 'fail' or 'warn'")
113
+ elif kind == "relationship":
114
+ types = cfg.pop("type", None)
115
+ types = [types] if isinstance(types, str) else types
116
+ if not types or not all(isinstance(t, str) and IDENT.match(t) for t in types):
117
+ raise _fail(origin, "config 'type' (a relationship type or list of types) is required for relationship models")
118
+ cfg["types"] = types
119
+ elif kind == "export":
120
+ _string(cfg, "table", origin)
121
+ if cfg["table"].count(".") != 1:
122
+ raise _fail(origin, "config 'table' must be 'database.table'")
123
+ columns = cfg.get("columns")
124
+ if not isinstance(columns, dict) or not columns:
125
+ raise _fail(origin, "config 'columns' must be a mapping of column name -> ClickHouse type")
126
+ cfg.setdefault("order_by", "tuple()")
127
+ cfg.setdefault("engine", "MergeTree")
128
+
129
+ if kind in ("node", "edge"):
130
+ cfg.setdefault("allow_empty", False)
131
+ cfg.setdefault("reconcile", True)
132
+ deps = cfg.get("depends_on", [])
133
+ cfg["depends_on"] = [deps] if isinstance(deps, str) else list(deps)
134
+ tests = cfg.get("tests", [])
135
+ cfg["tests"] = list(tests) if isinstance(tests, (list, tuple)) else [tests]
136
+ return cfg
137
+
138
+
139
+ def _default_materialization(rel_parts: tuple[str, ...]) -> str | None:
140
+ for part in rel_parts[:-1]:
141
+ if part in FOLDER_DEFAULTS:
142
+ return FOLDER_DEFAULTS[part]
143
+ return None
144
+
145
+
146
+ def discover_models(project: Project, renderer: Renderer) -> dict[str, Model]:
147
+ models: dict[str, Model] = {}
148
+ for base in project.model_paths:
149
+ if not base.is_dir():
150
+ continue
151
+ for path in sorted(base.rglob("*")):
152
+ language = LANGUAGE_BY_EXT.get(path.suffix.lower())
153
+ if not path.is_file() or language is None:
154
+ continue
155
+ rel = path.relative_to(project.root)
156
+ rel_path = rel.as_posix()
157
+ source = path.read_text(encoding="utf-8")
158
+ rendered = renderer.render(source, name=path.stem, origin=rel_path)
159
+ cfg = dict(rendered.config)
160
+ if cfg.get("enabled", True) is False:
161
+ continue
162
+ cfg.setdefault("materialized", _default_materialization(path.relative_to(base).parts))
163
+ kind = cfg["materialized"]
164
+ if kind not in LANGUAGE_OF:
165
+ raise _fail(
166
+ rel_path,
167
+ "set materialized= to one of node, edge, relationship, cypher, export "
168
+ "(or put the file under nodes/, edges/, derived/ or exports/)",
169
+ )
170
+ if LANGUAGE_OF[kind] != language:
171
+ raise _fail(rel_path, f"{kind} models must be {LANGUAGE_OF[kind].upper()} files")
172
+ if path.stem in models:
173
+ raise _fail(rel_path, f"duplicate model name '{path.stem}' (also {models[path.stem].rel_path})")
174
+ models[path.stem] = Model(
175
+ name=path.stem,
176
+ path=path,
177
+ rel_path=rel_path,
178
+ language=language,
179
+ source=source,
180
+ config=validate_config(cfg, rel_path),
181
+ refs=rendered.refs,
182
+ parsed_text=rendered.text,
183
+ )
184
+ return models
185
+
186
+
187
+ def owners(models: dict[str, Model]) -> tuple[dict[str, str], dict[str, str]]:
188
+ """Map each label / relationship type to the model that produces it."""
189
+ label_owner: dict[str, str] = {}
190
+ type_owner: dict[str, str] = {}
191
+ for m in models.values():
192
+ for label in m.produced_labels():
193
+ if label in label_owner:
194
+ raise _fail(m.rel_path, f"label '{label}' is already produced by model '{label_owner[label]}'")
195
+ label_owner[label] = m.name
196
+ for rel_type in m.produced_types():
197
+ if rel_type in type_owner:
198
+ raise _fail(m.rel_path, f"relationship type '{rel_type}' is already produced by model '{type_owner[rel_type]}'")
199
+ type_owner[rel_type] = m.name
200
+ return label_owner, type_owner
201
+
202
+
203
+ def resolve_dependencies(models: dict[str, Model]) -> None:
204
+ label_owner, type_owner = owners(models)
205
+ for m in models.values():
206
+ deps = set(m.config["depends_on"]) | set(m.refs)
207
+ for ref in m.refs:
208
+ if ref not in models:
209
+ raise _fail(m.rel_path, f"ref('{ref}') points at an unknown model")
210
+ if models[ref].materialized != "export":
211
+ raise _fail(m.rel_path, f"ref('{ref}') must point at an export model (its ClickHouse table)")
212
+ if m.materialized == "edge":
213
+ for side in ("from_label", "to_label"):
214
+ label = m.config[side]
215
+ if label not in label_owner:
216
+ raise _fail(m.rel_path, f"{side} '{label}' is not produced by any node model")
217
+ deps.add(label_owner[label])
218
+ if m.language == "cypher":
219
+ labels, types = references(m.parsed_text)
220
+ deps |= {label_owner[x] for x in labels if x in label_owner}
221
+ deps |= {type_owner[x] for x in types if x in type_owner}
222
+ deps.discard(m.name)
223
+ unknown = deps - models.keys()
224
+ if unknown:
225
+ raise _fail(m.rel_path, f"depends_on unknown model(s): {', '.join(sorted(unknown))}")
226
+ m.depends_on = deps
227
+ try:
228
+ topological_order(models)
229
+ except CycleError as exc:
230
+ raise GraphmillError("Dependency cycle: " + " -> ".join(exc.args[1])) from exc
231
+
232
+
233
+ def topological_order(models: dict[str, Model], subset: set[str] | None = None) -> list[str]:
234
+ sorter = TopologicalSorter({name: sorted(models[name].depends_on) for name in sorted(models)})
235
+ order = list(sorter.static_order())
236
+ return [n for n in order if subset is None or n in subset]
237
+
238
+
239
+ def select(models: dict[str, Model], selectors: list[str] | tuple[str, ...] | None) -> set[str]:
240
+ """dbt-style selection: name, glob, +name (with ancestors), name+ (with descendants)."""
241
+ items = [s.strip() for sel in (selectors or []) for s in sel.split(",") if s.strip()]
242
+ if not items:
243
+ return set(models)
244
+ children: dict[str, set[str]] = {n: set() for n in models}
245
+ for name, m in models.items():
246
+ for dep in m.depends_on:
247
+ children[dep].add(name)
248
+
249
+ def walk(start: str, edges: dict[str, set[str]]) -> set[str]:
250
+ seen, stack = set(), [start]
251
+ while stack:
252
+ for nxt in edges[stack.pop()]:
253
+ if nxt not in seen:
254
+ seen.add(nxt)
255
+ stack.append(nxt)
256
+ return seen
257
+
258
+ parents = {n: set(m.depends_on) for n, m in models.items()}
259
+ chosen: set[str] = set()
260
+ for item in items:
261
+ up, down = item.startswith("+"), item.endswith("+")
262
+ pattern = item.strip("+")
263
+ matched = [n for n in models if fnmatch.fnmatchcase(n, pattern)]
264
+ if not matched:
265
+ raise GraphmillError(f"--select '{item}' matched no models")
266
+ for name in matched:
267
+ chosen.add(name)
268
+ if up:
269
+ chosen |= walk(name, parents)
270
+ if down:
271
+ chosen |= walk(name, children)
272
+ return chosen