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,314 @@
|
|
|
1
|
+
"""Databricks sink: ``databricks://<host>/<http_path>?catalog=CAT&schema=SCH``.
|
|
2
|
+
|
|
3
|
+
Writes Delta tables in Unity Catalog through a SQL warehouse, with ``databricks-sql-connector``
|
|
4
|
+
(``pip install 'sqllocks-shape-databases[databricks]'``), loaded only when a connection opens.
|
|
5
|
+
``<http_path>`` is the warehouse's HTTP path without its leading slash, for example
|
|
6
|
+
``databricks://adb-123.4.azuredatabricks.net/sql/1.0/warehouses/abc123?catalog=main&schema=demo``.
|
|
7
|
+
|
|
8
|
+
Rows go in as multi-row ``INSERT`` statements of ``batch_size`` rows (default 1,000), every value
|
|
9
|
+
a bound parameter (``?`` markers; the connector's native parameters). Dates, timestamps and
|
|
10
|
+
binary values are bound as text and converted in the statement (``CAST(? AS DATE)``,
|
|
11
|
+
``CAST(? AS TIMESTAMP_NTZ)``, ``CAST(? AS TIMESTAMP)`` from UTC, ``UNHEX(?)``), so a value
|
|
12
|
+
reaches the table exactly, whatever the session time zone.
|
|
13
|
+
|
|
14
|
+
Transactions. A SQL warehouse commits every statement; there is no rollback. ``commit_rows`` is
|
|
15
|
+
accepted and is the batch boundary: every statement is already a commit, so ``commit_rows`` does
|
|
16
|
+
not shrink statements (``batch_size`` does); it makes a statement carry no rows from the next
|
|
17
|
+
input batch (rows become visible batch by batch while a stream runs), and a failure then keeps
|
|
18
|
+
the table and the rows already inserted, with :class:`~shape_databases.WriteError` saying how
|
|
19
|
+
many (``rows_committed``).
|
|
20
|
+
Without it, a failure drops a table this call created, and leaves in a table that already
|
|
21
|
+
existed (``append``) the rows of the statements that had run, which the error also counts.
|
|
22
|
+
``replace`` has already dropped the old table, and ``truncate`` has already emptied it.
|
|
23
|
+
|
|
24
|
+
Names. Unity Catalog stores table and schema names in lower case, so a name with capitals, a
|
|
25
|
+
space, ``.``, ``/`` or a backtick is refused before any connection, as is a column name with
|
|
26
|
+
a space or one of ``,;{}()=``, a tab or a newline (which Delta cannot hold), and any name over 255
|
|
27
|
+
characters. Column names are case-insensitive: two that differ only in case are refused.
|
|
28
|
+
|
|
29
|
+
Sign-in (a token is never accepted in the URI): a personal access token, the ``token`` option (a
|
|
30
|
+
reference or the value) or ``DATABRICKS_TOKEN``; or OAuth machine-to-machine, ``client_id`` (an
|
|
31
|
+
option, or in the URI) with ``client_secret`` (a reference or the value), exchanged at the
|
|
32
|
+
workspace's ``/oidc/v1/token`` endpoint for a token that lasts about an hour.
|
|
33
|
+
|
|
34
|
+
Options: ``write_mode``, ``schema_name``, ``table_prefix``, ``commit_rows``, ``columns``,
|
|
35
|
+
``primary_key``, ``schema`` (see :mod:`shape_databases.postgres`) and ``batch_size``.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import base64
|
|
41
|
+
import importlib
|
|
42
|
+
import json
|
|
43
|
+
import re
|
|
44
|
+
import urllib.error
|
|
45
|
+
import urllib.parse
|
|
46
|
+
import urllib.request
|
|
47
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
48
|
+
from typing import Any
|
|
49
|
+
|
|
50
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
51
|
+
import pyarrow.types as pat # type: ignore[import-untyped]
|
|
52
|
+
|
|
53
|
+
from shape.errors import ShapeError
|
|
54
|
+
|
|
55
|
+
from . import _cloud, _sql
|
|
56
|
+
from ._auth import Secret, _resolve_reference, resolve_password
|
|
57
|
+
from ._base import DatabaseSink, Plan, Target, as_text, chain_batches, chunks, parse_uri
|
|
58
|
+
from .errors import CredentialError
|
|
59
|
+
|
|
60
|
+
INSTALL = "pip install 'sqllocks-shape-databases[databricks]'"
|
|
61
|
+
_HOST = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$")
|
|
62
|
+
DEFAULT_BATCH_SIZE = 1000
|
|
63
|
+
Binding = tuple[str, Callable[[Any], Any] | None]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def binding(field: pa.Field) -> Binding:
|
|
67
|
+
"""The placeholder a column's value goes into and the conversion it needs first."""
|
|
68
|
+
t = field.type
|
|
69
|
+
if pat.is_timestamp(t):
|
|
70
|
+
if t.tz is None:
|
|
71
|
+
return "CAST(? AS TIMESTAMP_NTZ)", lambda v: None if v is None else v.isoformat(" ")
|
|
72
|
+
return "CAST(? AS TIMESTAMP)", lambda v: None if v is None else v.isoformat()
|
|
73
|
+
if pat.is_date(t):
|
|
74
|
+
return "CAST(? AS DATE)", lambda v: None if v is None else v.isoformat()
|
|
75
|
+
if pat.is_binary(t) or pat.is_large_binary(t) or pat.is_fixed_size_binary(t):
|
|
76
|
+
return "UNHEX(?)", lambda v: None if v is None else bytes(v).hex()
|
|
77
|
+
if pat.is_uint64(t):
|
|
78
|
+
return "CAST(? AS DECIMAL(20,0))", lambda v: None if v is None else str(v)
|
|
79
|
+
if _cloud.is_nested(t):
|
|
80
|
+
return "?", lambda v: None if v is None else _sql._json(v) # noqa: SLF001
|
|
81
|
+
return "?", None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def oauth_token(host: str, client_id: str, client_secret: str, *, opener: Any = None) -> str:
|
|
85
|
+
"""A workspace access token for a service principal (OAuth machine-to-machine)."""
|
|
86
|
+
if not _HOST.match(host):
|
|
87
|
+
raise ShapeError(f"not a usable Databricks host name: {host!r}")
|
|
88
|
+
basic = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
|
|
89
|
+
request = urllib.request.Request( # noqa: S310 - https only, host checked above
|
|
90
|
+
f"https://{host}/oidc/v1/token",
|
|
91
|
+
data=urllib.parse.urlencode(
|
|
92
|
+
{"grant_type": "client_credentials", "scope": "all-apis"}
|
|
93
|
+
).encode(),
|
|
94
|
+
headers={
|
|
95
|
+
"Authorization": f"Basic {basic}",
|
|
96
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
97
|
+
},
|
|
98
|
+
method="POST",
|
|
99
|
+
)
|
|
100
|
+
failure: CredentialError | None = None
|
|
101
|
+
try:
|
|
102
|
+
open_url = opener or urllib.request.urlopen # noqa: S310
|
|
103
|
+
with open_url(request, timeout=30) as response: # nosec B310
|
|
104
|
+
token = json.loads(response.read().decode("utf-8")).get("access_token")
|
|
105
|
+
if isinstance(token, str) and token:
|
|
106
|
+
return token
|
|
107
|
+
failure = CredentialError(f"the OAuth endpoint of {host} gave no access token")
|
|
108
|
+
except urllib.error.HTTPError as exc:
|
|
109
|
+
failure = CredentialError(f"OAuth sign-in to {host} was refused (HTTP {exc.code})")
|
|
110
|
+
except Exception as exc: # noqa: BLE001 - the text could echo what was sent
|
|
111
|
+
failure = CredentialError(f"OAuth sign-in to {host} failed ({type(exc).__name__})")
|
|
112
|
+
raise failure
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class _Session:
|
|
116
|
+
"""The connector's connection with the ``commit`` and ``rollback`` of DB-API: a warehouse
|
|
117
|
+
commits each statement, so both do nothing."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, conn: Any) -> None:
|
|
120
|
+
self._conn = conn
|
|
121
|
+
|
|
122
|
+
def cursor(self) -> Any:
|
|
123
|
+
return self._conn.cursor()
|
|
124
|
+
|
|
125
|
+
def commit(self) -> None:
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
def rollback(self) -> None:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
def close(self) -> None:
|
|
132
|
+
self._conn.close()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class DatabricksSink(DatabaseSink):
|
|
136
|
+
"""``RecordBatch``es for one table to a Delta table with batched, bound ``INSERT``."""
|
|
137
|
+
|
|
138
|
+
name = "databricks"
|
|
139
|
+
schemes = ("databricks",)
|
|
140
|
+
dialect = "databricks"
|
|
141
|
+
password_env = ("DATABRICKS_TOKEN",)
|
|
142
|
+
uri_params = {"catalog": as_text, "schema": as_text, "client_id": as_text}
|
|
143
|
+
exists_sql = (
|
|
144
|
+
"SELECT 1 FROM information_schema.tables "
|
|
145
|
+
"WHERE table_schema = COALESCE(?, current_schema()) AND table_name = ?"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# -- plan --------------------------------------------------------------------------------
|
|
149
|
+
def parse_target(self, uri: str) -> Target:
|
|
150
|
+
target = parse_uri(uri, self.schemes, self.uri_params)
|
|
151
|
+
if not target.host or not _HOST.match(target.host):
|
|
152
|
+
raise ShapeError(
|
|
153
|
+
"the destination needs a workspace host: databricks://<host>/<http_path>"
|
|
154
|
+
)
|
|
155
|
+
if target.user or target.port:
|
|
156
|
+
raise ShapeError(
|
|
157
|
+
"the destination must be databricks://<host>/<http_path>: no user and no port "
|
|
158
|
+
"(sign in with token or client_id and client_secret)"
|
|
159
|
+
)
|
|
160
|
+
path = (target.database or "").strip("/")
|
|
161
|
+
if not path:
|
|
162
|
+
raise ShapeError("the destination needs the warehouse's HTTP path after the host")
|
|
163
|
+
params = dict(target.params)
|
|
164
|
+
params["http_path"] = "/" + path
|
|
165
|
+
for key, kind in (("catalog", "catalog"), ("schema", "schema")):
|
|
166
|
+
if key in params:
|
|
167
|
+
_sql.check_identifier(params[key], kind, self.dialect)
|
|
168
|
+
return Target(target.host, None, None, path, params)
|
|
169
|
+
|
|
170
|
+
def resolve_auth(self, options: Mapping[str, Any]) -> tuple[Secret | None, dict[str, Any]]:
|
|
171
|
+
token = options.get("token")
|
|
172
|
+
client_secret = options.get("client_secret")
|
|
173
|
+
if token is not None and client_secret is not None:
|
|
174
|
+
raise CredentialError("give a token or client_id and client_secret, not both")
|
|
175
|
+
if client_secret is not None:
|
|
176
|
+
if not isinstance(client_secret, str) or not client_secret:
|
|
177
|
+
raise CredentialError("client_secret must be a non-empty string or a reference")
|
|
178
|
+
return None, {
|
|
179
|
+
"client_secret": Secret(_resolve_reference(client_secret) or client_secret)
|
|
180
|
+
}
|
|
181
|
+
given: dict[str, Any] = {"password": token} if token is not None else {}
|
|
182
|
+
return resolve_password(given, self.password_env), {}
|
|
183
|
+
|
|
184
|
+
def plan(self, uri: str, table: str, options: Mapping[str, Any]) -> Plan:
|
|
185
|
+
plan = super().plan(uri, table, options)
|
|
186
|
+
client_id = plan.options.get("client_id") or plan.target.params.get("client_id")
|
|
187
|
+
if "client_secret" in plan.auth and not client_id:
|
|
188
|
+
raise CredentialError("client_secret needs a client_id")
|
|
189
|
+
if client_id and "client_secret" not in plan.auth:
|
|
190
|
+
raise CredentialError("client_id needs a client_secret (a reference or the value)")
|
|
191
|
+
if client_id:
|
|
192
|
+
plan.target.params["client_id"] = str(client_id)
|
|
193
|
+
# the default batch size of this sink, not the MySQL one
|
|
194
|
+
plan.batch_size = int(
|
|
195
|
+
_sql.positive_int(options.get("batch_size", DEFAULT_BATCH_SIZE), "batch_size") or 0
|
|
196
|
+
)
|
|
197
|
+
return plan
|
|
198
|
+
|
|
199
|
+
def check_schema(self, schema: pa.Schema, plan: Plan) -> None:
|
|
200
|
+
_cloud.check_types(schema, self.dialect, plan.columns, plan.primary_key)
|
|
201
|
+
|
|
202
|
+
def create_table_sql(self, plan: Plan, schema: pa.Schema, first: pa.RecordBatch | None) -> str:
|
|
203
|
+
qualified = _sql.qualified(plan.schema_name, plan.table, self.dialect)
|
|
204
|
+
return _cloud.create_table_sql(
|
|
205
|
+
qualified, schema, self.dialect, plan.columns, plan.primary_key
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
# -- connection --------------------------------------------------------------------------
|
|
209
|
+
def connect_params(self, plan: Plan) -> dict[str, Any]:
|
|
210
|
+
t = plan.target
|
|
211
|
+
params: dict[str, Any] = {"server_hostname": t.host, "http_path": t.params["http_path"]}
|
|
212
|
+
for key in ("catalog", "schema"):
|
|
213
|
+
if key in t.params:
|
|
214
|
+
params[key] = t.params[key]
|
|
215
|
+
if plan.secret is not None:
|
|
216
|
+
params["access_token"] = plan.secret.reveal()
|
|
217
|
+
if "client_secret" in plan.auth:
|
|
218
|
+
params["client_id"] = t.params["client_id"]
|
|
219
|
+
params["client_secret"] = plan.auth["client_secret"].reveal()
|
|
220
|
+
return params
|
|
221
|
+
|
|
222
|
+
def default_connect(self, **params: Any) -> Any:
|
|
223
|
+
try:
|
|
224
|
+
dbsql = importlib.import_module("databricks.sql")
|
|
225
|
+
except ImportError:
|
|
226
|
+
raise ShapeError(
|
|
227
|
+
f"the databricks sink needs databricks-sql-connector: {INSTALL}"
|
|
228
|
+
) from None
|
|
229
|
+
client_secret = params.pop("client_secret", None)
|
|
230
|
+
client_id = params.pop("client_id", None)
|
|
231
|
+
if client_secret is not None:
|
|
232
|
+
params["access_token"] = oauth_token(
|
|
233
|
+
params["server_hostname"], client_id, client_secret
|
|
234
|
+
)
|
|
235
|
+
elif not params.get("access_token"):
|
|
236
|
+
raise CredentialError(
|
|
237
|
+
"no Databricks credentials: give token, or client_id and client_secret, "
|
|
238
|
+
"or set DATABRICKS_TOKEN"
|
|
239
|
+
)
|
|
240
|
+
return _Session(dbsql.connect(**params))
|
|
241
|
+
|
|
242
|
+
def ddl_is_transactional(self) -> bool:
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
def _exists(self, conn: Any, plan: Plan) -> bool:
|
|
246
|
+
cur = conn.cursor()
|
|
247
|
+
try:
|
|
248
|
+
cur.execute(self.exists_sql, [plan.schema_name, plan.table])
|
|
249
|
+
return bool(cur.fetchone() is not None)
|
|
250
|
+
finally:
|
|
251
|
+
cur.close()
|
|
252
|
+
|
|
253
|
+
def _undo(self, conn: Any, plan: Plan, created: bool, committed: int) -> int:
|
|
254
|
+
"""There is nothing to roll back: every statement already committed. A table this call
|
|
255
|
+
created is dropped unless ``commit_rows`` asked for rows to stay visible."""
|
|
256
|
+
if conn is None or not created or plan.commit_rows:
|
|
257
|
+
return committed
|
|
258
|
+
try:
|
|
259
|
+
cur = conn.cursor()
|
|
260
|
+
cur.execute(_sql.drop_table_sql(plan.schema_name, plan.table, self.dialect))
|
|
261
|
+
except Exception: # noqa: BLE001, S110 # nosec B110
|
|
262
|
+
return committed # the original error is the one to report
|
|
263
|
+
return 0
|
|
264
|
+
|
|
265
|
+
# -- load --------------------------------------------------------------------------------
|
|
266
|
+
def load(
|
|
267
|
+
self,
|
|
268
|
+
conn: Any,
|
|
269
|
+
qualified: str,
|
|
270
|
+
plan: Plan,
|
|
271
|
+
first: pa.RecordBatch | None,
|
|
272
|
+
rest: Iterator[pa.RecordBatch],
|
|
273
|
+
progress: list[int],
|
|
274
|
+
) -> int:
|
|
275
|
+
if first is None:
|
|
276
|
+
return 0
|
|
277
|
+
names = first.schema.names
|
|
278
|
+
columns = ", ".join(_sql.quote(n, self.dialect) for n in names)
|
|
279
|
+
bindings = [binding(f) for f in first.schema]
|
|
280
|
+
row_marks = "(" + ", ".join(b[0] for b in bindings) + ")"
|
|
281
|
+
converters = [b[1] for b in bindings]
|
|
282
|
+
|
|
283
|
+
def converted(batch: pa.RecordBatch) -> Iterator[tuple[Any, ...]]:
|
|
284
|
+
_sql.check_batch(first.schema, batch, plan.table)
|
|
285
|
+
return _sql.row_iterator(_cloud.parquet_batch(batch), self.dialect, converters)
|
|
286
|
+
|
|
287
|
+
def groups() -> Iterator[Iterator[tuple[Any, ...]]]:
|
|
288
|
+
if not plan.commit_rows:
|
|
289
|
+
yield from chunks(
|
|
290
|
+
(row for b in chain_batches(first, rest) for row in converted(b)),
|
|
291
|
+
plan.batch_size,
|
|
292
|
+
)
|
|
293
|
+
return
|
|
294
|
+
# a statement never waits for the next input batch: every statement commits, so
|
|
295
|
+
# rows become visible batch by batch while a stream runs
|
|
296
|
+
for batch in chain_batches(first, rest):
|
|
297
|
+
yield from chunks(converted(batch), plan.batch_size)
|
|
298
|
+
|
|
299
|
+
total = 0
|
|
300
|
+
cur = conn.cursor()
|
|
301
|
+
try:
|
|
302
|
+
for group in groups():
|
|
303
|
+
piece = list(group)
|
|
304
|
+
# identifiers only, each checked and quoted; every value is a bound parameter
|
|
305
|
+
statement = (
|
|
306
|
+
f"INSERT INTO {qualified} ({columns}) VALUES " # nosec B608
|
|
307
|
+
+ ", ".join([row_marks] * len(piece))
|
|
308
|
+
)
|
|
309
|
+
cur.execute(statement, [v for row in piece for v in row])
|
|
310
|
+
total += len(piece)
|
|
311
|
+
progress[0] = total
|
|
312
|
+
finally:
|
|
313
|
+
cur.close()
|
|
314
|
+
return total
|