ducats 0.2.0__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.
@@ -0,0 +1,39 @@
1
+ # Tests on every push and pull request; on a version tag (vX.Y.Z), build and
2
+ # publish to PyPI with trusted publishing (no token: PyPI trusts this
3
+ # workflow in the "pypi" environment of TUW-GEO/ducats).
4
+ name: ci
5
+
6
+ on:
7
+ push:
8
+ branches: [main]
9
+ tags: ["v*"]
10
+ pull_request:
11
+
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ matrix:
17
+ python: ["3.12", "3.13"]
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - uses: astral-sh/setup-uv@v6
21
+ with:
22
+ python-version: ${{ matrix.python }}
23
+ - run: uv sync --dev
24
+ - run: uv run pytest tests
25
+
26
+ publish:
27
+ if: startsWith(github.ref, 'refs/tags/v')
28
+ needs: test
29
+ runs-on: ubuntu-latest
30
+ environment: pypi
31
+ permissions:
32
+ id-token: write
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+ with:
36
+ fetch-depth: 0 # hatch-vcs reads the version from the tag
37
+ - uses: astral-sh/setup-uv@v6
38
+ - run: uv build
39
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ .venv/
5
+ src/ducats/_version.py
6
+ .agent-shell/
@@ -0,0 +1,5 @@
1
+ ============
2
+ Contributors
3
+ ============
4
+
5
+ * Clay Harrison <clay.harrison@geo.tuwien.ac.at>
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 TU Wien
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ducats-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.5
2
+ Name: ducats
3
+ Version: 0.2.0
4
+ Summary: Sync a queryable DuckDB catalog of file temporal coverage from a file archive on disk
5
+ Project-URL: Repository, https://github.com/TUW-GEO/ducats
6
+ Author-email: TU Wien <remote.sensing@geo.tuwien.ac.at>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.txt
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering
12
+ Requires-Python: >=3.12
13
+ Requires-Dist: duckdb>=1.1
14
+ Requires-Dist: numpy>=1.26
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ducats
18
+
19
+ Maintains a DuckDB catalog of file coverage — sat/product columns + a
20
+ start/end timestamp per file — kept in sync with what's actually on disk.
21
+ The job it does is **sync**; the job it deliberately does *not* do is
22
+ implement every question you might ask ("which file covers this instant",
23
+ "which METOP-B files fall in any January", "where are the gaps") as a
24
+ bespoke function. Once a product is synced, those are plain SQL against a
25
+ table.
26
+
27
+ ## Why
28
+
29
+ `glob()` lists files vectorized; `regexp_extract` pulls fields out of
30
+ filenames vectorized. For archives with tens of thousands of files, syncing
31
+ is fast and the resulting table is small — cheap enough to keep on disk and
32
+ query directly, from this package, another Python process, a notebook, or
33
+ the plain `duckdb` CLI.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install ducats
39
+ ```
40
+
41
+ (Formerly `ducat`; renamed because that name is taken on PyPI. The import
42
+ package and the CLI are `ducats` too.)
43
+
44
+ ## Quickstart
45
+
46
+ Register a product (see [Plugging in a new product](#plugging-in-a-new-product) below), then:
47
+
48
+ ```bash
49
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
50
+ uv run ducats status --catalog-path /data/catalog.duckdb
51
+ ```
52
+
53
+ Then just query:
54
+
55
+ ```bash
56
+ # which file covers this instant?
57
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
58
+ "SELECT file FROM my_hourly_files WHERE start_ts <= '2026-03-24 10:00:00' AND end_ts >= '2026-03-24 10:00:00'"
59
+
60
+ # which files fall in any January?
61
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
62
+ "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
63
+ ```
64
+
65
+ Or skip the CLI and open the file directly — it's a normal DuckDB database:
66
+
67
+ ```bash
68
+ duckdb /data/catalog.duckdb -c "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
69
+ ```
70
+
71
+ ## Two things worth a real function
72
+
73
+ Most questions are a one-line `WHERE` clause once a table's synced — not
74
+ worth wrapping. Two aren't, because they involve real computation (a
75
+ generated series anti-joined against what's present, or a window function
76
+ over ordered intervals), so `ducats.queries` provides them:
77
+
78
+ | query | for archives where... | flags... |
79
+ |---|---|---|
80
+ | `find_grid_gaps` | files arrive at a fixed cadence (e.g. one per UTC hour) | buckets with zero files |
81
+ | `find_contiguity_gaps` | files are variable-length intervals that should chain end-to-start (e.g. orbit swaths) | adjacent pairs whose `next.start - this.end` falls outside `[min_gap, max_gap]` |
82
+
83
+ ```bash
84
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
85
+ --mode grid --bucket 1h
86
+
87
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
88
+ --mode contiguity --min-gap 0s --max-gap 1h
89
+ ```
90
+
91
+ ## Plugging in a new product
92
+
93
+ A product is a `ProductConfig`: where its files live, an `Extractor` that
94
+ reads group columns + a start/end timestamp out of each file.
95
+
96
+ ```python
97
+ from ducats.extract import RegexExtractor
98
+ from ducats.registry import ProductConfig, register_product
99
+
100
+ register_product(ProductConfig(
101
+ name="my_hourly_files",
102
+ base_dir="/data/my_product",
103
+ glob="**/*.nc",
104
+ extractor=RegexExtractor(
105
+ pattern=r"my_product_(\d{14})_(\d{14})\.nc$",
106
+ group_cols={}, # no natural grouping here
107
+ start_group=1,
108
+ end_group=2,
109
+ ),
110
+ group_cols=[],
111
+ ))
112
+ ```
113
+
114
+ Put that in a module (say `myproject/gap_products.py`) and run:
115
+
116
+ ```bash
117
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
118
+ ```
119
+
120
+ Nothing is auto-discovered — a product only exists in a given run if its
121
+ module was explicitly imported via `--products-module`. That keeps "what's
122
+ registered" unambiguous instead of depending on import side effects from
123
+ unrelated code.
124
+
125
+ ### Two ways to extract fields
126
+
127
+ - **`RegexExtractor`** — everything needed (timestamps, grouping keys) is in
128
+ the filename. Stays entirely inside SQL; fast even at tens of thousands of
129
+ files. Use this whenever it applies.
130
+ - **`PythonExtractor`** — the info is inside the file (a NetCDF/HDF5 global
131
+ attribute, a sidecar JSON, ...). Registers a Python scalar UDF with DuckDB
132
+ that opens one file and returns a `STRUCT` of the fields you need; DuckDB
133
+ calls it once per row. Slower (one file open per matched file) but the
134
+ same shape comes out, so nothing downstream cares. See the docstring in
135
+ `ducats/extract.py` for a worked example.
136
+
137
+ Either extractor just needs to leave a temp table named `items` with
138
+ columns `file, <group_cols...>, start_ts, end_ts` — write your own if
139
+ neither fits.
140
+
141
+ `PythonExtractor` accepts `cache_path`: point it at a file and extracted
142
+ rows persist across runs, so repeat runs over a mostly-unchanged archive
143
+ only call `fn` for files not already cached. This is a different thing
144
+ from catalog persistence below — it avoids re-*opening files*, not
145
+ re-running Python. No staleness detection — if `fn`'s output for a path or
146
+ the `fields` schema changes, delete the cache file to force a rebuild.
147
+
148
+ ## Catalog persistence
149
+
150
+ `ducats.catalog` is the sync layer:
151
+
152
+ ```python
153
+ from ducats.catalog import open_catalog, sync_product
154
+ from myproject.gap_products import my_hourly_files # a ProductConfig you registered
155
+
156
+ con = open_catalog("/data/catalog.duckdb") # omit the path for in-memory, throwaway
157
+ sync_product(con, my_hourly_files)
158
+ con.sql("SELECT count(*) FROM my_hourly_files").show()
159
+ ```
160
+
161
+ `sync_product` always leaves the table matching the current glob — files
162
+ that disappeared from disk are dropped from it too. Point `open_catalog` at
163
+ a real path and the sync work only has to happen again for files that
164
+ weren't there last time; anything already in the table stays, and other
165
+ processes/tools can open the same file and query it without touching this
166
+ package at all.
167
+
168
+ ## Using the computed queries as a library
169
+
170
+ ```python
171
+ from datetime import timedelta
172
+ from ducats.queries import find_grid_gaps
173
+ from ducats.report import format_grid_reports
174
+
175
+ reports = find_grid_gaps(con, "resample", group_cols=["sat", "res"], bucket=timedelta(hours=1))
176
+ print(format_grid_reports(reports))
177
+ ```
178
+
179
+ `find_grid_gaps`/`find_contiguity_gaps` return dataclasses
180
+ (`GridGapReport`/`ContiguityReport`), not text — `ducats.report` is a
181
+ separate, optional formatting layer, so you can consume the structured
182
+ results directly (e.g. to page on-call, or feed a dashboard) without
183
+ scraping printed text.
184
+
185
+ ## Examples
186
+
187
+ Product-specific config (filename patterns, group wiring, contiguity
188
+ tolerances) lives in the consuming repo, not ducats. For a real-world
189
+ example, see
190
+ [`ascat_szf.yaml`](https://github.com/TUW-GEO/eumdac-store/blob/main/examples/ascat_szf.yaml)
191
+ in [eumdac-store](https://github.com/TUW-GEO/eumdac-store).
192
+
193
+ ## Development
194
+
195
+ ```bash
196
+ uv sync
197
+ uv run pytest
198
+ ```
ducats-0.2.0/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # ducats
2
+
3
+ Maintains a DuckDB catalog of file coverage — sat/product columns + a
4
+ start/end timestamp per file — kept in sync with what's actually on disk.
5
+ The job it does is **sync**; the job it deliberately does *not* do is
6
+ implement every question you might ask ("which file covers this instant",
7
+ "which METOP-B files fall in any January", "where are the gaps") as a
8
+ bespoke function. Once a product is synced, those are plain SQL against a
9
+ table.
10
+
11
+ ## Why
12
+
13
+ `glob()` lists files vectorized; `regexp_extract` pulls fields out of
14
+ filenames vectorized. For archives with tens of thousands of files, syncing
15
+ is fast and the resulting table is small — cheap enough to keep on disk and
16
+ query directly, from this package, another Python process, a notebook, or
17
+ the plain `duckdb` CLI.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install ducats
23
+ ```
24
+
25
+ (Formerly `ducat`; renamed because that name is taken on PyPI. The import
26
+ package and the CLI are `ducats` too.)
27
+
28
+ ## Quickstart
29
+
30
+ Register a product (see [Plugging in a new product](#plugging-in-a-new-product) below), then:
31
+
32
+ ```bash
33
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
34
+ uv run ducats status --catalog-path /data/catalog.duckdb
35
+ ```
36
+
37
+ Then just query:
38
+
39
+ ```bash
40
+ # which file covers this instant?
41
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
42
+ "SELECT file FROM my_hourly_files WHERE start_ts <= '2026-03-24 10:00:00' AND end_ts >= '2026-03-24 10:00:00'"
43
+
44
+ # which files fall in any January?
45
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
46
+ "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
47
+ ```
48
+
49
+ Or skip the CLI and open the file directly — it's a normal DuckDB database:
50
+
51
+ ```bash
52
+ duckdb /data/catalog.duckdb -c "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
53
+ ```
54
+
55
+ ## Two things worth a real function
56
+
57
+ Most questions are a one-line `WHERE` clause once a table's synced — not
58
+ worth wrapping. Two aren't, because they involve real computation (a
59
+ generated series anti-joined against what's present, or a window function
60
+ over ordered intervals), so `ducats.queries` provides them:
61
+
62
+ | query | for archives where... | flags... |
63
+ |---|---|---|
64
+ | `find_grid_gaps` | files arrive at a fixed cadence (e.g. one per UTC hour) | buckets with zero files |
65
+ | `find_contiguity_gaps` | files are variable-length intervals that should chain end-to-start (e.g. orbit swaths) | adjacent pairs whose `next.start - this.end` falls outside `[min_gap, max_gap]` |
66
+
67
+ ```bash
68
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
69
+ --mode grid --bucket 1h
70
+
71
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
72
+ --mode contiguity --min-gap 0s --max-gap 1h
73
+ ```
74
+
75
+ ## Plugging in a new product
76
+
77
+ A product is a `ProductConfig`: where its files live, an `Extractor` that
78
+ reads group columns + a start/end timestamp out of each file.
79
+
80
+ ```python
81
+ from ducats.extract import RegexExtractor
82
+ from ducats.registry import ProductConfig, register_product
83
+
84
+ register_product(ProductConfig(
85
+ name="my_hourly_files",
86
+ base_dir="/data/my_product",
87
+ glob="**/*.nc",
88
+ extractor=RegexExtractor(
89
+ pattern=r"my_product_(\d{14})_(\d{14})\.nc$",
90
+ group_cols={}, # no natural grouping here
91
+ start_group=1,
92
+ end_group=2,
93
+ ),
94
+ group_cols=[],
95
+ ))
96
+ ```
97
+
98
+ Put that in a module (say `myproject/gap_products.py`) and run:
99
+
100
+ ```bash
101
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
102
+ ```
103
+
104
+ Nothing is auto-discovered — a product only exists in a given run if its
105
+ module was explicitly imported via `--products-module`. That keeps "what's
106
+ registered" unambiguous instead of depending on import side effects from
107
+ unrelated code.
108
+
109
+ ### Two ways to extract fields
110
+
111
+ - **`RegexExtractor`** — everything needed (timestamps, grouping keys) is in
112
+ the filename. Stays entirely inside SQL; fast even at tens of thousands of
113
+ files. Use this whenever it applies.
114
+ - **`PythonExtractor`** — the info is inside the file (a NetCDF/HDF5 global
115
+ attribute, a sidecar JSON, ...). Registers a Python scalar UDF with DuckDB
116
+ that opens one file and returns a `STRUCT` of the fields you need; DuckDB
117
+ calls it once per row. Slower (one file open per matched file) but the
118
+ same shape comes out, so nothing downstream cares. See the docstring in
119
+ `ducats/extract.py` for a worked example.
120
+
121
+ Either extractor just needs to leave a temp table named `items` with
122
+ columns `file, <group_cols...>, start_ts, end_ts` — write your own if
123
+ neither fits.
124
+
125
+ `PythonExtractor` accepts `cache_path`: point it at a file and extracted
126
+ rows persist across runs, so repeat runs over a mostly-unchanged archive
127
+ only call `fn` for files not already cached. This is a different thing
128
+ from catalog persistence below — it avoids re-*opening files*, not
129
+ re-running Python. No staleness detection — if `fn`'s output for a path or
130
+ the `fields` schema changes, delete the cache file to force a rebuild.
131
+
132
+ ## Catalog persistence
133
+
134
+ `ducats.catalog` is the sync layer:
135
+
136
+ ```python
137
+ from ducats.catalog import open_catalog, sync_product
138
+ from myproject.gap_products import my_hourly_files # a ProductConfig you registered
139
+
140
+ con = open_catalog("/data/catalog.duckdb") # omit the path for in-memory, throwaway
141
+ sync_product(con, my_hourly_files)
142
+ con.sql("SELECT count(*) FROM my_hourly_files").show()
143
+ ```
144
+
145
+ `sync_product` always leaves the table matching the current glob — files
146
+ that disappeared from disk are dropped from it too. Point `open_catalog` at
147
+ a real path and the sync work only has to happen again for files that
148
+ weren't there last time; anything already in the table stays, and other
149
+ processes/tools can open the same file and query it without touching this
150
+ package at all.
151
+
152
+ ## Using the computed queries as a library
153
+
154
+ ```python
155
+ from datetime import timedelta
156
+ from ducats.queries import find_grid_gaps
157
+ from ducats.report import format_grid_reports
158
+
159
+ reports = find_grid_gaps(con, "resample", group_cols=["sat", "res"], bucket=timedelta(hours=1))
160
+ print(format_grid_reports(reports))
161
+ ```
162
+
163
+ `find_grid_gaps`/`find_contiguity_gaps` return dataclasses
164
+ (`GridGapReport`/`ContiguityReport`), not text — `ducats.report` is a
165
+ separate, optional formatting layer, so you can consume the structured
166
+ results directly (e.g. to page on-call, or feed a dashboard) without
167
+ scraping printed text.
168
+
169
+ ## Examples
170
+
171
+ Product-specific config (filename patterns, group wiring, contiguity
172
+ tolerances) lives in the consuming repo, not ducats. For a real-world
173
+ example, see
174
+ [`ascat_szf.yaml`](https://github.com/TUW-GEO/eumdac-store/blob/main/examples/ascat_szf.yaml)
175
+ in [eumdac-store](https://github.com/TUW-GEO/eumdac-store).
176
+
177
+ ## Development
178
+
179
+ ```bash
180
+ uv sync
181
+ uv run pytest
182
+ ```
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "ducats"
3
+ dynamic = ["version"]
4
+ description = "Sync a queryable DuckDB catalog of file temporal coverage from a file archive on disk"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ license-files = ["LICENSE.txt"]
9
+ authors = [{ name = "TU Wien", email = "remote.sensing@geo.tuwien.ac.at" }]
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "Operating System :: OS Independent",
13
+ "Topic :: Scientific/Engineering",
14
+ ]
15
+ dependencies = [
16
+ "duckdb>=1.1",
17
+ "numpy>=1.26",
18
+ ]
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/TUW-GEO/ducats"
22
+
23
+ [project.scripts]
24
+ ducats = "ducats.cli:main"
25
+
26
+ [build-system]
27
+ requires = ["hatchling", "hatch-vcs"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.hatch.version]
31
+ source = "vcs"
32
+
33
+ [tool.hatch.build.hooks.vcs]
34
+ version-file = "src/ducats/_version.py"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/ducats"]
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "pytest>=8.0",
42
+ ]
@@ -0,0 +1,35 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from .catalog import open_catalog, sync_product, sync_products, sync_status
6
+ from .extract import Extractor, PythonExtractor, RegexExtractor
7
+ from .queries import (
8
+ ContiguityBreak,
9
+ ContiguityReport,
10
+ GridGapReport,
11
+ find_contiguity_gaps,
12
+ find_grid_gaps,
13
+ )
14
+ from .registry import PRODUCTS, ProductConfig, register_product
15
+ from .report import format_contiguity_reports, format_grid_reports
16
+
17
+ __all__ = [
18
+ "open_catalog",
19
+ "sync_product",
20
+ "sync_products",
21
+ "sync_status",
22
+ "Extractor",
23
+ "PythonExtractor",
24
+ "RegexExtractor",
25
+ "ContiguityBreak",
26
+ "ContiguityReport",
27
+ "GridGapReport",
28
+ "find_contiguity_gaps",
29
+ "find_grid_gaps",
30
+ "PRODUCTS",
31
+ "ProductConfig",
32
+ "register_product",
33
+ "format_contiguity_reports",
34
+ "format_grid_reports",
35
+ ]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.2.0'
22
+ __version_tuple__ = version_tuple = (0, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,54 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import datetime, timezone
8
+ from typing import Iterable
9
+
10
+ import duckdb
11
+
12
+ from .registry import ProductConfig
13
+
14
+
15
+ def open_catalog(db_path: str | None = None) -> duckdb.DuckDBPyConnection:
16
+ return duckdb.connect(db_path) if db_path else duckdb.connect()
17
+
18
+
19
+ def sync_product(con: duckdb.DuckDBPyConnection, product: ProductConfig) -> int:
20
+ product.extractor.build_relation(con, product.base_dir, product.glob)
21
+ con.execute(f"CREATE OR REPLACE TABLE {product.name} AS SELECT * FROM items")
22
+ count = con.execute(f"SELECT count(*) FROM {product.name}").fetchone()[0]
23
+ _record_sync(con, product.name, count)
24
+ return count
25
+
26
+
27
+ def sync_products(con: duckdb.DuckDBPyConnection, products: Iterable[ProductConfig]) -> dict[str, int]:
28
+ return {p.name: sync_product(con, p) for p in products}
29
+
30
+
31
+ def _record_sync(con: duckdb.DuckDBPyConnection, product_name: str, count: int) -> None:
32
+ con.execute("""
33
+ CREATE TABLE IF NOT EXISTS _ducat_sync_log (
34
+ product VARCHAR PRIMARY KEY,
35
+ synced_at TIMESTAMP,
36
+ row_count BIGINT
37
+ )
38
+ """)
39
+ con.execute(
40
+ """
41
+ INSERT INTO _ducat_sync_log VALUES (?, ?, ?)
42
+ ON CONFLICT (product) DO UPDATE SET synced_at = excluded.synced_at, row_count = excluded.row_count
43
+ """,
44
+ [product_name, datetime.now(timezone.utc).replace(tzinfo=None), count],
45
+ )
46
+
47
+
48
+ def sync_status(con: duckdb.DuckDBPyConnection) -> list[tuple]:
49
+ exists = con.execute(
50
+ "SELECT count(*) FROM information_schema.tables WHERE table_name = '_ducat_sync_log'"
51
+ ).fetchone()[0]
52
+ if not exists:
53
+ return []
54
+ return con.execute("SELECT product, synced_at, row_count FROM _ducat_sync_log ORDER BY product").fetchall()