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.
@@ -0,0 +1,215 @@
1
+ """What the Snowflake and Databricks sinks share: the Arrow type maps, the checks made before
2
+ any connection, and the Parquet staging used by Snowflake.
3
+
4
+ Types are mapped here, not by core's script dialects, because a live write has to say exactly
5
+ what each Arrow type becomes (see the plugin README). A type with no mapping is refused before a
6
+ connection is opened, with the column's name in the message.
7
+
8
+ Nothing in this module builds a statement from a value: every name is checked
9
+ (:func:`shape_databases._sql.check_identifier`) and quoted, and a size, precision or scale is
10
+ an integer that has been checked.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import uuid
16
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
17
+ from typing import Any
18
+
19
+ import pyarrow as pa # type: ignore[import-untyped]
20
+ import pyarrow.compute as pc # type: ignore[import-untyped]
21
+ import pyarrow.types as pat # type: ignore[import-untyped]
22
+
23
+ from shape.errors import ShapeError
24
+
25
+ from . import _sql
26
+
27
+ DEFAULT_CHUNK_ROWS = 1_000_000
28
+ MAX_DECIMAL_PRECISION = 38
29
+ SNOWFLAKE_MAX_VARCHAR = 16_777_216
30
+
31
+
32
+ def is_nested(t: pa.DataType) -> bool:
33
+ return bool(
34
+ pat.is_list(t)
35
+ or pat.is_large_list(t)
36
+ or pat.is_fixed_size_list(t)
37
+ or pat.is_struct(t)
38
+ or pat.is_map(t)
39
+ )
40
+
41
+
42
+ def _value_type(t: pa.DataType) -> pa.DataType:
43
+ return t.value_type if pat.is_dictionary(t) else t
44
+
45
+
46
+ def _unsupported(field: pa.Field, dialect: str) -> ShapeError:
47
+ return ShapeError(
48
+ f"column {field.name!r} has type {field.type}, which the {dialect} sink cannot store: "
49
+ "convert it (for example to a string) before writing"
50
+ )
51
+
52
+
53
+ def _decimal(field: pa.Field, t: pa.DataType) -> str:
54
+ if t.precision > MAX_DECIMAL_PRECISION:
55
+ raise ShapeError(
56
+ f"column {field.name!r}: a decimal holds at most {MAX_DECIMAL_PRECISION} digits"
57
+ )
58
+ return f"({t.precision},{t.scale})"
59
+
60
+
61
+ def snowflake_type(field: pa.Field, meta: Mapping[str, Any] | None = None) -> str:
62
+ """The Snowflake type that holds ``field``."""
63
+ t = _value_type(field.type)
64
+ if pat.is_boolean(t):
65
+ return "BOOLEAN"
66
+ if pat.is_integer(t):
67
+ return "NUMBER(38,0)"
68
+ if pat.is_floating(t):
69
+ return "FLOAT"
70
+ if pat.is_decimal(t):
71
+ return "NUMBER" + _decimal(field, t)
72
+ if pat.is_string(t) or pat.is_large_string(t):
73
+ declared = (meta or {}).get("max_length")
74
+ if declared is not None:
75
+ size = declared
76
+ if (
77
+ isinstance(size, bool)
78
+ or not isinstance(size, int)
79
+ or not 1 <= size <= SNOWFLAKE_MAX_VARCHAR
80
+ ):
81
+ raise ShapeError(
82
+ f"column {field.name!r}: max_length must be between 1 and "
83
+ f"{SNOWFLAKE_MAX_VARCHAR}"
84
+ )
85
+ return f"VARCHAR({size})"
86
+ return "VARCHAR"
87
+ if pat.is_binary(t) or pat.is_large_binary(t) or pat.is_fixed_size_binary(t):
88
+ return "BINARY"
89
+ if pat.is_date(t):
90
+ return "DATE"
91
+ if pat.is_timestamp(t):
92
+ return "TIMESTAMP_NTZ" if t.tz is None else "TIMESTAMP_TZ"
93
+ if is_nested(t):
94
+ return "VARIANT"
95
+ raise _unsupported(field, "snowflake")
96
+
97
+
98
+ def databricks_type(field: pa.Field) -> str:
99
+ """The Databricks (Delta) type that holds ``field``."""
100
+ t = _value_type(field.type)
101
+ if pat.is_boolean(t):
102
+ return "BOOLEAN"
103
+ if pat.is_integer(t):
104
+ if pat.is_uint64(t):
105
+ return "DECIMAL(20,0)"
106
+ wide = t.bit_width == 64 or (pat.is_unsigned_integer(t) and t.bit_width == 32)
107
+ return "BIGINT" if wide else "INT"
108
+ if pat.is_floating(t):
109
+ return "DOUBLE"
110
+ if pat.is_decimal(t):
111
+ return "DECIMAL" + _decimal(field, t)
112
+ if pat.is_string(t) or pat.is_large_string(t) or is_nested(t):
113
+ return "STRING" # lists, structs and maps are JSON text
114
+ if pat.is_binary(t) or pat.is_large_binary(t) or pat.is_fixed_size_binary(t):
115
+ return "BINARY"
116
+ if pat.is_date(t):
117
+ return "DATE"
118
+ if pat.is_timestamp(t):
119
+ return "TIMESTAMP_NTZ" if t.tz is None else "TIMESTAMP"
120
+ raise _unsupported(field, "databricks")
121
+
122
+
123
+ def check_types(
124
+ schema: pa.Schema,
125
+ dialect: str,
126
+ columns: Mapping[str, Mapping[str, Any]] | None = None,
127
+ primary_key: Sequence[str] = (),
128
+ ) -> None:
129
+ """Refuse, before any connection, a column with no type, a bad ``columns`` entry or a key
130
+ that is not a column."""
131
+ for name in primary_key:
132
+ if name not in schema.names:
133
+ raise ShapeError(f"primary key column {name!r} is not a column of the table")
134
+ for field in schema:
135
+ if dialect == "snowflake":
136
+ snowflake_type(field, (columns or {}).get(field.name))
137
+ else:
138
+ databricks_type(field)
139
+
140
+
141
+ def create_table_sql(
142
+ qualified_name: str,
143
+ schema: pa.Schema,
144
+ dialect: str,
145
+ columns: Mapping[str, Mapping[str, Any]],
146
+ primary_key: Sequence[str],
147
+ ) -> str:
148
+ """``CREATE TABLE`` with the mapped types; key columns are ``NOT NULL`` and the key is
149
+ declared (neither database enforces it)."""
150
+ for name in primary_key:
151
+ if name not in schema.names:
152
+ raise ShapeError(f"primary key column {name!r} is not a column of the table")
153
+ lines = []
154
+ for field in schema:
155
+ meta = columns.get(field.name, {})
156
+ sql_type = snowflake_type(field, meta) if dialect == "snowflake" else databricks_type(field)
157
+ nullable = bool(meta.get("nullable", True)) and field.name not in primary_key
158
+ lines.append(
159
+ f" {_sql.quote(field.name, dialect)} {sql_type}{'' if nullable else ' NOT NULL'}"
160
+ )
161
+ if primary_key:
162
+ lines.append(f" PRIMARY KEY ({', '.join(_sql.quote(c, dialect) for c in primary_key)})")
163
+ body = ",\n".join(lines)
164
+ tail = " USING DELTA" if dialect == "databricks" else ""
165
+ return f"CREATE TABLE {qualified_name} (\n{body}\n){tail}" # nosec B608
166
+
167
+
168
+ # -- Parquet staging ----------------------------------------------------------------------
169
+
170
+
171
+ def parquet_batch(batch: pa.RecordBatch) -> pa.RecordBatch:
172
+ """``batch`` as it is staged: dictionaries decoded, timestamps in microseconds (a zone is
173
+ converted to UTC first)."""
174
+ arrays = []
175
+ for col in batch.columns:
176
+ t = col.type
177
+ if pat.is_dictionary(t):
178
+ col = col.cast(t.value_type)
179
+ t = col.type
180
+ if pat.is_timestamp(t):
181
+ if t.tz is not None:
182
+ col = col.cast(pa.timestamp(t.unit, "UTC"))
183
+ col = col.cast(pa.timestamp("us", t.tz and "UTC"), safe=False)
184
+ elif pat.is_floating(t) and pat.is_float16(t):
185
+ col = pc.cast(col, pa.float32())
186
+ arrays.append(col)
187
+ return pa.RecordBatch.from_arrays(arrays, names=batch.schema.names)
188
+
189
+
190
+ def chunked(batches: Iterable[pa.RecordBatch], chunk_rows: int) -> Iterator[list[pa.RecordBatch]]:
191
+ """``batches`` regrouped into lists of at most ``chunk_rows`` rows (batches are sliced)."""
192
+ group: list[pa.RecordBatch] = []
193
+ size = 0
194
+ for batch in batches:
195
+ offset = 0
196
+ while offset < batch.num_rows:
197
+ take = min(chunk_rows - size, batch.num_rows - offset)
198
+ group.append(batch.slice(offset, take))
199
+ size += take
200
+ offset += take
201
+ if size >= chunk_rows:
202
+ yield group
203
+ group, size = [], 0
204
+ if group:
205
+ yield group
206
+
207
+
208
+ def new_run_id() -> str:
209
+ return uuid.uuid4().hex[:12]
210
+
211
+
212
+ def string_literal(text: str) -> str:
213
+ """``text`` as a single-quoted SQL literal (backslash and quote escaped). Used only for
214
+ file paths and patterns that this package generated, which cannot be parameters."""
215
+ return "'" + text.replace("\\", "\\\\").replace("'", "''") + "'"
@@ -0,0 +1,282 @@
1
+ """SQL text and value preparation shared by the PostgreSQL and MySQL sinks.
2
+
3
+ Identifier quoting and the Arrow -> database type map are core's: the ``sql`` sink's script
4
+ dialects ``postgres`` and ``mysql`` (:mod:`shape.builtins.sinks.sql`), so a table created by a
5
+ live write has the same columns as the table the script would create. This module adds what a
6
+ live write needs on top: strict identifier checks (a database truncates or rejects what a script
7
+ file would not notice), the ``CREATE TABLE`` text, and per-column value conversion.
8
+
9
+ Values are never part of a statement: they go through ``COPY ... FROM STDIN`` (PostgreSQL) or
10
+ bound ``executemany`` parameters (MySQL). Everything that is interpolated is an identifier that
11
+ passed :func:`check_identifier` and then core's quoting.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import datetime as dt
17
+ import json
18
+ import math
19
+ from collections.abc import Callable, Iterator, Mapping, Sequence
20
+ from typing import Any
21
+
22
+ import pyarrow as pa # type: ignore[import-untyped]
23
+ import pyarrow.compute as pc # type: ignore[import-untyped]
24
+ import pyarrow.types as pat # type: ignore[import-untyped]
25
+
26
+ from shape.builtins.sinks import sql as core_sql
27
+ from shape.errors import ShapeError
28
+
29
+ WRITE_MODES = ("create", "append", "truncate", "replace")
30
+ DEFAULT_BATCH_SIZE = 5000
31
+ # PostgreSQL limits an identifier to 63 bytes and silently truncates longer names; MySQL to 64
32
+ # characters. A write fails instead of creating a table under a different name.
33
+ MAX_IDENTIFIER = {"postgres": 63, "mysql": 64, "snowflake": 255, "databricks": 255}
34
+ # Quoting is core's for the two classic dialects; Snowflake quotes like PostgreSQL and Databricks
35
+ # like MySQL (backticks).
36
+ _QUOTE_AS = {"snowflake": "postgres", "databricks": "mysql"}
37
+ # Characters Delta refuses in a column name (without column mapping), and those Unity Catalog
38
+ # refuses in a table or schema name.
39
+ _DELTA_COLUMN_BAD = frozenset(" ,;{}()\n\t=")
40
+ _UC_NAME_BAD = frozenset(" ./`")
41
+ # A string column longer than this becomes TEXT / LONGTEXT instead of VARCHAR(n).
42
+ MAX_VARCHAR = 4000
43
+ _TEXT = {"postgres": "TEXT", "mysql": "LONGTEXT"}
44
+
45
+
46
+ def check_identifier(name: Any, kind: str, dialect: str) -> str:
47
+ """``name`` when it is safe to quote and the database keeps it as is, else a ShapeError."""
48
+ if not isinstance(name, str) or not name:
49
+ raise ShapeError(f"{kind} name must be a non-empty string")
50
+ if "\x00" in name:
51
+ raise ShapeError(f"{kind} name {name!r} contains a NUL character")
52
+ limit = MAX_IDENTIFIER[dialect]
53
+ size = len(name.encode("utf-8")) if dialect == "postgres" else len(name)
54
+ if size > limit:
55
+ raise ShapeError(
56
+ f"{kind} name {name[:30]!r}... is longer than the {limit} {dialect} allows"
57
+ )
58
+ if dialect in ("snowflake", "databricks"):
59
+ _check_cloud_identifier(name, kind, dialect)
60
+ if dialect == "mysql":
61
+ if "%" in name:
62
+ # PyMySQL formats statements with %; a % in a name would be read as a placeholder.
63
+ raise ShapeError(f"{kind} name {name!r}: '%' is not allowed in a MySQL name")
64
+ if name != name.rstrip(" "):
65
+ raise ShapeError(f"{kind} name {name!r}: MySQL names cannot end with a space")
66
+ return name
67
+
68
+
69
+ def _check_cloud_identifier(name: str, kind: str, dialect: str) -> None:
70
+ """What Snowflake and Databricks would change or refuse, said before any connection."""
71
+ if any(ord(c) < 32 or ord(c) == 127 for c in name):
72
+ raise ShapeError(f"{kind} name {name!r} contains a control character")
73
+ if dialect == "snowflake":
74
+ if name != name.strip():
75
+ raise ShapeError(
76
+ f"{kind} name {name!r}: Snowflake names cannot start or end with a space"
77
+ )
78
+ return
79
+ if kind == "column":
80
+ bad = sorted(c for c in name if c in _DELTA_COLUMN_BAD)
81
+ if bad:
82
+ raise ShapeError(
83
+ f"column name {name!r} contains {bad[0]!r}, which a Delta column name cannot hold"
84
+ )
85
+ return
86
+ # a table or schema: Unity Catalog stores these in lower case, so a name with capitals would
87
+ # be created under a different name than the one asked for
88
+ if any(c in _UC_NAME_BAD for c in name):
89
+ raise ShapeError(
90
+ f"{kind} name {name!r}: Unity Catalog names cannot contain a space, '.', '/' or '`'"
91
+ )
92
+ if name != name.lower():
93
+ raise ShapeError(
94
+ f"{kind} name {name!r}: Unity Catalog stores {kind} names in lower case; "
95
+ f"use {name.lower()!r}"
96
+ )
97
+
98
+
99
+ def check_unique(names: Sequence[str], dialect: str) -> None:
100
+ """Column names that the database would take for one name are refused."""
101
+ seen: set[str] = set()
102
+ for name in names:
103
+ key = name.lower() if dialect == "databricks" else name
104
+ if key in seen:
105
+ raise ShapeError(f"column name {name!r} appears twice (or differs only in case)")
106
+ seen.add(key)
107
+
108
+
109
+ def quote(name: str, dialect: str) -> str:
110
+ """One quoted identifier (core's quoting: ``"x"`` for PostgreSQL and Snowflake, backticks for
111
+ MySQL and Databricks)."""
112
+ return str(core_sql._quote(name, _QUOTE_AS.get(dialect, dialect)))
113
+
114
+
115
+ def qualified(schema_name: str | None, table: str, dialect: str) -> str:
116
+ return (f"{quote(schema_name, dialect)}." if schema_name else "") + quote(table, dialect)
117
+
118
+
119
+ def check_mode(mode: Any) -> str:
120
+ if mode not in WRITE_MODES:
121
+ raise ShapeError(f"unknown write mode {mode!r}; choose one of {', '.join(WRITE_MODES)}")
122
+ return str(mode)
123
+
124
+
125
+ def positive_int(value: Any, name: str, *, optional: bool = False) -> int | None:
126
+ if value is None and optional:
127
+ return None
128
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
129
+ raise ShapeError(f"{name} must be a positive integer")
130
+ return value
131
+
132
+
133
+ def _observed_length(column: pa.ChunkedArray | pa.Array) -> int:
134
+ if not (pat.is_string(column.type) or pat.is_large_string(column.type)):
135
+ return -1
136
+ longest = pc.max(pc.utf8_length(column)).as_py()
137
+ return int(longest or 0)
138
+
139
+
140
+ def column_definitions(
141
+ schema: pa.Schema,
142
+ first: pa.RecordBatch | None,
143
+ meta: Mapping[str, Mapping[str, Any]],
144
+ key: Sequence[str],
145
+ dialect: str,
146
+ ) -> list[tuple[str, str, bool]]:
147
+ """``(name, sql type, nullable)`` per column: core's type map, with string columns wide
148
+ enough for the first batch (a later, longer value fails the write rather than truncating)."""
149
+ out: list[tuple[str, str, bool]] = []
150
+ for index, field in enumerate(schema):
151
+ info: dict[str, Any] = dict(meta.get(field.name, {}))
152
+ sql_type: str | None = None
153
+ if core_sql._logical_type(field.type) == "string" and not info.get("max_length"):
154
+ seen = _observed_length(first.column(index)) if first is not None else 0
155
+ if not (pat.is_string(field.type) or pat.is_large_string(field.type)):
156
+ seen = -1
157
+ if seen < 0 or seen > MAX_VARCHAR:
158
+ sql_type = _TEXT[dialect] # nested, dictionary or very long text
159
+ else:
160
+ info["max_length"] = max(255, seen)
161
+ if sql_type is None:
162
+ sql_type = core_sql._column_type(field, info, dialect)
163
+ nullable = bool(info.get("nullable", True)) and field.name not in key
164
+ out.append((field.name, sql_type, nullable))
165
+ return out
166
+
167
+
168
+ def create_table_sql(
169
+ schema_name: str | None,
170
+ table: str,
171
+ schema: pa.Schema,
172
+ dialect: str,
173
+ *,
174
+ first: pa.RecordBatch | None = None,
175
+ columns: Mapping[str, Mapping[str, Any]] | None = None,
176
+ primary_key: Sequence[str] = (),
177
+ ) -> str:
178
+ for name in schema.names:
179
+ check_identifier(name, "column", dialect)
180
+ for name in primary_key:
181
+ if name not in schema.names:
182
+ raise ShapeError(f"primary key column {name!r} is not a column of {table!r}")
183
+ defs = [
184
+ f" {quote(name, dialect)} {sql_type} {'NULL' if nullable else 'NOT NULL'}"
185
+ for name, sql_type, nullable in column_definitions(
186
+ schema, first, columns or {}, primary_key, dialect
187
+ )
188
+ ]
189
+ if primary_key:
190
+ defs.append(f" PRIMARY KEY ({', '.join(quote(c, dialect) for c in primary_key)})")
191
+ body = ",\n".join(defs)
192
+ return f"CREATE TABLE {qualified(schema_name, table, dialect)} (\n{body}\n)"
193
+
194
+
195
+ def drop_table_sql(schema_name: str | None, table: str, dialect: str) -> str:
196
+ suffix = " CASCADE" if dialect == "postgres" else ""
197
+ return f"DROP TABLE IF EXISTS {qualified(schema_name, table, dialect)}{suffix}"
198
+
199
+
200
+ def truncate_sql(schema_name: str | None, table: str, dialect: str) -> str:
201
+ return f"TRUNCATE TABLE {qualified(schema_name, table, dialect)}"
202
+
203
+
204
+ def check_batch(first: pa.Schema, batch: pa.RecordBatch, table: str) -> None:
205
+ if list(batch.schema.names) != list(first.names):
206
+ raise ShapeError(
207
+ f"a batch for {table!r} has columns {list(batch.schema.names)} but the first one "
208
+ f"had {list(first.names)}"
209
+ )
210
+
211
+
212
+ # -- values --------------------------------------------------------------------------------
213
+ def _utc_naive(value: dt.datetime) -> dt.datetime:
214
+ if value.tzinfo is None:
215
+ return value
216
+ return value.astimezone(dt.UTC).replace(tzinfo=None)
217
+
218
+
219
+ def _json(value: Any) -> str:
220
+ return json.dumps(value, default=str, ensure_ascii=False)
221
+
222
+
223
+ def _converter(field: pa.Field, dialect: str) -> Callable[[Any], Any] | None:
224
+ """The per-value fix a column needs before it reaches the driver, or ``None``.
225
+
226
+ Timestamps lose their zone as UTC (the column type has none, as in the script dialect);
227
+ nested values become JSON text; durations become text; MySQL cannot store NaN or infinity,
228
+ so they become NULL (as in the script dialect)."""
229
+ kind = field.type
230
+ if pat.is_timestamp(kind) and kind.tz is not None:
231
+ return lambda v: None if v is None else _utc_naive(v)
232
+ if pat.is_list(kind) or pat.is_large_list(kind) or pat.is_struct(kind) or pat.is_map(kind):
233
+ return lambda v: None if v is None else _json(v)
234
+ if pat.is_duration(kind):
235
+ return lambda v: None if v is None else str(v)
236
+ if dialect == "mysql" and pat.is_floating(kind):
237
+ return lambda v: None if v is None or not math.isfinite(v) else v
238
+ return None
239
+
240
+
241
+ def row_iterator(
242
+ batch: pa.RecordBatch, dialect: str, converters: Sequence[Callable[[Any], Any] | None]
243
+ ) -> Iterator[tuple[Any, ...]]:
244
+ columns = []
245
+ for index in range(batch.num_columns):
246
+ values = batch.column(index).to_pylist()
247
+ convert = converters[index]
248
+ columns.append(values if convert is None else [convert(v) for v in values])
249
+ return zip(*columns, strict=True)
250
+
251
+
252
+ def converters_for(schema: pa.Schema, dialect: str) -> list[Callable[[Any], Any] | None]:
253
+ return [_converter(field, dialect) for field in schema]
254
+
255
+
256
+ def _declared_integer(field: pa.Field, meta: Mapping[str, Mapping[str, Any]]) -> bool:
257
+ return pat.is_floating(field.type) and meta.get(field.name, {}).get("type") == "integer"
258
+
259
+
260
+ def normalize(
261
+ batch: pa.RecordBatch, columns: Mapping[str, Mapping[str, Any]] | None = None
262
+ ) -> pa.RecordBatch:
263
+ """Dictionary columns decoded, so every value reaches the driver as its plain value; a
264
+ floating column declared ``integer`` in ``columns`` (the DDL makes it BIGINT) cast to
265
+ int64, refused with its name when a value is not whole."""
266
+ meta = columns or {}
267
+ if not any(pat.is_dictionary(f.type) or _declared_integer(f, meta) for f in batch.schema):
268
+ return batch
269
+ arrays = []
270
+ for field, column in zip(batch.schema, batch.columns, strict=True):
271
+ if pat.is_dictionary(column.type):
272
+ column = column.dictionary_decode()
273
+ if _declared_integer(field, meta):
274
+ try:
275
+ column = pc.cast(column, pa.int64(), safe=True)
276
+ except (pa.ArrowInvalid, OverflowError) as exc:
277
+ raise ShapeError(
278
+ f"column {field.name!r} is declared integer but holds a value that is not "
279
+ f"a whole number in the int64 range ({exc})"
280
+ ) from None
281
+ arrays.append(column)
282
+ return pa.RecordBatch.from_arrays(arrays, names=batch.schema.names)