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,35 @@
|
|
|
1
|
+
"""Shape plugin: live database sinks.
|
|
2
|
+
|
|
3
|
+
* ``shape.sinks``: ``postgres`` (``postgresql://`` and ``postgres://``; ``COPY``), ``mysql``
|
|
4
|
+
(``mysql://``; batched multi-row ``INSERT``), ``snowflake`` (``snowflake://``; Parquet ``PUT``
|
|
5
|
+
to the table stage, then ``COPY INTO``) and ``databricks`` (``databricks://``; batched, bound
|
|
6
|
+
multi-row ``INSERT`` into Delta tables of a SQL warehouse).
|
|
7
|
+
* ``shape.sinks``: ``duckdb`` (``duckdb:///PATH.duckdb``; Arrow batches straight into a local DuckDB
|
|
8
|
+
file, extra ``duckdb``).
|
|
9
|
+
* :mod:`shape_databases.testing`: in-memory fake connections for tests.
|
|
10
|
+
|
|
11
|
+
The client libraries (``psycopg``, ``PyMySQL``, ``snowflake-connector-python``,
|
|
12
|
+
``databricks-sql-connector``, ``duckdb``) load only when a connection is opened.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from ._auth import Secret
|
|
16
|
+
from .databricks import DatabricksSink
|
|
17
|
+
from .duckdb_sink import DuckDbSink
|
|
18
|
+
from .errors import CredentialError, WriteError
|
|
19
|
+
from .mysql import MySqlSink
|
|
20
|
+
from .postgres import PostgresSink
|
|
21
|
+
from .snowflake import SnowflakeSink
|
|
22
|
+
|
|
23
|
+
SHAPE_API = "1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"SHAPE_API",
|
|
27
|
+
"CredentialError",
|
|
28
|
+
"DatabricksSink",
|
|
29
|
+
"DuckDbSink",
|
|
30
|
+
"MySqlSink",
|
|
31
|
+
"PostgresSink",
|
|
32
|
+
"Secret",
|
|
33
|
+
"SnowflakeSink",
|
|
34
|
+
"WriteError",
|
|
35
|
+
]
|
shape_databases/_auth.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Where a database password comes from, and keeping it out of every message.
|
|
2
|
+
|
|
3
|
+
Order, first one that is set wins:
|
|
4
|
+
|
|
5
|
+
1. the ``password`` option: the secret itself or a reference ``env://NAME``, ``file://PATH`` or
|
|
6
|
+
``kv://VAULT/SECRET`` (the references of the Fabric writers, resolved by core's
|
|
7
|
+
``shape.security.credrefs``; ``file://`` must not be readable by other users);
|
|
8
|
+
2. the ``credential`` option: an object with ``get_token(scope)`` returning something with a
|
|
9
|
+
``.token`` (every ``azure-identity`` credential, for Microsoft Entra database logins), a
|
|
10
|
+
function ``scope -> token``, or a reference string; the token is the password;
|
|
11
|
+
3. the environment: ``SHAPE_POSTGRES_PASSWORD`` then ``PGPASSWORD`` (PostgreSQL),
|
|
12
|
+
``SHAPE_MYSQL_PASSWORD`` then ``MYSQL_PWD`` (MySQL);
|
|
13
|
+
4. none: the driver's own default (PostgreSQL reads ``~/.pgpass``; ``trust`` logins need none).
|
|
14
|
+
|
|
15
|
+
A password is never accepted inside the URI, never put on a command line by this package, and
|
|
16
|
+
never part of an exception message, a log record or a ``repr``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Iterable, Mapping
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from .errors import CredentialError
|
|
27
|
+
|
|
28
|
+
# Scope Microsoft Entra issues database access tokens for: Azure Database for PostgreSQL and
|
|
29
|
+
# Azure Database for MySQL flexible server, public cloud (Microsoft Learn; #339). Other clouds
|
|
30
|
+
# (US Gov ``ossrdbms-aad.database.usgovcloudapi.net``, China ``...chinacloudapi.cn``) and any
|
|
31
|
+
# other resource are reached with the ``token_scope`` option.
|
|
32
|
+
ENTRA_DB_SCOPE = "https://ossrdbms-aad.database.windows.net/.default"
|
|
33
|
+
|
|
34
|
+
_KEYWORDS = re.compile(
|
|
35
|
+
r"(?i)\b(password|passwd|pwd|passfile|token|secret|client_secret|private_key|passphrase|"
|
|
36
|
+
r"access_token)\b\s*[=:]\s*\S+"
|
|
37
|
+
)
|
|
38
|
+
_PEM = re.compile(
|
|
39
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)", re.S
|
|
40
|
+
)
|
|
41
|
+
_URI_PASSWORD = re.compile(r"(?i)(\b[a-z][a-z0-9+.-]*://[^\s:/@]*:)[^\s@]*@")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Secret:
|
|
45
|
+
"""A password held so that it cannot leak through ``repr`` or ``str``."""
|
|
46
|
+
|
|
47
|
+
__slots__ = ("_value",)
|
|
48
|
+
|
|
49
|
+
def __init__(self, value: str) -> None:
|
|
50
|
+
self._value = value
|
|
51
|
+
|
|
52
|
+
def reveal(self) -> str:
|
|
53
|
+
return self._value
|
|
54
|
+
|
|
55
|
+
def __repr__(self) -> str:
|
|
56
|
+
return "Secret(***)"
|
|
57
|
+
|
|
58
|
+
__str__ = __repr__
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _resolve_reference(text: str) -> str | None:
|
|
62
|
+
"""The secret behind ``env://``, ``file://`` or ``kv://`` (core's one resolver,
|
|
63
|
+
``shape.security.credrefs``), or ``None`` when ``text`` is not a reference."""
|
|
64
|
+
from shape.security import credrefs
|
|
65
|
+
|
|
66
|
+
if not credrefs.is_reference(text):
|
|
67
|
+
return None
|
|
68
|
+
try:
|
|
69
|
+
return credrefs.resolve_reference(text)
|
|
70
|
+
except credrefs.CredentialReferenceError as exc:
|
|
71
|
+
raise CredentialError(str(exc)) from None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _token_from(credential: Any, scope: str) -> str:
|
|
75
|
+
failure: CredentialError | None = None
|
|
76
|
+
try:
|
|
77
|
+
if hasattr(credential, "get_token"):
|
|
78
|
+
return str(credential.get_token(scope).token)
|
|
79
|
+
if callable(credential):
|
|
80
|
+
return str(credential(scope))
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
failure = CredentialError(
|
|
83
|
+
f"the credential could not give a token for {scope} ({type(exc).__name__})"
|
|
84
|
+
)
|
|
85
|
+
if failure is not None: # raised outside the handler: no exception is kept as context
|
|
86
|
+
raise failure
|
|
87
|
+
raise CredentialError(
|
|
88
|
+
"a credential needs get_token(scope), or must be a function scope -> token, "
|
|
89
|
+
"or an env:// / file:// reference"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def resolve_password(
|
|
94
|
+
options: Mapping[str, Any], env_names: Iterable[str], *, scope: str = ENTRA_DB_SCOPE
|
|
95
|
+
) -> Secret | None:
|
|
96
|
+
"""The password for a write, from the sources in the module docstring (``None``: none)."""
|
|
97
|
+
password = options.get("password")
|
|
98
|
+
credential = options.get("credential")
|
|
99
|
+
if password is not None and credential is not None:
|
|
100
|
+
raise CredentialError("give password or credential, not both")
|
|
101
|
+
if password is not None:
|
|
102
|
+
if not isinstance(password, str) or not password:
|
|
103
|
+
raise CredentialError("password must be a non-empty string or an env:// / file:// ref")
|
|
104
|
+
return Secret(_resolve_reference(password) or password)
|
|
105
|
+
if credential is not None:
|
|
106
|
+
if isinstance(credential, str):
|
|
107
|
+
ref = _resolve_reference(credential)
|
|
108
|
+
if ref is None:
|
|
109
|
+
raise CredentialError("a credential string must be an env:// or file:// reference")
|
|
110
|
+
return Secret(ref)
|
|
111
|
+
return Secret(_token_from(credential, str(options.get("token_scope") or scope)))
|
|
112
|
+
for name in env_names:
|
|
113
|
+
value = os.environ.get(name)
|
|
114
|
+
if value:
|
|
115
|
+
return Secret(value)
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def scrub(text: str, secrets: Iterable[Secret | str | None] = (), limit: int = 400) -> str:
|
|
120
|
+
"""``text`` on one line with every known secret, ``password=...`` pair and URI password
|
|
121
|
+
hidden (a driver may echo what it was given in its message)."""
|
|
122
|
+
values = [s.reveal() if isinstance(s, Secret) else s for s in secrets]
|
|
123
|
+
out = _PEM.sub("***", str(text))
|
|
124
|
+
# Each secret is replaced before and after the whitespace is collapsed: a secret holding a
|
|
125
|
+
# run of spaces or a tab no longer matches the collapsed text.
|
|
126
|
+
for value in values:
|
|
127
|
+
if value:
|
|
128
|
+
out = out.replace(value, "***")
|
|
129
|
+
out = " ".join(out.split())
|
|
130
|
+
for value in values:
|
|
131
|
+
collapsed = " ".join(value.split()) if value else ""
|
|
132
|
+
if collapsed:
|
|
133
|
+
out = out.replace(collapsed, "***")
|
|
134
|
+
out = _URI_PASSWORD.sub(r"\1***@", out)
|
|
135
|
+
out = _KEYWORDS.sub(lambda m: m.group(1) + "=***", out)
|
|
136
|
+
return out[:limit]
|
shape_databases/_base.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""The write flow both sinks share; each sink supplies its dialect's pieces.
|
|
2
|
+
|
|
3
|
+
Modes (``write_mode``), chosen by the caller; the default never touches data already there:
|
|
4
|
+
|
|
5
|
+
``create`` create the table; an existing table is an error (the default)
|
|
6
|
+
``append`` add rows; the table is created when it is missing
|
|
7
|
+
``truncate`` empty the table, then add rows; created when missing
|
|
8
|
+
``replace`` drop the table and create it again (destroys the old rows)
|
|
9
|
+
|
|
10
|
+
Fail fast: bad names, options, URI or credentials are refused before a connection is opened;
|
|
11
|
+
a failure while writing rolls back and raises :class:`WriteError` (see each sink for exactly
|
|
12
|
+
what a failed write leaves behind).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ipaddress
|
|
18
|
+
import itertools
|
|
19
|
+
import logging
|
|
20
|
+
import re
|
|
21
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Any
|
|
24
|
+
from urllib.parse import parse_qsl, unquote, urlsplit
|
|
25
|
+
|
|
26
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
27
|
+
|
|
28
|
+
from shape.errors import ShapeError
|
|
29
|
+
|
|
30
|
+
from . import _sql
|
|
31
|
+
from ._auth import Secret, resolve_password, scrub
|
|
32
|
+
from .errors import WriteError
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger("shape_databases")
|
|
35
|
+
|
|
36
|
+
PEEK = tuple[pa.RecordBatch | None, Iterator[pa.RecordBatch]]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Target:
|
|
41
|
+
"""A parsed destination. ``label`` is safe to print (no password, no query)."""
|
|
42
|
+
|
|
43
|
+
host: str | None
|
|
44
|
+
port: int | None
|
|
45
|
+
user: str | None
|
|
46
|
+
database: str | None
|
|
47
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def label(self) -> str:
|
|
51
|
+
who = f"{self.user}@" if self.user else ""
|
|
52
|
+
where = (self.host or "localhost") + (f":{self.port}" if self.port else "")
|
|
53
|
+
return f"{who}{where}/{self.database or ''}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# URI query keys that would carry a credential: refused with a message that says so
|
|
57
|
+
_SECRET_KEYS = ("password", "passwd", "pwd", "token", "secret", "private_key", "passphrase")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_uri(
|
|
61
|
+
uri: str,
|
|
62
|
+
schemes: Sequence[str],
|
|
63
|
+
allowed: Mapping[str, Callable[[str], Any]],
|
|
64
|
+
) -> Target:
|
|
65
|
+
"""``scheme://user@host:port/database?key=value``. A password in the URI is refused: it
|
|
66
|
+
would end up in shell history and logs. ``allowed`` maps each accepted query key to its
|
|
67
|
+
value checker/converter."""
|
|
68
|
+
if not isinstance(uri, str):
|
|
69
|
+
raise ShapeError("the destination must be a URI string")
|
|
70
|
+
try:
|
|
71
|
+
parts = urlsplit(uri)
|
|
72
|
+
port = parts.port
|
|
73
|
+
except ValueError:
|
|
74
|
+
raise ShapeError("the destination is not a valid URI") from None
|
|
75
|
+
if parts.scheme not in schemes:
|
|
76
|
+
raise ShapeError(f"the destination scheme must be one of {', '.join(schemes)}")
|
|
77
|
+
if parts.password is not None:
|
|
78
|
+
raise ShapeError(
|
|
79
|
+
"a password must not be part of the URI (it would be logged and kept in shell "
|
|
80
|
+
"history): pass the password option, set the password environment variable, or "
|
|
81
|
+
"give an env:// or file:// reference"
|
|
82
|
+
)
|
|
83
|
+
params: dict[str, Any] = {}
|
|
84
|
+
for key, value in parse_qsl(parts.query, keep_blank_values=True):
|
|
85
|
+
if key not in allowed:
|
|
86
|
+
if any(word in key.lower() for word in _SECRET_KEYS):
|
|
87
|
+
raise ShapeError(
|
|
88
|
+
f"{key} must not be part of the URI (it would be logged and kept in shell "
|
|
89
|
+
"history): pass it as an option, set its environment variable, or give an "
|
|
90
|
+
"env:// or file:// reference"
|
|
91
|
+
)
|
|
92
|
+
raise ShapeError(
|
|
93
|
+
f"unknown URI parameter {key!r}; allowed: {', '.join(sorted(allowed))}"
|
|
94
|
+
)
|
|
95
|
+
try:
|
|
96
|
+
params[key] = allowed[key](value)
|
|
97
|
+
except ShapeError as exc:
|
|
98
|
+
failure = ShapeError(f"URI parameter {key!r} is {value!r}: {exc}")
|
|
99
|
+
raise failure from None
|
|
100
|
+
database = unquote(parts.path[1:]) if len(parts.path) > 1 else None
|
|
101
|
+
return Target(
|
|
102
|
+
host=parts.hostname or None,
|
|
103
|
+
port=port,
|
|
104
|
+
user=unquote(parts.username) if parts.username else None,
|
|
105
|
+
database=database,
|
|
106
|
+
params=params,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def is_loopback(host: str | None) -> bool:
|
|
111
|
+
"""True for no host (a Unix socket), a socket directory, ``localhost`` or a loopback address."""
|
|
112
|
+
if not host or host.startswith("/"):
|
|
113
|
+
return True
|
|
114
|
+
if host.lower().rstrip(".") == "localhost":
|
|
115
|
+
return True
|
|
116
|
+
try:
|
|
117
|
+
return ipaddress.ip_address(host.strip("[]")).is_loopback
|
|
118
|
+
except ValueError:
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def one_of(*choices: str) -> Callable[[str], str]:
|
|
123
|
+
def check(value: str) -> str:
|
|
124
|
+
if value not in choices:
|
|
125
|
+
raise ShapeError(f"must be one of {', '.join(choices)}")
|
|
126
|
+
return value
|
|
127
|
+
|
|
128
|
+
return check
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def as_int(value: str) -> int:
|
|
132
|
+
try:
|
|
133
|
+
return int(value)
|
|
134
|
+
except ValueError:
|
|
135
|
+
raise ShapeError("must be an integer") from None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def as_bool(value: str) -> bool:
|
|
139
|
+
if value.lower() in ("1", "true", "yes", "on"):
|
|
140
|
+
return True
|
|
141
|
+
if value.lower() in ("0", "false", "no", "off"):
|
|
142
|
+
return False
|
|
143
|
+
raise ShapeError("must be true or false")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def as_text(value: str) -> str:
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass
|
|
151
|
+
class Plan:
|
|
152
|
+
"""Everything validated before a connection is made."""
|
|
153
|
+
|
|
154
|
+
target: Target
|
|
155
|
+
mode: str
|
|
156
|
+
batch_size: int
|
|
157
|
+
commit_rows: int | None
|
|
158
|
+
schema_name: str | None
|
|
159
|
+
table: str
|
|
160
|
+
columns: Mapping[str, Mapping[str, Any]]
|
|
161
|
+
primary_key: Sequence[str]
|
|
162
|
+
schema: pa.Schema | None
|
|
163
|
+
secret: Secret | None
|
|
164
|
+
# sink-specific resolved sign-in material (never printed) and every secret to scrub
|
|
165
|
+
auth: dict[str, Any] = field(default_factory=dict)
|
|
166
|
+
secrets: tuple[Secret, ...] = ()
|
|
167
|
+
options: Mapping[str, Any] = field(default_factory=dict)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class DatabaseSink:
|
|
171
|
+
"""Shared ``write()``; subclasses set the class attributes and implement the hooks."""
|
|
172
|
+
|
|
173
|
+
name = ""
|
|
174
|
+
schemes: Sequence[str] = ()
|
|
175
|
+
dialect = ""
|
|
176
|
+
password_env: Sequence[str] = ()
|
|
177
|
+
uri_params: Mapping[str, Callable[[str], Any]] = {}
|
|
178
|
+
# ``SELECT 1`` when the table exists; parameters are (schema or None, table).
|
|
179
|
+
exists_sql = ""
|
|
180
|
+
|
|
181
|
+
def __init__(self, connect: Callable[..., Any] | None = None) -> None:
|
|
182
|
+
self._connect = connect
|
|
183
|
+
|
|
184
|
+
# -- hooks -------------------------------------------------------------------------------
|
|
185
|
+
def parse_target(self, uri: str) -> Target:
|
|
186
|
+
return parse_uri(uri, self.schemes, self.uri_params)
|
|
187
|
+
|
|
188
|
+
def resolve_auth(self, options: Mapping[str, Any]) -> tuple[Secret | None, dict[str, Any]]:
|
|
189
|
+
"""The password (and any other sign-in material) for a write, resolved before any
|
|
190
|
+
connection is opened."""
|
|
191
|
+
return resolve_password(options, self.password_env), {}
|
|
192
|
+
|
|
193
|
+
def create_table_sql(self, plan: Plan, schema: pa.Schema, first: pa.RecordBatch | None) -> str:
|
|
194
|
+
return _sql.create_table_sql(
|
|
195
|
+
plan.schema_name,
|
|
196
|
+
plan.table,
|
|
197
|
+
schema,
|
|
198
|
+
self.dialect,
|
|
199
|
+
first=first,
|
|
200
|
+
columns=plan.columns,
|
|
201
|
+
primary_key=plan.primary_key,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def keys_sql(self, plan: Plan) -> str:
|
|
205
|
+
"""``SELECT`` of the primary key columns of the planned table (``shape seed --mode append``
|
|
206
|
+
reads them to refuse a key that is already there before anything is written)."""
|
|
207
|
+
if not plan.primary_key:
|
|
208
|
+
raise ShapeError(f"table {plan.table!r} has no primary key to read")
|
|
209
|
+
# identifiers checked by plan() and quoted; no value is in the statement
|
|
210
|
+
columns = ", ".join(_sql.quote(c, self.dialect) for c in plan.primary_key)
|
|
211
|
+
table = _sql.qualified(plan.schema_name, plan.table, self.dialect)
|
|
212
|
+
return f"SELECT {columns} FROM {table}" # nosec B608
|
|
213
|
+
|
|
214
|
+
def check_schema(self, schema: pa.Schema, plan: Plan) -> None:
|
|
215
|
+
"""Refuse, before any connection, a column the table cannot hold."""
|
|
216
|
+
|
|
217
|
+
def connect_params(self, plan: Plan) -> dict[str, Any]:
|
|
218
|
+
raise NotImplementedError
|
|
219
|
+
|
|
220
|
+
def default_connect(self, **params: Any) -> Any:
|
|
221
|
+
raise NotImplementedError
|
|
222
|
+
|
|
223
|
+
def load(
|
|
224
|
+
self,
|
|
225
|
+
conn: Any,
|
|
226
|
+
qualified: str,
|
|
227
|
+
plan: Plan,
|
|
228
|
+
first: pa.RecordBatch | None,
|
|
229
|
+
rest: Iterator[pa.RecordBatch],
|
|
230
|
+
progress: list[int],
|
|
231
|
+
) -> int:
|
|
232
|
+
"""Stream the rows in; ``progress[0]`` is kept at the number of rows committed."""
|
|
233
|
+
raise NotImplementedError
|
|
234
|
+
|
|
235
|
+
def tls_opt_out(self, plan: Plan) -> str | None:
|
|
236
|
+
"""How to opt out of the secure TLS default, or None when it was not applied to ``plan``."""
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
def ddl_is_transactional(self) -> bool:
|
|
240
|
+
raise NotImplementedError
|
|
241
|
+
|
|
242
|
+
# -- the flow ----------------------------------------------------------------------------
|
|
243
|
+
def plan(self, uri: str, table: str, options: Mapping[str, Any]) -> Plan:
|
|
244
|
+
dialect = self.dialect
|
|
245
|
+
target = self.parse_target(uri)
|
|
246
|
+
prefix = options.get("table_prefix") or ""
|
|
247
|
+
if not isinstance(prefix, str):
|
|
248
|
+
raise ShapeError("table_prefix must be a string")
|
|
249
|
+
full = _sql.check_identifier(prefix + str(table), "table", dialect)
|
|
250
|
+
schema_name = options.get("schema_name")
|
|
251
|
+
if schema_name is not None:
|
|
252
|
+
_sql.check_identifier(schema_name, "schema", dialect)
|
|
253
|
+
key = list(options.get("primary_key") or [])
|
|
254
|
+
for name in key:
|
|
255
|
+
_sql.check_identifier(name, "column", dialect)
|
|
256
|
+
schema = options.get("schema")
|
|
257
|
+
if schema is not None and not isinstance(schema, pa.Schema):
|
|
258
|
+
raise ShapeError("schema must be a pyarrow Schema")
|
|
259
|
+
secret, auth = self.resolve_auth(options)
|
|
260
|
+
return Plan(
|
|
261
|
+
target=target,
|
|
262
|
+
mode=_sql.check_mode(options.get("write_mode", "create")),
|
|
263
|
+
batch_size=int(
|
|
264
|
+
_sql.positive_int(options.get("batch_size", _sql.DEFAULT_BATCH_SIZE), "batch_size")
|
|
265
|
+
or 0
|
|
266
|
+
),
|
|
267
|
+
commit_rows=_sql.positive_int(options.get("commit_rows"), "commit_rows", optional=True),
|
|
268
|
+
schema_name=schema_name,
|
|
269
|
+
table=full,
|
|
270
|
+
columns=options.get("columns") or {},
|
|
271
|
+
primary_key=key,
|
|
272
|
+
schema=schema,
|
|
273
|
+
secret=secret,
|
|
274
|
+
auth=auth,
|
|
275
|
+
secrets=tuple(v for v in auth.values() if isinstance(v, Secret)),
|
|
276
|
+
options=options,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
def write(self, uri: str, table: str, batches: Iterable[pa.RecordBatch], **options: Any) -> int:
|
|
280
|
+
plan = self.plan(uri, table, options)
|
|
281
|
+
first, rest = self._peek(batches, plan)
|
|
282
|
+
use_schema = first.schema if first is not None else plan.schema
|
|
283
|
+
if use_schema is None:
|
|
284
|
+
raise ShapeError(
|
|
285
|
+
f"table {table!r} has no batches and no schema: pass schema= to create it empty"
|
|
286
|
+
)
|
|
287
|
+
for name in use_schema.names:
|
|
288
|
+
_sql.check_identifier(name, "column", self.dialect)
|
|
289
|
+
_sql.check_unique(use_schema.names, self.dialect)
|
|
290
|
+
self.check_schema(use_schema, plan)
|
|
291
|
+
injected = options.get("connection")
|
|
292
|
+
label = plan.target.label
|
|
293
|
+
secrets = [plan.secret, *plan.secrets]
|
|
294
|
+
conn = injected
|
|
295
|
+
progress = [0]
|
|
296
|
+
created = False
|
|
297
|
+
failure: WriteError
|
|
298
|
+
name = _sql.qualified(plan.schema_name, plan.table, self.dialect)
|
|
299
|
+
try:
|
|
300
|
+
if conn is None:
|
|
301
|
+
conn = self._open(plan, label, secrets, options.get("connect"))
|
|
302
|
+
log.debug("writing %s to %s (mode %s)", name, label, plan.mode)
|
|
303
|
+
created = self._prepare(conn, plan, use_schema, first)
|
|
304
|
+
if plan.commit_rows:
|
|
305
|
+
conn.commit() # the table is there for readers before the first rows arrive
|
|
306
|
+
rows = self.load(conn, name, plan, first, rest, progress)
|
|
307
|
+
conn.commit()
|
|
308
|
+
log.debug("wrote %d rows to %s", rows, name)
|
|
309
|
+
return rows
|
|
310
|
+
except ShapeError:
|
|
311
|
+
self._undo(conn, plan, created, progress[0])
|
|
312
|
+
raise
|
|
313
|
+
except Exception as exc:
|
|
314
|
+
kept_rows = self._undo(conn, plan, created, progress[0])
|
|
315
|
+
kept = f"; {kept_rows} rows were committed before it failed" if kept_rows else ""
|
|
316
|
+
# Raised after this block: inside it, the driver's exception (whose message may
|
|
317
|
+
# hold what it was given) would stay reachable as __context__.
|
|
318
|
+
failure = WriteError(
|
|
319
|
+
f"writing {name} at {label} failed ({type(exc).__name__}): "
|
|
320
|
+
f"{scrub(str(exc), secrets)}{kept}",
|
|
321
|
+
kept_rows,
|
|
322
|
+
)
|
|
323
|
+
finally:
|
|
324
|
+
if conn is not None and injected is None:
|
|
325
|
+
try:
|
|
326
|
+
conn.close()
|
|
327
|
+
except Exception: # noqa: S110 # nosec B110
|
|
328
|
+
# closing is best effort: the write's own result or error is what matters
|
|
329
|
+
pass
|
|
330
|
+
raise failure
|
|
331
|
+
|
|
332
|
+
def _peek(self, batches: Iterable[pa.RecordBatch], plan: Plan) -> PEEK:
|
|
333
|
+
it = iter(batches)
|
|
334
|
+
first = next(it, None)
|
|
335
|
+
if first is not None:
|
|
336
|
+
first = _sql.normalize(first, plan.columns)
|
|
337
|
+
return first, (_sql.normalize(b, plan.columns) for b in it)
|
|
338
|
+
|
|
339
|
+
def _open(self, plan: Plan, label: str, secrets: list[Secret | None], connect: Any) -> Any:
|
|
340
|
+
params = self.connect_params(plan)
|
|
341
|
+
opener = connect or self._connect or self.default_connect
|
|
342
|
+
try:
|
|
343
|
+
return opener(**params)
|
|
344
|
+
except ShapeError:
|
|
345
|
+
raise
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
detail = scrub(str(exc), secrets)
|
|
348
|
+
opt_out = self.tls_opt_out(plan)
|
|
349
|
+
hint = ""
|
|
350
|
+
if opt_out and re.search(
|
|
351
|
+
r"ssl|tls|certificate", f"{type(exc).__name__} {detail}", re.I
|
|
352
|
+
):
|
|
353
|
+
hint = (
|
|
354
|
+
f"; {plan.target.host} is not a loopback host, so TLS with certificate "
|
|
355
|
+
f"verification is the default. Fix the certificate or trust store, or opt out "
|
|
356
|
+
f"explicitly with {opt_out} in the URI"
|
|
357
|
+
)
|
|
358
|
+
failure = WriteError(
|
|
359
|
+
f"could not connect to {label} ({type(exc).__name__}): {detail}{hint}"
|
|
360
|
+
)
|
|
361
|
+
raise failure # outside the handler: the driver's exception is not kept as context
|
|
362
|
+
|
|
363
|
+
# -- table preparation -------------------------------------------------------------------
|
|
364
|
+
def _exists(self, conn: Any, plan: Plan) -> bool:
|
|
365
|
+
cur = conn.cursor()
|
|
366
|
+
try:
|
|
367
|
+
cur.execute(self.exists_sql, (plan.schema_name, plan.table))
|
|
368
|
+
return bool(cur.fetchone() is not None)
|
|
369
|
+
finally:
|
|
370
|
+
cur.close()
|
|
371
|
+
|
|
372
|
+
def _prepare(
|
|
373
|
+
self, conn: Any, plan: Plan, schema: pa.Schema, first: pa.RecordBatch | None
|
|
374
|
+
) -> bool:
|
|
375
|
+
"""Make the table ready for the mode; return whether this call created it."""
|
|
376
|
+
dialect = self.dialect
|
|
377
|
+
cur = conn.cursor()
|
|
378
|
+
try:
|
|
379
|
+
exists = self._exists(conn, plan)
|
|
380
|
+
if plan.mode == "create" and exists:
|
|
381
|
+
raise ShapeError(
|
|
382
|
+
f"table {plan.table} already exists; set write_mode to append, truncate "
|
|
383
|
+
"or replace to write into it"
|
|
384
|
+
)
|
|
385
|
+
if plan.mode == "replace" and exists:
|
|
386
|
+
cur.execute(_sql.drop_table_sql(plan.schema_name, plan.table, dialect))
|
|
387
|
+
exists = False
|
|
388
|
+
elif plan.mode == "truncate" and exists:
|
|
389
|
+
cur.execute(_sql.truncate_sql(plan.schema_name, plan.table, dialect))
|
|
390
|
+
if exists:
|
|
391
|
+
return False
|
|
392
|
+
if plan.schema_name:
|
|
393
|
+
cur.execute(self.create_schema_sql(plan.schema_name))
|
|
394
|
+
cur.execute(self.create_table_sql(plan, schema, first))
|
|
395
|
+
return True
|
|
396
|
+
finally:
|
|
397
|
+
cur.close()
|
|
398
|
+
|
|
399
|
+
def create_schema_sql(self, schema_name: str) -> str:
|
|
400
|
+
return f"CREATE SCHEMA IF NOT EXISTS {_sql.quote(schema_name, self.dialect)}"
|
|
401
|
+
|
|
402
|
+
def _undo(self, conn: Any, plan: Plan, created: bool, committed: int) -> int:
|
|
403
|
+
"""After a failure: roll back the open transaction; drop a table this call made when
|
|
404
|
+
nothing of it was committed and the database could not roll the creation back. Returns
|
|
405
|
+
the number of committed rows still visible afterwards."""
|
|
406
|
+
if conn is None:
|
|
407
|
+
return committed
|
|
408
|
+
try:
|
|
409
|
+
conn.rollback()
|
|
410
|
+
if (
|
|
411
|
+
created
|
|
412
|
+
and committed == 0
|
|
413
|
+
and not plan.commit_rows
|
|
414
|
+
and not self.ddl_is_transactional()
|
|
415
|
+
):
|
|
416
|
+
cur = conn.cursor()
|
|
417
|
+
cur.execute(_sql.drop_table_sql(plan.schema_name, plan.table, self.dialect))
|
|
418
|
+
conn.commit()
|
|
419
|
+
except Exception: # noqa: S110 # nosec B110
|
|
420
|
+
pass # the original error is the one to report
|
|
421
|
+
return committed
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def chunks(
|
|
425
|
+
rows: Iterator[tuple[Any, ...]], size: int | None
|
|
426
|
+
) -> Iterator[Iterator[tuple[Any, ...]]]:
|
|
427
|
+
"""Successive groups of at most ``size`` rows (all of them when ``size`` is ``None``); each
|
|
428
|
+
group is consumed lazily so memory does not grow with the table."""
|
|
429
|
+
if size is None:
|
|
430
|
+
yield rows
|
|
431
|
+
return
|
|
432
|
+
while True:
|
|
433
|
+
group = itertools.islice(rows, size)
|
|
434
|
+
head = next(group, None)
|
|
435
|
+
if head is None:
|
|
436
|
+
return
|
|
437
|
+
yield itertools.chain([head], group)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def chain_batches(
|
|
441
|
+
first: pa.RecordBatch, rest: Iterator[pa.RecordBatch]
|
|
442
|
+
) -> Iterator[pa.RecordBatch]:
|
|
443
|
+
yield first
|
|
444
|
+
yield from rest
|