graphmill 0.1.0__tar.gz → 0.1.1__tar.gz
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-0.1.0 → graphmill-0.1.1}/PKG-INFO +70 -4
- {graphmill-0.1.0 → graphmill-0.1.1}/README.md +69 -3
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/adapters/neo4j.py +73 -4
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/checks.py +41 -5
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/models.py +50 -2
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/planner.py +10 -3
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/render.py +24 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/runner.py +127 -53
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/values.py +24 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/PKG-INFO +70 -4
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/SOURCES.txt +2 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/pyproject.toml +1 -1
- graphmill-0.1.1/tests/test_e2e_history.py +206 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/tests/test_models.py +38 -0
- graphmill-0.1.1/tests/test_render.py +17 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/tests/test_values.py +22 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/LICENSE +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/__init__.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/adapters/__init__.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/adapters/clickhouse.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/cli.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/context.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/cypher.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/errors.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill/project.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/dependency_links.txt +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/entry_points.txt +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/requires.txt +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/graphmill.egg-info/top_level.txt +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/setup.cfg +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/tests/test_cypher.py +0 -0
- {graphmill-0.1.0 → graphmill-0.1.1}/tests/test_e2e.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: graphmill
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.1
|
|
4
4
|
Summary: dbt-style modeling for graphs: load warehouse data into Neo4j, derive relationships in Cypher, export results back.
|
|
5
5
|
Author: Muhammad Mirza Fahmi
|
|
6
6
|
License-Expression: MIT
|
|
@@ -162,8 +162,8 @@ Every model starts with `{{ config(...) }}`. Common keys: `materialized`, `depen
|
|
|
162
162
|
|
|
163
163
|
| materialized | language | required config | optional config |
|
|
164
164
|
|---|---|---|---|
|
|
165
|
-
| `node` | SQL | `label`, `key` (column, becomes the unique property) | `labels` (extra static labels), `incremental`, `allow_empty`, `reconcile
|
|
166
|
-
| `edge` | SQL | `type`, `from_label`, `from_key`, `to_label`, `to_key` (columns holding endpoint keys) | `key` (relationship identity column), `on_missing_endpoint` (`fail`/`warn`), `incremental`, `allow_empty`, `reconcile
|
|
165
|
+
| `node` | SQL | `label`, `key` (column, becomes the unique property) | `labels` (extra static labels), `incremental`, `allow_empty`, `reconcile`, [history](#history) |
|
|
166
|
+
| `edge` | SQL | `type`, `from_label`, `from_key`, `to_label`, `to_key` (columns holding endpoint keys) | `key` (relationship identity column), `on_missing_endpoint` (`fail`/`warn`), `incremental`, `allow_empty`, `reconcile`, [history](#history) |
|
|
167
167
|
| `relationship` | Cypher | `type` (one or a list of derived relationship types) | |
|
|
168
168
|
| `cypher` | Cypher | | |
|
|
169
169
|
| `export` | Cypher | `table` (`db.table`), `columns` (name -> ClickHouse type) | `order_by`, `engine` |
|
|
@@ -204,6 +204,8 @@ Statements receive `$run_id` and `$model` parameters.
|
|
|
204
204
|
| `ref(model)` | the ClickHouse table of an export model (adds a dependency) |
|
|
205
205
|
| `is_incremental()`, `watermark()` | incremental loading, see below |
|
|
206
206
|
| `stamp(alias)` | `SET` items that mark what a relationship model wrote |
|
|
207
|
+
| `as_of(alias, at)` | Cypher predicate: valid at `at` (a Cypher expression), or current if `at` is omitted |
|
|
208
|
+
| `ts('2026-03-01')` | timestamp literal comparable with `_valid_from` / `_valid_to` |
|
|
207
209
|
|
|
208
210
|
## Commands
|
|
209
211
|
|
|
@@ -254,6 +256,65 @@ All accept `-s/--select` (`name`, glob, `+name` with upstream, `name+` with down
|
|
|
254
256
|
`EXCHANGE TABLES`, so readers never see a half-written table.
|
|
255
257
|
- Failed models skip their downstream models; results go to `target/run_results.json`.
|
|
256
258
|
|
|
259
|
+
## History
|
|
260
|
+
|
|
261
|
+
Node and edge models can keep history. Versioned elements carry `_valid_from` and
|
|
262
|
+
`_valid_to` (UTC `LocalDateTime`; `_valid_to` is null while current). There are two modes:
|
|
263
|
+
|
|
264
|
+
| | source-provided validity | `history='snapshot'` |
|
|
265
|
+
|---|---|---|
|
|
266
|
+
| use when | the source already knows the history (versioned records, effective dates) | the source overwrites rows in place |
|
|
267
|
+
| config | `valid_from='col'`, `valid_to='col'` | `history='snapshot'`, optional `changed_at='col'`, `check_cols=[...]` |
|
|
268
|
+
| a version is | one source row (the key must be unique per version) | created by graphmill when a row changes between runs |
|
|
269
|
+
| deleted rows | swept like any model: the source is the record | closed (`_valid_to` set), never deleted |
|
|
270
|
+
| history starts | as far back as the source goes | at the first run |
|
|
271
|
+
|
|
272
|
+
**Source-provided**: each row is one version, e.g. one line of one recipe version:
|
|
273
|
+
|
|
274
|
+
```sql
|
|
275
|
+
{{ config(materialized='edge', type='USES', from_label='Product', from_key='parent',
|
|
276
|
+
to_label='Product', to_key='component', key='line_version_key',
|
|
277
|
+
valid_from='valid_from', valid_to='valid_to',
|
|
278
|
+
tests=[{'no_overlap': {'group': 'bom_id'}}]) }}
|
|
279
|
+
SELECT ... -- valid_to NULL = still valid
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
**Snapshot**: graphmill fingerprints each row (all property columns except `changed_at`,
|
|
283
|
+
or only `check_cols`, plus the endpoints). When the fingerprint changes, the current
|
|
284
|
+
version is closed and a new one opened, with `_valid_from` taken from `changed_at` (or the
|
|
285
|
+
run time). Rows that disappear are closed with the run time.
|
|
286
|
+
|
|
287
|
+
```sql
|
|
288
|
+
{{ config(materialized='edge', type='OWNS', from_label='Account', from_key='owner_id',
|
|
289
|
+
to_label='Account', to_key='account_id', key='id',
|
|
290
|
+
history='snapshot', changed_at='updated_at') }}
|
|
291
|
+
SELECT id, owner_id, account_id, share, updated_at FROM ...
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Snapshot rules: edges need a `key`; their endpoint node models must also use
|
|
295
|
+
`history='snapshot'` (deleting a node would destroy its relationship history), and
|
|
296
|
+
snapshot nodes keep one node per key with their lifetime in `_valid_from`/`_valid_to`
|
|
297
|
+
and current property values. Snapshot models always read the full source (no
|
|
298
|
+
`incremental`), and `--full-refresh` never wipes history.
|
|
299
|
+
|
|
300
|
+
**Querying.** `as_of` keeps the versions valid at a moment; elements without history
|
|
301
|
+
always pass, so one query works across versioned and unversioned models:
|
|
302
|
+
|
|
303
|
+
```cypher
|
|
304
|
+
// current recipes
|
|
305
|
+
MATCH path = (p:Product)-[:USES*1..10]->(raw:Product)
|
|
306
|
+
WHERE all(u IN relationships(path) WHERE {{ as_of('u') }})
|
|
307
|
+
|
|
308
|
+
// recipes on the 1st of each month since January
|
|
309
|
+
UNWIND range(0, 10) AS i
|
|
310
|
+
WITH localdatetime({date: date('2026-01-01') + duration({months: i})}) AS at
|
|
311
|
+
MATCH path = (p:Product)-[:USES*1..10]->(raw:Product)
|
|
312
|
+
WHERE all(u IN relationships(path) WHERE {{ as_of('u', 'at') }})
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`reconcile`, `acyclic` and `degree` tests look at current versions; `no_overlap` checks
|
|
316
|
+
that versions don't overlap in time.
|
|
317
|
+
|
|
257
318
|
## Tests
|
|
258
319
|
|
|
259
320
|
`graphmill test` runs:
|
|
@@ -264,6 +325,9 @@ All accept `-s/--select` (`name`, glob, `+name` with upstream, `name+` with down
|
|
|
264
325
|
- Generic tests from `config(tests=[...])`:
|
|
265
326
|
- `acyclic` (`max_depth`, default 10): no cycles along the model's relationship type.
|
|
266
327
|
- `{'degree': {'direction': 'out'|'in', 'min': 1, 'max': 1, 'where': "n.active"}}`.
|
|
328
|
+
- `no_overlap`: versions of the same relationship (same key) never overlap in time;
|
|
329
|
+
`{'no_overlap': {'group': 'bom_id'}}`: relationships from the same node with different
|
|
330
|
+
`bom_id` never overlap.
|
|
267
331
|
- Singular tests: `tests/*.cypher` queries that return failing rows. Add
|
|
268
332
|
`{{ config(severity='warn') }}` to warn instead of fail. With `--select`, only singular
|
|
269
333
|
tests touching the selected models' labels/types run.
|
|
@@ -286,7 +350,7 @@ GRAPHMILL_E2E=1 pytest # + end-to-end tests (they wi
|
|
|
286
350
|
The `Publish to PyPI` workflow checks that the tag matches the version, runs the tests,
|
|
287
351
|
builds, and publishes through PyPI trusted publishing.
|
|
288
352
|
|
|
289
|
-
## Limitations
|
|
353
|
+
## Limitations
|
|
290
354
|
|
|
291
355
|
- One node model per label and one model per relationship type.
|
|
292
356
|
- Neo4j 5.26+ (uses `CALL (x) { ... } IN TRANSACTIONS`). Memgraph would need its own adapter.
|
|
@@ -294,6 +358,8 @@ builds, and publishes through PyPI trusted publishing.
|
|
|
294
358
|
only mentioned in strings (e.g. `gds.graph.project('g', 'Product', ...)`) need
|
|
295
359
|
`depends_on=[...]`.
|
|
296
360
|
- `plan` pulls all keys from both sides to diff them. Fine for millions, not billions.
|
|
361
|
+
- Snapshot nodes keep only current property values (their lifetime is versioned, their
|
|
362
|
+
properties are not). Version relationships, or model changing attributes as edges.
|
|
297
363
|
|
|
298
364
|
## License
|
|
299
365
|
|
|
@@ -126,8 +126,8 @@ Every model starts with `{{ config(...) }}`. Common keys: `materialized`, `depen
|
|
|
126
126
|
|
|
127
127
|
| materialized | language | required config | optional config |
|
|
128
128
|
|---|---|---|---|
|
|
129
|
-
| `node` | SQL | `label`, `key` (column, becomes the unique property) | `labels` (extra static labels), `incremental`, `allow_empty`, `reconcile
|
|
130
|
-
| `edge` | SQL | `type`, `from_label`, `from_key`, `to_label`, `to_key` (columns holding endpoint keys) | `key` (relationship identity column), `on_missing_endpoint` (`fail`/`warn`), `incremental`, `allow_empty`, `reconcile
|
|
129
|
+
| `node` | SQL | `label`, `key` (column, becomes the unique property) | `labels` (extra static labels), `incremental`, `allow_empty`, `reconcile`, [history](#history) |
|
|
130
|
+
| `edge` | SQL | `type`, `from_label`, `from_key`, `to_label`, `to_key` (columns holding endpoint keys) | `key` (relationship identity column), `on_missing_endpoint` (`fail`/`warn`), `incremental`, `allow_empty`, `reconcile`, [history](#history) |
|
|
131
131
|
| `relationship` | Cypher | `type` (one or a list of derived relationship types) | |
|
|
132
132
|
| `cypher` | Cypher | | |
|
|
133
133
|
| `export` | Cypher | `table` (`db.table`), `columns` (name -> ClickHouse type) | `order_by`, `engine` |
|
|
@@ -168,6 +168,8 @@ Statements receive `$run_id` and `$model` parameters.
|
|
|
168
168
|
| `ref(model)` | the ClickHouse table of an export model (adds a dependency) |
|
|
169
169
|
| `is_incremental()`, `watermark()` | incremental loading, see below |
|
|
170
170
|
| `stamp(alias)` | `SET` items that mark what a relationship model wrote |
|
|
171
|
+
| `as_of(alias, at)` | Cypher predicate: valid at `at` (a Cypher expression), or current if `at` is omitted |
|
|
172
|
+
| `ts('2026-03-01')` | timestamp literal comparable with `_valid_from` / `_valid_to` |
|
|
171
173
|
|
|
172
174
|
## Commands
|
|
173
175
|
|
|
@@ -218,6 +220,65 @@ All accept `-s/--select` (`name`, glob, `+name` with upstream, `name+` with down
|
|
|
218
220
|
`EXCHANGE TABLES`, so readers never see a half-written table.
|
|
219
221
|
- Failed models skip their downstream models; results go to `target/run_results.json`.
|
|
220
222
|
|
|
223
|
+
## History
|
|
224
|
+
|
|
225
|
+
Node and edge models can keep history. Versioned elements carry `_valid_from` and
|
|
226
|
+
`_valid_to` (UTC `LocalDateTime`; `_valid_to` is null while current). There are two modes:
|
|
227
|
+
|
|
228
|
+
| | source-provided validity | `history='snapshot'` |
|
|
229
|
+
|---|---|---|
|
|
230
|
+
| use when | the source already knows the history (versioned records, effective dates) | the source overwrites rows in place |
|
|
231
|
+
| config | `valid_from='col'`, `valid_to='col'` | `history='snapshot'`, optional `changed_at='col'`, `check_cols=[...]` |
|
|
232
|
+
| a version is | one source row (the key must be unique per version) | created by graphmill when a row changes between runs |
|
|
233
|
+
| deleted rows | swept like any model: the source is the record | closed (`_valid_to` set), never deleted |
|
|
234
|
+
| history starts | as far back as the source goes | at the first run |
|
|
235
|
+
|
|
236
|
+
**Source-provided**: each row is one version, e.g. one line of one recipe version:
|
|
237
|
+
|
|
238
|
+
```sql
|
|
239
|
+
{{ config(materialized='edge', type='USES', from_label='Product', from_key='parent',
|
|
240
|
+
to_label='Product', to_key='component', key='line_version_key',
|
|
241
|
+
valid_from='valid_from', valid_to='valid_to',
|
|
242
|
+
tests=[{'no_overlap': {'group': 'bom_id'}}]) }}
|
|
243
|
+
SELECT ... -- valid_to NULL = still valid
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
**Snapshot**: graphmill fingerprints each row (all property columns except `changed_at`,
|
|
247
|
+
or only `check_cols`, plus the endpoints). When the fingerprint changes, the current
|
|
248
|
+
version is closed and a new one opened, with `_valid_from` taken from `changed_at` (or the
|
|
249
|
+
run time). Rows that disappear are closed with the run time.
|
|
250
|
+
|
|
251
|
+
```sql
|
|
252
|
+
{{ config(materialized='edge', type='OWNS', from_label='Account', from_key='owner_id',
|
|
253
|
+
to_label='Account', to_key='account_id', key='id',
|
|
254
|
+
history='snapshot', changed_at='updated_at') }}
|
|
255
|
+
SELECT id, owner_id, account_id, share, updated_at FROM ...
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Snapshot rules: edges need a `key`; their endpoint node models must also use
|
|
259
|
+
`history='snapshot'` (deleting a node would destroy its relationship history), and
|
|
260
|
+
snapshot nodes keep one node per key with their lifetime in `_valid_from`/`_valid_to`
|
|
261
|
+
and current property values. Snapshot models always read the full source (no
|
|
262
|
+
`incremental`), and `--full-refresh` never wipes history.
|
|
263
|
+
|
|
264
|
+
**Querying.** `as_of` keeps the versions valid at a moment; elements without history
|
|
265
|
+
always pass, so one query works across versioned and unversioned models:
|
|
266
|
+
|
|
267
|
+
```cypher
|
|
268
|
+
// current recipes
|
|
269
|
+
MATCH path = (p:Product)-[:USES*1..10]->(raw:Product)
|
|
270
|
+
WHERE all(u IN relationships(path) WHERE {{ as_of('u') }})
|
|
271
|
+
|
|
272
|
+
// recipes on the 1st of each month since January
|
|
273
|
+
UNWIND range(0, 10) AS i
|
|
274
|
+
WITH localdatetime({date: date('2026-01-01') + duration({months: i})}) AS at
|
|
275
|
+
MATCH path = (p:Product)-[:USES*1..10]->(raw:Product)
|
|
276
|
+
WHERE all(u IN relationships(path) WHERE {{ as_of('u', 'at') }})
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
`reconcile`, `acyclic` and `degree` tests look at current versions; `no_overlap` checks
|
|
280
|
+
that versions don't overlap in time.
|
|
281
|
+
|
|
221
282
|
## Tests
|
|
222
283
|
|
|
223
284
|
`graphmill test` runs:
|
|
@@ -228,6 +289,9 @@ All accept `-s/--select` (`name`, glob, `+name` with upstream, `name+` with down
|
|
|
228
289
|
- Generic tests from `config(tests=[...])`:
|
|
229
290
|
- `acyclic` (`max_depth`, default 10): no cycles along the model's relationship type.
|
|
230
291
|
- `{'degree': {'direction': 'out'|'in', 'min': 1, 'max': 1, 'where': "n.active"}}`.
|
|
292
|
+
- `no_overlap`: versions of the same relationship (same key) never overlap in time;
|
|
293
|
+
`{'no_overlap': {'group': 'bom_id'}}`: relationships from the same node with different
|
|
294
|
+
`bom_id` never overlap.
|
|
231
295
|
- Singular tests: `tests/*.cypher` queries that return failing rows. Add
|
|
232
296
|
`{{ config(severity='warn') }}` to warn instead of fail. With `--select`, only singular
|
|
233
297
|
tests touching the selected models' labels/types run.
|
|
@@ -250,7 +314,7 @@ GRAPHMILL_E2E=1 pytest # + end-to-end tests (they wi
|
|
|
250
314
|
The `Publish to PyPI` workflow checks that the tag matches the version, runs the tests,
|
|
251
315
|
builds, and publishes through PyPI trusted publishing.
|
|
252
316
|
|
|
253
|
-
## Limitations
|
|
317
|
+
## Limitations
|
|
254
318
|
|
|
255
319
|
- One node model per label and one model per relationship type.
|
|
256
320
|
- Neo4j 5.26+ (uses `CALL (x) { ... } IN TRANSACTIONS`). Memgraph would need its own adapter.
|
|
@@ -258,6 +322,8 @@ builds, and publishes through PyPI trusted publishing.
|
|
|
258
322
|
only mentioned in strings (e.g. `gds.graph.project('g', 'Product', ...)`) need
|
|
259
323
|
`depends_on=[...]`.
|
|
260
324
|
- `plan` pulls all keys from both sides to diff them. Fine for millions, not billions.
|
|
325
|
+
- Snapshot nodes keep only current property values (their lifetime is versioned, their
|
|
326
|
+
properties are not). Version relationships, or model changing attributes as edges.
|
|
261
327
|
|
|
262
328
|
## License
|
|
263
329
|
|
|
@@ -147,11 +147,80 @@ RETURN count(*) AS missing,
|
|
|
147
147
|
|
|
148
148
|
# --- counting & sweeping --------------------------------------------------------
|
|
149
149
|
|
|
150
|
-
def count_nodes(self, label: str, model: str) -> int:
|
|
151
|
-
|
|
150
|
+
def count_nodes(self, label: str, model: str, current_only: bool = False) -> int:
|
|
151
|
+
current = " AND n._valid_to IS NULL" if current_only else ""
|
|
152
|
+
return self.read(
|
|
153
|
+
f"MATCH (n:{q(label)}) WHERE n._model = $model{current} RETURN count(n) AS c", model=model
|
|
154
|
+
)[0]["c"]
|
|
155
|
+
|
|
156
|
+
def count_rels(self, rel_type: str, model: str, current_only: bool = False) -> int:
|
|
157
|
+
current = " AND r._valid_to IS NULL" if current_only else ""
|
|
158
|
+
return self.read(
|
|
159
|
+
f"MATCH ()-[r:{q(rel_type)}]->() WHERE r._model = $model{current} RETURN count(r) AS c", model=model
|
|
160
|
+
)[0]["c"]
|
|
161
|
+
|
|
162
|
+
# --- history: snapshot mode ----------------------------------------------------------
|
|
163
|
+
# One node per key (relationships need a stable endpoint); nodes record their lifetime.
|
|
164
|
+
# Relationships are versioned: a change closes the current version and opens a new one.
|
|
165
|
+
|
|
166
|
+
def upsert_nodes_snapshot(self, label: str, key: str, extra_labels: list[str], rows: list[dict], model: str, run_id: str) -> int:
|
|
167
|
+
add_labels = "".join(f", n:{q(x)}" for x in extra_labels)
|
|
168
|
+
query = f"""
|
|
169
|
+
UNWIND $rows AS row
|
|
170
|
+
MERGE (n:{q(label)} {{{q(key)}: row.k}})
|
|
171
|
+
ON CREATE SET n._valid_from = row.vf
|
|
172
|
+
SET n += row.p, n._valid_to = null, n._model = $model, n._run_id = $run_id, n._loaded_at = datetime(){add_labels}
|
|
173
|
+
RETURN count(n) AS written"""
|
|
174
|
+
return self.write(query, rows=rows, model=model, run_id=run_id)[0]["written"]
|
|
175
|
+
|
|
176
|
+
def upsert_edges_snapshot(
|
|
177
|
+
self, *, rel_type: str, from_label: str, from_prop: str, to_label: str, to_prop: str,
|
|
178
|
+
key: str, rows: list[dict], model: str, run_id: str,
|
|
179
|
+
) -> tuple[int, int]:
|
|
180
|
+
"""Returns (rows written, new versions opened)."""
|
|
181
|
+
t, k = q(rel_type), q(key)
|
|
182
|
+
query = f"""
|
|
183
|
+
UNWIND $rows AS row
|
|
184
|
+
{self._endpoints(from_label, from_prop, to_label, to_prop)}
|
|
185
|
+
OPTIONAL MATCH ()-[cur:{t} {{{k}: row.k}}]->()
|
|
186
|
+
WHERE cur._valid_to IS NULL AND cur._model = $model
|
|
187
|
+
WITH row, a, b, cur,
|
|
188
|
+
cur IS NOT NULL AND cur._hash = row.h AND startNode(cur) = a AND endNode(cur) = b AS same
|
|
189
|
+
WITH row, a, b, cur, same,
|
|
190
|
+
CASE WHEN cur IS NOT NULL AND row.vf < cur._valid_from THEN cur._valid_from ELSE row.vf END AS vf
|
|
191
|
+
FOREACH (_ IN CASE WHEN same THEN [1] ELSE [] END |
|
|
192
|
+
SET cur += row.p, cur._run_id = $run_id, cur._loaded_at = datetime())
|
|
193
|
+
FOREACH (_ IN CASE WHEN NOT same AND cur IS NOT NULL THEN [1] ELSE [] END |
|
|
194
|
+
SET cur._valid_to = vf)
|
|
195
|
+
FOREACH (_ IN CASE WHEN NOT same THEN [1] ELSE [] END |
|
|
196
|
+
CREATE (a)-[r:{t}]->(b)
|
|
197
|
+
SET r = row.p, r.{k} = row.k, r._hash = row.h, r._valid_from = vf,
|
|
198
|
+
r._model = $model, r._run_id = $run_id, r._loaded_at = datetime())
|
|
199
|
+
RETURN count(*) AS written, sum(CASE WHEN same THEN 0 ELSE 1 END) AS opened"""
|
|
200
|
+
result = self.write(query, rows=rows, model=model, run_id=run_id)[0]
|
|
201
|
+
return result["written"], result["opened"]
|
|
202
|
+
|
|
203
|
+
def close_nodes(self, label: str, model: str, run_id: str, at: Any) -> int:
|
|
204
|
+
"""Close (not delete) current nodes that this run did not see."""
|
|
205
|
+
match = f"MATCH (n:{q(label)}) WHERE n._model = $model AND n._valid_to IS NULL AND n._run_id <> $run_id"
|
|
206
|
+
count = self.read(f"{match} RETURN count(n) AS c", model=model, run_id=run_id)[0]["c"]
|
|
207
|
+
if count:
|
|
208
|
+
self.auto(
|
|
209
|
+
f"{match} CALL (n) {{ SET n._valid_to = $at }} IN TRANSACTIONS OF {SWEEP_BATCH} ROWS",
|
|
210
|
+
model=model, run_id=run_id, at=at,
|
|
211
|
+
)
|
|
212
|
+
return count
|
|
152
213
|
|
|
153
|
-
def
|
|
154
|
-
|
|
214
|
+
def close_rels(self, rel_type: str, model: str, run_id: str, at: Any) -> int:
|
|
215
|
+
"""Close (not delete) current relationship versions whose source row disappeared."""
|
|
216
|
+
match = f"MATCH ()-[r:{q(rel_type)}]->() WHERE r._model = $model AND r._valid_to IS NULL AND r._run_id <> $run_id"
|
|
217
|
+
count = self.read(f"{match} RETURN count(r) AS c", model=model, run_id=run_id)[0]["c"]
|
|
218
|
+
if count:
|
|
219
|
+
self.auto(
|
|
220
|
+
f"{match} CALL (r) {{ SET r._valid_to = $at }} IN TRANSACTIONS OF {SWEEP_BATCH} ROWS",
|
|
221
|
+
model=model, run_id=run_id, at=at,
|
|
222
|
+
)
|
|
223
|
+
return count
|
|
155
224
|
|
|
156
225
|
def sweep_nodes(self, label: str, model: str, run_id: str) -> int:
|
|
157
226
|
"""Delete nodes this model wrote in earlier runs but not in this one."""
|
|
@@ -3,6 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
|
|
4
4
|
import json
|
|
5
5
|
import time
|
|
6
|
+
from datetime import datetime
|
|
6
7
|
from dataclasses import dataclass, field
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
from typing import Any, Callable
|
|
@@ -73,12 +74,12 @@ def _reconcile(ctx: Context, m: Model) -> Check:
|
|
|
73
74
|
sql = ctx.compile(m)
|
|
74
75
|
if m.materialized == "node":
|
|
75
76
|
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
|
+
graph = ctx.neo.count_nodes(cfg["label"], ctx.owner_id(m), current_only=m.history == "snapshot")
|
|
77
78
|
what = f":{cfg['label']} nodes"
|
|
78
79
|
else:
|
|
79
80
|
expr = quote_ch(cfg["key"]) if cfg.get("key") else f"{quote_ch(cfg['from_key'])}, {quote_ch(cfg['to_key'])}"
|
|
80
81
|
src = ctx.ch.scalar(f"SELECT uniqExact({expr}) FROM {wrap(sql)}")
|
|
81
|
-
graph = ctx.neo.count_rels(cfg["type"], ctx.owner_id(m))
|
|
82
|
+
graph = ctx.neo.count_rels(cfg["type"], ctx.owner_id(m), current_only=m.history == "snapshot")
|
|
82
83
|
what = f":{cfg['type']} relationships"
|
|
83
84
|
diff = abs(int(src) - int(graph))
|
|
84
85
|
return diff, [], f"source has {int(src):,} distinct keys, graph has {int(graph):,} {what}"
|
|
@@ -94,10 +95,11 @@ def _acyclic(ctx: Context, m: Model, args: dict) -> Check:
|
|
|
94
95
|
depth = int(args.get("max_depth", 10))
|
|
95
96
|
start = f":{q(m.config['from_label'])}" if m.materialized == "edge" else ""
|
|
96
97
|
pattern = "|".join(q(t) for t in types)
|
|
98
|
+
current = " WHERE all(r IN relationships(p) WHERE r._valid_to IS NULL)" if m.history else ""
|
|
97
99
|
|
|
98
100
|
def run():
|
|
99
101
|
row = ctx.neo.read(
|
|
100
|
-
f"MATCH (n{start})-[:{pattern}*1..{depth}]->(n) WITH DISTINCT n "
|
|
102
|
+
f"MATCH p = (n{start})-[:{pattern}*1..{depth}]->(n){current} WITH DISTINCT n "
|
|
101
103
|
f"RETURN count(n) AS failures, collect(properties(n))[0..{SAMPLE_LIMIT}] AS samples"
|
|
102
104
|
)[0]
|
|
103
105
|
return row["failures"], row["samples"], f"{row['failures']:,} node(s) are on a :{'|'.join(types)} cycle (depth <= {depth})"
|
|
@@ -117,7 +119,9 @@ def _degree(ctx: Context, m: Model, args: dict) -> Check:
|
|
|
117
119
|
label = args.get("label")
|
|
118
120
|
if not label:
|
|
119
121
|
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)}]-()"
|
|
122
|
+
arrow = f"(n)-[r:{q(rel_type)}]->()" if direction == "out" else f"(n)<-[r:{q(rel_type)}]-()"
|
|
123
|
+
if m.history:
|
|
124
|
+
arrow += " WHERE r._valid_to IS NULL"
|
|
121
125
|
conditions = []
|
|
122
126
|
if args.get("min") is not None:
|
|
123
127
|
conditions.append(f"degree < {int(args['min'])}")
|
|
@@ -138,7 +142,39 @@ def _degree(ctx: Context, m: Model, args: dict) -> Check:
|
|
|
138
142
|
return Check(f"degree:{m.name}:{direction}", args.get("severity", "error"), run)
|
|
139
143
|
|
|
140
144
|
|
|
141
|
-
|
|
145
|
+
def _no_overlap(ctx: Context, m: Model, args: dict) -> Check:
|
|
146
|
+
"""Versioned relationships from the same start node must not be valid at the same time.
|
|
147
|
+
|
|
148
|
+
With `group`, relationships with *different* values of that property must not overlap
|
|
149
|
+
(e.g. lines of two different BoMs for the same product). Without it, versions of the
|
|
150
|
+
same relationship (same key, or same endpoints) must not overlap.
|
|
151
|
+
"""
|
|
152
|
+
if m.materialized != "edge":
|
|
153
|
+
raise GraphmillError(f"{m.rel_path}: no_overlap applies to edge models")
|
|
154
|
+
cfg = m.config
|
|
155
|
+
rel, start = q(cfg["type"]), q(cfg["from_label"])
|
|
156
|
+
if args.get("group"):
|
|
157
|
+
same, what = f"r1.{q(args['group'])} <> r2.{q(args['group'])}", f"different '{args['group']}'"
|
|
158
|
+
elif cfg.get("key"):
|
|
159
|
+
same, what = f"r1.{q(cfg['key'])} = r2.{q(cfg['key'])}", "versions of the same key"
|
|
160
|
+
else:
|
|
161
|
+
same, what = "endNode(r1) = endNode(r2)", "versions of the same relationship"
|
|
162
|
+
|
|
163
|
+
def run():
|
|
164
|
+
row = ctx.neo.read(
|
|
165
|
+
f"MATCH (a:{start})-[r1:{rel}]->(), (a)-[r2:{rel}]->() "
|
|
166
|
+
f"WHERE elementId(r1) < elementId(r2) AND {same} "
|
|
167
|
+
"AND coalesce(r1._valid_from, $min) < coalesce(r2._valid_to, $max) "
|
|
168
|
+
"AND coalesce(r2._valid_from, $min) < coalesce(r1._valid_to, $max) "
|
|
169
|
+
f"WITH DISTINCT a RETURN count(a) AS failures, collect(properties(a))[0..{SAMPLE_LIMIT}] AS samples",
|
|
170
|
+
min=datetime(1, 1, 1), max=datetime(9999, 12, 31),
|
|
171
|
+
)[0]
|
|
172
|
+
return row["failures"], row["samples"], f"{row['failures']:,} :{cfg['from_label']} node(s) with overlapping :{cfg['type']} validity ({what})"
|
|
173
|
+
|
|
174
|
+
return Check(f"no_overlap:{m.name}", args.get("severity", "error"), run)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
GENERIC = {"acyclic": _acyclic, "degree": _degree, "no_overlap": _no_overlap}
|
|
142
178
|
|
|
143
179
|
|
|
144
180
|
# --- singular tests (tests/*.cypher) -------------------------------------------------------
|
|
@@ -24,9 +24,10 @@ LANGUAGE_OF = {
|
|
|
24
24
|
"export": "cypher",
|
|
25
25
|
}
|
|
26
26
|
COMMON_KEYS = {"materialized", "depends_on", "enabled", "batch_size", "tests", "description"}
|
|
27
|
+
HISTORY_KEYS = {"history", "valid_from", "valid_to", "changed_at", "check_cols"}
|
|
27
28
|
ALLOWED_KEYS = {
|
|
28
|
-
"node": COMMON_KEYS | {"label", "key", "labels", "incremental", "allow_empty", "reconcile"},
|
|
29
|
-
"edge": COMMON_KEYS
|
|
29
|
+
"node": COMMON_KEYS | HISTORY_KEYS | {"label", "key", "labels", "incremental", "allow_empty", "reconcile"},
|
|
30
|
+
"edge": COMMON_KEYS | HISTORY_KEYS
|
|
30
31
|
| {"type", "from_label", "from_key", "to_label", "to_key", "key", "on_missing_endpoint",
|
|
31
32
|
"incremental", "allow_empty", "reconcile"},
|
|
32
33
|
"relationship": COMMON_KEYS | {"type"},
|
|
@@ -55,6 +56,15 @@ class Model:
|
|
|
55
56
|
def is_load(self) -> bool:
|
|
56
57
|
return self.materialized in ("node", "edge")
|
|
57
58
|
|
|
59
|
+
@property
|
|
60
|
+
def history(self) -> str | None:
|
|
61
|
+
"""'snapshot' (graphmill records changes), 'source' (valid_from/valid_to columns) or None."""
|
|
62
|
+
if self.config.get("history") == "snapshot":
|
|
63
|
+
return "snapshot"
|
|
64
|
+
if self.config.get("valid_from"):
|
|
65
|
+
return "source"
|
|
66
|
+
return None
|
|
67
|
+
|
|
58
68
|
def produced_labels(self) -> set[str]:
|
|
59
69
|
return {self.config["label"]} if self.materialized == "node" else set()
|
|
60
70
|
|
|
@@ -86,6 +96,35 @@ def _string(cfg: dict, key: str, origin: str) -> None:
|
|
|
86
96
|
raise _fail(origin, f"config '{key}' is required for materialized='{cfg['materialized']}'")
|
|
87
97
|
|
|
88
98
|
|
|
99
|
+
def _validate_history(cfg: dict[str, Any], origin: str) -> None:
|
|
100
|
+
history = cfg.get("history")
|
|
101
|
+
if history not in (None, False, "snapshot"):
|
|
102
|
+
raise _fail(origin, "config 'history' must be 'snapshot' (or use valid_from/valid_to columns)")
|
|
103
|
+
for name in ("valid_from", "valid_to", "changed_at"):
|
|
104
|
+
if cfg.get(name) is not None and (not isinstance(cfg[name], str) or not cfg[name].strip()):
|
|
105
|
+
raise _fail(origin, f"config '{name}' must be a column name")
|
|
106
|
+
if cfg.get("valid_to") and not cfg.get("valid_from"):
|
|
107
|
+
raise _fail(origin, "config 'valid_to' needs 'valid_from'")
|
|
108
|
+
if history == "snapshot":
|
|
109
|
+
if cfg.get("valid_from"):
|
|
110
|
+
raise _fail(
|
|
111
|
+
origin,
|
|
112
|
+
"use either history='snapshot' (graphmill records changes) or valid_from/valid_to "
|
|
113
|
+
"(the source provides validity), not both",
|
|
114
|
+
)
|
|
115
|
+
if cfg.get("incremental"):
|
|
116
|
+
raise _fail(origin, "history='snapshot' reads the full source to detect deletes; remove 'incremental'")
|
|
117
|
+
if cfg["materialized"] == "edge" and not cfg.get("key"):
|
|
118
|
+
raise _fail(origin, "history='snapshot' edges need a 'key' to track versions of the same relationship")
|
|
119
|
+
check_cols = cfg.get("check_cols")
|
|
120
|
+
if check_cols is not None and (
|
|
121
|
+
not isinstance(check_cols, list) or not all(isinstance(c, str) for c in check_cols)
|
|
122
|
+
):
|
|
123
|
+
raise _fail(origin, "config 'check_cols' must be a list of column names")
|
|
124
|
+
elif cfg.get("changed_at") or cfg.get("check_cols"):
|
|
125
|
+
raise _fail(origin, "'changed_at' and 'check_cols' only apply with history='snapshot'")
|
|
126
|
+
|
|
127
|
+
|
|
89
128
|
def validate_config(cfg: dict[str, Any], origin: str) -> dict[str, Any]:
|
|
90
129
|
kind = cfg["materialized"]
|
|
91
130
|
unknown = set(cfg) - ALLOWED_KEYS[kind]
|
|
@@ -129,6 +168,7 @@ def validate_config(cfg: dict[str, Any], origin: str) -> dict[str, Any]:
|
|
|
129
168
|
if kind in ("node", "edge"):
|
|
130
169
|
cfg.setdefault("allow_empty", False)
|
|
131
170
|
cfg.setdefault("reconcile", True)
|
|
171
|
+
_validate_history(cfg, origin)
|
|
132
172
|
deps = cfg.get("depends_on", [])
|
|
133
173
|
cfg["depends_on"] = [deps] if isinstance(deps, str) else list(deps)
|
|
134
174
|
tests = cfg.get("tests", [])
|
|
@@ -214,6 +254,14 @@ def resolve_dependencies(models: dict[str, Model]) -> None:
|
|
|
214
254
|
label = m.config[side]
|
|
215
255
|
if label not in label_owner:
|
|
216
256
|
raise _fail(m.rel_path, f"{side} '{label}' is not produced by any node model")
|
|
257
|
+
owner = models[label_owner[label]]
|
|
258
|
+
if m.history == "snapshot" and owner.history != "snapshot":
|
|
259
|
+
raise _fail(
|
|
260
|
+
m.rel_path,
|
|
261
|
+
f"history='snapshot' keeps relationship versions only in the graph, so endpoint node "
|
|
262
|
+
f"model '{owner.name}' must use history='snapshot' too: deleting a node would destroy "
|
|
263
|
+
"its relationship history",
|
|
264
|
+
)
|
|
217
265
|
deps.add(label_owner[label])
|
|
218
266
|
if m.language == "cypher":
|
|
219
267
|
labels, types = references(m.parsed_text)
|
|
@@ -34,14 +34,17 @@ def _source_keys(ctx: Context, m: Model, sql: str) -> set[str]:
|
|
|
34
34
|
|
|
35
35
|
def _graph_keys(ctx: Context, m: Model) -> set[str]:
|
|
36
36
|
cfg = m.config
|
|
37
|
+
# snapshot models: compare against current versions; closed ones are history
|
|
38
|
+
n_cur = " AND n._valid_to IS NULL" if m.history == "snapshot" else ""
|
|
39
|
+
r_cur = " AND r._valid_to IS NULL" if m.history == "snapshot" else ""
|
|
37
40
|
if m.materialized == "node":
|
|
38
|
-
query = f"MATCH (n:{q(cfg['label'])}) WHERE n._model = $model RETURN toString(n.{q(cfg['key'])}) AS k"
|
|
41
|
+
query = f"MATCH (n:{q(cfg['label'])}) WHERE n._model = $model{n_cur} RETURN toString(n.{q(cfg['key'])}) AS k"
|
|
39
42
|
elif cfg.get("key"):
|
|
40
|
-
query = f"MATCH ()-[r:{q(cfg['type'])}]->() WHERE r._model = $model RETURN toString(r.{q(cfg['key'])}) AS k"
|
|
43
|
+
query = f"MATCH ()-[r:{q(cfg['type'])}]->() WHERE r._model = $model{r_cur} RETURN toString(r.{q(cfg['key'])}) AS k"
|
|
41
44
|
else:
|
|
42
45
|
fp, tp = ctx.node_key_of(cfg["from_label"]), ctx.node_key_of(cfg["to_label"])
|
|
43
46
|
query = (
|
|
44
|
-
f"MATCH (a)-[r:{q(cfg['type'])}]->(b) WHERE r._model = $model "
|
|
47
|
+
f"MATCH (a)-[r:{q(cfg['type'])}]->(b) WHERE r._model = $model{r_cur} "
|
|
45
48
|
f"RETURN toString(a.{q(fp)}) + '->' + toString(b.{q(tp)}) AS k"
|
|
46
49
|
)
|
|
47
50
|
return {row["k"] for row in ctx.neo.read(query, model=ctx.owner_id(m))}
|
|
@@ -63,6 +66,10 @@ def plan(ctx: Context, order: list[str], *, full_refresh: bool) -> list[PlanRow]
|
|
|
63
66
|
graph = _graph_keys(ctx, m)
|
|
64
67
|
delete = 0 if incremental else len(graph - source)
|
|
65
68
|
note = f"incremental since {watermark['value']}" if incremental else ""
|
|
69
|
+
if m.history == "snapshot":
|
|
70
|
+
note = "snapshot: changed rows open new versions, 'delete' = close"
|
|
71
|
+
elif m.history == "source":
|
|
72
|
+
note = "versioned by source (valid_from/valid_to)"
|
|
66
73
|
rows.append(PlanRow(name, m.materialized, target, len(source - graph), len(source & graph), delete, note))
|
|
67
74
|
elif m.materialized == "relationship":
|
|
68
75
|
current = sum(ctx.neo.count_rels(t, ctx.owner_id(m)) for t in cfg["types"])
|
|
@@ -26,6 +26,28 @@ def stamp(alias: str) -> str:
|
|
|
26
26
|
return f"{alias}._run_id = $run_id, {alias}._model = $model, {alias}._loaded_at = datetime()"
|
|
27
27
|
|
|
28
28
|
|
|
29
|
+
def as_of(alias: str, at: str | None = None) -> str:
|
|
30
|
+
"""Cypher predicate: the element was valid at `at` (a Cypher expression), or is current if omitted.
|
|
31
|
+
|
|
32
|
+
Elements without history (no _valid_from / _valid_to) always pass, so the same query
|
|
33
|
+
works over versioned and unversioned parts of the graph.
|
|
34
|
+
"""
|
|
35
|
+
if at is None:
|
|
36
|
+
return f"{alias}._valid_to IS NULL"
|
|
37
|
+
return (
|
|
38
|
+
f"(({alias}._valid_from IS NULL OR {alias}._valid_from <= {at}) "
|
|
39
|
+
f"AND ({alias}._valid_to IS NULL OR {alias}._valid_to > {at}))"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ts(value: str) -> str:
|
|
44
|
+
"""Cypher literal for a timestamp in the same type as _valid_from: ts('2026-03-01')."""
|
|
45
|
+
text = str(value).strip().replace(" ", "T")
|
|
46
|
+
if len(text) == 10:
|
|
47
|
+
text += "T00:00:00"
|
|
48
|
+
return f"localdatetime('{text}')"
|
|
49
|
+
|
|
50
|
+
|
|
29
51
|
@dataclass
|
|
30
52
|
class Rendered:
|
|
31
53
|
text: str
|
|
@@ -94,6 +116,8 @@ class Renderer:
|
|
|
94
116
|
"is_incremental": lambda: incremental,
|
|
95
117
|
"watermark": _watermark,
|
|
96
118
|
"stamp": stamp,
|
|
119
|
+
"as_of": as_of,
|
|
120
|
+
"ts": ts,
|
|
97
121
|
"this": name,
|
|
98
122
|
}
|
|
99
123
|
try:
|