sqllocks-shape-databases 0.9.1__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.
- shape_databases/__init__.py +35 -0
- shape_databases/_auth.py +136 -0
- shape_databases/_base.py +444 -0
- shape_databases/_cloud.py +215 -0
- shape_databases/_sql.py +282 -0
- shape_databases/databricks.py +314 -0
- shape_databases/duckdb_sink.py +404 -0
- shape_databases/errors.py +24 -0
- shape_databases/mysql.py +199 -0
- shape_databases/postgres.py +147 -0
- shape_databases/snowflake.py +371 -0
- shape_databases/testing.py +669 -0
- sqllocks_shape_databases-0.9.1.dist-info/METADATA +349 -0
- sqllocks_shape_databases-0.9.1.dist-info/RECORD +18 -0
- sqllocks_shape_databases-0.9.1.dist-info/WHEEL +5 -0
- sqllocks_shape_databases-0.9.1.dist-info/entry_points.txt +6 -0
- sqllocks_shape_databases-0.9.1.dist-info/licenses/LICENSE +21 -0
- sqllocks_shape_databases-0.9.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""The ``duckdb`` sink: tables into a local DuckDB database file, straight from Arrow.
|
|
2
|
+
|
|
3
|
+
duckdb:///PATH.duckdb[?schema=main]
|
|
4
|
+
|
|
5
|
+
``duckdb:///data/out.duckdb`` is a path relative to the working directory and
|
|
6
|
+
``duckdb:////var/data/out.duckdb`` (four slashes) an absolute one, as in SQLAlchemy URLs; on
|
|
7
|
+
Windows ``duckdb:///C:/data/out.duckdb``. The database is created when it is missing. A URI with a
|
|
8
|
+
host, a password, no path or ``:memory:`` (the data would vanish with the connection) is refused.
|
|
9
|
+
|
|
10
|
+
Each Arrow batch is handed to DuckDB as an Arrow table (a zero-copy scan: no value is converted in
|
|
11
|
+
Python), then ``INSERT ... SELECT``-ed into the table. A missing table is created from the Arrow
|
|
12
|
+
schema:
|
|
13
|
+
|
|
14
|
+
===================================== ====================================================
|
|
15
|
+
Arrow type DuckDB column
|
|
16
|
+
===================================== ====================================================
|
|
17
|
+
bool ``BOOLEAN``
|
|
18
|
+
int8 / 16 / 32 / 64 ``TINYINT`` / ``SMALLINT`` / ``INTEGER`` / ``BIGINT``
|
|
19
|
+
uint8 / 16 / 32 / 64 ``UTINYINT`` / ``USMALLINT`` / ``UINTEGER`` / ``UBIGINT``
|
|
20
|
+
float32 / float64 (float16 as float32) ``FLOAT`` / ``DOUBLE``
|
|
21
|
+
decimal128(p, s), p at most 38 ``DECIMAL(p,s)``
|
|
22
|
+
string, large_string, dictionary ``VARCHAR``; ``UUID`` when the column's ``columns`` entry
|
|
23
|
+
says ``"type": "uuid"``
|
|
24
|
+
binary, large_binary, fixed binary ``BLOB``
|
|
25
|
+
date32 / date64 ``DATE``
|
|
26
|
+
time32 / time64 ``TIME`` (nanoseconds are cut to microseconds)
|
|
27
|
+
timestamp, no zone: s / ms / us / ns ``TIMESTAMP_S`` / ``TIMESTAMP_MS`` / ``TIMESTAMP`` /
|
|
28
|
+
``TIMESTAMP_NS``
|
|
29
|
+
timestamp with a zone ``TIMESTAMPTZ`` (microseconds)
|
|
30
|
+
===================================== ====================================================
|
|
31
|
+
|
|
32
|
+
Anything else (nested values, durations) is refused with the column named: convert it first. The
|
|
33
|
+
primary key (``primary_key``) is a ``PRIMARY KEY`` constraint; a column is ``NOT NULL`` when it is
|
|
34
|
+
a key column or its ``columns`` entry says ``"nullable": false``. Reading the table back gives
|
|
35
|
+
the same ``shape.repro.dataset_id`` as the tables that were written.
|
|
36
|
+
|
|
37
|
+
Write modes (``write_mode``, or ``?write_mode=`` in the URI; the option wins): ``create`` (the
|
|
38
|
+
default: an existing table is an error and is never touched), ``append`` (the table is created
|
|
39
|
+
when missing), ``truncate`` (``DELETE`` all rows, then add; created when missing), ``replace``
|
|
40
|
+
(drop and create again) and ``upsert`` (``INSERT OR REPLACE`` on the primary key, so rerunning the
|
|
41
|
+
same load leaves the same rows; a table without a primary key is refused:
|
|
42
|
+
``upsert needs a primary key on <table>``).
|
|
43
|
+
|
|
44
|
+
One table is one transaction: a failure rolls everything back, including the table this call
|
|
45
|
+
created and a ``replace``'s drop (a ``?schema=`` schema is created first, in a step of its own that
|
|
46
|
+
stays). With ``commit_rows=N`` (``--commit-rows``) the rows are committed
|
|
47
|
+
every ``N`` rows (rounded up to a batch), so another connection sees them as they arrive; a
|
|
48
|
+
failure then rolls back only the open chunk (``WriteError.rows_committed`` says how many stay).
|
|
49
|
+
Tables of one run are written at the same time (``shape generate --to`` in parallel, ``shape emit``
|
|
50
|
+
with every table open for the whole stream): each write has its own connection and transaction, and
|
|
51
|
+
DuckDB lets transactions on different tables of one file proceed side by side.
|
|
52
|
+
|
|
53
|
+
A database file that another process holds locked ends the write with exit code 2 and DuckDB's own
|
|
54
|
+
message. DuckDB is an optional dependency (``pip install 'sqllocks-shape-databases[duckdb]'``,
|
|
55
|
+
``'sqllocks-shape[duckdb]'``): it is imported when a write starts.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
from __future__ import annotations
|
|
59
|
+
|
|
60
|
+
import logging
|
|
61
|
+
import threading
|
|
62
|
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
|
63
|
+
from typing import Any
|
|
64
|
+
|
|
65
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
66
|
+
import pyarrow.types as pat # type: ignore[import-untyped]
|
|
67
|
+
|
|
68
|
+
from shape.errors import ShapeError
|
|
69
|
+
|
|
70
|
+
from . import _sql
|
|
71
|
+
from ._base import as_int, as_text, one_of, parse_uri
|
|
72
|
+
from .errors import WriteError
|
|
73
|
+
|
|
74
|
+
log = logging.getLogger("shape_databases")
|
|
75
|
+
|
|
76
|
+
WRITE_MODES = (*_sql.WRITE_MODES, "upsert")
|
|
77
|
+
DEFAULT_SCHEMA = "main"
|
|
78
|
+
_VIEW = "shape_batch"
|
|
79
|
+
_SCHEMA_LOCK = threading.Lock() # two transactions creating the same schema conflict in DuckDB
|
|
80
|
+
# A last connection closing while another opens can race DuckDB's file-handle cache.
|
|
81
|
+
# Serialize only open/close calls; independent table transactions still run in parallel.
|
|
82
|
+
_CONNECTION_LOCK = threading.Lock()
|
|
83
|
+
_INTS = {
|
|
84
|
+
(True, 8): "TINYINT",
|
|
85
|
+
(True, 16): "SMALLINT",
|
|
86
|
+
(True, 32): "INTEGER",
|
|
87
|
+
(True, 64): "BIGINT",
|
|
88
|
+
(False, 8): "UTINYINT",
|
|
89
|
+
(False, 16): "USMALLINT",
|
|
90
|
+
(False, 32): "UINTEGER",
|
|
91
|
+
(False, 64): "UBIGINT",
|
|
92
|
+
}
|
|
93
|
+
_TIMESTAMPS = {"s": "TIMESTAMP_S", "ms": "TIMESTAMP_MS", "us": "TIMESTAMP", "ns": "TIMESTAMP_NS"}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _quote(name: str) -> str:
|
|
97
|
+
return '"' + name.replace('"', '""') + '"'
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _check_name(name: Any, kind: str) -> str:
|
|
101
|
+
if not isinstance(name, str) or not name:
|
|
102
|
+
raise ShapeError(f"{kind} name must be a non-empty string")
|
|
103
|
+
if "\x00" in name:
|
|
104
|
+
raise ShapeError(f"{kind} name {name!r} contains a NUL character")
|
|
105
|
+
return name
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _qualified(schema_name: str, table: str) -> str:
|
|
109
|
+
return f"{_quote(schema_name)}.{_quote(table)}"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def duckdb_type(field: pa.Field, meta: Mapping[str, Any]) -> str:
|
|
113
|
+
"""The DuckDB column type that holds Arrow ``field`` (see the module docstring)."""
|
|
114
|
+
kind = field.type
|
|
115
|
+
if pat.is_dictionary(kind):
|
|
116
|
+
kind = kind.value_type
|
|
117
|
+
if pat.is_boolean(kind):
|
|
118
|
+
return "BOOLEAN"
|
|
119
|
+
if pat.is_integer(kind):
|
|
120
|
+
return _INTS[(bool(pat.is_signed_integer(kind)), kind.bit_width)]
|
|
121
|
+
if pat.is_floating(kind):
|
|
122
|
+
return "DOUBLE" if kind.bit_width == 64 else "FLOAT"
|
|
123
|
+
if pat.is_decimal(kind):
|
|
124
|
+
if kind.precision > 38:
|
|
125
|
+
raise ShapeError(f"column {field.name!r}: DuckDB decimals hold at most 38 digits")
|
|
126
|
+
return f"DECIMAL({kind.precision},{kind.scale})"
|
|
127
|
+
if pat.is_timestamp(kind):
|
|
128
|
+
return "TIMESTAMPTZ" if kind.tz is not None else _TIMESTAMPS[kind.unit]
|
|
129
|
+
if pat.is_date(kind):
|
|
130
|
+
return "DATE"
|
|
131
|
+
if pat.is_time(kind):
|
|
132
|
+
return "TIME"
|
|
133
|
+
if pat.is_binary(kind) or pat.is_large_binary(kind) or pat.is_fixed_size_binary(kind):
|
|
134
|
+
return "BLOB"
|
|
135
|
+
if pat.is_string(kind) or pat.is_large_string(kind):
|
|
136
|
+
return "UUID" if str(meta.get("type")) == "uuid" else "VARCHAR"
|
|
137
|
+
raise ShapeError(
|
|
138
|
+
f"column {field.name!r} has type {kind}, which a DuckDB column written by Shape cannot "
|
|
139
|
+
"hold: convert it (for example to a JSON string) before writing"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def create_table_sql(
|
|
144
|
+
schema_name: str,
|
|
145
|
+
table: str,
|
|
146
|
+
schema: pa.Schema,
|
|
147
|
+
*,
|
|
148
|
+
columns: Mapping[str, Mapping[str, Any]] | None = None,
|
|
149
|
+
primary_key: Sequence[str] = (),
|
|
150
|
+
) -> str:
|
|
151
|
+
columns = columns or {}
|
|
152
|
+
unknown = [c for c in primary_key if c not in schema.names]
|
|
153
|
+
if unknown:
|
|
154
|
+
raise ShapeError(f"primary key column {unknown[0]!r} is not a column of {table!r}")
|
|
155
|
+
lines = []
|
|
156
|
+
for field in schema:
|
|
157
|
+
meta = columns.get(field.name, {})
|
|
158
|
+
required = field.name in primary_key or not bool(meta.get("nullable", True))
|
|
159
|
+
lines.append(
|
|
160
|
+
f" {_quote(_check_name(field.name, 'column'))} {duckdb_type(field, meta)}"
|
|
161
|
+
f"{' NOT NULL' if required else ''}"
|
|
162
|
+
)
|
|
163
|
+
if primary_key:
|
|
164
|
+
lines.append(f" PRIMARY KEY ({', '.join(_quote(c) for c in primary_key)})")
|
|
165
|
+
return f"CREATE TABLE {_qualified(schema_name, table)} (\n" + ",\n".join(lines) + "\n)"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def normalize(batch: pa.RecordBatch) -> pa.RecordBatch:
|
|
169
|
+
"""Dictionary columns decoded, nanosecond times cut to microseconds, half floats widened, and
|
|
170
|
+
zoned timestamps in microseconds: the Arrow types DuckDB's columns above take."""
|
|
171
|
+
arrays = []
|
|
172
|
+
changed = False
|
|
173
|
+
for column in batch.columns:
|
|
174
|
+
kind = column.type
|
|
175
|
+
if pat.is_dictionary(kind):
|
|
176
|
+
column, kind = column.cast(kind.value_type), kind.value_type
|
|
177
|
+
changed = True
|
|
178
|
+
if pat.is_time(kind) and kind.bit_width == 64 and kind.unit == "ns":
|
|
179
|
+
column, changed = column.cast(pa.time64("us"), safe=False), True
|
|
180
|
+
elif pat.is_float16(kind):
|
|
181
|
+
column, changed = column.cast(pa.float32()), True
|
|
182
|
+
elif pat.is_timestamp(kind) and kind.tz is not None and kind.unit != "us":
|
|
183
|
+
column, changed = column.cast(pa.timestamp("us", kind.tz), safe=False), True
|
|
184
|
+
arrays.append(column)
|
|
185
|
+
return pa.RecordBatch.from_arrays(arrays, names=batch.schema.names) if changed else batch
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _file_path(uri: str, allowed: Mapping[str, Any]) -> tuple[str, dict[str, Any]]:
|
|
189
|
+
target = parse_uri(uri, ("duckdb",), allowed)
|
|
190
|
+
if target.host or target.port or target.user:
|
|
191
|
+
raise ShapeError(
|
|
192
|
+
"a DuckDB URI is a file path, duckdb:///PATH.duckdb (or duckdb:////absolute/path): "
|
|
193
|
+
"it has no host, port or user"
|
|
194
|
+
)
|
|
195
|
+
path = target.database
|
|
196
|
+
if not path:
|
|
197
|
+
raise ShapeError("give the database file: duckdb:///PATH.duckdb")
|
|
198
|
+
if path == ":memory:" or path.startswith(":memory:"):
|
|
199
|
+
raise ShapeError(
|
|
200
|
+
"duckdb:///:memory: would lose the data when the write ends: give a file, "
|
|
201
|
+
"duckdb:///PATH.duckdb"
|
|
202
|
+
)
|
|
203
|
+
return path, target.params
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _driver() -> Any:
|
|
207
|
+
try:
|
|
208
|
+
import duckdb
|
|
209
|
+
except ImportError as exc:
|
|
210
|
+
raise ShapeError(
|
|
211
|
+
"the duckdb sink needs DuckDB: pip install 'sqllocks-shape-databases[duckdb]' "
|
|
212
|
+
"(or 'sqllocks-shape[duckdb]')"
|
|
213
|
+
) from exc
|
|
214
|
+
return duckdb
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class DuckDbSink:
|
|
218
|
+
"""Rows into a local DuckDB file; see the module docstring."""
|
|
219
|
+
|
|
220
|
+
name = "duckdb"
|
|
221
|
+
schemes = ("duckdb",)
|
|
222
|
+
uri_params: Mapping[str, Any] = {
|
|
223
|
+
"schema": as_text,
|
|
224
|
+
"write_mode": one_of(*WRITE_MODES),
|
|
225
|
+
"commit_rows": as_int,
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
def write(self, uri: str, table: str, batches: Iterable[pa.RecordBatch], **options: Any) -> int:
|
|
229
|
+
path, query = _file_path(uri, self.uri_params)
|
|
230
|
+
mode = options.get("write_mode", query.get("write_mode", "create"))
|
|
231
|
+
if mode not in WRITE_MODES:
|
|
232
|
+
raise ShapeError(f"unknown write mode {mode!r}; choose one of {', '.join(WRITE_MODES)}")
|
|
233
|
+
schema_name = options.get("schema_name")
|
|
234
|
+
schema_name = _check_name(
|
|
235
|
+
query.get("schema", DEFAULT_SCHEMA) if schema_name is None else schema_name, "schema"
|
|
236
|
+
)
|
|
237
|
+
_check_name(table, "table")
|
|
238
|
+
commit_rows = _sql.positive_int(
|
|
239
|
+
options.get("commit_rows", query.get("commit_rows")), "commit_rows", optional=True
|
|
240
|
+
)
|
|
241
|
+
key = list(options.get("primary_key") or [])
|
|
242
|
+
for name in key:
|
|
243
|
+
_check_name(name, "column")
|
|
244
|
+
if mode == "upsert" and not key:
|
|
245
|
+
raise ShapeError(f"upsert needs a primary key on {table}")
|
|
246
|
+
meta: Mapping[str, Mapping[str, Any]] = options.get("columns") or {}
|
|
247
|
+
given = options.get("schema")
|
|
248
|
+
if given is not None and not isinstance(given, pa.Schema):
|
|
249
|
+
raise ShapeError("schema must be a pyarrow Schema")
|
|
250
|
+
it = iter(batches)
|
|
251
|
+
first = next(it, None)
|
|
252
|
+
use_schema = first.schema if first is not None else given
|
|
253
|
+
if use_schema is None:
|
|
254
|
+
raise ShapeError(
|
|
255
|
+
f"table {table!r} has no batches and no schema: pass schema= to create it empty"
|
|
256
|
+
)
|
|
257
|
+
duckdb = _driver()
|
|
258
|
+
return self._write(
|
|
259
|
+
duckdb, path, schema_name, table, mode, use_schema, first, it, meta, key, commit_rows
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
def _write(
|
|
263
|
+
self,
|
|
264
|
+
duckdb: Any,
|
|
265
|
+
path: str,
|
|
266
|
+
schema_name: str,
|
|
267
|
+
table: str,
|
|
268
|
+
mode: str,
|
|
269
|
+
schema: pa.Schema,
|
|
270
|
+
first: pa.RecordBatch | None,
|
|
271
|
+
rest: Iterator[pa.RecordBatch],
|
|
272
|
+
meta: Mapping[str, Mapping[str, Any]],
|
|
273
|
+
key: list[str],
|
|
274
|
+
commit_rows: int | None,
|
|
275
|
+
) -> int:
|
|
276
|
+
try:
|
|
277
|
+
with _CONNECTION_LOCK:
|
|
278
|
+
con = duckdb.connect(path)
|
|
279
|
+
except duckdb.Error as exc:
|
|
280
|
+
raise ShapeError(f"cannot open the DuckDB database {path}: {exc}") from None
|
|
281
|
+
committed = [0]
|
|
282
|
+
failure: WriteError | None = None
|
|
283
|
+
try:
|
|
284
|
+
try:
|
|
285
|
+
if schema_name != DEFAULT_SCHEMA: # its own committed step, never inside a table's
|
|
286
|
+
with _SCHEMA_LOCK:
|
|
287
|
+
con.execute(f"CREATE SCHEMA IF NOT EXISTS {_quote(schema_name)}")
|
|
288
|
+
con.begin()
|
|
289
|
+
self._prepare(con, schema_name, table, mode, schema, meta, key)
|
|
290
|
+
if commit_rows:
|
|
291
|
+
con.commit() # the table is there for readers before the first rows
|
|
292
|
+
con.begin()
|
|
293
|
+
rows = self._load(
|
|
294
|
+
con, schema_name, table, mode, first, rest, schema, commit_rows, committed
|
|
295
|
+
)
|
|
296
|
+
con.commit()
|
|
297
|
+
log.debug("wrote %d rows to %s in %s", rows, table, path)
|
|
298
|
+
return rows
|
|
299
|
+
except ShapeError:
|
|
300
|
+
self._rollback(con)
|
|
301
|
+
raise
|
|
302
|
+
except Exception as exc:
|
|
303
|
+
self._rollback(con)
|
|
304
|
+
kept = (
|
|
305
|
+
f"; {committed[0]} rows were committed before it failed" if committed[0] else ""
|
|
306
|
+
)
|
|
307
|
+
failure = WriteError(
|
|
308
|
+
f"writing {_qualified(schema_name, table)} in {path} failed "
|
|
309
|
+
f"({type(exc).__name__}): {exc}{kept}",
|
|
310
|
+
committed[0],
|
|
311
|
+
)
|
|
312
|
+
finally:
|
|
313
|
+
with _CONNECTION_LOCK:
|
|
314
|
+
con.close()
|
|
315
|
+
raise failure
|
|
316
|
+
|
|
317
|
+
@staticmethod
|
|
318
|
+
def _rollback(con: Any) -> None:
|
|
319
|
+
try:
|
|
320
|
+
con.rollback()
|
|
321
|
+
except Exception: # noqa: S110 # nosec B110 - no transaction left to undo
|
|
322
|
+
pass
|
|
323
|
+
|
|
324
|
+
def _exists(self, con: Any, schema_name: str, table: str) -> bool:
|
|
325
|
+
row = con.execute(
|
|
326
|
+
"SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",
|
|
327
|
+
[schema_name, table],
|
|
328
|
+
).fetchone()
|
|
329
|
+
return row is not None
|
|
330
|
+
|
|
331
|
+
def _prepare(
|
|
332
|
+
self,
|
|
333
|
+
con: Any,
|
|
334
|
+
schema_name: str,
|
|
335
|
+
table: str,
|
|
336
|
+
mode: str,
|
|
337
|
+
schema: pa.Schema,
|
|
338
|
+
meta: Mapping[str, Mapping[str, Any]],
|
|
339
|
+
key: Sequence[str],
|
|
340
|
+
) -> None:
|
|
341
|
+
name = _qualified(schema_name, table)
|
|
342
|
+
exists = self._exists(con, schema_name, table)
|
|
343
|
+
if mode == "create" and exists:
|
|
344
|
+
raise ShapeError(
|
|
345
|
+
f"table {table} already exists; set write_mode to append, truncate, replace or "
|
|
346
|
+
"upsert to write into it"
|
|
347
|
+
)
|
|
348
|
+
if mode == "replace" and exists:
|
|
349
|
+
con.execute(f"DROP TABLE {name}")
|
|
350
|
+
exists = False
|
|
351
|
+
elif mode == "truncate" and exists:
|
|
352
|
+
con.execute(f"DELETE FROM {name}") # nosec B608 - quoted names only
|
|
353
|
+
if not exists:
|
|
354
|
+
con.execute(create_table_sql(schema_name, table, schema, columns=meta, primary_key=key))
|
|
355
|
+
|
|
356
|
+
def _load(
|
|
357
|
+
self,
|
|
358
|
+
con: Any,
|
|
359
|
+
schema_name: str,
|
|
360
|
+
table: str,
|
|
361
|
+
mode: str,
|
|
362
|
+
first: pa.RecordBatch | None,
|
|
363
|
+
rest: Iterator[pa.RecordBatch],
|
|
364
|
+
schema: pa.Schema,
|
|
365
|
+
commit_rows: int | None,
|
|
366
|
+
committed: list[int],
|
|
367
|
+
) -> int:
|
|
368
|
+
if first is None:
|
|
369
|
+
return 0
|
|
370
|
+
names = list(schema.names)
|
|
371
|
+
columns = ", ".join(_quote(n) for n in names)
|
|
372
|
+
verb = "INSERT OR REPLACE INTO" if mode == "upsert" else "INSERT INTO"
|
|
373
|
+
sql = ( # every name is quoted; the rows come from the registered Arrow table
|
|
374
|
+
f"{verb} {_qualified(schema_name, table)} ({columns}) " # nosec B608
|
|
375
|
+
f"SELECT {columns} FROM {_VIEW}"
|
|
376
|
+
)
|
|
377
|
+
rows = 0
|
|
378
|
+
pending = 0
|
|
379
|
+
|
|
380
|
+
def batches() -> Iterator[pa.RecordBatch]:
|
|
381
|
+
yield first
|
|
382
|
+
yield from rest
|
|
383
|
+
|
|
384
|
+
for raw in batches():
|
|
385
|
+
if list(raw.schema.names) != names:
|
|
386
|
+
raise ShapeError(
|
|
387
|
+
f"a batch for {table!r} has columns {list(raw.schema.names)} but the first "
|
|
388
|
+
f"one had {names}"
|
|
389
|
+
)
|
|
390
|
+
if raw.num_rows == 0:
|
|
391
|
+
continue
|
|
392
|
+
con.register(_VIEW, pa.Table.from_batches([normalize(raw)]))
|
|
393
|
+
try:
|
|
394
|
+
con.execute(sql)
|
|
395
|
+
finally:
|
|
396
|
+
con.unregister(_VIEW)
|
|
397
|
+
rows += raw.num_rows
|
|
398
|
+
pending += raw.num_rows
|
|
399
|
+
if commit_rows and pending >= commit_rows:
|
|
400
|
+
con.commit()
|
|
401
|
+
con.begin()
|
|
402
|
+
pending = 0
|
|
403
|
+
committed[0] = rows
|
|
404
|
+
return rows
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Errors of the database sinks.
|
|
2
|
+
|
|
3
|
+
Nothing here ever carries a password, token or connection secret: messages are built from
|
|
4
|
+
names and counts, and anything that came from a database driver is scrubbed first (see
|
|
5
|
+
:func:`shape_databases._auth.scrub`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from shape.errors import ShapeError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class WriteError(ShapeError):
|
|
14
|
+
"""A write failed. ``rows_committed`` is how many rows a ``commit_rows`` write had already
|
|
15
|
+
committed (and so are visible to readers) when it stopped; it is 0 for a write that rolled
|
|
16
|
+
back completely."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, message: str, rows_committed: int = 0) -> None:
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
self.rows_committed = rows_committed
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CredentialError(ShapeError):
|
|
24
|
+
"""No usable password or credential. The message names the source, never the value."""
|
shape_databases/mysql.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""MySQL sink: ``mysql://user@host:3306/database?ssl_ca=/path/ca.pem``.
|
|
2
|
+
|
|
3
|
+
Client: PyMySQL (pure Python; no ``libmysqlclient`` to install). Rows are sent with
|
|
4
|
+
``executemany("INSERT INTO ... VALUES (%s, ...)")``, ``batch_size`` rows per call, which PyMySQL
|
|
5
|
+
turns into multi-row ``INSERT`` statements with every value bound as a parameter. ``LOAD DATA
|
|
6
|
+
LOCAL INFILE`` is not used: servers commonly disable it (``local_infile=0``) and enabling it on
|
|
7
|
+
the client opens the connection to a server-driven file read, so it is neither the default nor
|
|
8
|
+
an option.
|
|
9
|
+
|
|
10
|
+
Transactions. MySQL commits implicitly at every DDL statement, so unlike PostgreSQL the table
|
|
11
|
+
creation cannot be rolled back with the rows. By default all rows of the table are one
|
|
12
|
+
transaction (committed at the end); on a failure the rows roll back and a table this call
|
|
13
|
+
created is dropped again. ``replace`` has already dropped the old table by then, and ``truncate``
|
|
14
|
+
(also DDL in MySQL) has already emptied it. With ``commit_rows=N`` the write commits every N rows
|
|
15
|
+
so readers see rows while a stream runs; a failure then keeps the committed rows and the table,
|
|
16
|
+
and :class:`WriteError` says how many (``rows_committed``).
|
|
17
|
+
|
|
18
|
+
TLS. A host that is not loopback (``localhost``, ``127.0.0.0/8``, ``::1``) is reached over TLS
|
|
19
|
+
with certificate and host name verification: the system CA store, or ``ssl_ca`` when given.
|
|
20
|
+
``ssl=false`` or ``ssl-mode=DISABLED`` in the URI is the explicit opt-out; ``ssl-mode=VERIFY_CA``
|
|
21
|
+
skips the host name check. Giving ``ssl_verify_cert`` / ``ssl_verify_identity`` hands the driver
|
|
22
|
+
its own options unchanged. A TLS failure names the host and the opt-out.
|
|
23
|
+
|
|
24
|
+
``schema_name`` is the MySQL database to write into (default: the one in the URI). NaN and
|
|
25
|
+
infinity, which MySQL cannot store, are written as NULL, as the ``sql`` sink's script does.
|
|
26
|
+
Options are those of the PostgreSQL sink (see :mod:`shape_databases.postgres`).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import importlib
|
|
32
|
+
import ssl
|
|
33
|
+
from collections.abc import Iterator
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
37
|
+
|
|
38
|
+
from shape.errors import ShapeError
|
|
39
|
+
|
|
40
|
+
from . import _sql
|
|
41
|
+
from ._base import (
|
|
42
|
+
DatabaseSink,
|
|
43
|
+
Plan,
|
|
44
|
+
as_bool,
|
|
45
|
+
as_int,
|
|
46
|
+
as_text,
|
|
47
|
+
chain_batches,
|
|
48
|
+
chunks,
|
|
49
|
+
is_loopback,
|
|
50
|
+
one_of,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
DEFAULT_CHARSET = "utf8mb4"
|
|
54
|
+
SSL_MODES = ("DISABLED", "VERIFY_CA", "VERIFY_IDENTITY")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _ssl_mode(value: str) -> str:
|
|
58
|
+
return one_of(*SSL_MODES)(value.upper())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class MySqlSink(DatabaseSink):
|
|
62
|
+
"""``RecordBatch``es for one table to a MySQL table with batched multi-row ``INSERT``."""
|
|
63
|
+
|
|
64
|
+
name = "mysql"
|
|
65
|
+
schemes = ("mysql",)
|
|
66
|
+
dialect = "mysql"
|
|
67
|
+
password_env = ("SHAPE_MYSQL_PASSWORD", "MYSQL_PWD")
|
|
68
|
+
uri_params = {
|
|
69
|
+
"ssl_ca": as_text,
|
|
70
|
+
"ssl_cert": as_text,
|
|
71
|
+
"ssl_key": as_text,
|
|
72
|
+
"ssl_verify_cert": as_bool,
|
|
73
|
+
"ssl_verify_identity": as_bool,
|
|
74
|
+
"ssl": as_bool,
|
|
75
|
+
"ssl-mode": _ssl_mode,
|
|
76
|
+
"charset": as_text,
|
|
77
|
+
"connect_timeout": as_int,
|
|
78
|
+
}
|
|
79
|
+
exists_sql = (
|
|
80
|
+
"SELECT 1 FROM information_schema.tables "
|
|
81
|
+
"WHERE table_schema = COALESCE(%s, DATABASE()) AND table_name = %s"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def create_schema_sql(self, schema_name: str) -> str:
|
|
85
|
+
# In MySQL a schema is a database (created, like a PostgreSQL schema, when missing).
|
|
86
|
+
return f"CREATE DATABASE IF NOT EXISTS {_sql.quote(schema_name, self.dialect)}"
|
|
87
|
+
|
|
88
|
+
def connect_params(self, plan: Plan) -> dict[str, Any]:
|
|
89
|
+
t = plan.target
|
|
90
|
+
params: dict[str, Any] = dict(t.params)
|
|
91
|
+
for key, value in (("host", t.host), ("port", t.port), ("user", t.user)):
|
|
92
|
+
if value is not None:
|
|
93
|
+
params[key] = value
|
|
94
|
+
if t.database:
|
|
95
|
+
params["database"] = t.database
|
|
96
|
+
params.setdefault("charset", DEFAULT_CHARSET)
|
|
97
|
+
self._apply_tls(plan, params)
|
|
98
|
+
params["local_infile"] = False
|
|
99
|
+
params["autocommit"] = False
|
|
100
|
+
if plan.secret is not None:
|
|
101
|
+
params["password"] = plan.secret.reveal()
|
|
102
|
+
return params
|
|
103
|
+
|
|
104
|
+
def _tls_off(self, plan: Plan) -> bool:
|
|
105
|
+
params = plan.target.params
|
|
106
|
+
return params.get("ssl") is False or params.get("ssl-mode") == "DISABLED"
|
|
107
|
+
|
|
108
|
+
def tls_opt_out(self, plan: Plan) -> str | None:
|
|
109
|
+
t = plan.target
|
|
110
|
+
# The URI chose the TLS settings itself (including the driver's own ssl_* options).
|
|
111
|
+
if is_loopback(t.host) or self._tls_off(plan) or self._tls_chosen(plan):
|
|
112
|
+
return None
|
|
113
|
+
return "ssl=false (or ssl-mode=DISABLED)"
|
|
114
|
+
|
|
115
|
+
@staticmethod
|
|
116
|
+
def _tls_chosen(plan: Plan) -> bool:
|
|
117
|
+
params = plan.target.params
|
|
118
|
+
return "ssl_verify_cert" in params or "ssl_verify_identity" in params
|
|
119
|
+
|
|
120
|
+
def _apply_tls(self, plan: Plan, params: dict[str, Any]) -> None:
|
|
121
|
+
"""Translate the URI's TLS keys; verified TLS is the default for a non-loopback host."""
|
|
122
|
+
for key in ("ssl", "ssl-mode"):
|
|
123
|
+
params.pop(key, None)
|
|
124
|
+
if self._tls_off(plan):
|
|
125
|
+
params["ssl_disabled"] = True
|
|
126
|
+
return
|
|
127
|
+
if is_loopback(plan.target.host) or self._tls_chosen(plan):
|
|
128
|
+
return # today's behaviour: the driver's options as the URI gave them
|
|
129
|
+
ca = params.pop("ssl_ca", None)
|
|
130
|
+
cert = params.pop("ssl_cert", None)
|
|
131
|
+
key = params.pop("ssl_key", None)
|
|
132
|
+
try:
|
|
133
|
+
# check_hostname and CERT_REQUIRED are on in a default context; without ssl_ca the
|
|
134
|
+
# system CA store is the trust store. (PyMySQL's own ``ssl`` dict would skip
|
|
135
|
+
# verification when it is given no CA, so a context is passed instead.)
|
|
136
|
+
ctx = ssl.create_default_context(cafile=ca)
|
|
137
|
+
if plan.target.params.get("ssl-mode") == "VERIFY_CA":
|
|
138
|
+
ctx.check_hostname = False
|
|
139
|
+
if cert:
|
|
140
|
+
ctx.load_cert_chain(cert, key)
|
|
141
|
+
except (OSError, ssl.SSLError) as exc:
|
|
142
|
+
raise ShapeError(f"cannot set up TLS for {plan.target.label}: {exc}") from None
|
|
143
|
+
params["ssl"] = ctx
|
|
144
|
+
|
|
145
|
+
def default_connect(self, **params: Any) -> Any:
|
|
146
|
+
try:
|
|
147
|
+
pymysql = importlib.import_module("pymysql")
|
|
148
|
+
except ImportError:
|
|
149
|
+
raise ShapeError(
|
|
150
|
+
"the mysql sink needs PyMySQL: pip install 'sqllocks-shape[mysql]'"
|
|
151
|
+
) from None
|
|
152
|
+
return pymysql.connect(**params)
|
|
153
|
+
|
|
154
|
+
def ddl_is_transactional(self) -> bool:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
def load(
|
|
158
|
+
self,
|
|
159
|
+
conn: Any,
|
|
160
|
+
qualified: str,
|
|
161
|
+
plan: Plan,
|
|
162
|
+
first: pa.RecordBatch | None,
|
|
163
|
+
rest: Iterator[pa.RecordBatch],
|
|
164
|
+
progress: list[int],
|
|
165
|
+
) -> int:
|
|
166
|
+
if first is None:
|
|
167
|
+
return 0
|
|
168
|
+
names = first.schema.names
|
|
169
|
+
columns = ", ".join(_sql.quote(n, self.dialect) for n in names)
|
|
170
|
+
marks = ", ".join(["%s"] * len(names))
|
|
171
|
+
# Identifiers only, each checked and quoted; every value is a bound parameter.
|
|
172
|
+
statement = f"INSERT INTO {qualified} ({columns}) VALUES ({marks})" # nosec B608
|
|
173
|
+
converters = _sql.converters_for(first.schema, self.dialect)
|
|
174
|
+
step = min(plan.batch_size, plan.commit_rows or plan.batch_size)
|
|
175
|
+
|
|
176
|
+
def rows() -> Iterator[tuple[Any, ...]]:
|
|
177
|
+
for batch in chain_batches(first, rest):
|
|
178
|
+
_sql.check_batch(first.schema, batch, plan.table)
|
|
179
|
+
yield from _sql.row_iterator(batch, self.dialect, converters)
|
|
180
|
+
|
|
181
|
+
total = 0
|
|
182
|
+
since_commit = 0
|
|
183
|
+
cur = conn.cursor()
|
|
184
|
+
try:
|
|
185
|
+
for group in chunks(rows(), step):
|
|
186
|
+
piece = list(group)
|
|
187
|
+
cur.executemany(statement, piece)
|
|
188
|
+
total += len(piece)
|
|
189
|
+
since_commit += len(piece)
|
|
190
|
+
if plan.commit_rows and since_commit >= plan.commit_rows:
|
|
191
|
+
conn.commit()
|
|
192
|
+
progress[0] = total
|
|
193
|
+
since_commit = 0
|
|
194
|
+
finally:
|
|
195
|
+
cur.close()
|
|
196
|
+
if plan.commit_rows and since_commit:
|
|
197
|
+
conn.commit()
|
|
198
|
+
progress[0] = total
|
|
199
|
+
return total
|