datarecord 0.1.0a1__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.
- datarecord/__init__.py +44 -0
- datarecord/duck.py +584 -0
- datarecord/layered/__init__.py +0 -0
- datarecord/layered/fold.py +249 -0
- datarecord/layered/resolve.py +1247 -0
- datarecord/layered/revision.py +396 -0
- datarecord/layered/sources.py +343 -0
- datarecord/layered/write.py +494 -0
- datarecord/mutable.py +2274 -0
- datarecord/py.typed +0 -0
- datarecord/record.py +307 -0
- datarecord/schema.py +1222 -0
- datarecord/tools/__init__.py +16 -0
- datarecord/tools/base.py +308 -0
- datarecord/tools/pypsa.py +1826 -0
- datarecord-0.1.0a1.dist-info/METADATA +100 -0
- datarecord-0.1.0a1.dist-info/RECORD +19 -0
- datarecord-0.1.0a1.dist-info/WHEEL +4 -0
- datarecord-0.1.0a1.dist-info/licenses/LICENSE +21 -0
datarecord/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: datarecord contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = importlib.metadata.version(__name__)
|
|
10
|
+
except importlib.metadata.PackageNotFoundError as e: # pragma: no cover
|
|
11
|
+
warnings.warn(f"Could not determine version of {__name__}\n{e!s}", stacklevel=2)
|
|
12
|
+
__version__ = "unknown"
|
|
13
|
+
|
|
14
|
+
from datarecord.duck import connect, layer_dir
|
|
15
|
+
from datarecord.layered.revision import Record, Revision
|
|
16
|
+
from datarecord.layered.write import write_record
|
|
17
|
+
from datarecord.mutable import Directory, NewChild, WorkingRecord
|
|
18
|
+
from datarecord.record import (
|
|
19
|
+
Flags,
|
|
20
|
+
Frames,
|
|
21
|
+
LazyFrames,
|
|
22
|
+
RecordLike,
|
|
23
|
+
)
|
|
24
|
+
from datarecord.schema import AttributeSpec, Dimension, Group, Schema, Trait
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"AttributeSpec",
|
|
28
|
+
"Dimension",
|
|
29
|
+
"Directory",
|
|
30
|
+
"Flags",
|
|
31
|
+
"Frames",
|
|
32
|
+
"Group",
|
|
33
|
+
"LazyFrames",
|
|
34
|
+
"NewChild",
|
|
35
|
+
"Record",
|
|
36
|
+
"RecordLike",
|
|
37
|
+
"Revision",
|
|
38
|
+
"Schema",
|
|
39
|
+
"Trait",
|
|
40
|
+
"WorkingRecord",
|
|
41
|
+
"connect",
|
|
42
|
+
"layer_dir",
|
|
43
|
+
"write_record",
|
|
44
|
+
]
|
datarecord/duck.py
ADDED
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: datarecord contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""DuckDB connection setup for the record layer.
|
|
6
|
+
|
|
7
|
+
Owns the `revisions` metadata table and the `layer_dir` path convention
|
|
8
|
+
that maps a record UUID to its record location. The connection is passed as a
|
|
9
|
+
parameter throughout, never a module global, so each test can open its own
|
|
10
|
+
`:memory:` connection.
|
|
11
|
+
|
|
12
|
+
Nothing here knows about a modelling framework: the entity-type axis is typed
|
|
13
|
+
as the *schema* declares it, whatever a tool's registry holds, so a record whose
|
|
14
|
+
types no tool recognises still reads and it is a tool's `verify` that reports
|
|
15
|
+
them.
|
|
16
|
+
|
|
17
|
+
Notes
|
|
18
|
+
-----
|
|
19
|
+
- [the schema](https://energy-models.github.io/datarecord/design/schema/)
|
|
20
|
+
- [consuming a record](https://energy-models.github.io/datarecord/design/tools/)
|
|
21
|
+
- [module layout](https://energy-models.github.io/datarecord/design/module-layout/)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence
|
|
27
|
+
from functools import partial, reduce
|
|
28
|
+
from glob import glob
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
from urllib.error import HTTPError
|
|
32
|
+
from urllib.request import urlopen
|
|
33
|
+
from uuid import UUID
|
|
34
|
+
from weakref import WeakKeyDictionary
|
|
35
|
+
|
|
36
|
+
import duckdb
|
|
37
|
+
import narwhals as nw
|
|
38
|
+
import narwhals._duckdb.utils as _nw_duckdb
|
|
39
|
+
from duckdb import CoalesceOperator as coalesce
|
|
40
|
+
from duckdb import ColumnExpression as col
|
|
41
|
+
from duckdb import ConstantExpression as lit
|
|
42
|
+
from duckdb import DuckDBPyConnection, DuckDBPyRelation, Expression, FunctionExpression
|
|
43
|
+
from duckdb import SQLExpression as sql
|
|
44
|
+
from duckdb import StarExpression as star
|
|
45
|
+
from narwhals._utils import Version
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Functions:
|
|
49
|
+
"""`fn.bool_or(x)` for `FunctionExpression("bool_or", x)`.
|
|
50
|
+
|
|
51
|
+
Attribute access reads closer to the SQL it builds than a name-as-string
|
|
52
|
+
call does, and keeps aggregates out of `SQLExpression` strings, where a
|
|
53
|
+
column name would have to be quoted by hand.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __getattr__(self, name: str) -> Callable[..., Expression]:
|
|
57
|
+
return partial(FunctionExpression, name)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
fn = _Functions()
|
|
61
|
+
|
|
62
|
+
CREATE_TABLE = """
|
|
63
|
+
CREATE TABLE IF NOT EXISTS revisions (
|
|
64
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
65
|
+
parent UUID
|
|
66
|
+
)
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
# Where layers live; `layer_dir(id)` derives every record path from it (https://energy-models.github.io/datarecord/design/module-layout/).
|
|
70
|
+
DEFAULT_BASE_URI = os.environ.get("DATARECORD_BASE_URI", "")
|
|
71
|
+
|
|
72
|
+
# The record root each connection was opened against (https://energy-models.github.io/datarecord/design/schema/#one-schema-per-record). A connection is
|
|
73
|
+
# already scoped to one record - `connect` registers its `layer_dir` macro from
|
|
74
|
+
# this root - so the schema beside those layers is a property of the connection
|
|
75
|
+
# too, and reading it needs no separate parameter threaded through the fold.
|
|
76
|
+
# Weak, so a closed connection does not pin its entry.
|
|
77
|
+
_BASE_URIS: MutableMapping[DuckDBPyConnection, str] = WeakKeyDictionary()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def base_uri_of(con: DuckDBPyConnection) -> str:
|
|
81
|
+
"""The record root `con` was opened against, or the process default.
|
|
82
|
+
|
|
83
|
+
A connection not opened through `connect` - one a caller made itself -
|
|
84
|
+
falls back to `DEFAULT_BASE_URI`, which is what every path helper here
|
|
85
|
+
already does when passed no explicit root.
|
|
86
|
+
|
|
87
|
+
Notes
|
|
88
|
+
-----
|
|
89
|
+
- [one schema per record](https://energy-models.github.io/datarecord/design/schema/#one-schema-per-record)
|
|
90
|
+
"""
|
|
91
|
+
return _BASE_URIS.get(con, DEFAULT_BASE_URI)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def schema_uri(base_uri: str | None = None) -> str:
|
|
95
|
+
"""Where a layered record's one schema lives: beside `layers/`, not in it.
|
|
96
|
+
|
|
97
|
+
One schema for the whole tree. A layer directory holds only data, which is
|
|
98
|
+
what keeps it a plain parquet directory a tool knowing nothing about layering
|
|
99
|
+
can read.
|
|
100
|
+
|
|
101
|
+
Notes
|
|
102
|
+
-----
|
|
103
|
+
- [one schema per record](https://energy-models.github.io/datarecord/design/schema/#one-schema-per-record)
|
|
104
|
+
"""
|
|
105
|
+
base = DEFAULT_BASE_URI if base_uri is None else base_uri
|
|
106
|
+
return f"{base.rstrip('/')}/manifest.json" if base else "manifest.json"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def layer_dir(revision_id: UUID | str, base_uri: str | None = None) -> str:
|
|
110
|
+
"""Return the record directory for `revision_id`, with a trailing slash.
|
|
111
|
+
|
|
112
|
+
The layer location is derived from the UUID, never stored, so
|
|
113
|
+
changing the layout is a change in this one function and its SQL macro.
|
|
114
|
+
This is a plain PyPSA parquet directory: only the layer's own
|
|
115
|
+
contribution lives at the top level, so a non-blocks reader sees a normal
|
|
116
|
+
record. Derived caches (the owner map, resolved dims) go in the
|
|
117
|
+
`resolved/` subdirectory, which no single-level glob reaches.
|
|
118
|
+
|
|
119
|
+
Notes
|
|
120
|
+
-----
|
|
121
|
+
- [the record format](https://energy-models.github.io/datarecord/design/format/)
|
|
122
|
+
- [module layout](https://energy-models.github.io/datarecord/design/module-layout/)
|
|
123
|
+
"""
|
|
124
|
+
base = DEFAULT_BASE_URI if base_uri is None else base_uri
|
|
125
|
+
return (
|
|
126
|
+
f"{base.rstrip('/')}/layers/{revision_id}/"
|
|
127
|
+
if base
|
|
128
|
+
else f"layers/{revision_id}/"
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def resolved_dir(revision_id: UUID | str, base_uri: str | None = None) -> str:
|
|
133
|
+
"""Return the resolved-cache directory for `revision_id`, with a trailing slash.
|
|
134
|
+
|
|
135
|
+
A subdirectory of `layer_dir`, not a sibling tree: one directory per record
|
|
136
|
+
holds both what the layer wrote and what the fold derived from it. The
|
|
137
|
+
nesting is safe because every glob into a layer is single-level
|
|
138
|
+
(`inputs/*.parquet`, `dims/*.parquet`), so `resolved/` is invisible to a
|
|
139
|
+
reader that knows nothing about it - which is what keeps a layer directory a
|
|
140
|
+
plain parquet directory a foreign reader can consume.
|
|
141
|
+
|
|
142
|
+
Only the layer's *inputs* are write-once, then: `materialise` writes here
|
|
143
|
+
after the fact, which invalidates nothing because results and caches are
|
|
144
|
+
derived rather than depended on.
|
|
145
|
+
|
|
146
|
+
Notes
|
|
147
|
+
-----
|
|
148
|
+
- [a layer's data is write-once](https://energy-models.github.io/datarecord/design/layers/#a-layers-data-is-write-once)
|
|
149
|
+
- [materialised node caches](https://energy-models.github.io/datarecord/design/layers/#materialised-node-caches)
|
|
150
|
+
- [deletion](https://energy-models.github.io/datarecord/design/layers/#deletion)
|
|
151
|
+
"""
|
|
152
|
+
return f"{layer_dir(revision_id, base_uri)}resolved/"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _register_macros(con: DuckDBPyConnection, base_uri: str) -> None:
|
|
156
|
+
"""Register `layer_dir` so SQL composes record paths inline.
|
|
157
|
+
|
|
158
|
+
Notes
|
|
159
|
+
-----
|
|
160
|
+
- [module layout](https://energy-models.github.io/datarecord/design/module-layout/)
|
|
161
|
+
"""
|
|
162
|
+
base = base_uri.rstrip("/")
|
|
163
|
+
prefix = f"{base}/" if base else ""
|
|
164
|
+
con.execute("DROP MACRO IF EXISTS layer_dir")
|
|
165
|
+
con.execute(f"CREATE MACRO layer_dir(id) AS '{prefix}layers/' || id || '/'")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def connect(
|
|
169
|
+
database: str = ":memory:", base_uri: str | None = None
|
|
170
|
+
) -> DuckDBPyConnection:
|
|
171
|
+
"""Open a connection with the record layer's table and macros.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
database
|
|
176
|
+
DuckDB database, `:memory:` by default.
|
|
177
|
+
base_uri
|
|
178
|
+
Root of the record tree; `layer_dir` derives every path from it.
|
|
179
|
+
|
|
180
|
+
Notes
|
|
181
|
+
-----
|
|
182
|
+
- [module layout](https://energy-models.github.io/datarecord/design/module-layout/)
|
|
183
|
+
"""
|
|
184
|
+
con = duckdb.connect(database)
|
|
185
|
+
base = DEFAULT_BASE_URI if base_uri is None else base_uri
|
|
186
|
+
# `httpfs` and the S3 secret are only meaningful for remote layers, and
|
|
187
|
+
# `PROVIDER credential_chain` probes instance-metadata endpoints that hang
|
|
188
|
+
# for ~2 minutes where none exist. Never pay that for a local record.
|
|
189
|
+
if "://" in base:
|
|
190
|
+
try:
|
|
191
|
+
con.execute("INSTALL httpfs; LOAD httpfs;")
|
|
192
|
+
# S3 credentials come from the environment, never hard-coded (https://energy-models.github.io/datarecord/design/module-layout/).
|
|
193
|
+
con.execute(
|
|
194
|
+
"CREATE SECRET IF NOT EXISTS (TYPE s3, PROVIDER credential_chain)"
|
|
195
|
+
)
|
|
196
|
+
except duckdb.Error:
|
|
197
|
+
pass
|
|
198
|
+
con.execute(CREATE_TABLE)
|
|
199
|
+
_register_macros(con, base)
|
|
200
|
+
# Remembered so `read_schema` finds the manifest beside *this* record's
|
|
201
|
+
# layers rather than the process default's (https://energy-models.github.io/datarecord/design/schema/#one-schema-per-record).
|
|
202
|
+
_BASE_URIS[con] = base
|
|
203
|
+
return con
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
_default_con: DuckDBPyConnection | None = None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def default_connection() -> DuckDBPyConnection:
|
|
210
|
+
"""The process-level connection, created on first use.
|
|
211
|
+
|
|
212
|
+
`Revision` attaches this lazily to any record created/loaded without an
|
|
213
|
+
explicit `con` (including one deserialized in a new process, e.g. across
|
|
214
|
+
a Prefect task boundary); tests always pass their own connection instead.
|
|
215
|
+
"""
|
|
216
|
+
global _default_con
|
|
217
|
+
if _default_con is None:
|
|
218
|
+
_default_con = connect()
|
|
219
|
+
return _default_con
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def try_read_parquet(
|
|
223
|
+
uri: str, con: DuckDBPyConnection, **kwargs: object
|
|
224
|
+
) -> DuckDBPyRelation | None:
|
|
225
|
+
"""`con.read_parquet(uri)`, or `None` if `uri` (possibly a glob) matches nothing.
|
|
226
|
+
|
|
227
|
+
Parameters
|
|
228
|
+
----------
|
|
229
|
+
uri
|
|
230
|
+
Path or glob to read, local or remote.
|
|
231
|
+
con
|
|
232
|
+
Connection to read with.
|
|
233
|
+
**kwargs
|
|
234
|
+
Forwarded to `con.read_parquet`.
|
|
235
|
+
|
|
236
|
+
Returns
|
|
237
|
+
-------
|
|
238
|
+
DuckDBPyRelation | None
|
|
239
|
+
The relation, or `None` if `uri` matches no files.
|
|
240
|
+
|
|
241
|
+
Raises
|
|
242
|
+
------
|
|
243
|
+
duckdb.Error
|
|
244
|
+
If the read fails for any reason other than a local or remote miss
|
|
245
|
+
(e.g. DNS/TLS/timeout) - a connection failure should not be mistaken
|
|
246
|
+
for a missing layer.
|
|
247
|
+
|
|
248
|
+
Notes
|
|
249
|
+
-----
|
|
250
|
+
A local miss is answered without asking DuckDB at all. Inside a transaction
|
|
251
|
+
a failed read *aborts* it, and catching the exception here does not undo
|
|
252
|
+
that - every later statement on the connection would fail until a rollback,
|
|
253
|
+
which would discard whatever the transaction had staged. A missing kind is
|
|
254
|
+
ordinary (an attribute a layer never wrote), so it must not depend on being
|
|
255
|
+
outside one.
|
|
256
|
+
"""
|
|
257
|
+
if "://" not in uri and not (
|
|
258
|
+
glob(uri) if any(c in uri for c in "*?[") else Path(uri).exists()
|
|
259
|
+
):
|
|
260
|
+
return None
|
|
261
|
+
try:
|
|
262
|
+
return con.read_parquet(uri, **kwargs) # type: ignore[arg-type]
|
|
263
|
+
except duckdb.HTTPException as e:
|
|
264
|
+
# This duckdb build exposes no status code, only the message ("HTTP
|
|
265
|
+
# Error: ... (HTTP 404 Not Found)"). 403 also counts as a miss: S3
|
|
266
|
+
# signals a missing key that way when the caller lacks ListBucket.
|
|
267
|
+
if "HTTP 404" in str(e) or "HTTP 403" in str(e):
|
|
268
|
+
return None
|
|
269
|
+
raise
|
|
270
|
+
except duckdb.IOException as e:
|
|
271
|
+
if "No files found" in str(e):
|
|
272
|
+
return None
|
|
273
|
+
raise
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def parquet_names(dir_uri: str, con: DuckDBPyConnection) -> set[str]:
|
|
277
|
+
"""Basenames of the `*.parquet` files directly under `dir_uri`.
|
|
278
|
+
|
|
279
|
+
One listing regardless of how many files exist there, local or remote -
|
|
280
|
+
what a caller otherwise probing one filename at a time (`try_read_parquet`
|
|
281
|
+
per candidate) should glob instead.
|
|
282
|
+
"""
|
|
283
|
+
rows = con.sql(
|
|
284
|
+
"SELECT file FROM glob(?)", params=[f"{dir_uri}*.parquet"]
|
|
285
|
+
).fetchall()
|
|
286
|
+
return {os.path.basename(row[0]) for row in rows}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def union_all_by_name(
|
|
290
|
+
rels: Sequence[DuckDBPyRelation], con: DuckDBPyConnection
|
|
291
|
+
) -> DuckDBPyRelation:
|
|
292
|
+
"""Fold relations pairwise through `UNION ALL BY NAME`.
|
|
293
|
+
|
|
294
|
+
The local names `u` and `rel` are load-bearing: DuckDB's replacement scan
|
|
295
|
+
binds them by *name* out of this frame's locals, so the SQL below reads
|
|
296
|
+
them despite them looking unused. Renaming either silently returns a short
|
|
297
|
+
union; `test_union_all_by_name_folds_every_relation` pins it.
|
|
298
|
+
|
|
299
|
+
Not `con.register`: measured at 2.2-2.6x slower here, widening with layer
|
|
300
|
+
count (the deep-overlay case materialised caches exist to make cheap), and it leaves a
|
|
301
|
+
named view per call on a connection that outlives the fold.
|
|
302
|
+
|
|
303
|
+
Notes
|
|
304
|
+
-----
|
|
305
|
+
- [materialised node caches](https://energy-models.github.io/datarecord/design/layers/#materialised-node-caches)
|
|
306
|
+
- [resolving a relation](https://energy-models.github.io/datarecord/design/read-path/#resolving-a-relation)
|
|
307
|
+
"""
|
|
308
|
+
u = rels[0]
|
|
309
|
+
for rel in rels[1:]: # noqa: F841 - bound by name in the SQL below
|
|
310
|
+
u = con.sql("FROM u UNION ALL BY NAME FROM rel")
|
|
311
|
+
return u
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def ex_all(exprs: Iterable[Expression]) -> Expression:
|
|
315
|
+
"""AND every expression in `exprs` together."""
|
|
316
|
+
return reduce(lambda x, y: x & y, exprs)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def null_safe(alias_a: str, alias_b: str, columns: Iterable[str]) -> Expression:
|
|
320
|
+
"""NULL-safe equality on `columns`, between two aliased relations.
|
|
321
|
+
|
|
322
|
+
What an address coordinate is matched on everywhere: a row exists or it does
|
|
323
|
+
not, so NULL means "this key has no value there" and must match the same
|
|
324
|
+
NULL on the other side, which a plain `=` never does.
|
|
325
|
+
"""
|
|
326
|
+
return ex_all(
|
|
327
|
+
sql(f"{col(alias_a, c)} IS NOT DISTINCT FROM {col(alias_b, c)}")
|
|
328
|
+
for c in columns
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def broadcast_match(
|
|
333
|
+
alias_a: str, alias_b: str, fixed: Iterable[str], dims: Iterable[str]
|
|
334
|
+
) -> Expression:
|
|
335
|
+
"""NULL-safe equality on `fixed`, broadcast-OR on `dims`.
|
|
336
|
+
|
|
337
|
+
A raw row's `dim = NULL` means "every value of `dim`", so it must match
|
|
338
|
+
regardless of the resolved side's value there, unlike the `IS NOT DISTINCT
|
|
339
|
+
FROM` of `null_safe` which only matches NULL against NULL. `alias_a` is the
|
|
340
|
+
broadcasting side.
|
|
341
|
+
|
|
342
|
+
Notes
|
|
343
|
+
-----
|
|
344
|
+
- [the broadcast rule](https://energy-models.github.io/datarecord/design/record/#the-broadcast-rule)
|
|
345
|
+
- [partial](https://energy-models.github.io/datarecord/design/schema/#partial-the-granularity-of-an-override)
|
|
346
|
+
"""
|
|
347
|
+
match = null_safe(alias_a, alias_b, fixed)
|
|
348
|
+
for dim in dims:
|
|
349
|
+
match = match & (
|
|
350
|
+
col(alias_a, dim).isnull()
|
|
351
|
+
| sql(f"{col(alias_a, dim)} IS NOT DISTINCT FROM {col(alias_b, dim)}")
|
|
352
|
+
)
|
|
353
|
+
return match
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def distinct_values(
|
|
357
|
+
rel: DuckDBPyRelation, column: str, *, order: bool = True
|
|
358
|
+
) -> tuple[Any, ...]:
|
|
359
|
+
"""`rel`'s distinct values of `column`, as a tuple.
|
|
360
|
+
|
|
361
|
+
What keys a `LazyFrames` built over a relation: the values are read from a
|
|
362
|
+
column rather than from a directory listing, so one code path serves a local
|
|
363
|
+
directory and a remote prefix alike.
|
|
364
|
+
"""
|
|
365
|
+
projected = rel.project(column).distinct()
|
|
366
|
+
if order:
|
|
367
|
+
projected = projected.order(column)
|
|
368
|
+
return tuple(r[0] for r in projected.fetchall())
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def as_relation(frame: nw.LazyFrame, con: DuckDBPyConnection) -> DuckDBPyRelation:
|
|
372
|
+
"""One narwhals frame as a DuckDB relation, without collecting where possible.
|
|
373
|
+
|
|
374
|
+
A DuckDB-backed frame is already a plan, so it passes straight through; any
|
|
375
|
+
other backend is collected to arrow and re-registered. The one boundary where
|
|
376
|
+
a native representation is reached, shared by the write and edit paths.
|
|
377
|
+
"""
|
|
378
|
+
native = frame.to_native()
|
|
379
|
+
if isinstance(native, DuckDBPyRelation):
|
|
380
|
+
return native
|
|
381
|
+
arrow = frame.collect(backend="pyarrow").to_native() # noqa: F841 - bound by name
|
|
382
|
+
return con.sql("FROM arrow")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def ensure_local_dir(uri: str, *, parent: bool = False) -> None:
|
|
386
|
+
"""Create `uri`'s directory where it is a local path, a no-op for a remote one.
|
|
387
|
+
|
|
388
|
+
A remote store needs no directory created; a local write does, and a record
|
|
389
|
+
that wrote nothing to its layer has no directory yet either.
|
|
390
|
+
|
|
391
|
+
Parameters
|
|
392
|
+
----------
|
|
393
|
+
parent
|
|
394
|
+
`uri` names a file whose directory is created, rather than the directory
|
|
395
|
+
itself.
|
|
396
|
+
"""
|
|
397
|
+
if "://" in uri:
|
|
398
|
+
return
|
|
399
|
+
path = Path(uri)
|
|
400
|
+
(path.parent if parent else path).mkdir(parents=True, exist_ok=True)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def struct_of(fields: Mapping[str, Expression]) -> Expression:
|
|
404
|
+
"""A struct expression: field name to the expression for its value.
|
|
405
|
+
|
|
406
|
+
A struct rather than a column per field, because it comes back as a dict
|
|
407
|
+
keyed by name: the caller filters it by name instead of counting columns
|
|
408
|
+
into a positional slice.
|
|
409
|
+
|
|
410
|
+
`struct_pack` is what says this in DuckDB, and the field names are its
|
|
411
|
+
*keyword* arguments - which `FunctionExpression` cannot pass, being
|
|
412
|
+
positional-only. So the call is assembled as text here and the values are
|
|
413
|
+
interpolated as the expressions they already are, keeping SQL text out of
|
|
414
|
+
every caller.
|
|
415
|
+
|
|
416
|
+
Never empty, DuckDB having no empty struct.
|
|
417
|
+
"""
|
|
418
|
+
packed = ", ".join(f'"{name}" := {value}' for name, value in fields.items())
|
|
419
|
+
return sql(f"struct_pack({packed})")
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class DuckTypes:
|
|
423
|
+
"""Builds DuckDB types and typed shapes from narwhals dtypes, just in time.
|
|
424
|
+
|
|
425
|
+
Built once per connection and called per dtype - the constructor's
|
|
426
|
+
relation is where a timezone-aware `Datetime` resolves its zone (DuckDB
|
|
427
|
+
keeps timezone on the connection, not the dtype), and is fetched at most
|
|
428
|
+
once no matter how many dtypes this instance translates.
|
|
429
|
+
|
|
430
|
+
Reaches into narwhals' private DuckDB backend
|
|
431
|
+
(`narwhals._duckdb.utils.narwhals_to_native_dtype`) rather than a local
|
|
432
|
+
translation table - unversioned within the `narwhals>=2,<3` pin, so
|
|
433
|
+
`pixi run test` is what catches a break, not a type error here.
|
|
434
|
+
|
|
435
|
+
Parameters
|
|
436
|
+
----------
|
|
437
|
+
rel_or_con
|
|
438
|
+
A connection is queried for the throwaway relation
|
|
439
|
+
`DeferredTimeZone` needs; a relation already in hand is used as-is,
|
|
440
|
+
skipping that query.
|
|
441
|
+
"""
|
|
442
|
+
|
|
443
|
+
deferred_tz: _nw_duckdb.DeferredTimeZone
|
|
444
|
+
con: DuckDBPyConnection | None
|
|
445
|
+
|
|
446
|
+
def __init__(self, rel_or_con: DuckDBPyRelation | DuckDBPyConnection):
|
|
447
|
+
if isinstance(rel_or_con, DuckDBPyConnection):
|
|
448
|
+
self.con = rel_or_con
|
|
449
|
+
rel = rel_or_con.sql("SELECT 1")
|
|
450
|
+
else:
|
|
451
|
+
self.con = None
|
|
452
|
+
rel = rel_or_con
|
|
453
|
+
self.deferred_tz = _nw_duckdb.DeferredTimeZone(rel)
|
|
454
|
+
|
|
455
|
+
def __call__(self, dtype: nw.dtypes.DType) -> duckdb.sqltypes.DuckDBPyType:
|
|
456
|
+
"""`dtype`'s DuckDB type."""
|
|
457
|
+
return _nw_duckdb.narwhals_to_native_dtype(
|
|
458
|
+
dtype, Version.MAIN, self.deferred_tz
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
def lit(self, value: Any, dtype: nw.dtypes.DType) -> Expression:
|
|
462
|
+
"""`value`, cast to `dtype`'s DuckDB type - a typed literal."""
|
|
463
|
+
return lit(value).cast(self(dtype))
|
|
464
|
+
|
|
465
|
+
def null(self, dtype: nw.dtypes.DType) -> Expression:
|
|
466
|
+
"""A typed NULL, which is one column of a shape-only relation."""
|
|
467
|
+
return self.lit(None, dtype)
|
|
468
|
+
|
|
469
|
+
def empty_relation(self, **columns: nw.dtypes.DType) -> DuckDBPyRelation:
|
|
470
|
+
"""A row-less relation with `columns`' names and types.
|
|
471
|
+
|
|
472
|
+
What a staging table is created from: `create` takes the table's
|
|
473
|
+
shape from the relation, so a shape is built as expressions rather
|
|
474
|
+
than assembled as DDL text. One row of typed NULLs, kept for its
|
|
475
|
+
types and dropped for its rows.
|
|
476
|
+
|
|
477
|
+
A tuple rather than a list is what routes `values` to its expression
|
|
478
|
+
overload; the stub types only the scalar one.
|
|
479
|
+
"""
|
|
480
|
+
assert self.con is not None
|
|
481
|
+
return self.con.values(
|
|
482
|
+
tuple(self.null(t).alias(n) for n, t in columns.items())
|
|
483
|
+
).limit(0) # type: ignore[arg-type]
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def fold_axis(
|
|
487
|
+
axes: Sequence[DuckDBPyRelation | None],
|
|
488
|
+
key: tuple[str, ...],
|
|
489
|
+
con: DuckDBPyConnection,
|
|
490
|
+
) -> DuckDBPyRelation | None:
|
|
491
|
+
"""Fold one keyed relation over each layer's, keyed by `key`, in member order.
|
|
492
|
+
|
|
493
|
+
The one fold for every axis - a dim's coordinates, a group, the entity axis.
|
|
494
|
+
`axes` is root first, one entry per layer - `None` where that layer has no
|
|
495
|
+
rows. Last-writer-wins per `key`, which is `Schema.axis_key` for a dim or
|
|
496
|
+
`Schema.group_key` for a group, so a nested dim is keyed by `(*parents, dim)`
|
|
497
|
+
and two periods' identically labelled timesteps stay distinct.
|
|
498
|
+
|
|
499
|
+
A `deleted = true` row is a tombstone: it removes its key unless a still-
|
|
500
|
+
deeper layer restates it, and never survives into the output, which carries
|
|
501
|
+
no `deleted` column. The output is returned **in first-introduced member
|
|
502
|
+
order** - root first, then within a layer file order - so a reader recovers
|
|
503
|
+
member order from the resolved file's own row order without a persisted
|
|
504
|
+
`order_key`.
|
|
505
|
+
|
|
506
|
+
`_row` is tagged **per layer, before any union**: `UNION ALL` defines no
|
|
507
|
+
order, so a bare `row_number() OVER ()` over the unioned relation would
|
|
508
|
+
silently scramble which row counts as first-introduced.
|
|
509
|
+
|
|
510
|
+
Notes
|
|
511
|
+
-----
|
|
512
|
+
- [one fold for every axis](https://energy-models.github.io/datarecord/design/read-path/#one-fold-for-every-axis)
|
|
513
|
+
- [axis order](https://energy-models.github.io/datarecord/design/record/#axis-order)
|
|
514
|
+
- [within](https://energy-models.github.io/datarecord/design/schema/#within-an-axis-inside-an-axis)
|
|
515
|
+
- [deletion](https://energy-models.github.io/datarecord/design/layers/#deletion)
|
|
516
|
+
"""
|
|
517
|
+
layers = []
|
|
518
|
+
for depth, rel in enumerate(axes):
|
|
519
|
+
if rel is None:
|
|
520
|
+
continue
|
|
521
|
+
layers.append(
|
|
522
|
+
rel.project(
|
|
523
|
+
lit(depth).alias("_depth"),
|
|
524
|
+
sql("row_number() OVER ()").alias("_row"),
|
|
525
|
+
col("*"),
|
|
526
|
+
)
|
|
527
|
+
)
|
|
528
|
+
if not layers:
|
|
529
|
+
return None
|
|
530
|
+
|
|
531
|
+
union = union_all_by_name(layers, con)
|
|
532
|
+
has_deleted = "deleted" in union.columns
|
|
533
|
+
partition = ", ".join(str(col(c)) for c in key)
|
|
534
|
+
# `OVER (PARTITION BY ...)` stays text below: DuckDB's expression API has no
|
|
535
|
+
# window construct, so only what the window wraps is built as an expression.
|
|
536
|
+
ranked = union.project(
|
|
537
|
+
star(),
|
|
538
|
+
sql(f"row_number() OVER (PARTITION BY {partition} ORDER BY _depth DESC)").alias(
|
|
539
|
+
"_rank"
|
|
540
|
+
),
|
|
541
|
+
# The first-introducing (depth, row) pair, as one orderable struct -
|
|
542
|
+
# `min()` over two separate window aggregates would answer "smallest
|
|
543
|
+
# _depth" and "smallest _row" independently, not the pair belonging
|
|
544
|
+
# to the earliest actual row.
|
|
545
|
+
sql(
|
|
546
|
+
f"{fn.min(struct_of({'d': col('_depth'), 'r': col('_row')}))} "
|
|
547
|
+
f"OVER (PARTITION BY {partition})"
|
|
548
|
+
).alias("_first"),
|
|
549
|
+
)
|
|
550
|
+
winners = ranked.filter(col("_rank") == lit(1))
|
|
551
|
+
# The deepest statement of a key wins; a tombstone there removes it.
|
|
552
|
+
if has_deleted:
|
|
553
|
+
# A row from a layer whose file lacks the column reads `deleted` as NULL
|
|
554
|
+
# once unioned by name; NULL is not a tombstone, so coalesce to false
|
|
555
|
+
# rather than letting `~NULL` drop a live row.
|
|
556
|
+
winners = winners.filter(~coalesce(col("deleted"), lit(False))) # noqa: FBT003
|
|
557
|
+
scaffold = [
|
|
558
|
+
"_depth",
|
|
559
|
+
"_rank",
|
|
560
|
+
"_row",
|
|
561
|
+
"_first",
|
|
562
|
+
*(["deleted"] if has_deleted else []),
|
|
563
|
+
]
|
|
564
|
+
return winners.order("_first").project(star(exclude=scaffold))
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def read_json(uri: str) -> dict[str, Any] | None:
|
|
568
|
+
"""Read one JSON file, or `None` if it doesn't exist (e.g. an undeclared schema).
|
|
569
|
+
|
|
570
|
+
Only a genuine miss (local `FileNotFoundError`, remote 404/403) maps to
|
|
571
|
+
`None` - any other failure raises rather than silently reading as absent.
|
|
572
|
+
"""
|
|
573
|
+
try:
|
|
574
|
+
if "://" in uri:
|
|
575
|
+
with urlopen(uri) as fh: # noqa: S310 - record URIs are derived, not user input
|
|
576
|
+
return json.load(fh)
|
|
577
|
+
with open(uri) as fh:
|
|
578
|
+
return json.load(fh)
|
|
579
|
+
except FileNotFoundError:
|
|
580
|
+
return None
|
|
581
|
+
except HTTPError as e:
|
|
582
|
+
if e.code in (403, 404): # 403: S3's "missing key" without ListBucket
|
|
583
|
+
return None
|
|
584
|
+
raise
|
|
File without changes
|