sqlload-api 0.85.0__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,68 @@
1
+ """SQLLoad's Python API for describing data and requests, without the engine.
2
+
3
+ A table function (or another tool's loader) yields what these build, and the engine that reads them runs it:
4
+
5
+ - `http(...)` jobs (`paginate`, `fan_out`) that make every request and parse every page in Rust;
6
+ - `json(...)` and `ndjson(...)` bytes, parsed without the GIL;
7
+ - `checkpoint(...)` positions between a logged table's rows.
8
+
9
+ Each crosses as plain data through a method the engine looks for (`__sqlload_http_job__`, `__sqlload_json__`,
10
+ `__sqlload_checkpoint__`), so this package holds no compiled code. `sqlload` re-exports it: `import sqlload as sl;
11
+ sl.http` is `sqlload_api.http`. Without a SQLLoad source, name the connection: `http(connection="shop_api")`.
12
+ """
13
+
14
+ from importlib.metadata import version
15
+
16
+ from sqlload_api._data import Checkpoint, Field, JsonData, checkpoint, field, json, key, ndjson, parent
17
+ from sqlload_api._http import (
18
+ CellName,
19
+ Cells,
20
+ ConnectionOwner,
21
+ Http,
22
+ Job,
23
+ cells,
24
+ cursor,
25
+ header_row,
26
+ http,
27
+ link_header,
28
+ listed,
29
+ next_link,
30
+ offset,
31
+ page_number,
32
+ single,
33
+ )
34
+ from sqlload_api._http_paths import literal_paths
35
+ from sqlload_api._transform import TransformContext, transform
36
+
37
+ __version__: str = version("sqlload-api")
38
+
39
+ __all__ = [
40
+ "CellName",
41
+ "Cells",
42
+ "Checkpoint",
43
+ "ConnectionOwner",
44
+ "Field",
45
+ "Http",
46
+ "Job",
47
+ "JsonData",
48
+ "TransformContext",
49
+ "__version__",
50
+ "cells",
51
+ "checkpoint",
52
+ "cursor",
53
+ "field",
54
+ "header_row",
55
+ "http",
56
+ "json",
57
+ "key",
58
+ "link_header",
59
+ "listed",
60
+ "literal_paths",
61
+ "ndjson",
62
+ "next_link",
63
+ "offset",
64
+ "page_number",
65
+ "parent",
66
+ "single",
67
+ "transform",
68
+ ]
sqlload_api/_data.py ADDED
@@ -0,0 +1,213 @@
1
+ """What a table function can yield besides rows: JSON bytes, which Rust parses without the GIL, and checkpoints.
2
+
3
+ Each crosses into the engine through a method returning plain data (`__sqlload_json__`, `__sqlload_checkpoint__`), so
4
+ this module needs no compiled code; the engine checks what it reads.
5
+ """
6
+
7
+ import json as _json
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ BytesLike = bytes | bytearray | memoryview | str
13
+
14
+
15
+ #: What `sl.field(parse=...)` takes, the shape of a table's `parse` entry: an epoch word, or a mapping with `timestamp` or `date` (a format or a list of formats), and optionally `tz` and `on_error`; anything else belongs in a `transform`.
16
+ Parse = str | Mapping[str, Any]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Field:
21
+ """One projected column's path, whether every row must have a value there, and how that value converts."""
22
+
23
+ path: str
24
+ required: bool = False
25
+ parse: Parse | None = None
26
+ on_error: str = "fail"
27
+ #: Where `path` starts when not at the row: `sl.parent`'s enclosing object or `sl.key`'s request key, as the spec's `from`.
28
+ source: Mapping[str, Any] | None = None
29
+
30
+
31
+ #: `fields=`: each column's path, such as `"$.address.city"` or `"$.items[0].id"`, or an `sl.field(...)`.
32
+ Fields = Mapping[str, "str | Field"]
33
+
34
+
35
+ def field(path: str, *, required: bool = False, parse: Parse | None = None, on_error: str = "fail") -> Field:
36
+ """The value at `path` (such as `"$.updated-at"` or `"$.items[0].id"`) for `fields=`; `required=True` fails the table on a
37
+ row without one. A path is dotted keys after `$`, each optionally followed by list indexes: `[0]` is the first item and
38
+ `[-1]` the last. A missing key, an index past the end of the list or on a value that isn't a list gives NULL. Other
39
+ JSONPath syntax (`[*]`, filters, slices, `..`) is refused, naming the field.
40
+
41
+ `parse` converts the value, as a table's `parse` setting does: `"epoch_s"`, `"epoch_ms"` or `"epoch_us"` turn a number
42
+ (or numeric text) into a UTC timestamp; `{"timestamp": ["iso", "%m/%d/%Y %H:%M"]}` and `{"date": "%d/%m/%Y"}` read
43
+ text with a format, or each of a list of formats in turn, the first that reads it winning. A time without an offset
44
+ is read in `"tz"` (such as `{"timestamp": "%d/%m/%Y %H:%M", "tz": "Europe/Paris"}`), else the table's `timezone`,
45
+ else UTC, and loads as `timestamp_tz`. A value that doesn't convert fails the table, naming the field and the value,
46
+ or loads NULL with `on_error="null"`. Other conversions belong in a `transform`."""
47
+ return Field(path, required, parse, on_error)
48
+
49
+
50
+ def parent(path: str, *, levels: int = 1, required: bool = False, parse: Parse | None = None, on_error: str = "fail") -> Field:
51
+ """In an `sl.http` job's `fields=`, the value at `path` in the object around each row that `select` passes through:
52
+ the nearest with `levels=1`, further out with more, the response document itself outermost (so a page's envelope
53
+ works too). `required`, `parse` and `on_error` are as for `sl.field`; `plan` refuses more levels than `select` has."""
54
+ if isinstance(levels, bool) or not isinstance(levels, int):
55
+ raise TypeError(f"sl.parent levels takes a whole number, not {levels!r}")
56
+ return Field(path, required, parse, on_error, {"kind": "parent", "levels": levels})
57
+
58
+
59
+ def key(name: str, *, required: bool = False) -> Field:
60
+ """In a `fan_out`'s `fields=`, the value of key field `name` its request was made for, from any level above
61
+ (each key keeps the fields of the keys above it). `plan` refuses a name no level provides, and `batch=`, where
62
+ one request carries many keys."""
63
+ if not isinstance(name, str):
64
+ raise TypeError(f"sl.key takes a key field's name, not {name!r}")
65
+ return Field("$", required, None, "fail", {"kind": "key", "name": name})
66
+
67
+
68
+ class JsonData:
69
+ """JSON or NDJSON bytes yielded by a table function (`sl.json(...)`, `sl.ndjson(...)`), parsed by the engine.
70
+
71
+ It crosses as `__sqlload_json__()`: the bytes, and how to read them as JSON. The engine checks the read when the
72
+ item crosses (a field's path syntax among it), failing the table with the problem."""
73
+
74
+ __slots__ = ("_bytes", "_fields", "_keep_record", "_lines", "_path")
75
+
76
+ def __init__(
77
+ self,
78
+ data: bytes | bytearray,
79
+ *,
80
+ lines: bool = False,
81
+ path: str | None = None,
82
+ fields: list[dict[str, Any]] | None = None,
83
+ keep_record: str | None = None,
84
+ ) -> None:
85
+ if lines and path is not None:
86
+ raise ValueError("path picks rows out of a JSON document; NDJSON has none")
87
+ if keep_record is not None and fields is None:
88
+ raise ValueError("keep_record needs fields: name the columns to load beside the whole record")
89
+ self._bytes = data
90
+ self._lines = lines
91
+ self._path = path
92
+ self._fields = fields
93
+ self._keep_record = keep_record
94
+
95
+ @property
96
+ def lines(self) -> bool:
97
+ """Whether the bytes are NDJSON."""
98
+ return self._lines
99
+
100
+ @property
101
+ def path(self) -> str | None:
102
+ """The dotted path to the rows inside the document, if any."""
103
+ return self._path
104
+
105
+ def __len__(self) -> int:
106
+ return len(self._bytes)
107
+
108
+ def __sqlload_json__(self) -> tuple[bytes | bytearray, str]:
109
+ """The bytes, and the read as the engine takes it: layout, path, fields and keep_record."""
110
+ read = {
111
+ "layout": "lines" if self._lines else "document",
112
+ "path": self._path,
113
+ "fields": self._fields,
114
+ "keep_record": self._keep_record,
115
+ }
116
+ return self._bytes, _json.dumps(read)
117
+
118
+ def __repr__(self) -> str:
119
+ kind = "sl.ndjson" if self._lines else "sl.json"
120
+ return f"{kind}({len(self._bytes)} bytes)"
121
+
122
+
123
+ def json(data: BytesLike, path: str | None = None, *, fields: Fields | None = None, keep_record: str | None = None) -> JsonData:
124
+ """Rows in a JSON document: an array of objects (at dotted `path`, such as `"data.items"`), or objects.
125
+
126
+ `fields` loads only those values, renamed (`{"account_code": "$.code"}`); `keep_record` adds each row's whole
127
+ object as a JSON column."""
128
+ return JsonData(_as_bytes(data), path=path, fields=_json_fields(fields), keep_record=keep_record)
129
+
130
+
131
+ def ndjson(data: BytesLike, *, fields: Fields | None = None, keep_record: str | None = None) -> JsonData:
132
+ """Rows as newline-delimited JSON, one object per line; `fields` and `keep_record` as for `sl.json`."""
133
+ return JsonData(_as_bytes(data), lines=True, fields=_json_fields(fields), keep_record=keep_record)
134
+
135
+
136
+ def field_list(fields: Fields | None) -> list[dict[str, Any]] | None:
137
+ """`fields` as the specs Rust reads (name, path, required, and parse and on_error when set), in the order given."""
138
+ if fields is None:
139
+ return None
140
+ if not isinstance(fields, Mapping):
141
+ raise TypeError(f"fields takes a mapping of column name to path, such as {{\"id\": \"$.id\"}}, not {fields!r}")
142
+ listed = []
143
+ for name, spec in fields.items():
144
+ projected = spec if isinstance(spec, Field) else Field(spec)
145
+ if not isinstance(name, str):
146
+ raise TypeError(f"fields names columns with text, not {name!r}")
147
+ if not isinstance(projected.path, str):
148
+ raise TypeError(f"fields[{name!r}] takes a path such as \"$.id\" or sl.field(...), not {spec!r}")
149
+ if not isinstance(projected.required, bool):
150
+ raise TypeError(f"fields[{name!r}]: required takes True or False, not {projected.required!r}")
151
+ source = {} if projected.source is None else {"from": dict(projected.source)}
152
+ listed.append({"name": name, "path": projected.path, "required": projected.required, **_conversion(name, projected), **source})
153
+ return listed
154
+
155
+
156
+ def _conversion(name: str, projected: Field) -> dict[str, Any]:
157
+ """`projected`'s parse and on_error as spec keys, left out when unset so specs without them are unchanged."""
158
+ if projected.on_error not in ("fail", "null"):
159
+ raise ValueError(f'fields[{name!r}]: on_error must be "fail" or "null", not {projected.on_error!r}')
160
+ parse = projected.parse
161
+ if parse is None:
162
+ if projected.on_error != "fail":
163
+ raise ValueError(f"fields[{name!r}]: on_error applies to values parse converts; set parse too")
164
+ return {}
165
+ if not isinstance(parse, (str, Mapping)):
166
+ raise ValueError(
167
+ f'fields[{name!r}]: parse takes "epoch_s", "epoch_ms", "epoch_us", or {{"timestamp": formats}} or {{"date": formats}}, not {parse!r}; '
168
+ "other conversions belong in a transform"
169
+ )
170
+ # Rust reads the rest, as it reads a table's parse setting.
171
+ return {"parse": parse if isinstance(parse, str) else dict(parse), **({"on_error": "null"} if projected.on_error == "null" else {})}
172
+
173
+
174
+ def _json_fields(fields: Fields | None) -> list[dict[str, Any]] | None:
175
+ """`fields` as the list of specs `JsonData` crosses with."""
176
+ listed = field_list(fields)
177
+ for spec in listed or []:
178
+ if "from" in spec:
179
+ raise ValueError(f"fields[{spec['name']!r}]: sl.parent and sl.key read around the rows of an sl.http job; sl.json and sl.ndjson rows have no request")
180
+ return listed
181
+
182
+
183
+ def _as_bytes(data: BytesLike) -> bytes | bytearray:
184
+ if isinstance(data, str):
185
+ return data.encode()
186
+ if isinstance(data, memoryview):
187
+ return data.tobytes()
188
+ return data
189
+
190
+
191
+ class Checkpoint:
192
+ """A position yielded among a logged table's rows; see `checkpoint`."""
193
+
194
+ def __init__(self, state: Any) -> None:
195
+ try:
196
+ self._state = _json.dumps(state)
197
+ except (TypeError, ValueError) as error:
198
+ raise TypeError(f"sl.checkpoint state is not JSON: {error}") from error
199
+
200
+ def __sqlload_checkpoint__(self) -> str:
201
+ return self._state
202
+
203
+ def __repr__(self) -> str:
204
+ return f"sl.checkpoint({self._state})"
205
+
206
+
207
+ def checkpoint(state: Any) -> Checkpoint:
208
+ """The position (any JSON value) that covers exactly the rows yielded before it, for a `state="logged"`
209
+ table: `yield sl.checkpoint(page.next_token)` after a page's rows. A commit records the latest checkpoint
210
+ whose rows are all in it, so a run that fails part-way resumes there without loading any row twice; the
211
+ next run reads it as `ctx.state`. Rows yielded after the last checkpoint are loaded again by the next run
212
+ unless the function leaves the final position in `ctx.state`; `sl.checkpoint(None)` clears the position."""
213
+ return Checkpoint(state)