ab-analysis-kit 0.0.1.dev0__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.
- ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
- abkit/__init__.py +40 -0
- abkit/cli/__init__.py +1 -0
- abkit/cli/_output.py +111 -0
- abkit/cli/commands/__init__.py +1 -0
- abkit/cli/commands/_context.py +83 -0
- abkit/cli/commands/clean.py +133 -0
- abkit/cli/commands/explore.py +208 -0
- abkit/cli/commands/init.py +427 -0
- abkit/cli/commands/run.py +282 -0
- abkit/cli/commands/unlock.py +59 -0
- abkit/cli/commands/validate.py +264 -0
- abkit/cli/main.py +279 -0
- abkit/compute/__init__.py +5 -0
- abkit/compute/recompute_backend.py +140 -0
- abkit/config/__init__.py +51 -0
- abkit/config/discovery.py +168 -0
- abkit/config/experiment_config.py +511 -0
- abkit/config/method_config.py +80 -0
- abkit/config/metric_config.py +214 -0
- abkit/config/profile.py +301 -0
- abkit/config/project_config.py +244 -0
- abkit/config/validator.py +393 -0
- abkit/core/__init__.py +26 -0
- abkit/core/interval.py +148 -0
- abkit/core/models.py +121 -0
- abkit/core/period_planner.py +206 -0
- abkit/database/__init__.py +51 -0
- abkit/database/_sql_manager.py +432 -0
- abkit/database/clickhouse_manager.py +495 -0
- abkit/database/internal_tables/__init__.py +6 -0
- abkit/database/internal_tables/_aa_runs.py +53 -0
- abkit/database/internal_tables/_base.py +71 -0
- abkit/database/internal_tables/_experiments.py +82 -0
- abkit/database/internal_tables/_exposures.py +163 -0
- abkit/database/internal_tables/_maintenance.py +72 -0
- abkit/database/internal_tables/_results.py +231 -0
- abkit/database/internal_tables/_schema.py +23 -0
- abkit/database/internal_tables/_tasks.py +237 -0
- abkit/database/internal_tables/_unit_state.py +148 -0
- abkit/database/internal_tables/manager.py +30 -0
- abkit/database/manager.py +450 -0
- abkit/database/mysql_manager.py +175 -0
- abkit/database/postgres_manager.py +145 -0
- abkit/database/tables.py +326 -0
- abkit/loaders/__init__.py +28 -0
- abkit/loaders/exposure_loader.py +121 -0
- abkit/loaders/metric_loader.py +251 -0
- abkit/loaders/query_template.py +167 -0
- abkit/loaders/templates/abkit_assignment.jinja +62 -0
- abkit/pipeline/__init__.py +37 -0
- abkit/pipeline/_types.py +52 -0
- abkit/pipeline/analyze.py +223 -0
- abkit/pipeline/driver.py +477 -0
- abkit/pipeline/enrich.py +137 -0
- abkit/pipeline/readout.py +779 -0
- abkit/reporting/__init__.py +19 -0
- abkit/reporting/assets/report.js +138 -0
- abkit/reporting/builder.py +484 -0
- abkit/reporting/calibration.py +182 -0
- abkit/reporting/html_report.py +109 -0
- abkit/stats/__init__.py +94 -0
- abkit/stats/accumulate.py +82 -0
- abkit/stats/base.py +347 -0
- abkit/stats/bootstrap/__init__.py +69 -0
- abkit/stats/bootstrap/applier.py +81 -0
- abkit/stats/bootstrap/bootstrap.py +311 -0
- abkit/stats/bootstrap/ci.py +72 -0
- abkit/stats/bootstrap/engine.py +383 -0
- abkit/stats/bootstrap/paired_bootstrap.py +57 -0
- abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
- abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
- abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
- abkit/stats/correction.py +88 -0
- abkit/stats/effects.py +141 -0
- abkit/stats/exceptions.py +31 -0
- abkit/stats/factory.py +26 -0
- abkit/stats/parametric/__init__.py +10 -0
- abkit/stats/parametric/cuped_ttest.py +183 -0
- abkit/stats/parametric/paired_cuped_ttest.py +125 -0
- abkit/stats/parametric/paired_ttest.py +136 -0
- abkit/stats/parametric/ratio_delta.py +113 -0
- abkit/stats/parametric/ttest.py +105 -0
- abkit/stats/parametric/ztest.py +134 -0
- abkit/stats/power.py +278 -0
- abkit/stats/registry.py +111 -0
- abkit/stats/result.py +84 -0
- abkit/stats/rng.py +39 -0
- abkit/stats/samples.py +531 -0
- abkit/stats/sequential/__init__.py +18 -0
- abkit/stats/sequential/apply.py +37 -0
- abkit/stats/sequential/confidence_sequence.py +96 -0
- abkit/stats/sequential/mixture.py +70 -0
- abkit/stats/srm.py +221 -0
- abkit/tuning/__init__.py +59 -0
- abkit/tuning/assets/explore.js +173 -0
- abkit/tuning/config_writer.py +409 -0
- abkit/tuning/html.py +88 -0
- abkit/tuning/payload.py +122 -0
- abkit/tuning/recompute.py +1039 -0
- abkit/tuning/server.py +882 -0
- abkit/tuning/session.py +233 -0
- abkit/utils/__init__.py +27 -0
- abkit/utils/datetime_utils.py +97 -0
- abkit/utils/env_interpolation.py +50 -0
- abkit/utils/json_utils.py +38 -0
- abkit/validate/__init__.py +36 -0
- abkit/validate/_types.py +35 -0
- abkit/validate/inject.py +75 -0
- abkit/validate/load.py +160 -0
- abkit/validate/panel.py +59 -0
- abkit/validate/persistence.py +59 -0
- abkit/validate/resample.py +94 -0
- abkit/validate/result.py +60 -0
- abkit/validate/run_id.py +45 -0
- abkit/validate/runner.py +389 -0
- abkit/validate/scoring.py +544 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""Shared base for SQL (PostgreSQL / MySQL) database managers.
|
|
2
|
+
|
|
3
|
+
Both PostgreSQL and MySQL are standard SQL engines with an *enforced* primary
|
|
4
|
+
key and native upsert, so they share almost all of the implementation. This
|
|
5
|
+
module owns the DB-API 2.0 flow once (connection, cursor → dict rows,
|
|
6
|
+
transactions, numpy → driver value coercion, DDL rendering, version-aware
|
|
7
|
+
upserts, the atomic lock claim) and exposes a handful of dialect hooks that the
|
|
8
|
+
two concrete backends override:
|
|
9
|
+
|
|
10
|
+
- ``_connect()`` — open the DB-API connection.
|
|
11
|
+
- ``_ensure_locations()`` — create the internal/data schema-or-database.
|
|
12
|
+
- ``_TYPE_MAP`` / ``_string_type()`` — map the abstract ``TableModel`` column
|
|
13
|
+
types onto native column types.
|
|
14
|
+
- ``_build_insert_sql()`` — render the dialect's insert + conflict handling.
|
|
15
|
+
- ``_build_claim_sql()`` — render the dialect's single-statement lock claim.
|
|
16
|
+
|
|
17
|
+
The contract matches the ClickHouse backend's behaviour: versioned tables
|
|
18
|
+
(``version_column`` set, e.g. ``_ab_results``) get last-writer-wins semantics
|
|
19
|
+
via a version-aware upsert mirroring ``ReplacingMergeTree``; plain tables are
|
|
20
|
+
replaced transactionally via :meth:`upsert_record`.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
from datetime import datetime, timedelta, timezone
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
from abkit.core.models import ColumnDefinition, TableModel
|
|
32
|
+
from abkit.database.manager import BaseDatabaseManager
|
|
33
|
+
from abkit.utils.datetime_utils import now_utc_naive
|
|
34
|
+
|
|
35
|
+
_EPOCH = np.datetime64("1970-01-01T00:00:00")
|
|
36
|
+
_ONE_SECOND = np.timedelta64(1, "s")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SQLDatabaseManager(BaseDatabaseManager):
|
|
40
|
+
"""Base class for standard-SQL backends (PostgreSQL, MySQL).
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
host: Database host.
|
|
44
|
+
port: Database port.
|
|
45
|
+
user: Database user.
|
|
46
|
+
password: Database password.
|
|
47
|
+
internal_location: Schema (PostgreSQL) or database (MySQL) for the
|
|
48
|
+
internal ``_ab_*`` tables.
|
|
49
|
+
data_location: Schema (PostgreSQL) or database (MySQL) for user data.
|
|
50
|
+
database: Connection-target database. Required for PostgreSQL (the
|
|
51
|
+
database to connect to, inside which the schemas live); optional for
|
|
52
|
+
MySQL (which addresses tables as ``database.table``).
|
|
53
|
+
settings: Extra driver-specific connection options.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
#: Maps the canonical column kind to a native SQL type. Subclasses override.
|
|
57
|
+
_TYPE_MAP: dict[str, str] = {}
|
|
58
|
+
|
|
59
|
+
#: Identifier quote character (double-quote for PostgreSQL, backtick MySQL).
|
|
60
|
+
_IDENT_QUOTE = '"'
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
host: str = "localhost",
|
|
65
|
+
port: int = 5432,
|
|
66
|
+
user: str = "",
|
|
67
|
+
password: str = "",
|
|
68
|
+
internal_location: str = "abkit",
|
|
69
|
+
data_location: str = "public",
|
|
70
|
+
database: str | None = None,
|
|
71
|
+
settings: dict[str, Any] | None = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
self._host = host
|
|
74
|
+
self._port = port
|
|
75
|
+
self._user = user
|
|
76
|
+
self._password = password
|
|
77
|
+
self._internal_location = internal_location
|
|
78
|
+
self._data_location = data_location
|
|
79
|
+
self._database = database
|
|
80
|
+
self._settings = settings or {}
|
|
81
|
+
# bare table name -> (primary_key columns, version column) recorded at
|
|
82
|
+
# create_table time and consulted by the insert path.
|
|
83
|
+
self._table_meta: dict[str, tuple[list[str], str | None]] = {}
|
|
84
|
+
|
|
85
|
+
self._conn: Any = self._connect()
|
|
86
|
+
self._ensure_locations()
|
|
87
|
+
|
|
88
|
+
# ── dialect hooks (subclasses override) ─────────────────────────────────
|
|
89
|
+
|
|
90
|
+
def _connect(self) -> Any:
|
|
91
|
+
"""Open and return a DB-API 2.0 connection."""
|
|
92
|
+
raise NotImplementedError
|
|
93
|
+
|
|
94
|
+
def _ensure_locations(self) -> None:
|
|
95
|
+
"""Create the internal/data schema (PostgreSQL) or database (MySQL)."""
|
|
96
|
+
raise NotImplementedError
|
|
97
|
+
|
|
98
|
+
def _string_type(self, in_primary_key: bool, max_length: int | None = None) -> str:
|
|
99
|
+
"""Native type for an abstract ``String`` column."""
|
|
100
|
+
return self._TYPE_MAP["string"]
|
|
101
|
+
|
|
102
|
+
def _build_insert_sql(
|
|
103
|
+
self,
|
|
104
|
+
table_name: str,
|
|
105
|
+
columns: list[str],
|
|
106
|
+
primary_key: list[str],
|
|
107
|
+
version_column: str | None,
|
|
108
|
+
conflict_strategy: str,
|
|
109
|
+
) -> str:
|
|
110
|
+
"""Render the dialect's INSERT statement (single VALUES row template)."""
|
|
111
|
+
raise NotImplementedError
|
|
112
|
+
|
|
113
|
+
def _build_claim_sql(
|
|
114
|
+
self,
|
|
115
|
+
table_name: str,
|
|
116
|
+
columns: list[str],
|
|
117
|
+
primary_key: list[str],
|
|
118
|
+
status_column: str,
|
|
119
|
+
heartbeat_column: str,
|
|
120
|
+
) -> str:
|
|
121
|
+
"""Render the dialect's single-statement conditional lock claim.
|
|
122
|
+
|
|
123
|
+
The statement must insert the row when absent, overwrite it when the
|
|
124
|
+
claim condition holds (status <> ``%(_abk_running)s`` OR heartbeat <
|
|
125
|
+
``%(_abk_stale_before)s``), leave it untouched otherwise, and report
|
|
126
|
+
the outcome via the cursor's affected-row count (>= 1 means claimed).
|
|
127
|
+
"""
|
|
128
|
+
raise NotImplementedError
|
|
129
|
+
|
|
130
|
+
# ── type mapping / DDL ───────────────────────────────────────────────────
|
|
131
|
+
|
|
132
|
+
def _q(self, identifier: str) -> str:
|
|
133
|
+
"""Quote a SQL identifier (column/table name) for the dialect.
|
|
134
|
+
|
|
135
|
+
Necessary because some column names (e.g. ``interval``) are reserved
|
|
136
|
+
words on MySQL.
|
|
137
|
+
"""
|
|
138
|
+
return f"{self._IDENT_QUOTE}{identifier}{self._IDENT_QUOTE}"
|
|
139
|
+
|
|
140
|
+
@staticmethod
|
|
141
|
+
def _canonical_type(ch_type: str) -> str:
|
|
142
|
+
"""Reduce a ClickHouse-flavored ``TableModel`` type to a canonical kind."""
|
|
143
|
+
t = ch_type.strip()
|
|
144
|
+
if t.startswith("Nullable(") and t.endswith(")"):
|
|
145
|
+
t = t[len("Nullable(") : -1].strip()
|
|
146
|
+
if t.startswith("DateTime"):
|
|
147
|
+
return "datetime"
|
|
148
|
+
if t.startswith("Date"):
|
|
149
|
+
return "date"
|
|
150
|
+
if t.startswith("String") or t.startswith("FixedString"):
|
|
151
|
+
return "string"
|
|
152
|
+
if t.startswith("Float"):
|
|
153
|
+
return "float"
|
|
154
|
+
if t.startswith("UInt") or t.startswith("Int"):
|
|
155
|
+
return "int"
|
|
156
|
+
if t.startswith("Bool"):
|
|
157
|
+
return "bool"
|
|
158
|
+
raise ValueError(f"Cannot map column type to a SQL dialect: {ch_type!r}")
|
|
159
|
+
|
|
160
|
+
def _map_type(self, ch_type: str, in_primary_key: bool, max_length: int | None = None) -> str:
|
|
161
|
+
kind = self._canonical_type(ch_type)
|
|
162
|
+
if kind == "string":
|
|
163
|
+
return self._string_type(in_primary_key, max_length)
|
|
164
|
+
return self._TYPE_MAP[kind]
|
|
165
|
+
|
|
166
|
+
@staticmethod
|
|
167
|
+
def _is_nullable(col: ColumnDefinition) -> bool:
|
|
168
|
+
return col.nullable or (col.type.startswith("Nullable(") and col.type.endswith(")"))
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def _render_default(col: ColumnDefinition) -> str:
|
|
172
|
+
if col.default is None:
|
|
173
|
+
return ""
|
|
174
|
+
d = col.default
|
|
175
|
+
if isinstance(d, (int, float)):
|
|
176
|
+
return f" DEFAULT {d}"
|
|
177
|
+
if isinstance(d, str) and d.lstrip("-").isdigit():
|
|
178
|
+
return f" DEFAULT {d}"
|
|
179
|
+
return f" DEFAULT '{d}'"
|
|
180
|
+
|
|
181
|
+
def _render_column(self, col: ColumnDefinition, in_primary_key: bool) -> str:
|
|
182
|
+
native = self._map_type(col.type, in_primary_key, col.max_length)
|
|
183
|
+
# Primary-key columns are always NOT NULL; otherwise honor the model.
|
|
184
|
+
nullable = self._is_nullable(col) and not in_primary_key
|
|
185
|
+
null_sql = "" if nullable else " NOT NULL"
|
|
186
|
+
return f"{self._q(col.name)} {native}{null_sql}{self._render_default(col)}"
|
|
187
|
+
|
|
188
|
+
def register_table(self, table_name: str, table_model: TableModel) -> None:
|
|
189
|
+
"""Record the PK / version column for the insert path.
|
|
190
|
+
|
|
191
|
+
Keyed by the bare table name (``table_name`` is schema/database-qualified).
|
|
192
|
+
Called for every internal table on every run so a fresh manager instance
|
|
193
|
+
knows the schema even when the table already exists and the DDL is skipped.
|
|
194
|
+
"""
|
|
195
|
+
bare = table_name.split(".")[-1]
|
|
196
|
+
self._table_meta[bare] = (table_model.primary_key, table_model.version_column)
|
|
197
|
+
|
|
198
|
+
def create_table(
|
|
199
|
+
self, table_name: str, table_model: TableModel, if_not_exists: bool = True
|
|
200
|
+
) -> None:
|
|
201
|
+
"""Create a table with an enforced PRIMARY KEY (no ClickHouse engine)."""
|
|
202
|
+
pk = table_model.primary_key
|
|
203
|
+
col_defs = [self._render_column(col, col.name in pk) for col in table_model.columns]
|
|
204
|
+
col_defs.append(f"PRIMARY KEY ({', '.join(self._q(c) for c in pk)})")
|
|
205
|
+
body = ",\n ".join(col_defs)
|
|
206
|
+
if_not_exists_clause = "IF NOT EXISTS " if if_not_exists else ""
|
|
207
|
+
ddl = f"CREATE TABLE {if_not_exists_clause}{table_name} (\n {body}\n)"
|
|
208
|
+
self.execute_query(ddl)
|
|
209
|
+
self.register_table(table_name, table_model)
|
|
210
|
+
|
|
211
|
+
# ── queries ──────────────────────────────────────────────────────────────
|
|
212
|
+
|
|
213
|
+
def execute_query(
|
|
214
|
+
self, query: str, params: dict[str, Any] | None = None
|
|
215
|
+
) -> list[dict[str, Any]]:
|
|
216
|
+
"""Execute a query and return rows as dicts (commits the transaction)."""
|
|
217
|
+
try:
|
|
218
|
+
with self._conn.cursor() as cur:
|
|
219
|
+
cur.execute(query, params if params else None)
|
|
220
|
+
if cur.description is None:
|
|
221
|
+
rows: list[dict[str, Any]] = []
|
|
222
|
+
else:
|
|
223
|
+
columns = [desc[0] for desc in cur.description]
|
|
224
|
+
rows = [dict(zip(columns, row, strict=True)) for row in cur.fetchall()]
|
|
225
|
+
self._conn.commit()
|
|
226
|
+
return rows
|
|
227
|
+
except Exception:
|
|
228
|
+
self._conn.rollback()
|
|
229
|
+
raise
|
|
230
|
+
|
|
231
|
+
def table_exists(self, table_name: str, schema: str | None = None) -> bool:
|
|
232
|
+
"""Check ``information_schema.tables`` for the table in one/both locations."""
|
|
233
|
+
locations = [schema] if schema else [self._internal_location, self._data_location]
|
|
234
|
+
query = (
|
|
235
|
+
"SELECT 1 FROM information_schema.tables "
|
|
236
|
+
"WHERE table_schema = %(schema)s AND table_name = %(table)s"
|
|
237
|
+
)
|
|
238
|
+
for loc in locations:
|
|
239
|
+
if self.execute_query(query, {"schema": loc, "table": table_name}):
|
|
240
|
+
return True
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
def get_max_timestamp(
|
|
244
|
+
self,
|
|
245
|
+
table_name: str,
|
|
246
|
+
where_clause: str = "",
|
|
247
|
+
params: dict[str, Any] | None = None,
|
|
248
|
+
timestamp_column: str = "timestamp",
|
|
249
|
+
) -> datetime | None:
|
|
250
|
+
"""Return ``max(timestamp_column)`` under the WHERE clause, or ``None``."""
|
|
251
|
+
query = f"SELECT max({self._q(timestamp_column)}) AS last_ts FROM {table_name}"
|
|
252
|
+
if where_clause:
|
|
253
|
+
query += f" WHERE {where_clause}"
|
|
254
|
+
result = self.execute_query(query, params)
|
|
255
|
+
if result and result[0]["last_ts"] is not None:
|
|
256
|
+
return result[0]["last_ts"]
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
# ── writes ────────────────────────────────────────────────────────────────
|
|
260
|
+
|
|
261
|
+
def _coerce(self, value: Any) -> Any:
|
|
262
|
+
"""Convert a numpy scalar to a driver-friendly Python value."""
|
|
263
|
+
if value is None:
|
|
264
|
+
return None
|
|
265
|
+
if isinstance(value, np.datetime64):
|
|
266
|
+
if np.isnat(value):
|
|
267
|
+
return None
|
|
268
|
+
seconds = (value - _EPOCH) / _ONE_SECOND
|
|
269
|
+
# Store naive UTC (matches the codebase's naive-UTC convention).
|
|
270
|
+
return datetime.fromtimestamp(float(seconds), tz=timezone.utc).replace(tzinfo=None)
|
|
271
|
+
if isinstance(value, np.bool_):
|
|
272
|
+
return bool(value)
|
|
273
|
+
if isinstance(value, np.integer):
|
|
274
|
+
return int(value)
|
|
275
|
+
if isinstance(value, np.floating):
|
|
276
|
+
f = float(value)
|
|
277
|
+
return None if math.isnan(f) else f
|
|
278
|
+
if isinstance(value, float) and math.isnan(value):
|
|
279
|
+
return None
|
|
280
|
+
if isinstance(value, np.ndarray):
|
|
281
|
+
return value.tolist()
|
|
282
|
+
return value
|
|
283
|
+
|
|
284
|
+
def _rows_from_arrays(
|
|
285
|
+
self, data: dict[str, np.ndarray]
|
|
286
|
+
) -> tuple[list[str], list[tuple[Any, ...]]]:
|
|
287
|
+
columns = list(data.keys())
|
|
288
|
+
lengths = {len(arr) for arr in data.values()}
|
|
289
|
+
if len(lengths) > 1:
|
|
290
|
+
raise ValueError(
|
|
291
|
+
"All arrays must have same length, got: "
|
|
292
|
+
f"{ {k: len(v) for k, v in data.items()} }"
|
|
293
|
+
)
|
|
294
|
+
num_rows = lengths.pop() if lengths else 0
|
|
295
|
+
rows = [tuple(self._coerce(data[c][i]) for c in columns) for i in range(num_rows)]
|
|
296
|
+
return columns, rows
|
|
297
|
+
|
|
298
|
+
def _insert(
|
|
299
|
+
self, cur: Any, table_name: str, data: dict[str, np.ndarray], conflict_strategy: str
|
|
300
|
+
) -> int:
|
|
301
|
+
columns, rows = self._rows_from_arrays(data)
|
|
302
|
+
if not rows:
|
|
303
|
+
return 0
|
|
304
|
+
bare = table_name.split(".")[-1]
|
|
305
|
+
primary_key, version_column = self._table_meta.get(bare, ([], None))
|
|
306
|
+
sql = self._build_insert_sql(
|
|
307
|
+
table_name, columns, primary_key, version_column, conflict_strategy
|
|
308
|
+
)
|
|
309
|
+
cur.executemany(sql, rows)
|
|
310
|
+
return len(rows)
|
|
311
|
+
|
|
312
|
+
def insert_batch(
|
|
313
|
+
self, table_name: str, data: dict[str, np.ndarray], conflict_strategy: str = "ignore"
|
|
314
|
+
) -> int:
|
|
315
|
+
"""Insert rows honoring ``conflict_strategy`` against the enforced PK."""
|
|
316
|
+
if not data:
|
|
317
|
+
return 0
|
|
318
|
+
try:
|
|
319
|
+
with self._conn.cursor() as cur:
|
|
320
|
+
inserted = self._insert(cur, table_name, data, conflict_strategy)
|
|
321
|
+
self._conn.commit()
|
|
322
|
+
return inserted
|
|
323
|
+
except Exception:
|
|
324
|
+
self._conn.rollback()
|
|
325
|
+
raise
|
|
326
|
+
|
|
327
|
+
def delete_rows(
|
|
328
|
+
self,
|
|
329
|
+
table_name: str,
|
|
330
|
+
where_clause: str,
|
|
331
|
+
params: dict[str, Any] | None = None,
|
|
332
|
+
sync: bool = False,
|
|
333
|
+
) -> int:
|
|
334
|
+
"""Delete rows with a plain ``DELETE FROM`` (``sync`` is a no-op here)."""
|
|
335
|
+
try:
|
|
336
|
+
with self._conn.cursor() as cur:
|
|
337
|
+
cur.execute(
|
|
338
|
+
f"DELETE FROM {table_name} WHERE {where_clause}", params if params else None
|
|
339
|
+
)
|
|
340
|
+
affected = int(cur.rowcount)
|
|
341
|
+
self._conn.commit()
|
|
342
|
+
return max(affected, 0)
|
|
343
|
+
except Exception:
|
|
344
|
+
self._conn.rollback()
|
|
345
|
+
raise
|
|
346
|
+
|
|
347
|
+
def upsert_record(
|
|
348
|
+
self,
|
|
349
|
+
table_name: str,
|
|
350
|
+
key_columns: dict[str, Any],
|
|
351
|
+
data: dict[str, np.ndarray],
|
|
352
|
+
sync: bool = False,
|
|
353
|
+
) -> int:
|
|
354
|
+
"""Atomically replace a row: DELETE by key + INSERT, in one transaction.
|
|
355
|
+
|
|
356
|
+
``sync`` is a no-op here — the transaction already guarantees the old
|
|
357
|
+
row is gone before the insert commits.
|
|
358
|
+
"""
|
|
359
|
+
where = " AND ".join(f"{col} = %({col})s" for col in key_columns)
|
|
360
|
+
try:
|
|
361
|
+
with self._conn.cursor() as cur:
|
|
362
|
+
cur.execute(f"DELETE FROM {table_name} WHERE {where}", dict(key_columns))
|
|
363
|
+
inserted = self._insert(cur, table_name, data, conflict_strategy="fail")
|
|
364
|
+
self._conn.commit()
|
|
365
|
+
return inserted
|
|
366
|
+
except Exception:
|
|
367
|
+
self._conn.rollback()
|
|
368
|
+
raise
|
|
369
|
+
|
|
370
|
+
# ── locking ──────────────────────────────────────────────────────────────
|
|
371
|
+
|
|
372
|
+
def try_acquire_lock(
|
|
373
|
+
self,
|
|
374
|
+
table_name: str,
|
|
375
|
+
key_columns: dict[str, Any],
|
|
376
|
+
row: dict[str, Any],
|
|
377
|
+
*,
|
|
378
|
+
status_column: str = "status",
|
|
379
|
+
running_value: str = "running",
|
|
380
|
+
heartbeat_column: str = "started_at",
|
|
381
|
+
timeout_seconds: int = 3600,
|
|
382
|
+
token_column: str | None = None,
|
|
383
|
+
) -> bool:
|
|
384
|
+
"""Claim the lock row in ONE conditional upsert statement (atomic).
|
|
385
|
+
|
|
386
|
+
``token_column`` is accepted for interface parity but unused: the
|
|
387
|
+
enforced primary key + single-statement claim make the outcome exact,
|
|
388
|
+
so no read-back verification is needed.
|
|
389
|
+
"""
|
|
390
|
+
for key, value in key_columns.items():
|
|
391
|
+
if key not in row:
|
|
392
|
+
raise ValueError(f"lock row must contain key column {key!r}")
|
|
393
|
+
if row[key] != value:
|
|
394
|
+
raise ValueError(
|
|
395
|
+
f"lock row value for {key!r} ({row[key]!r}) != key_columns value ({value!r})"
|
|
396
|
+
)
|
|
397
|
+
columns = list(row.keys())
|
|
398
|
+
primary_key = list(key_columns.keys())
|
|
399
|
+
if not [c for c in columns if c not in primary_key]:
|
|
400
|
+
raise ValueError("lock row must have at least one non-key column")
|
|
401
|
+
|
|
402
|
+
stale_before = now_utc_naive() - timedelta(seconds=timeout_seconds)
|
|
403
|
+
sql = self._build_claim_sql(
|
|
404
|
+
table_name, columns, primary_key, status_column, heartbeat_column
|
|
405
|
+
)
|
|
406
|
+
params = {c: self._coerce(v) for c, v in row.items()}
|
|
407
|
+
params["_abk_running"] = running_value
|
|
408
|
+
params["_abk_stale_before"] = stale_before
|
|
409
|
+
try:
|
|
410
|
+
with self._conn.cursor() as cur:
|
|
411
|
+
cur.execute(sql, params)
|
|
412
|
+
affected = int(cur.rowcount)
|
|
413
|
+
self._conn.commit()
|
|
414
|
+
return affected >= 1
|
|
415
|
+
except Exception:
|
|
416
|
+
self._conn.rollback()
|
|
417
|
+
raise
|
|
418
|
+
|
|
419
|
+
# ── locations / lifecycle ─────────────────────────────────────────────────
|
|
420
|
+
|
|
421
|
+
@property
|
|
422
|
+
def internal_location(self) -> str:
|
|
423
|
+
return self._internal_location
|
|
424
|
+
|
|
425
|
+
@property
|
|
426
|
+
def data_location(self) -> str:
|
|
427
|
+
return self._data_location
|
|
428
|
+
|
|
429
|
+
def close(self) -> None:
|
|
430
|
+
conn = getattr(self, "_conn", None)
|
|
431
|
+
if conn is not None:
|
|
432
|
+
conn.close()
|