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 ADDED
@@ -0,0 +1,8 @@
1
+ """graphmill: dbt-style modeling for property graphs."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("graphmill") # single source of truth: pyproject.toml
7
+ except PackageNotFoundError: # running from a source tree that isn't installed
8
+ __version__ = "0.0.0+unknown"
File without changes
@@ -0,0 +1,96 @@
1
+ """ClickHouse: the source of node/edge rows and the destination of export models."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Iterable, Iterator
5
+
6
+ from ..errors import GraphmillError
7
+ from ..render import quote_ch
8
+
9
+ _CLIENT_KEYS = {
10
+ "host", "port", "username", "password", "database", "secure", "verify",
11
+ "connect_timeout", "send_receive_timeout", "interface",
12
+ }
13
+
14
+
15
+ def wrap(sql: str) -> str:
16
+ """Make model SQL usable as a subquery (strip a trailing ';', guard trailing comments)."""
17
+ body = sql.strip()
18
+ while body.endswith(";"):
19
+ body = body[:-1].rstrip()
20
+ return f"(\n{body}\n)"
21
+
22
+
23
+ class ClickHouseSource:
24
+ def __init__(self, cfg: dict[str, Any]):
25
+ import clickhouse_connect
26
+
27
+ kwargs = {k: v for k, v in cfg.items() if k in _CLIENT_KEYS and v is not None and v != ""}
28
+ if "password" in cfg and cfg["password"] is not None:
29
+ kwargs["password"] = cfg["password"]
30
+ self.where = f"{kwargs.get('host', 'localhost')}:{kwargs.get('port', '')}".rstrip(":")
31
+ try:
32
+ self.client = clickhouse_connect.get_client(**kwargs, settings=cfg.get("settings") or {})
33
+ except Exception as exc: # driver raises a variety of exception types
34
+ raise GraphmillError(f"Could not connect to ClickHouse at {self.where}: {exc}") from exc
35
+
36
+ def close(self) -> None:
37
+ self.client.close()
38
+
39
+ def version(self) -> str:
40
+ return str(self.client.command("SELECT version()"))
41
+
42
+ def stream(self, sql: str, batch_size: int) -> Iterator[tuple[list[str], list[tuple]]]:
43
+ """Yield (column_names, rows) batches of at most batch_size rows."""
44
+ query = "SELECT * FROM " + wrap(sql)
45
+ with self.client.query_row_block_stream(query) as stream:
46
+ columns = list(stream.source.column_names)
47
+ batch: list[tuple] = []
48
+ for block in stream:
49
+ batch.extend(block)
50
+ while len(batch) >= batch_size:
51
+ yield columns, batch[:batch_size]
52
+ del batch[:batch_size]
53
+ if batch:
54
+ yield columns, batch
55
+
56
+ def rows(self, sql: str, parameters: dict[str, Any] | None = None) -> list[tuple]:
57
+ return self.client.query(sql, parameters=parameters).result_rows
58
+
59
+ def scalar(self, sql: str) -> Any:
60
+ rows = self.rows(sql)
61
+ return rows[0][0] if rows else None
62
+
63
+ def replace_table(
64
+ self,
65
+ table: str,
66
+ columns: dict[str, str],
67
+ order_by: str,
68
+ engine: str,
69
+ batches: Iterable[list[list[Any]]],
70
+ ) -> int:
71
+ """Load rows into a temporary table, then atomically swap it in place of `table`."""
72
+ database, _, name = table.partition(".")
73
+ target = f"{quote_ch(database)}.{quote_ch(name)}"
74
+ tmp_name = f"{name}__graphmill_tmp"
75
+ tmp = f"{quote_ch(database)}.{quote_ch(tmp_name)}"
76
+ ddl_columns = ",\n ".join(f"{quote_ch(c)} {t}" for c, t in columns.items())
77
+
78
+ self.client.command(f"DROP TABLE IF EXISTS {tmp}")
79
+ self.client.command(f"CREATE TABLE {tmp} (\n {ddl_columns}\n) ENGINE = {engine} ORDER BY {order_by}")
80
+ written = 0
81
+ try:
82
+ for batch in batches:
83
+ self.client.insert(tmp_name, batch, column_names=list(columns), database=database)
84
+ written += len(batch)
85
+ if int(self.client.command(f"EXISTS TABLE {target}")):
86
+ self.client.command(f"EXCHANGE TABLES {tmp} AND {target}")
87
+ self.client.command(f"DROP TABLE IF EXISTS {tmp}")
88
+ else:
89
+ self.client.command(f"RENAME TABLE {tmp} TO {target}")
90
+ except BaseException:
91
+ try:
92
+ self.client.command(f"DROP TABLE IF EXISTS {tmp}")
93
+ except Exception:
94
+ pass
95
+ raise
96
+ return written
@@ -0,0 +1,199 @@
1
+ """Neo4j: the graph target. All writes go through here."""
2
+ from __future__ import annotations
3
+
4
+ from contextlib import contextmanager
5
+ from typing import Any, Iterator
6
+
7
+ from ..errors import GraphmillError
8
+
9
+ STATE_LABEL = "_GraphmillState"
10
+ SWEEP_BATCH = 10000
11
+
12
+
13
+ def q(name: str) -> str:
14
+ """Quote a Cypher identifier."""
15
+ return "`" + name.replace("`", "``") + "`"
16
+
17
+
18
+ def _counters(counters: Any) -> dict[str, int]:
19
+ names = (
20
+ "nodes_created", "nodes_deleted", "relationships_created", "relationships_deleted",
21
+ "properties_set", "labels_added", "labels_removed",
22
+ )
23
+ return {n: getattr(counters, n) for n in names if getattr(counters, n, 0)}
24
+
25
+
26
+ class Neo4jTarget:
27
+ def __init__(self, cfg: dict[str, Any]):
28
+ from neo4j import GraphDatabase
29
+
30
+ self.uri = cfg.get("uri") or "bolt://127.0.0.1:7687"
31
+ self.database = cfg.get("database") or None
32
+ self.driver = GraphDatabase.driver(
33
+ self.uri,
34
+ auth=(cfg.get("user") or "neo4j", cfg.get("password") or ""),
35
+ # e.g. "property _model does not exist" on a fresh database: noise, not errors
36
+ notifications_min_severity="OFF",
37
+ )
38
+
39
+ def verify(self) -> None:
40
+ try:
41
+ self.driver.verify_connectivity()
42
+ except Exception as exc:
43
+ raise GraphmillError(f"Could not connect to Neo4j at {self.uri}: {exc}") from exc
44
+
45
+ def close(self) -> None:
46
+ self.driver.close()
47
+
48
+ def _session(self):
49
+ return self.driver.session(database=self.database)
50
+
51
+ # --- generic execution ----------------------------------------------------
52
+
53
+ def read(self, query: str, **params: Any) -> list[dict[str, Any]]:
54
+ with self._session() as session:
55
+ return session.execute_read(lambda tx: [r.data() for r in tx.run(query, params)])
56
+
57
+ def write(self, query: str, **params: Any) -> list[dict[str, Any]]:
58
+ with self._session() as session:
59
+ return session.execute_write(lambda tx: [r.data() for r in tx.run(query, params)])
60
+
61
+ def auto(self, query: str, **params: Any) -> tuple[list[dict[str, Any]], dict[str, int]]:
62
+ """Run in an auto-commit transaction (required for CALL ... IN TRANSACTIONS)."""
63
+ with self._session() as session:
64
+ result = session.run(query, params)
65
+ records = [r.data() for r in result]
66
+ return records, _counters(result.consume().counters)
67
+
68
+ @contextmanager
69
+ def stream(self, query: str, **params: Any) -> Iterator[tuple[list[str], Iterator[dict[str, Any]]]]:
70
+ with self._session() as session:
71
+ result = session.run(query, params)
72
+ yield list(result.keys()), (r.data() for r in result)
73
+
74
+ def version(self) -> str:
75
+ rows = self.read("CALL dbms.components() YIELD name, versions, edition RETURN name, versions[0] AS version, edition")
76
+ return ", ".join(f"{r['name']} {r['version']} ({r['edition']})" for r in rows)
77
+
78
+ # --- schema -----------------------------------------------------------------
79
+
80
+ def ensure_node_key(self, label: str, key: str) -> None:
81
+ name = f"graphmill_{label}_{key}".lower()
82
+ self.auto(f"CREATE CONSTRAINT {q(name)} IF NOT EXISTS FOR (n:{q(label)}) REQUIRE n.{q(key)} IS UNIQUE")
83
+
84
+ def ensure_rel_index(self, rel_type: str, key: str) -> None:
85
+ name = f"graphmill_{rel_type}_{key}".lower()
86
+ self.auto(f"CREATE INDEX {q(name)} IF NOT EXISTS FOR ()-[r:{q(rel_type)}]-() ON (r.{q(key)})")
87
+
88
+ def await_indexes(self, seconds: int = 300) -> None:
89
+ self.auto("CALL db.awaitIndexes($seconds)", seconds=seconds)
90
+
91
+ # --- loading ----------------------------------------------------------------
92
+
93
+ def upsert_nodes(self, label: str, key: str, extra_labels: list[str], rows: list[dict], model: str, run_id: str) -> int:
94
+ add_labels = "".join(f", n:{q(x)}" for x in extra_labels)
95
+ query = f"""
96
+ UNWIND $rows AS row
97
+ MERGE (n:{q(label)} {{{q(key)}: row.k}})
98
+ SET n += row.p, n._model = $model, n._run_id = $run_id, n._loaded_at = datetime(){add_labels}
99
+ RETURN count(n) AS written"""
100
+ return self.write(query, rows=rows, model=model, run_id=run_id)[0]["written"]
101
+
102
+ def _endpoints(self, from_label: str, from_prop: str, to_label: str, to_prop: str, optional: bool = False) -> str:
103
+ match = "OPTIONAL MATCH" if optional else "MATCH"
104
+ return (
105
+ f"{match} (a:{q(from_label)} {{{q(from_prop)}: row.f}})\n"
106
+ f"{match} (b:{q(to_label)} {{{q(to_prop)}: row.t}})"
107
+ )
108
+
109
+ def upsert_edges(
110
+ self, *, rel_type: str, from_label: str, from_prop: str, to_label: str, to_prop: str,
111
+ key: str | None, rows: list[dict], model: str, run_id: str,
112
+ ) -> int:
113
+ endpoints = self._endpoints(from_label, from_prop, to_label, to_prop)
114
+ stamp = "r._model = $model, r._run_id = $run_id, r._loaded_at = datetime()"
115
+ if key:
116
+ # A keyed relationship whose endpoints changed is moved, not duplicated.
117
+ query = f"""
118
+ UNWIND $rows AS row
119
+ {endpoints}
120
+ OPTIONAL MATCH (x)-[stale:{q(rel_type)} {{{q(key)}: row.k}}]->(y)
121
+ WHERE x <> a OR y <> b
122
+ DELETE stale
123
+ WITH DISTINCT row, a, b
124
+ MERGE (a)-[r:{q(rel_type)} {{{q(key)}: row.k}}]->(b)
125
+ SET r += row.p, {stamp}
126
+ RETURN count(r) AS written"""
127
+ else:
128
+ query = f"""
129
+ UNWIND $rows AS row
130
+ {endpoints}
131
+ MERGE (a)-[r:{q(rel_type)}]->(b)
132
+ SET r += row.p, {stamp}
133
+ RETURN count(r) AS written"""
134
+ return self.write(query, rows=rows, model=model, run_id=run_id)[0]["written"]
135
+
136
+ def missing_endpoints(
137
+ self, *, from_label: str, from_prop: str, to_label: str, to_prop: str, rows: list[dict], limit: int = 5,
138
+ ) -> tuple[int, list[dict]]:
139
+ query = f"""
140
+ UNWIND $rows AS row
141
+ {self._endpoints(from_label, from_prop, to_label, to_prop, optional=True)}
142
+ WITH row, a, b WHERE a IS NULL OR b IS NULL
143
+ RETURN count(*) AS missing,
144
+ collect({{from_key: row.f, to_key: row.t, from_missing: a IS NULL, to_missing: b IS NULL}})[0..$limit] AS samples"""
145
+ result = self.read(query, rows=rows, limit=limit)[0]
146
+ return result["missing"], result["samples"]
147
+
148
+ # --- counting & sweeping --------------------------------------------------------
149
+
150
+ def count_nodes(self, label: str, model: str) -> int:
151
+ return self.read(f"MATCH (n:{q(label)}) WHERE n._model = $model RETURN count(n) AS c", model=model)[0]["c"]
152
+
153
+ def count_rels(self, rel_type: str, model: str) -> int:
154
+ return self.read(f"MATCH ()-[r:{q(rel_type)}]->() WHERE r._model = $model RETURN count(r) AS c", model=model)[0]["c"]
155
+
156
+ def sweep_nodes(self, label: str, model: str, run_id: str) -> int:
157
+ """Delete nodes this model wrote in earlier runs but not in this one."""
158
+ match = f"MATCH (n:{q(label)}) WHERE n._model = $model AND n._run_id <> $run_id"
159
+ stale = self.read(f"{match} RETURN count(n) AS c", model=model, run_id=run_id)[0]["c"]
160
+ if stale:
161
+ self.auto(
162
+ f"{match} CALL (n) {{ DETACH DELETE n }} IN TRANSACTIONS OF {SWEEP_BATCH} ROWS",
163
+ model=model, run_id=run_id,
164
+ )
165
+ return stale
166
+
167
+ def sweep_rels(self, rel_type: str, model: str, run_id: str) -> int:
168
+ match = f"MATCH ()-[r:{q(rel_type)}]->() WHERE r._model = $model AND r._run_id <> $run_id"
169
+ stale = self.read(f"{match} RETURN count(r) AS c", model=model, run_id=run_id)[0]["c"]
170
+ if stale:
171
+ self.auto(
172
+ f"{match} CALL (r) {{ DELETE r }} IN TRANSACTIONS OF {SWEEP_BATCH} ROWS",
173
+ model=model, run_id=run_id,
174
+ )
175
+ return stale
176
+
177
+ # --- incremental state -----------------------------------------------------------
178
+
179
+ def ensure_state(self) -> None:
180
+ self.ensure_node_key(STATE_LABEL, "model")
181
+
182
+ def get_watermark(self, model: str) -> dict[str, str] | None:
183
+ rows = self.read(
184
+ f"MATCH (s:{STATE_LABEL} {{model: $model}}) RETURN s.watermark AS value, s.watermark_type AS type",
185
+ model=model,
186
+ )
187
+ if not rows or rows[0]["value"] is None:
188
+ return None
189
+ return {"type": rows[0]["type"], "value": rows[0]["value"]}
190
+
191
+ def set_watermark(self, model: str, state: dict[str, str] | None, run_id: str) -> None:
192
+ self.write(
193
+ f"""MERGE (s:{STATE_LABEL} {{model: $model}})
194
+ SET s.watermark = $value, s.watermark_type = $type, s.run_id = $run_id, s.updated_at = datetime()""",
195
+ model=model,
196
+ value=state["value"] if state else None,
197
+ type=state["type"] if state else None,
198
+ run_id=run_id,
199
+ )
graphmill/checks.py ADDED
@@ -0,0 +1,209 @@
1
+ """`graphmill test`: built-in, generic and singular data tests."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import time
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+
10
+ from .adapters.clickhouse import wrap
11
+ from .adapters.neo4j import q
12
+ from .context import Context
13
+ from .cypher import references, split_statements
14
+ from .errors import GraphmillError
15
+ from .models import Model
16
+ from .render import quote_ch
17
+
18
+ SAMPLE_LIMIT = 5
19
+
20
+
21
+ @dataclass
22
+ class TestResult:
23
+ name: str
24
+ status: str # pass | warn | fail | error
25
+ failures: int = 0
26
+ message: str = ""
27
+ samples: list[Any] = field(default_factory=list)
28
+ seconds: float = 0.0
29
+
30
+
31
+ @dataclass
32
+ class Check:
33
+ name: str
34
+ severity: str # error | warn
35
+ run: Callable[[], tuple[int, list[Any], str]] # -> failures, samples, message
36
+
37
+
38
+ def _fmt(value: Any) -> str:
39
+ if isinstance(value, dict):
40
+ value = {k: v for k, v in value.items() if not str(k).startswith("_")}
41
+ text = json.dumps(value, default=str, ensure_ascii=False)
42
+ return text if len(text) <= 160 else text[:157] + "..."
43
+
44
+
45
+ def _normalize(spec: Any, origin: str) -> tuple[str, dict[str, Any]]:
46
+ if isinstance(spec, str):
47
+ return spec, {}
48
+ if isinstance(spec, dict) and len(spec) == 1:
49
+ name, args = next(iter(spec.items()))
50
+ return name, dict(args or {})
51
+ raise GraphmillError(f"{origin}: invalid test spec {spec!r} (use 'name' or {{'name': {{...args}}}})")
52
+
53
+
54
+ # --- built-in checks for load models -----------------------------------------------
55
+
56
+ def _unique_key(ctx: Context, m: Model) -> Check:
57
+ key = m.config["key"]
58
+
59
+ def run():
60
+ sql = ctx.compile(m)
61
+ inner = f"SELECT {quote_ch(key)} AS k, count() AS n FROM {wrap(sql)} GROUP BY k HAVING n > 1"
62
+ failures = int(ctx.ch.scalar(f"SELECT count() FROM ({inner})") or 0)
63
+ samples = [f"{k!r} x{n}" for k, n in ctx.ch.rows(f"{inner} ORDER BY n DESC LIMIT {SAMPLE_LIMIT}")] if failures else []
64
+ return failures, samples, f"{failures:,} duplicate value(s) of '{key}' in the source query"
65
+
66
+ return Check(f"unique_key:{m.name}", "error", run)
67
+
68
+
69
+ def _reconcile(ctx: Context, m: Model) -> Check:
70
+ cfg = m.config
71
+
72
+ def run():
73
+ sql = ctx.compile(m)
74
+ if m.materialized == "node":
75
+ src = ctx.ch.scalar(f"SELECT uniqExact({quote_ch(cfg['key'])}) FROM {wrap(sql)}")
76
+ graph = ctx.neo.count_nodes(cfg["label"], ctx.owner_id(m))
77
+ what = f":{cfg['label']} nodes"
78
+ else:
79
+ expr = quote_ch(cfg["key"]) if cfg.get("key") else f"{quote_ch(cfg['from_key'])}, {quote_ch(cfg['to_key'])}"
80
+ src = ctx.ch.scalar(f"SELECT uniqExact({expr}) FROM {wrap(sql)}")
81
+ graph = ctx.neo.count_rels(cfg["type"], ctx.owner_id(m))
82
+ what = f":{cfg['type']} relationships"
83
+ diff = abs(int(src) - int(graph))
84
+ return diff, [], f"source has {int(src):,} distinct keys, graph has {int(graph):,} {what}"
85
+
86
+ severity = "warn" if cfg.get("incremental") or cfg.get("on_missing_endpoint") == "warn" else "error"
87
+ return Check(f"reconcile:{m.name}", severity, run)
88
+
89
+
90
+ # --- generic checks declared in config(tests=[...]) ------------------------------------
91
+
92
+ def _acyclic(ctx: Context, m: Model, args: dict) -> Check:
93
+ types = [m.config["type"]] if m.materialized == "edge" else m.config.get("types", [])
94
+ depth = int(args.get("max_depth", 10))
95
+ start = f":{q(m.config['from_label'])}" if m.materialized == "edge" else ""
96
+ pattern = "|".join(q(t) for t in types)
97
+
98
+ def run():
99
+ row = ctx.neo.read(
100
+ f"MATCH (n{start})-[:{pattern}*1..{depth}]->(n) WITH DISTINCT n "
101
+ f"RETURN count(n) AS failures, collect(properties(n))[0..{SAMPLE_LIMIT}] AS samples"
102
+ )[0]
103
+ return row["failures"], row["samples"], f"{row['failures']:,} node(s) are on a :{'|'.join(types)} cycle (depth <= {depth})"
104
+
105
+ return Check(f"acyclic:{m.name}", args.get("severity", "error"), run)
106
+
107
+
108
+ def _degree(ctx: Context, m: Model, args: dict) -> Check:
109
+ direction = args.get("direction", "out")
110
+ if direction not in ("out", "in"):
111
+ raise GraphmillError(f"{m.rel_path}: degree test direction must be 'out' or 'in'")
112
+ if m.materialized == "edge":
113
+ rel_type = m.config["type"]
114
+ label = args.get("label") or m.config["from_label" if direction == "out" else "to_label"]
115
+ else:
116
+ rel_type = args.get("type") or m.config["types"][0]
117
+ label = args.get("label")
118
+ if not label:
119
+ raise GraphmillError(f"{m.rel_path}: degree test on a relationship model needs a 'label' argument")
120
+ arrow = f"(n)-[:{q(rel_type)}]->()" if direction == "out" else f"(n)<-[:{q(rel_type)}]-()"
121
+ conditions = []
122
+ if args.get("min") is not None:
123
+ conditions.append(f"degree < {int(args['min'])}")
124
+ if args.get("max") is not None:
125
+ conditions.append(f"degree > {int(args['max'])}")
126
+ if not conditions:
127
+ raise GraphmillError(f"{m.rel_path}: degree test needs 'min' and/or 'max'")
128
+ where = f"WHERE {args['where']}" if args.get("where") else ""
129
+
130
+ def run():
131
+ row = ctx.neo.read(
132
+ f"MATCH (n:{q(label)}) {where} WITH n, COUNT {{ {arrow} }} AS degree WHERE {' OR '.join(conditions)} "
133
+ f"RETURN count(n) AS failures, collect(n{{.*, degree: degree}})[0..{SAMPLE_LIMIT}] AS samples"
134
+ )[0]
135
+ bounds = ", ".join(f"{k}={args[k]}" for k in ("min", "max") if args.get(k) is not None)
136
+ return row["failures"], row["samples"], f"{row['failures']:,} :{label} node(s) with {direction}-degree of :{rel_type} outside {bounds}"
137
+
138
+ return Check(f"degree:{m.name}:{direction}", args.get("severity", "error"), run)
139
+
140
+
141
+ GENERIC = {"acyclic": _acyclic, "degree": _degree}
142
+
143
+
144
+ # --- singular tests (tests/*.cypher) -------------------------------------------------------
145
+
146
+ def _singular(ctx: Context, path: Path) -> tuple[Check, set[str]]:
147
+ rel = path.relative_to(ctx.project.root).as_posix()
148
+ rendered = ctx.renderer.render(path.read_text(encoding="utf-8"), name=path.stem, origin=rel)
149
+ severity = rendered.config.get("severity", "error")
150
+ if severity not in ("error", "warn"):
151
+ raise GraphmillError(f"{rel}: severity must be 'error' or 'warn'")
152
+ statements = split_statements(rendered.text)
153
+ if len(statements) != 1:
154
+ raise GraphmillError(f"{rel}: a test must be exactly one Cypher query that returns failing rows")
155
+
156
+ labels, types = references(rendered.text)
157
+ related = {ctx.label_owner[x] for x in labels if x in ctx.label_owner}
158
+ related |= {ctx.type_owner[x] for x in types if x in ctx.type_owner}
159
+
160
+ def run():
161
+ records, _ = ctx.neo.auto(statements[0])
162
+ return len(records), records[:SAMPLE_LIMIT], f"{len(records):,} failing row(s)"
163
+
164
+ return Check(f"test:{path.stem}", severity, run), related
165
+
166
+
167
+ def collect(ctx: Context, selected: set[str], selection_given: bool) -> list[Check]:
168
+ checks: list[Check] = []
169
+ for name in sorted(selected):
170
+ m = ctx.models[name]
171
+ if m.is_load:
172
+ if m.materialized == "node" or m.config.get("key"):
173
+ checks.append(_unique_key(ctx, m))
174
+ if m.config.get("reconcile", True):
175
+ checks.append(_reconcile(ctx, m))
176
+ for spec in m.config.get("tests", []):
177
+ test_name, args = _normalize(spec, m.rel_path)
178
+ if test_name not in GENERIC:
179
+ raise GraphmillError(f"{m.rel_path}: unknown test '{test_name}' (available: {', '.join(GENERIC)})")
180
+ checks.append(GENERIC[test_name](ctx, m, args))
181
+ for base in ctx.project.test_paths:
182
+ if not base.is_dir():
183
+ continue
184
+ for path in sorted(base.rglob("*.cypher")):
185
+ check, related = _singular(ctx, path)
186
+ if not selection_given or related & selected:
187
+ checks.append(check)
188
+ return checks
189
+
190
+
191
+ def run_checks(checks: list[Check], echo: Callable[[int, int, TestResult], None]) -> list[TestResult]:
192
+ results = []
193
+ for index, check in enumerate(checks, 1):
194
+ started = time.perf_counter()
195
+ try:
196
+ failures, samples, message = check.run()
197
+ if failures == 0:
198
+ status = "pass"
199
+ else:
200
+ status = "warn" if check.severity == "warn" else "fail"
201
+ result = TestResult(check.name, status, failures, message, [_fmt(s) for s in samples])
202
+ except GraphmillError as exc:
203
+ result = TestResult(check.name, "error", message=str(exc))
204
+ except Exception as exc:
205
+ result = TestResult(check.name, "error", message=f"{type(exc).__name__}: {exc}")
206
+ result.seconds = time.perf_counter() - started
207
+ echo(index, len(checks), result)
208
+ results.append(result)
209
+ return results