ectype-data 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype/io/adapters.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Edge adapters: get tables into and out of polars.
|
|
2
|
+
|
|
3
|
+
Everything inside the engine is polars. These functions are the only place that knows about
|
|
4
|
+
pandas, pyarrow and file formats. pandas is optional and imported lazily.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import polars as pl
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
18
|
+
import pandas
|
|
19
|
+
|
|
20
|
+
__all__ = ["FORMATS", "infer_format", "read_table", "to_pandas", "write_table"]
|
|
21
|
+
|
|
22
|
+
#: file extension -> canonical format name
|
|
23
|
+
FORMATS: dict[str, str] = {
|
|
24
|
+
".csv": "csv",
|
|
25
|
+
".tsv": "tsv",
|
|
26
|
+
".parquet": "parquet",
|
|
27
|
+
".pq": "parquet",
|
|
28
|
+
".arrow": "ipc",
|
|
29
|
+
".feather": "ipc",
|
|
30
|
+
".ipc": "ipc",
|
|
31
|
+
".json": "json",
|
|
32
|
+
".ndjson": "ndjson",
|
|
33
|
+
".jsonl": "ndjson",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_FORMAT_ALIASES = {
|
|
37
|
+
"csv": "csv",
|
|
38
|
+
"tsv": "tsv",
|
|
39
|
+
"parquet": "parquet",
|
|
40
|
+
"pq": "parquet",
|
|
41
|
+
"ipc": "ipc",
|
|
42
|
+
"arrow": "ipc",
|
|
43
|
+
"feather": "ipc",
|
|
44
|
+
"json": "json",
|
|
45
|
+
"ndjson": "ndjson",
|
|
46
|
+
"jsonl": "ndjson",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _normalize_format(fmt: str) -> str:
|
|
51
|
+
key = fmt.lower().lstrip(".")
|
|
52
|
+
try:
|
|
53
|
+
return _FORMAT_ALIASES[key]
|
|
54
|
+
except KeyError:
|
|
55
|
+
raise ValueError(
|
|
56
|
+
f"unsupported table format {fmt!r}; supported: {sorted(set(_FORMAT_ALIASES))}"
|
|
57
|
+
) from None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def infer_format(path: str | os.PathLike[str]) -> str:
|
|
61
|
+
"""Canonical format name for ``path`` from its extension (case-insensitive)."""
|
|
62
|
+
suffix = Path(path).suffix.lower()
|
|
63
|
+
try:
|
|
64
|
+
return FORMATS[suffix]
|
|
65
|
+
except KeyError:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
f"cannot infer table format from extension {suffix or '(none)'!r} of {str(path)!r}; "
|
|
68
|
+
f"supported extensions: {', '.join(sorted(FORMATS))} (or pass format=...)"
|
|
69
|
+
) from None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _normalize_columns(columns: str | Sequence[str] | None) -> list[str] | None:
|
|
73
|
+
if columns is None:
|
|
74
|
+
return None
|
|
75
|
+
if isinstance(columns, str):
|
|
76
|
+
return [columns]
|
|
77
|
+
cols = list(columns)
|
|
78
|
+
bad = [c for c in cols if not isinstance(c, str)]
|
|
79
|
+
if bad:
|
|
80
|
+
raise TypeError(f"columns must be strings, got {bad!r}")
|
|
81
|
+
return cols
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _check_columns(available: Sequence[str], wanted: list[str], what: str) -> None:
|
|
85
|
+
missing = [c for c in wanted if c not in available]
|
|
86
|
+
if missing:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f"column(s) {missing!r} not found in {what}; available: {list(available)!r}"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _select(df: pl.DataFrame, columns: list[str] | None, what: str) -> pl.DataFrame:
|
|
93
|
+
if columns is None:
|
|
94
|
+
return df
|
|
95
|
+
_check_columns(df.columns, columns, what)
|
|
96
|
+
return df.select(columns)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _is_pandas_frame(obj: Any) -> bool:
|
|
100
|
+
pd = sys.modules.get("pandas") # if pandas was never imported, obj cannot be a pandas frame
|
|
101
|
+
return pd is not None and isinstance(obj, pd.DataFrame)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _is_arrow_table(obj: Any) -> bool:
|
|
105
|
+
pa = sys.modules.get("pyarrow")
|
|
106
|
+
return pa is not None and isinstance(obj, pa.Table | pa.RecordBatch)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _from_pandas(pdf: pandas.DataFrame) -> pl.DataFrame:
|
|
110
|
+
# A named index carries data (e.g. after a groupby); an unnamed one is just row labels.
|
|
111
|
+
if any(n is not None for n in pdf.index.names):
|
|
112
|
+
pdf = pdf.reset_index()
|
|
113
|
+
if any(not isinstance(c, str) for c in pdf.columns):
|
|
114
|
+
pdf = pdf.rename(columns=str)
|
|
115
|
+
return pl.from_pandas(pdf)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _read_path(path: Path, columns: list[str] | None, fmt: str | None) -> pl.DataFrame:
|
|
119
|
+
if not path.exists():
|
|
120
|
+
raise FileNotFoundError(f"no such table file: {str(path)!r}")
|
|
121
|
+
if path.is_dir():
|
|
122
|
+
raise IsADirectoryError(f"expected a file, got a directory: {str(path)!r}")
|
|
123
|
+
fmt = _normalize_format(fmt) if fmt is not None else infer_format(path)
|
|
124
|
+
what = f"{str(path)!r}"
|
|
125
|
+
|
|
126
|
+
if fmt in ("csv", "tsv", "parquet", "ipc"):
|
|
127
|
+
if fmt in ("csv", "tsv"):
|
|
128
|
+
lf = pl.scan_csv(path, separator="\t" if fmt == "tsv" else ",",
|
|
129
|
+
try_parse_dates=True)
|
|
130
|
+
elif fmt == "parquet":
|
|
131
|
+
lf = pl.scan_parquet(path)
|
|
132
|
+
else:
|
|
133
|
+
lf = pl.scan_ipc(path)
|
|
134
|
+
if columns is not None:
|
|
135
|
+
_check_columns(lf.collect_schema().names(), columns, what)
|
|
136
|
+
lf = lf.select(columns)
|
|
137
|
+
return lf.collect()
|
|
138
|
+
if fmt == "json":
|
|
139
|
+
return _select(pl.read_json(path), columns, what)
|
|
140
|
+
if fmt == "ndjson":
|
|
141
|
+
return _select(pl.read_ndjson(path), columns, what)
|
|
142
|
+
raise AssertionError(fmt) # pragma: no cover
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_table(source: Any, *, columns: str | Sequence[str] | None = None,
|
|
146
|
+
format: str | None = None) -> pl.DataFrame:
|
|
147
|
+
"""Load ``source`` as an eager polars DataFrame.
|
|
148
|
+
|
|
149
|
+
``source`` may be a ``pl.DataFrame``, ``pl.LazyFrame``, ``pl.Series``, ``pandas.DataFrame``,
|
|
150
|
+
``pyarrow.Table``/``RecordBatch``, or a path (``str``/``PathLike``) to a ``.csv``, ``.tsv``,
|
|
151
|
+
``.parquet``, ``.arrow``/``.feather``/``.ipc``, ``.json`` or ``.ndjson`` file. ``format``
|
|
152
|
+
overrides extension-based detection for paths. ``columns`` selects (and orders) columns;
|
|
153
|
+
unknown names raise ``ValueError``. CSV input is read with ``try_parse_dates=True``.
|
|
154
|
+
"""
|
|
155
|
+
cols = _normalize_columns(columns)
|
|
156
|
+
if isinstance(source, pl.DataFrame):
|
|
157
|
+
return _select(source, cols, "DataFrame")
|
|
158
|
+
if isinstance(source, pl.LazyFrame):
|
|
159
|
+
if cols is not None:
|
|
160
|
+
_check_columns(source.collect_schema().names(), cols, "LazyFrame")
|
|
161
|
+
source = source.select(cols)
|
|
162
|
+
return source.collect()
|
|
163
|
+
if isinstance(source, pl.Series):
|
|
164
|
+
return _select(source.to_frame(), cols, "Series")
|
|
165
|
+
if isinstance(source, str | os.PathLike):
|
|
166
|
+
return _read_path(Path(source), cols, format)
|
|
167
|
+
if _is_pandas_frame(source):
|
|
168
|
+
return _select(_from_pandas(source), cols, "pandas DataFrame")
|
|
169
|
+
if _is_arrow_table(source):
|
|
170
|
+
df = pl.from_arrow(source)
|
|
171
|
+
assert isinstance(df, pl.DataFrame)
|
|
172
|
+
return _select(df, cols, "pyarrow Table")
|
|
173
|
+
raise TypeError(
|
|
174
|
+
f"unsupported table source of type {type(source).__module__}.{type(source).__qualname__}; "
|
|
175
|
+
"expected a polars DataFrame/LazyFrame, pandas DataFrame, pyarrow Table or a path to "
|
|
176
|
+
f"one of {', '.join(sorted(FORMATS))}"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def write_table(df: pl.DataFrame | pl.LazyFrame, path: str | os.PathLike[str], *,
|
|
181
|
+
format: str | None = None) -> Path:
|
|
182
|
+
"""Write ``df`` to ``path`` (format from the extension unless ``format`` is given).
|
|
183
|
+
|
|
184
|
+
Parent directories are created. Returns the resolved path.
|
|
185
|
+
"""
|
|
186
|
+
if isinstance(df, pl.LazyFrame):
|
|
187
|
+
df = df.collect()
|
|
188
|
+
if not isinstance(df, pl.DataFrame):
|
|
189
|
+
raise TypeError(f"write_table expects a polars DataFrame, got {type(df).__qualname__}; "
|
|
190
|
+
"convert with read_table(...) first")
|
|
191
|
+
out = Path(path)
|
|
192
|
+
fmt = _normalize_format(format) if format is not None else infer_format(out)
|
|
193
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
if fmt == "csv":
|
|
195
|
+
df.write_csv(out)
|
|
196
|
+
elif fmt == "tsv":
|
|
197
|
+
df.write_csv(out, separator="\t")
|
|
198
|
+
elif fmt == "parquet":
|
|
199
|
+
df.write_parquet(out)
|
|
200
|
+
elif fmt == "ipc":
|
|
201
|
+
df.write_ipc(out)
|
|
202
|
+
elif fmt == "json":
|
|
203
|
+
df.write_json(out)
|
|
204
|
+
elif fmt == "ndjson":
|
|
205
|
+
df.write_ndjson(out)
|
|
206
|
+
else: # pragma: no cover
|
|
207
|
+
raise AssertionError(fmt)
|
|
208
|
+
return out.resolve()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def to_pandas(df: Any) -> pandas.DataFrame:
|
|
212
|
+
"""Convert a polars frame (or anything ``read_table`` accepts) to pandas.
|
|
213
|
+
|
|
214
|
+
pandas is an optional dependency and is imported only here.
|
|
215
|
+
"""
|
|
216
|
+
try:
|
|
217
|
+
import pandas # noqa: F401
|
|
218
|
+
except ImportError as exc: # pragma: no cover - depends on environment
|
|
219
|
+
raise ImportError(
|
|
220
|
+
"to_pandas requires the optional dependency 'pandas' (pip install pandas)"
|
|
221
|
+
) from exc
|
|
222
|
+
if _is_pandas_frame(df):
|
|
223
|
+
return df
|
|
224
|
+
return read_table(df).to_pandas()
|
ectype/io/sql.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Read-only SQL sources through DuckDB (M32, the optional ``[sql]`` extra).
|
|
2
|
+
|
|
3
|
+
:func:`read_sql` accepts
|
|
4
|
+
|
|
5
|
+
* a ``SELECT`` / ``WITH`` / ``FROM``-first query,
|
|
6
|
+
* a table or view name (``orders``, ``main.orders``, ``db.main.orders``), or
|
|
7
|
+
* a file path or glob DuckDB can scan directly: Parquet (``data/*.parquet``), CSV/TSV (via
|
|
8
|
+
``read_csv_auto``) or JSON/NDJSON,
|
|
9
|
+
|
|
10
|
+
against a DuckDB database file (``database=``, opened ``read_only=True``), an existing DuckDB
|
|
11
|
+
``connection=`` (e.g. in-memory), or a fresh in-memory connection.
|
|
12
|
+
|
|
13
|
+
Sampling is pushed down into DuckDB: ``USING SAMPLE reservoir(n ROWS) REPEATABLE (seed)``, run
|
|
14
|
+
single-threaded so the same seed gives the same rows.
|
|
15
|
+
|
|
16
|
+
Read-only guard: queries are checked conservatively before execution. Only one statement is
|
|
17
|
+
allowed (no ``;`` chains), it must start with ``SELECT``, ``WITH`` or ``FROM``, and keywords
|
|
18
|
+
that write or change state (``INSERT``, ``COPY``, ``ATTACH``, ``PRAGMA``, ``SET``, ...) are
|
|
19
|
+
refused anywhere outside string literals (single-quoted, ``E'...'`` escape strings and
|
|
20
|
+
``$tag$...$tag$`` dollar quotes are all recognised). Calls to functions with side effects
|
|
21
|
+
(``nextval``, ``setval``, ``setseed``, ``checkpoint``, logging/profiling switches, ``query``
|
|
22
|
+
which runs SQL held in a string, ...) are refused too. This is a guard rail, not a sandbox:
|
|
23
|
+
for untrusted SQL, also use a ``read_only`` database file.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import re
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import TYPE_CHECKING, Any
|
|
31
|
+
|
|
32
|
+
import polars as pl
|
|
33
|
+
|
|
34
|
+
from ectype.errors import EctypeError
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
37
|
+
from ectype.fingerprint.core import Fingerprint
|
|
38
|
+
|
|
39
|
+
__all__ = ["ReadOnlyViolation", "profile_sql", "read_sql", "source_sql"]
|
|
40
|
+
|
|
41
|
+
_INSTALL_HINT = ("DuckDB is required for SQL sources: install the optional extra with "
|
|
42
|
+
"`pip install ectype-data[sql]` (or `pip install duckdb`).")
|
|
43
|
+
|
|
44
|
+
_FORBIDDEN = frozenset({
|
|
45
|
+
"INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT", "DROP", "CREATE", "ALTER", "TRUNCATE",
|
|
46
|
+
"ATTACH", "DETACH", "COPY", "EXPORT", "IMPORT", "INSTALL", "LOAD", "PRAGMA", "SET",
|
|
47
|
+
"RESET", "CALL", "CHECKPOINT", "FORCE", "VACUUM", "GRANT", "REVOKE", "BEGIN", "COMMIT",
|
|
48
|
+
"ROLLBACK", "ABORT", "USE", "PREPARE", "EXECUTE", "DEALLOCATE", "ANALYZE", "COMMENT",
|
|
49
|
+
})
|
|
50
|
+
#: Functions that change database/session state (or run SQL hidden in a string literal, which
|
|
51
|
+
#: the keyword guard cannot see). ``currval`` only reads and stays allowed.
|
|
52
|
+
_FORBIDDEN_FUNCTIONS = frozenset({
|
|
53
|
+
"nextval", "setval", "setseed", "checkpoint", "force_checkpoint",
|
|
54
|
+
"enable_logging", "disable_logging", "truncate_duckdb_logs", "write_log",
|
|
55
|
+
"enable_profiling", "disable_profiling", "add_grammar_extension",
|
|
56
|
+
"remove_grammar_extension", "create_external_resource", "destroy_external_resource",
|
|
57
|
+
"register_external_resource", "register_external_resource_type",
|
|
58
|
+
"deregister_external_resource", "python_map_function", "query",
|
|
59
|
+
"json_execute_serialized_sql", "import_database", "copy_database",
|
|
60
|
+
})
|
|
61
|
+
_FUNC_CALL_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_$]*)\s*\(")
|
|
62
|
+
_DOLLAR_RE = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)?\$")
|
|
63
|
+
_STARTERS = ("SELECT", "WITH", "FROM")
|
|
64
|
+
_IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}$")
|
|
65
|
+
_FILE_READERS = {
|
|
66
|
+
".parquet": "read_parquet", ".pq": "read_parquet",
|
|
67
|
+
".csv": "read_csv_auto", ".tsv": "read_csv_auto", ".txt": "read_csv_auto",
|
|
68
|
+
".gz": "read_csv_auto",
|
|
69
|
+
".json": "read_json_auto", ".ndjson": "read_json_auto", ".jsonl": "read_json_auto",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ReadOnlyViolation(EctypeError, ValueError):
|
|
74
|
+
"""A SQL source was not a single read-only SELECT statement."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _duckdb() -> Any:
|
|
78
|
+
try:
|
|
79
|
+
import duckdb
|
|
80
|
+
except ImportError as e: # pragma: no cover - depends on the environment
|
|
81
|
+
raise ImportError(_INSTALL_HINT) from e
|
|
82
|
+
return duckdb
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _is_ident_char(ch: str) -> bool:
|
|
86
|
+
return ch.isalnum() or ch in "_$"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _strip_literals(sql: str, *, keep_identifiers: bool = False) -> str:
|
|
90
|
+
"""Remove comments and string/identifier literals so keyword checks see only code.
|
|
91
|
+
|
|
92
|
+
With ``keep_identifiers`` a double-quoted identifier is replaced by its (space-padded)
|
|
93
|
+
content instead of a placeholder, so quoted function names stay visible.
|
|
94
|
+
"""
|
|
95
|
+
out: list[str] = []
|
|
96
|
+
i, n = 0, len(sql)
|
|
97
|
+
while i < n:
|
|
98
|
+
ch = sql[i]
|
|
99
|
+
prev = sql[i - 1] if i > 0 else ""
|
|
100
|
+
if sql.startswith("--", i):
|
|
101
|
+
j = sql.find("\n", i)
|
|
102
|
+
i = n if j < 0 else j
|
|
103
|
+
out.append(" ")
|
|
104
|
+
elif sql.startswith("/*", i):
|
|
105
|
+
j = sql.find("*/", i + 2)
|
|
106
|
+
if j < 0:
|
|
107
|
+
raise ReadOnlyViolation("unterminated /* comment in SQL")
|
|
108
|
+
i = j + 2
|
|
109
|
+
out.append(" ")
|
|
110
|
+
elif ch == "$" and not _is_ident_char(prev) and (m := _DOLLAR_RE.match(sql, i)):
|
|
111
|
+
tag = m.group(0)
|
|
112
|
+
j = sql.find(tag, m.end())
|
|
113
|
+
if j < 0:
|
|
114
|
+
raise ReadOnlyViolation(f"unterminated dollar-quoted string {tag} in SQL")
|
|
115
|
+
out.append(" '' ")
|
|
116
|
+
i = j + len(tag)
|
|
117
|
+
elif ch in ("'", '"'):
|
|
118
|
+
# E'...' escape strings honour backslash escapes
|
|
119
|
+
escapes = (ch == "'" and prev in ("E", "e")
|
|
120
|
+
and not (i >= 2 and _is_ident_char(sql[i - 2])))
|
|
121
|
+
j = i + 1
|
|
122
|
+
while True:
|
|
123
|
+
if escapes:
|
|
124
|
+
while j < n and sql[j] != ch:
|
|
125
|
+
j += 2 if sql[j] == "\\" else 1
|
|
126
|
+
if j >= n:
|
|
127
|
+
j = -1
|
|
128
|
+
else:
|
|
129
|
+
j = sql.find(ch, j)
|
|
130
|
+
if j < 0:
|
|
131
|
+
raise ReadOnlyViolation("unterminated quoted literal in SQL")
|
|
132
|
+
if j + 1 < n and sql[j + 1] == ch: # doubled quote escape
|
|
133
|
+
j += 2
|
|
134
|
+
continue
|
|
135
|
+
break
|
|
136
|
+
if ch == "'":
|
|
137
|
+
out.append(" '' ")
|
|
138
|
+
elif keep_identifiers:
|
|
139
|
+
out.append(" " + sql[i + 1:j].replace('""', '"') + " ")
|
|
140
|
+
else:
|
|
141
|
+
out.append(' "x" ')
|
|
142
|
+
i = j + 1
|
|
143
|
+
else:
|
|
144
|
+
out.append(ch)
|
|
145
|
+
i += 1
|
|
146
|
+
return "".join(out)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def check_read_only(sql: str) -> str:
|
|
150
|
+
"""Return ``sql`` (without a trailing ``;``) if it passes the read-only guard, else raise
|
|
151
|
+
:class:`ReadOnlyViolation`."""
|
|
152
|
+
code = _strip_literals(sql).strip()
|
|
153
|
+
if code.endswith(";"):
|
|
154
|
+
code = code[:-1].rstrip()
|
|
155
|
+
sql = sql.rstrip()
|
|
156
|
+
sql = sql[: sql.rfind(";")]
|
|
157
|
+
if ";" in code:
|
|
158
|
+
raise ReadOnlyViolation("only a single SQL statement is allowed (found ';')")
|
|
159
|
+
words = re.findall(r"[A-Za-z_][A-Za-z0-9_]*", code)
|
|
160
|
+
if not words or words[0].upper() not in _STARTERS:
|
|
161
|
+
raise ReadOnlyViolation(
|
|
162
|
+
f"only read-only queries starting with {'/'.join(_STARTERS)} are allowed, got "
|
|
163
|
+
f"{(words[0] if words else '(empty)')!r}")
|
|
164
|
+
bad = sorted({w.upper() for w in words} & _FORBIDDEN)
|
|
165
|
+
if bad:
|
|
166
|
+
raise ReadOnlyViolation(f"refusing SQL that contains non-read-only keyword(s) {bad}")
|
|
167
|
+
calls = {m.group(1).lower() for m in
|
|
168
|
+
_FUNC_CALL_RE.finditer(_strip_literals(sql, keep_identifiers=True))}
|
|
169
|
+
bad_calls = sorted(calls & _FORBIDDEN_FUNCTIONS)
|
|
170
|
+
if bad_calls:
|
|
171
|
+
raise ReadOnlyViolation(
|
|
172
|
+
f"refusing SQL that calls state-changing function(s) {bad_calls}")
|
|
173
|
+
return sql
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _quote_ident(name: str) -> str:
|
|
177
|
+
return ".".join('"' + part.replace('"', '""') + '"' for part in name.split("."))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _quote_str(s: str) -> str:
|
|
181
|
+
return "'" + s.replace("'", "''") + "'"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _looks_like_query(text: str) -> bool:
|
|
185
|
+
m = re.match(r"\s*\(*\s*([A-Za-z_]+)", text)
|
|
186
|
+
return m is not None and m.group(1).upper() in _STARTERS and len(text.split()) > 1
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def source_sql(query_or_table: str | Path) -> str:
|
|
190
|
+
"""The checked ``SELECT`` that reads ``query_or_table`` (query, table name or file)."""
|
|
191
|
+
if isinstance(query_or_table, Path):
|
|
192
|
+
text = str(query_or_table)
|
|
193
|
+
elif isinstance(query_or_table, str):
|
|
194
|
+
text = query_or_table.strip()
|
|
195
|
+
else:
|
|
196
|
+
raise TypeError(f"query_or_table must be a str or Path, not "
|
|
197
|
+
f"{type(query_or_table).__name__}")
|
|
198
|
+
if not text:
|
|
199
|
+
raise ValueError("empty SQL source")
|
|
200
|
+
suffix = Path(text).suffix.lower()
|
|
201
|
+
is_path = isinstance(query_or_table, Path)
|
|
202
|
+
if not is_path and _IDENT_RE.match(text) and (suffix not in _FILE_READERS
|
|
203
|
+
or not Path(text).exists()):
|
|
204
|
+
return f"SELECT * FROM {_quote_ident(text)}"
|
|
205
|
+
if is_path or (suffix in _FILE_READERS and not _looks_like_query(text)):
|
|
206
|
+
reader = _FILE_READERS.get(suffix)
|
|
207
|
+
if reader is None:
|
|
208
|
+
raise ValueError(f"cannot read {text!r} with DuckDB: unsupported extension "
|
|
209
|
+
f"{suffix or '(none)'!r}; supported: {sorted(_FILE_READERS)}")
|
|
210
|
+
path = text.replace("\\", "/")
|
|
211
|
+
extra = ", delim='\\t'" if suffix == ".tsv" else ""
|
|
212
|
+
return f"SELECT * FROM {reader}({_quote_str(path)}{extra})"
|
|
213
|
+
return check_read_only(text)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _sampled(sql: str, sample_rows: int, seed: int) -> str:
|
|
217
|
+
# newline before ')' so a trailing ``--`` comment in ``sql`` cannot swallow it
|
|
218
|
+
return (f"SELECT * FROM ({sql}\n) AS _ts_source "
|
|
219
|
+
f"USING SAMPLE reservoir({int(sample_rows)} ROWS) REPEATABLE ({int(seed)})")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _check_parsed(con: Any, duckdb: Any, sql: str) -> None:
|
|
223
|
+
"""Second guard: DuckDB's own parser must see exactly one SELECT statement."""
|
|
224
|
+
extract = getattr(con, "extract_statements", None)
|
|
225
|
+
if extract is None: # pragma: no cover - very old DuckDB
|
|
226
|
+
return
|
|
227
|
+
stmts = extract(sql)
|
|
228
|
+
if len(stmts) != 1 or stmts[0].type != duckdb.StatementType.SELECT:
|
|
229
|
+
raise ReadOnlyViolation("only a single read-only SELECT statement is allowed")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _fetch(con: Any, sql: str) -> pl.DataFrame:
|
|
233
|
+
out = pl.from_arrow(con.sql(sql).to_arrow_table())
|
|
234
|
+
assert isinstance(out, pl.DataFrame)
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def read_sql(query_or_table: str | Path, *, connection: Any = None,
|
|
239
|
+
database: str | Path | None = None, sample_rows: int | None = None,
|
|
240
|
+
seed: int = 0) -> pl.DataFrame:
|
|
241
|
+
"""Run a read-only query (or read a table / file) through DuckDB into a polars frame.
|
|
242
|
+
|
|
243
|
+
``connection`` is an open ``duckdb.DuckDBPyConnection``; ``database`` a DuckDB file path
|
|
244
|
+
(opened read-only). Give at most one; with neither, an in-memory connection is used (handy
|
|
245
|
+
for file sources). ``sample_rows`` draws a reservoir sample of that many rows inside
|
|
246
|
+
DuckDB, reproducibly for a given ``seed``.
|
|
247
|
+
"""
|
|
248
|
+
duckdb = _duckdb()
|
|
249
|
+
if connection is not None and database is not None:
|
|
250
|
+
raise ValueError("pass either connection= or database=, not both")
|
|
251
|
+
if sample_rows is not None and (isinstance(sample_rows, bool) or int(sample_rows) < 0):
|
|
252
|
+
raise ValueError(f"sample_rows must be a non-negative integer, got {sample_rows!r}")
|
|
253
|
+
sql = source_sql(query_or_table)
|
|
254
|
+
own = connection is None
|
|
255
|
+
if database is not None:
|
|
256
|
+
db = Path(database)
|
|
257
|
+
if not db.exists():
|
|
258
|
+
raise FileNotFoundError(f"no such DuckDB database: {str(db)!r}")
|
|
259
|
+
con = duckdb.connect(str(db), read_only=True)
|
|
260
|
+
elif connection is not None:
|
|
261
|
+
con = connection
|
|
262
|
+
else:
|
|
263
|
+
con = duckdb.connect(":memory:")
|
|
264
|
+
try:
|
|
265
|
+
_check_parsed(con, duckdb, sql)
|
|
266
|
+
if sample_rows is None:
|
|
267
|
+
return _fetch(con, sql)
|
|
268
|
+
# Reservoir sampling is only repeatable single-threaded; restore the setting after.
|
|
269
|
+
threads = con.execute("SELECT current_setting('threads')").fetchone()[0]
|
|
270
|
+
con.execute("SET threads = 1")
|
|
271
|
+
try:
|
|
272
|
+
return _fetch(con, _sampled(sql, int(sample_rows), int(seed)))
|
|
273
|
+
finally:
|
|
274
|
+
con.execute(f"SET threads = {int(threads)}")
|
|
275
|
+
finally:
|
|
276
|
+
if own:
|
|
277
|
+
con.close()
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def profile_sql(query_or_table: str | Path, *, connection: Any = None,
|
|
281
|
+
database: str | Path | None = None, sample_rows: int | None = 100_000,
|
|
282
|
+
seed: int = 0, **profiler_kwargs: Any) -> Fingerprint:
|
|
283
|
+
"""Read a (sampled) SQL source and fit a fingerprint: ``Profiler(seed=seed, ...).fit``."""
|
|
284
|
+
from ectype.profiler import Profiler
|
|
285
|
+
|
|
286
|
+
df = read_sql(query_or_table, connection=connection, database=database,
|
|
287
|
+
sample_rows=sample_rows, seed=seed)
|
|
288
|
+
profiler_kwargs.setdefault("seed", seed)
|
|
289
|
+
return Profiler(**profiler_kwargs).fit(df)
|