sqllocks-shape-integrations 0.9.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.
Files changed (37) hide show
  1. sqllocks_shape_integrations-0.9.1/LICENSE +21 -0
  2. sqllocks_shape_integrations-0.9.1/PKG-INFO +47 -0
  3. sqllocks_shape_integrations-0.9.1/README.md +11 -0
  4. sqllocks_shape_integrations-0.9.1/pyproject.toml +57 -0
  5. sqllocks_shape_integrations-0.9.1/setup.cfg +4 -0
  6. sqllocks_shape_integrations-0.9.1/src/shape_integrations/__init__.py +16 -0
  7. sqllocks_shape_integrations-0.9.1/src/shape_integrations/anonymeter_eval.py +223 -0
  8. sqllocks_shape_integrations-0.9.1/src/shape_integrations/duckdb_source.py +144 -0
  9. sqllocks_shape_integrations-0.9.1/src/shape_integrations/evaluate.py +182 -0
  10. sqllocks_shape_integrations-0.9.1/src/shape_integrations/evaluation.py +83 -0
  11. sqllocks_shape_integrations-0.9.1/src/shape_integrations/extras.py +38 -0
  12. sqllocks_shape_integrations-0.9.1/src/shape_integrations/ibis.py +39 -0
  13. sqllocks_shape_integrations-0.9.1/src/shape_integrations/lineage.py +254 -0
  14. sqllocks_shape_integrations-0.9.1/src/shape_integrations/manifest_view.py +106 -0
  15. sqllocks_shape_integrations-0.9.1/src/shape_integrations/mlflow_log.py +227 -0
  16. sqllocks_shape_integrations-0.9.1/src/shape_integrations/openlineage_events.py +63 -0
  17. sqllocks_shape_integrations-0.9.1/src/shape_integrations/presidio_detector.py +194 -0
  18. sqllocks_shape_integrations-0.9.1/src/shape_integrations/schemas/shape-run-facet.json +31 -0
  19. sqllocks_shape_integrations-0.9.1/src/shape_integrations/sdmetrics_eval.py +109 -0
  20. sqllocks_shape_integrations-0.9.1/src/shape_integrations/testing.py +89 -0
  21. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/PKG-INFO +47 -0
  22. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/SOURCES.txt +35 -0
  23. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/dependency_links.txt +1 -0
  24. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/entry_points.txt +10 -0
  25. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/requires.txt +20 -0
  26. sqllocks_shape_integrations-0.9.1/src/sqllocks_shape_integrations.egg-info/top_level.txt +1 -0
  27. sqllocks_shape_integrations-0.9.1/tests/test_duckdb_integration.py +183 -0
  28. sqllocks_shape_integrations-0.9.1/tests/test_duckdb_unit.py +101 -0
  29. sqllocks_shape_integrations-0.9.1/tests/test_evaluate_integration.py +144 -0
  30. sqllocks_shape_integrations-0.9.1/tests/test_evaluate_unit.py +227 -0
  31. sqllocks_shape_integrations-0.9.1/tests/test_lineage_integration.py +198 -0
  32. sqllocks_shape_integrations-0.9.1/tests/test_lineage_plan.py +221 -0
  33. sqllocks_shape_integrations-0.9.1/tests/test_mlflow_integration.py +149 -0
  34. sqllocks_shape_integrations-0.9.1/tests/test_mlflow_unit.py +103 -0
  35. sqllocks_shape_integrations-0.9.1/tests/test_presidio_integration.py +108 -0
  36. sqllocks_shape_integrations-0.9.1/tests/test_presidio_unit.py +112 -0
  37. sqllocks_shape_integrations-0.9.1/tests/test_skeleton.py +114 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 SQLLocks (Jonathan Stewart)
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.
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqllocks-shape-integrations
3
+ Version: 0.9.1
4
+ Summary: Shape plugin: OpenLineage, MLflow, Presidio, SDMetrics, Anonymeter and Ibis/DuckDB adapters
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/sqllocks/shape
7
+ Project-URL: Repository, https://github.com/sqllocks/shape
8
+ Project-URL: Issues, https://github.com/sqllocks/shape/issues
9
+ Project-URL: Documentation, https://github.com/sqllocks/shape/tree/main/plugins/shape-integrations
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Database
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: sqllocks-shape==0.9.1
22
+ Provides-Extra: openlineage
23
+ Requires-Dist: openlineage-python<2,>=1.20; extra == "openlineage"
24
+ Provides-Extra: mlflow
25
+ Requires-Dist: mlflow<4,>=3; extra == "mlflow"
26
+ Provides-Extra: presidio
27
+ Requires-Dist: presidio-analyzer<3,>=2.2; extra == "presidio"
28
+ Provides-Extra: sdmetrics
29
+ Requires-Dist: sdmetrics<1,>=0.18; extra == "sdmetrics"
30
+ Provides-Extra: anonymeter
31
+ Requires-Dist: anonymeter<2,>=1; extra == "anonymeter"
32
+ Provides-Extra: ibis
33
+ Requires-Dist: ibis-framework[duckdb]<13,>=12; extra == "ibis"
34
+ Requires-Dist: duckdb<2,>=1.2; extra == "ibis"
35
+ Dynamic: license-file
36
+
37
+ # sqllocks-shape-integrations
38
+
39
+ Thin, optional adapters between Shape and OpenLineage, MLflow, Presidio, SDMetrics, Anonymeter
40
+ and Ibis/DuckDB. One distribution, one extra per integration:
41
+
42
+ ```
43
+ pip install 'sqllocks-shape-integrations[openlineage]'
44
+ ```
45
+
46
+ See [docs/plugins/integrations.md](../../docs/plugins/integrations.md) for each integration:
47
+ install, command or API, what is sent or written, and what is never sent.
@@ -0,0 +1,11 @@
1
+ # sqllocks-shape-integrations
2
+
3
+ Thin, optional adapters between Shape and OpenLineage, MLflow, Presidio, SDMetrics, Anonymeter
4
+ and Ibis/DuckDB. One distribution, one extra per integration:
5
+
6
+ ```
7
+ pip install 'sqllocks-shape-integrations[openlineage]'
8
+ ```
9
+
10
+ See [docs/plugins/integrations.md](../../docs/plugins/integrations.md) for each integration:
11
+ install, command or API, what is sent or written, and what is never sent.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sqllocks-shape-integrations"
7
+ # Lockstep with core (T-09): scripts/check_plugin_skeletons.py fails when this drifts.
8
+ version = "0.9.1"
9
+ description = "Shape plugin: OpenLineage, MLflow, Presidio, SDMetrics, Anonymeter and Ibis/DuckDB adapters"
10
+ readme = "README.md"
11
+ requires-python = ">=3.11"
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Operating System :: OS Independent",
22
+ "Topic :: Database",
23
+ ]
24
+ # Every third-party library is an extra, so a host installs only the adapters it uses and core
25
+ # never carries them (T-07). Without its library an adapter exits 2 with the pip command.
26
+ dependencies = ["sqllocks-shape==0.9.1"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/sqllocks/shape"
30
+ Repository = "https://github.com/sqllocks/shape"
31
+ Issues = "https://github.com/sqllocks/shape/issues"
32
+ Documentation = "https://github.com/sqllocks/shape/tree/main/plugins/shape-integrations"
33
+
34
+ [project.optional-dependencies]
35
+ openlineage = ["openlineage-python>=1.20,<2"]
36
+ mlflow = ["mlflow>=3,<4"]
37
+ presidio = ["presidio-analyzer>=2.2,<3"]
38
+ sdmetrics = ["sdmetrics>=0.18,<1"]
39
+ anonymeter = ["anonymeter>=1,<2"]
40
+ ibis = ["ibis-framework[duckdb]>=12,<13", "duckdb>=1.2,<2"]
41
+
42
+ [project.entry-points."shape.commands"]
43
+ lineage = "shape_integrations.lineage:LineageCommand"
44
+ mlflow = "shape_integrations.mlflow_log:MlflowCommand"
45
+ evaluate = "shape_integrations.evaluate:EvaluateCommand"
46
+
47
+ [project.entry-points."shape.detectors"]
48
+ presidio = "shape_integrations.presidio_detector:PresidioDetector"
49
+
50
+ [project.entry-points."shape.sources"]
51
+ duckdb = "shape_integrations.duckdb_source:DuckDbSource"
52
+
53
+ [tool.setuptools.packages.find]
54
+ where = ["src"]
55
+
56
+ [tool.setuptools.package-data]
57
+ shape_integrations = ["schemas/*.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,16 @@
1
+ """Shape plugin: thin, optional adapters for tools teams already use.
2
+
3
+ * ``shape.commands``: ``lineage`` (OpenLineage), ``mlflow`` (MLflow) and ``evaluate``
4
+ (SDMetrics, Anonymeter).
5
+ * ``shape.detectors``: ``presidio``.
6
+ * ``shape.sources``: ``duckdb``; :func:`shape_integrations.ibis.connect` for notebooks.
7
+
8
+ Importing this package imports none of the third-party libraries; each adapter loads its own
9
+ when it runs, and exits 2 with the pip command when the extra is missing.
10
+ """
11
+
12
+ from .extras import EXTRAS, MissingExtraError
13
+
14
+ SHAPE_API = "1.0"
15
+
16
+ __all__ = ["EXTRAS", "SHAPE_API", "MissingExtraError"]
@@ -0,0 +1,223 @@
1
+ """Anonymeter privacy-risk report (imports Anonymeter: needs the ``anonymeter`` extra).
2
+
3
+ Per table: singling out (multivariate queries of up to three columns, fixed seed),
4
+ linkability (the columns split in two halves in table order, ten neighbours at most) and
5
+ inference (each column in turn as the secret, the others as what the attacker knows).
6
+ ``n_attacks`` is 500, or fewer when the real or control table has fewer rows.
7
+
8
+ The singling-out *attack* queries are seeded, so its attack rate repeats. Anonymeter does not
9
+ seed its baseline (random-guess) rates or the linkability and inference sampling, so those
10
+ can differ a little between runs.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import warnings
17
+ from typing import Any
18
+
19
+ import pyarrow as pa # type: ignore[import-untyped]
20
+
21
+ from .evaluate import EvaluateInputError
22
+ from .extras import require
23
+
24
+ SHAPE_API = "1.0"
25
+
26
+ N_ATTACKS = 500
27
+ MIN_ROWS = 2
28
+ SEED = 20261003
29
+ ATTEMPTS_PER_ATTACK = 100
30
+ MAX_NEIGHBORS = 10
31
+
32
+
33
+ def _supported(t: pa.DataType) -> bool:
34
+ return not (
35
+ pa.types.is_list(t)
36
+ or pa.types.is_large_list(t)
37
+ or pa.types.is_struct(t)
38
+ or pa.types.is_map(t)
39
+ or pa.types.is_binary(t)
40
+ or pa.types.is_large_binary(t)
41
+ or pa.types.is_fixed_size_binary(t)
42
+ or pa.types.is_null(t)
43
+ )
44
+
45
+
46
+ def _rate(r: Any) -> dict[str, float]:
47
+ return {"value": float(r.value), "error": float(r.error)}
48
+
49
+
50
+ def _outcome(res: Any, n_attacks: int, notes: list[str]) -> dict[str, Any]:
51
+ risk = res.risk()
52
+ out: dict[str, Any] = {
53
+ "n_attacks": n_attacks,
54
+ "n_success": int(res.n_success),
55
+ "n_baseline": int(res.n_baseline),
56
+ "attack_rate": _rate(res.attack_rate),
57
+ "baseline_rate": _rate(res.baseline_rate),
58
+ "risk": {"value": float(risk.value), "ci": [float(risk.ci[0]), float(risk.ci[1])]},
59
+ }
60
+ if res.control_rate is not None:
61
+ out["n_control"] = int(res.n_control)
62
+ out["control_rate"] = _rate(res.control_rate)
63
+ if notes:
64
+ out["notes"] = notes
65
+ return out
66
+
67
+
68
+ class _Notes(logging.Handler):
69
+ def __init__(self) -> None:
70
+ super().__init__(level=logging.WARNING)
71
+ self.messages: list[str] = []
72
+
73
+ def emit(self, record: logging.LogRecord) -> None:
74
+ self.messages.append(record.getMessage())
75
+
76
+
77
+ def _collect(run: Any) -> tuple[Any, list[str]]:
78
+ """Call ``run()`` and return its result with Anonymeter's own warnings as notes."""
79
+ handler = _Notes()
80
+ logger = logging.getLogger("anonymeter")
81
+ logger.addHandler(handler)
82
+ try:
83
+ with warnings.catch_warnings(record=True) as caught:
84
+ warnings.simplefilter("always")
85
+ result = run()
86
+ finally:
87
+ logger.removeHandler(handler)
88
+ notes = [str(w.message) for w in caught if "anonymeter" in str(w.filename)] + handler.messages
89
+ return result, sorted(set(notes))
90
+
91
+
92
+ def _table_results(real: Any, synth: Any, control: Any, attacks: list[str]) -> dict[str, Any]:
93
+ from anonymeter.evaluators import (
94
+ InferenceEvaluator,
95
+ LinkabilityEvaluator,
96
+ SinglingOutEvaluator,
97
+ )
98
+
99
+ n = min(N_ATTACKS, len(real), len(control))
100
+ cols = list(real.columns)
101
+ out: dict[str, Any] = {"rows": {"real": len(real), "synthetic": len(synth)}}
102
+ if "singling-out" in attacks:
103
+
104
+ def singling() -> Any:
105
+ e = SinglingOutEvaluator(
106
+ ori=real,
107
+ syn=synth,
108
+ control=control,
109
+ n_attacks=n,
110
+ n_cols=min(3, len(cols)),
111
+ seed=SEED,
112
+ max_attempts=ATTEMPTS_PER_ATTACK * n,
113
+ )
114
+ e.evaluate(mode="multivariate")
115
+ return e.results()
116
+
117
+ res, notes = _collect(singling)
118
+ out["singling_out"] = _outcome(res, n, notes)
119
+ if "linkability" in attacks:
120
+ if len(cols) < 2:
121
+ out["linkability"] = {"skipped": "needs at least 2 columns"}
122
+ else:
123
+ half = len(cols) // 2
124
+
125
+ def linkability() -> Any:
126
+ e = LinkabilityEvaluator(
127
+ ori=real,
128
+ syn=synth,
129
+ control=control,
130
+ n_attacks=n,
131
+ aux_cols=(cols[:half], cols[half:]),
132
+ n_neighbors=min(MAX_NEIGHBORS, len(synth)),
133
+ )
134
+ e.evaluate(n_jobs=1)
135
+ return e.results()
136
+
137
+ res, notes = _collect(linkability)
138
+ out["linkability"] = _outcome(res, n, notes)
139
+ if "inference" in attacks:
140
+ if len(cols) < 2:
141
+ out["inference"] = {"skipped": "needs at least 2 columns"}
142
+ else:
143
+ per_secret = {}
144
+ for secret in cols:
145
+
146
+ def inference(secret: str = secret) -> Any:
147
+ e = InferenceEvaluator(
148
+ ori=real,
149
+ syn=synth,
150
+ control=control,
151
+ aux_cols=[c for c in cols if c != secret],
152
+ secret=secret,
153
+ regression=real[secret].dtype.kind == "f",
154
+ n_attacks=n,
155
+ )
156
+ e.evaluate(n_jobs=1)
157
+ return e.results()
158
+
159
+ res, notes = _collect(inference)
160
+ per_secret[secret] = _outcome(res, n, notes)
161
+ out["inference"] = {"secrets": per_secret}
162
+ return out
163
+
164
+
165
+ def run(
166
+ real: dict[str, pa.Table],
167
+ synth: dict[str, pa.Table],
168
+ control: dict[str, pa.Table],
169
+ attacks: list[str],
170
+ ) -> tuple[str, dict[str, Any]]:
171
+ mod = require("anonymeter", "anonymeter", name="Anonymeter")
172
+ from importlib import metadata
173
+
174
+ try:
175
+ tool_version = metadata.version("anonymeter")
176
+ except metadata.PackageNotFoundError:
177
+ tool_version = str(getattr(mod, "__version__", "unknown"))
178
+ tables: dict[str, Any] = {}
179
+ skipped: dict[str, list[str]] = {}
180
+ for name in sorted(real):
181
+ keep = [f.name for f in real[name].schema if _supported(f.type)]
182
+ dropped = [c for c in real[name].column_names if c not in keep]
183
+ if dropped:
184
+ skipped[name] = dropped
185
+ if not keep:
186
+ raise EvaluateInputError(f"table {name!r} has no column Anonymeter can evaluate")
187
+ frames = [t[name].select(keep).to_pandas() for t in (real, synth, control)]
188
+ if min(len(frames[0]), len(frames[2])) < MIN_ROWS or len(frames[1]) < 1:
189
+ raise EvaluateInputError(
190
+ f"table {name!r}: Anonymeter needs at least {MIN_ROWS} real and control rows "
191
+ "and one synthetic row"
192
+ )
193
+ try:
194
+ tables[name] = _table_results(frames[0], frames[1], frames[2], attacks)
195
+ except (ValueError, KeyError, TypeError) as exc:
196
+ raise EvaluateInputError(
197
+ f"Anonymeter could not evaluate table {name!r}: {exc}"
198
+ ) from None
199
+ return tool_version, {
200
+ "attacks": list(attacks),
201
+ "tables": tables,
202
+ "skipped_columns": skipped,
203
+ }
204
+
205
+
206
+ def summary(results: dict[str, Any]) -> list[str]:
207
+ lines = ["Anonymeter privacy risk (0 is best, 1 is worst)"]
208
+ for table, res in results["tables"].items():
209
+ lines.append(f" {table}")
210
+ for key in ("singling_out", "linkability"):
211
+ if key in res:
212
+ lines.append(f" {key}: {_risk(res[key])}")
213
+ if "inference" in res:
214
+ for secret, r in res["inference"].get("secrets", {}).items():
215
+ lines.append(f" inference of {secret}: {_risk(r)}")
216
+ return lines
217
+
218
+
219
+ def _risk(res: dict[str, Any]) -> str:
220
+ if "skipped" in res:
221
+ return f"skipped ({res['skipped']})"
222
+ lo, hi = res["risk"]["ci"]
223
+ return f"{res['risk']['value']:.3f} (95% CI {lo:.3f} to {hi:.3f})"
@@ -0,0 +1,144 @@
1
+ """The ``duckdb`` source (``shape.sources``): ``duckdb://FILE.duckdb?table=T``.
2
+
3
+ Everything between ``duckdb://`` and ``?`` is the file path (``duckdb:///tmp/x.duckdb`` is
4
+ absolute, ``duckdb://data/x.duckdb`` is relative to the working directory). ``table`` is ``T`` or
5
+ ``SCHEMA.T``. The only query option is ``table``; any other option, in particular anything that
6
+ could ask for a writable connection, is refused rather than ignored.
7
+
8
+ The connection is always read-only (``read_only=True``), a missing file is an error and is
9
+ never created, and rows come out as Arrow batches (``batch_size`` rows at most, 65,536 by
10
+ default). Table names are quoted as identifiers, never spliced into SQL as text.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import urllib.parse
16
+ from collections.abc import Iterator
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import pyarrow as pa # type: ignore[import-untyped]
22
+
23
+ from .extras import require
24
+
25
+ SHAPE_API = "1.0"
26
+
27
+ SCHEME = "duckdb"
28
+ DEFAULT_BATCH_ROWS = 65536
29
+ _PREFIX = f"{SCHEME}://"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class DuckDbUri:
34
+ path: str
35
+ table: str
36
+
37
+
38
+ def _is_duckdb(uri: str) -> bool:
39
+ return isinstance(uri, str) and uri.lower().startswith(_PREFIX)
40
+
41
+
42
+ def parse(uri: str) -> DuckDbUri:
43
+ if not _is_duckdb(uri):
44
+ raise ValueError(f"not a duckdb:// URI: {uri!r}")
45
+ rest = uri[len(_PREFIX) :]
46
+ location, _, query = rest.partition("?")
47
+ path = urllib.parse.unquote(location)
48
+ if not path:
49
+ raise ValueError("duckdb:// URI has no file: duckdb://FILE.duckdb?table=T")
50
+ if path.startswith(":memory:") or path == ":memory:":
51
+ raise ValueError("an in-memory DuckDB cannot be opened read-only: name a .duckdb file")
52
+ params = urllib.parse.parse_qs(query, keep_blank_values=True)
53
+ for key in params:
54
+ if key != "table":
55
+ raise ValueError(f"unknown option {key!r} in duckdb:// URI (only 'table' is allowed)")
56
+ tables = params.get("table", [])
57
+ if not tables or not tables[0]:
58
+ raise ValueError("duckdb:// URI needs a table: duckdb://FILE.duckdb?table=T")
59
+ if len(tables) > 1:
60
+ raise ValueError("'table' may be given once in a duckdb:// URI")
61
+ table = tables[0]
62
+ parts = table.split(".")
63
+ if len(parts) > 2 or not all(parts):
64
+ raise ValueError(f"table {table!r} must be 'table' or 'schema.table'")
65
+ return DuckDbUri(path, table)
66
+
67
+
68
+ def quote_table(table: str) -> str:
69
+ """``T`` or ``S.T`` as quoted SQL identifiers."""
70
+ return ".".join('"' + part.replace('"', '""') + '"' for part in table.split("."))
71
+
72
+
73
+ def _connect(target: DuckDbUri) -> Any:
74
+ if not Path(target.path).is_file():
75
+ raise FileNotFoundError(f"DuckDB file not found: {target.path}")
76
+ duckdb = require("duckdb", "ibis", name="DuckDB")
77
+ return duckdb.connect(target.path, read_only=True)
78
+
79
+
80
+ def _check_table(con: Any, target: DuckDbUri) -> None:
81
+ parts = target.table.split(".")
82
+ schema, name = (parts[0], parts[1]) if len(parts) == 2 else (None, parts[0])
83
+ rows = con.execute(
84
+ "SELECT table_schema, table_name FROM information_schema.tables "
85
+ "WHERE table_name = ? AND (? IS NULL OR table_schema = ?)",
86
+ [name, schema, schema],
87
+ ).fetchall()
88
+ if rows:
89
+ return
90
+ names = [
91
+ f"{s}.{n}" if s != "main" else n
92
+ for s, n in con.execute(
93
+ "SELECT table_schema, table_name FROM information_schema.tables "
94
+ "WHERE table_schema NOT IN ('information_schema', 'pg_catalog') "
95
+ "ORDER BY 1, 2 LIMIT 20"
96
+ ).fetchall()
97
+ ]
98
+ raise ValueError(
99
+ f"no table {target.table!r} in {target.path}"
100
+ + (f" (tables: {', '.join(names)})" if names else " (it has no tables)")
101
+ )
102
+
103
+
104
+ def _reader(result: Any, batch_size: int) -> Any:
105
+ """A record-batch reader of a DuckDB result (``to_arrow_reader`` replaced the older name)."""
106
+ method = getattr(result, "to_arrow_reader", None) or result.fetch_record_batch
107
+ return method(batch_size)
108
+
109
+
110
+ class DuckDbSource:
111
+ """A table of a DuckDB file, read-only, as Arrow batches."""
112
+
113
+ name = "duckdb"
114
+ schemes = (SCHEME,)
115
+
116
+ def can_open(self, uri: str) -> bool:
117
+ return _is_duckdb(uri)
118
+
119
+ def schema(self, uri: str, **options: Any) -> pa.Schema:
120
+ target = parse(uri)
121
+ con = _connect(target)
122
+ try:
123
+ _check_table(con, target)
124
+ reader = con.execute(f"SELECT * FROM {quote_table(target.table)} LIMIT 0")
125
+ schema: pa.Schema = _reader(reader, 1).schema
126
+ return schema
127
+ finally:
128
+ con.close()
129
+
130
+ def read(self, uri: str, **options: Any) -> Iterator[pa.RecordBatch]:
131
+ batch_size = options.get("batch_size", DEFAULT_BATCH_ROWS)
132
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1:
133
+ raise ValueError(f"batch_size must be a positive integer, got {batch_size!r}")
134
+ target = parse(uri)
135
+ return self._batches(target, batch_size)
136
+
137
+ def _batches(self, target: DuckDbUri, batch_size: int) -> Iterator[pa.RecordBatch]:
138
+ con = _connect(target)
139
+ try:
140
+ _check_table(con, target)
141
+ reader = con.execute(f"SELECT * FROM {quote_table(target.table)}")
142
+ yield from _reader(reader, batch_size)
143
+ finally:
144
+ con.close()