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.
- sqlload_api/__init__.py +68 -0
- sqlload_api/_data.py +213 -0
- sqlload_api/_http.py +428 -0
- sqlload_api/_http_paths.py +218 -0
- sqlload_api/_registry.py +103 -0
- sqlload_api/_transform.py +113 -0
- sqlload_api/_wire/__init__.py +149 -0
- sqlload_api/_wire/checkpoint.json +6 -0
- sqlload_api/_wire/fan_out_batch.json +53 -0
- sqlload_api/_wire/fan_out_nested.json +85 -0
- sqlload_api/_wire/fan_out_values.json +28 -0
- sqlload_api/_wire/json_document.json +17 -0
- sqlload_api/_wire/ndjson_lines.json +17 -0
- sqlload_api/_wire/paginate_cells.json +34 -0
- sqlload_api/_wire/paginate_cursor.json +23 -0
- sqlload_api/_wire/paginate_header_row.json +29 -0
- sqlload_api/_wire/paginate_link_header.json +24 -0
- sqlload_api/_wire/paginate_next_link.json +21 -0
- sqlload_api/_wire/paginate_offset.json +27 -0
- sqlload_api/_wire/paginate_page_number_post.json +30 -0
- sqlload_api/_wire/paginate_projected.json +53 -0
- sqlload_api/py.typed +0 -0
- sqlload_api-0.85.0.dist-info/METADATA +34 -0
- sqlload_api-0.85.0.dist-info/RECORD +26 -0
- sqlload_api-0.85.0.dist-info/WHEEL +4 -0
- sqlload_api-0.85.0.dist-info/licenses/LICENSE +201 -0
sqlload_api/_http.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""HTTP jobs a table function returns or yields: built in Python, run entirely in Rust.
|
|
2
|
+
|
|
3
|
+
Calling `paginate` or `fan_out` sends no request; it builds a job definition. A table function
|
|
4
|
+
returns or yields it, and SQLLoad runs every request, page and fan-out in Rust, parsing each
|
|
5
|
+
response once into the table's rows.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Protocol
|
|
12
|
+
|
|
13
|
+
from sqlload_api._data import Field, Fields, field_list
|
|
14
|
+
from sqlload_api._transform import TRANSFORMS
|
|
15
|
+
|
|
16
|
+
#: What moved from `sl.http` onto the `http` connection in sqlload.toml.
|
|
17
|
+
CONNECTION_SETTINGS = ("auth", "rate_limit", "max_in_flight", "retries")
|
|
18
|
+
|
|
19
|
+
ROW_LOOP_HINT = (
|
|
20
|
+
"rows of an sl.http job stay in Rust and are never handed to Python one at a time (rule python_row_loop); "
|
|
21
|
+
"return or yield the job itself, and filter the rows downstream, or reshape each page with transform="
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConnectionOwner(Protocol):
|
|
26
|
+
"""What `sl.http` reads a connection from: a SQLLoad `sl.source(...)`, or anything with a name and settings."""
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def name(self) -> str: ...
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def settings(self) -> Mapping[str, Any]: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Paginator:
|
|
37
|
+
"""How the next page is found; every paginate names one."""
|
|
38
|
+
|
|
39
|
+
spec: Mapping[str, Any]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Cells:
|
|
44
|
+
"""How each row's list of cells becomes columns; `paginate` and `fan_out` take it as `cells=`."""
|
|
45
|
+
|
|
46
|
+
spec: Mapping[str, Any]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class CellName:
|
|
51
|
+
"""Where the cells' column names come from: `sl.listed(...)` or `sl.header_row()`; `sl.cells` takes it as `name=`."""
|
|
52
|
+
|
|
53
|
+
spec: Mapping[str, Any]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cells(pointer: str = "$.cells", *, value: str | Sequence[str] = "$.value", name: str | CellName) -> Cells:
|
|
57
|
+
"""Each row's cells at `pointer` as one column per named column, typed like any other value; a missing cell loads NULL.
|
|
58
|
+
|
|
59
|
+
`value` is where a cell's value is, or several places tried in turn. `name` is where each cell's column name comes
|
|
60
|
+
from: a path in the cell (`"$.FIELDNAME"`), so each cell names itself; `sl.listed("$.columns")`, the columns the
|
|
61
|
+
response lists; or `sl.header_row()`, the first row's cells. The names then load like any other column's, through
|
|
62
|
+
`naming` and `rename`."""
|
|
63
|
+
values = [value] if isinstance(value, str) else list(value)
|
|
64
|
+
if isinstance(name, str):
|
|
65
|
+
named: dict[str, Any] = {"kind": "field", "path": name}
|
|
66
|
+
elif isinstance(name, CellName):
|
|
67
|
+
named = dict(name.spec)
|
|
68
|
+
else:
|
|
69
|
+
raise TypeError(f'sl.cells name= takes a path in the cell such as "$.name", sl.listed(...) or sl.header_row(), not {name!r}')
|
|
70
|
+
return Cells({"pointer": pointer, "value": values, "name": named})
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def listed(path: str, /, *, key: str | None = "columnId", id_key: str = "id", name_key: str | None = "title", by_position: bool = False) -> CellName:
|
|
74
|
+
"""The columns a response lists at `path` (such as `"$.columns"`; a page without the list keeps the names before it).
|
|
75
|
+
|
|
76
|
+
Each cell's `key` field is matched to a listed column's `id_key`, and the column is named by its `name_key`
|
|
77
|
+
(Smartsheet: the defaults); `name_key=None` when each listed column is its name. `by_position=True` matches cells to
|
|
78
|
+
the listed columns by position instead. A cell whose column is not listed fails the load."""
|
|
79
|
+
return CellName({"kind": "listed", "from": path, "key": None if by_position else key, "id_key": id_key, "name_key": name_key})
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def header_row() -> CellName:
|
|
83
|
+
"""The first row's cells name the columns, matched by position (Google's grid data); that row does not load."""
|
|
84
|
+
return CellName({"kind": "header_row"})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def single() -> Paginator:
|
|
88
|
+
"""One request, no further pages."""
|
|
89
|
+
return Paginator({"kind": "single"})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def next_link(pointer: str, *, read_ahead: int | None = None) -> Paginator:
|
|
93
|
+
"""The next page's URL at `pointer` in the body (such as `"$.next"`); ends when missing, null or empty."""
|
|
94
|
+
_no_read_ahead("sl.next_link", read_ahead)
|
|
95
|
+
return Paginator({"kind": "next_link", "pointer": pointer})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def link_header(*, read_ahead: int | None = None) -> Paginator:
|
|
99
|
+
"""The `Link` header's `rel="next"` URL."""
|
|
100
|
+
_no_read_ahead("sl.link_header", read_ahead)
|
|
101
|
+
return Paginator({"kind": "link_header"})
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def offset(
|
|
105
|
+
param: str = "offset", *, limit: int, limit_param: str = "limit", location: str = "query", read_ahead: int | None = None
|
|
106
|
+
) -> Paginator:
|
|
107
|
+
"""`param` counts rows from 0 by `limit`; ends at a page with fewer than `limit` rows.
|
|
108
|
+
|
|
109
|
+
With `location="body"`, `param` and `limit_param` are paths in the POST's JSON body, such as `"$.page.offset"`.
|
|
110
|
+
With `read_ahead=N`, the pages after a full first page are requested N at a time and still loaded in page order."""
|
|
111
|
+
return Paginator(
|
|
112
|
+
{"kind": "offset", "param": param, "limit_param": limit_param, "limit": limit, "location": _location(location), **_read_ahead(read_ahead)}
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def page_number(
|
|
117
|
+
param: str = "page",
|
|
118
|
+
*,
|
|
119
|
+
start: int = 1,
|
|
120
|
+
page_size: int | None = None,
|
|
121
|
+
page_size_param: str | None = "page_size",
|
|
122
|
+
location: str = "query",
|
|
123
|
+
read_ahead: int | None = None,
|
|
124
|
+
) -> Paginator:
|
|
125
|
+
"""`param` counts pages from `start`; ends at an empty page, or with `page_size=N` at a page with fewer than N rows.
|
|
126
|
+
|
|
127
|
+
`page_size` is sent as `page_size_param` with every page; `page_size_param=None` sends nothing, for an API whose
|
|
128
|
+
page size is fixed. A short page is checked with one more request until the API has shown it doesn't cap its pages
|
|
129
|
+
lower: an API that does still loads every row, paged to an empty page.
|
|
130
|
+
With `location="body"`, `param` and `page_size_param` are paths in the JSON body.
|
|
131
|
+
With `read_ahead=N`, the pages after a full first page are requested N at a time and still loaded in page order."""
|
|
132
|
+
sized: dict[str, Any] = {}
|
|
133
|
+
if page_size is not None:
|
|
134
|
+
if isinstance(page_size, bool) or not isinstance(page_size, int):
|
|
135
|
+
raise TypeError(f"sl.page_number page_size takes a whole number of rows, not {page_size!r}")
|
|
136
|
+
if page_size < 1:
|
|
137
|
+
raise ValueError(f"sl.page_number page_size must be at least 1, not {page_size}")
|
|
138
|
+
sized = {"page_size": page_size, "page_size_param": page_size_param}
|
|
139
|
+
elif page_size_param != "page_size":
|
|
140
|
+
raise ValueError("sl.page_number page_size_param needs page_size: the number of rows a page holds")
|
|
141
|
+
return Paginator(
|
|
142
|
+
{"kind": "page_number", "param": param, "start": start, **sized, "location": _location(location), **_read_ahead(read_ahead)}
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cursor(pointer: str, param: str, *, location: str = "query", read_ahead: int | None = None) -> Paginator:
|
|
147
|
+
"""The token at `pointer` in the response goes back as query parameter `param`; ends when missing, null or empty.
|
|
148
|
+
|
|
149
|
+
With `location="body"`, `param` is a path in the POST's JSON body, such as `"$.page.cursor"`."""
|
|
150
|
+
_no_read_ahead("sl.cursor", read_ahead)
|
|
151
|
+
return Paginator({"kind": "cursor", "pointer": pointer, "param": param, "location": _location(location)})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _read_ahead(read_ahead: int | None) -> dict[str, Any]:
|
|
155
|
+
"""`read_ahead` as a paginator field, left out when unset so paginators without it are unchanged."""
|
|
156
|
+
if read_ahead is not None and (isinstance(read_ahead, bool) or not isinstance(read_ahead, int)):
|
|
157
|
+
raise TypeError(f"read_ahead takes a whole number of pages, not {read_ahead!r}")
|
|
158
|
+
return {} if read_ahead is None else {"read_ahead": read_ahead}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _no_read_ahead(paginator: str, read_ahead: int | None) -> None:
|
|
162
|
+
if read_ahead is not None:
|
|
163
|
+
raise ValueError(
|
|
164
|
+
f"{paginator} cannot take read_ahead: each page's address comes from the page before it; read_ahead needs sl.offset or sl.page_number"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _location(location: str) -> str:
|
|
169
|
+
if location not in ("query", "body"):
|
|
170
|
+
raise ValueError(f'location must be "query" or "body", not {location!r}')
|
|
171
|
+
return location
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _param_text(value: Any) -> str:
|
|
175
|
+
"""A request parameter JSON has no form for, such as a `datetime` cursor value: ISO text for dates and times, else `str()`."""
|
|
176
|
+
isoformat = getattr(value, "isoformat", None)
|
|
177
|
+
return isoformat() if callable(isoformat) else str(value)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class Job:
|
|
181
|
+
"""An HTTP job definition; a table function returns or yields it, and Rust runs it."""
|
|
182
|
+
|
|
183
|
+
def __init__(self, definition: dict[str, Any], transform: Callable[..., Any] | str | None = None) -> None:
|
|
184
|
+
self._definition = definition
|
|
185
|
+
#: Kept as given, and looked up when the job is handed to Rust: a job built at module level outlives the run that
|
|
186
|
+
#: first registered a function passed as itself, and each run lets go of those when it finishes.
|
|
187
|
+
self._transform = transform
|
|
188
|
+
|
|
189
|
+
def __sqlload_http_job__(self) -> str:
|
|
190
|
+
definition = self._definition
|
|
191
|
+
if self._transform is not None:
|
|
192
|
+
function, name = TRANSFORMS.key(self._transform)
|
|
193
|
+
definition = {**definition, "transform": {"function": function, "name": name}}
|
|
194
|
+
return json.dumps(definition, default=_param_text)
|
|
195
|
+
|
|
196
|
+
def __iter__(self) -> Iterator["Job"]:
|
|
197
|
+
"""`yield from job` hands the job itself to Rust."""
|
|
198
|
+
yield self
|
|
199
|
+
|
|
200
|
+
def __getitem__(self, key: Any) -> Any:
|
|
201
|
+
raise TypeError(ROW_LOOP_HINT)
|
|
202
|
+
|
|
203
|
+
def get(self, key: Any, default: Any = None) -> Any:
|
|
204
|
+
raise TypeError(ROW_LOOP_HINT)
|
|
205
|
+
|
|
206
|
+
def __repr__(self) -> str:
|
|
207
|
+
return f"sl.http job {json.dumps(self._definition)}"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class Http:
|
|
211
|
+
"""Requests to one HTTP connection, a source's or one named: `paginate` and `fan_out` build jobs."""
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self,
|
|
215
|
+
source: ConnectionOwner | None = None,
|
|
216
|
+
*,
|
|
217
|
+
headers: Mapping[str, str] | None = None,
|
|
218
|
+
connection: str | None = None,
|
|
219
|
+
**moved: Any,
|
|
220
|
+
) -> None:
|
|
221
|
+
name = connection or (None if source is None else source.settings.get("connection"))
|
|
222
|
+
if not name and source is None:
|
|
223
|
+
raise ValueError("sl.http needs a connection: pass connection=, or a source that sets one")
|
|
224
|
+
if not name:
|
|
225
|
+
raise ValueError(f"sl.http needs a connection: set connection= on source {source.name} or pass connection=")
|
|
226
|
+
for key in moved:
|
|
227
|
+
if key in CONNECTION_SETTINGS:
|
|
228
|
+
raise TypeError(f"sl.http no longer takes {key}: set {key} on [connections.{name}] in sqlload.toml")
|
|
229
|
+
raise TypeError(f"sl.http got an unexpected keyword argument {key!r}")
|
|
230
|
+
self._client = {"connection": name, "headers": dict(headers or {})}
|
|
231
|
+
|
|
232
|
+
def paginate(
|
|
233
|
+
self,
|
|
234
|
+
path: str,
|
|
235
|
+
*,
|
|
236
|
+
paginator: Paginator,
|
|
237
|
+
params: Mapping[str, Any] | None = None,
|
|
238
|
+
select: str | None = None,
|
|
239
|
+
on_status: Mapping[int, str] | None = None,
|
|
240
|
+
fields: Fields | None = None,
|
|
241
|
+
keep_record: str | None = None,
|
|
242
|
+
method: str = "GET",
|
|
243
|
+
json_body: Mapping[str, Any] | None = None,
|
|
244
|
+
key: str | None = None,
|
|
245
|
+
cells: Cells | None = None,
|
|
246
|
+
select_missing: str = "fail",
|
|
247
|
+
error_path: str | None = None,
|
|
248
|
+
transform: Callable[..., Any] | str | None = None,
|
|
249
|
+
) -> Job:
|
|
250
|
+
"""Every page of `path`; `select` (such as `"$.items"`) is where the rows are, `on_status={404: "skip"}` treats a status as no rows.
|
|
251
|
+
|
|
252
|
+
A response without the `select` path fails the load, naming what it holds, unless `select_missing="empty"` reads it as
|
|
253
|
+
no rows, for APIs that leave an empty list out (as Google's do); an empty list or null is no rows either way.
|
|
254
|
+
`error_path` (such as `"$.errors"`) is where an API answering 200 reports an error: any value there but null,
|
|
255
|
+
false, `""`, `[]` or `{}` fails the table with it, before that page's rows load.
|
|
256
|
+
|
|
257
|
+
`fields` loads only those values of each row, renamed (`{"account_code": "$.code"}`); `keep_record` adds each
|
|
258
|
+
row's whole object as a JSON column. `method="POST"` sends `json_body` as JSON with every page, each page's copy
|
|
259
|
+
holding the paginator's values when its `location` is `"body"`. As a fan-out's `over`, `key` names the
|
|
260
|
+
placeholder the selected values fill when it is not the field's own name (`select="$.items[*].id", key="order_id"`).
|
|
261
|
+
|
|
262
|
+
`transform` (a function, or the name `@sl.transform` registered one under) is called once per page, in page
|
|
263
|
+
order, on the page's rows after `select`, `fields` and `cells`, as `f(rows, ctx)`; what it returns or yields loads."""
|
|
264
|
+
request = self._request(path, paginator, params, select, on_status, (method, json_body))
|
|
265
|
+
return Job(
|
|
266
|
+
{
|
|
267
|
+
"kind": "paginate",
|
|
268
|
+
**request,
|
|
269
|
+
**_projection(fields, keep_record),
|
|
270
|
+
**_key(key),
|
|
271
|
+
**_cells(cells),
|
|
272
|
+
**_select_missing(select_missing),
|
|
273
|
+
**_error_path(error_path),
|
|
274
|
+
},
|
|
275
|
+
_transform(transform),
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def fan_out(
|
|
279
|
+
self,
|
|
280
|
+
path: str,
|
|
281
|
+
*,
|
|
282
|
+
over: Job | Iterable[Any],
|
|
283
|
+
concurrency: int = 8,
|
|
284
|
+
paginator: Paginator | None = None,
|
|
285
|
+
params: Mapping[str, Any] | None = None,
|
|
286
|
+
select: str | None = None,
|
|
287
|
+
on_status: Mapping[int, str] | None = None,
|
|
288
|
+
fields: Fields | None = None,
|
|
289
|
+
keep_record: str | None = None,
|
|
290
|
+
method: str = "GET",
|
|
291
|
+
json_body: Mapping[str, Any] | None = None,
|
|
292
|
+
key: str | None = None,
|
|
293
|
+
cells: Cells | None = None,
|
|
294
|
+
batch: int | None = None,
|
|
295
|
+
select_missing: str = "fail",
|
|
296
|
+
error_path: str | None = None,
|
|
297
|
+
key_path: str | Field | None = None,
|
|
298
|
+
transform: Callable[..., Any] | str | None = None,
|
|
299
|
+
) -> Job:
|
|
300
|
+
"""Every page of `path` once per key of `over`, up to `concurrency` at a time: `over` is a paginate whose
|
|
301
|
+
`select` picks the keys (`"$.items[*].id"` fills `{id}`), or values (`["uk", "fr"]` fill the one placeholder;
|
|
302
|
+
dicts fill them by name).
|
|
303
|
+
|
|
304
|
+
`over` can also be another fan_out whose `select` picks keys, as deep as they nest: each key keeps the
|
|
305
|
+
fields of the keys above it, so a third level's path can use `{order_id}` and `{item_id}`. `key` names the
|
|
306
|
+
placeholder this fan-out's selected values fill when it is itself an `over`.
|
|
307
|
+
|
|
308
|
+
With `method="POST"`, `{name}` placeholders in `json_body`'s string values are filled from each key as well:
|
|
309
|
+
a value that is just `"{id}"` takes the key as it is (a number stays a number), and `plan` checks a level
|
|
310
|
+
above gives every one. `batch=1000` sends up to 1000 keys per request instead, each such value holding the
|
|
311
|
+
list of the batch's keys (`{"ids": "{id}"}` sends `{"ids": [1, 2, 3]}`); each batch is one request,
|
|
312
|
+
retried as a whole. `select_missing` and `error_path` are as for `paginate`.
|
|
313
|
+
|
|
314
|
+
`key_path="$.issueId"` (from each record, or `sl.parent("$.issueId")` from an object around it) fails the
|
|
315
|
+
table when a record's key is not among the keys its request sent (with `batch=`, the batch's), catching an
|
|
316
|
+
API that answers for other keys.
|
|
317
|
+
|
|
318
|
+
`transform` is as for `paginate`, once per page of each key; its `ctx.key` holds the key's fields (`None` with
|
|
319
|
+
`batch=`)."""
|
|
320
|
+
if isinstance(over, (str, bytes)):
|
|
321
|
+
raise TypeError("fan_out over= takes a paginate or fan_out job or a list of values, not one string")
|
|
322
|
+
if isinstance(over, Job) and over._transform is not None:
|
|
323
|
+
raise TypeError("transform is for the job whose rows load, not for the job given as fan_out's over=")
|
|
324
|
+
over_spec = dict(over._definition) if isinstance(over, Job) else {"kind": "values", "values": list(over)}
|
|
325
|
+
request = self._request(path, paginator or single(), params, select, on_status, (method, json_body))
|
|
326
|
+
projected = _projection(fields, keep_record)
|
|
327
|
+
batched = {} if batch is None else {"batch": batch}
|
|
328
|
+
return Job(
|
|
329
|
+
{
|
|
330
|
+
"kind": "fan_out",
|
|
331
|
+
**request,
|
|
332
|
+
**projected,
|
|
333
|
+
**_key(key),
|
|
334
|
+
**_cells(cells),
|
|
335
|
+
**_select_missing(select_missing),
|
|
336
|
+
**_error_path(error_path),
|
|
337
|
+
**_key_path(key_path),
|
|
338
|
+
"over": over_spec,
|
|
339
|
+
"concurrency": concurrency,
|
|
340
|
+
**batched,
|
|
341
|
+
},
|
|
342
|
+
_transform(transform),
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
def _request(
|
|
346
|
+
self,
|
|
347
|
+
path: str,
|
|
348
|
+
paginator: Paginator,
|
|
349
|
+
params: Mapping[str, Any] | None,
|
|
350
|
+
select: str | None,
|
|
351
|
+
on_status: Mapping[int, str] | None,
|
|
352
|
+
body: tuple[str, Mapping[str, Any] | None],
|
|
353
|
+
) -> dict[str, Any]:
|
|
354
|
+
method, json_body = body
|
|
355
|
+
if method.upper() not in ("GET", "POST"):
|
|
356
|
+
raise ValueError(f'method must be "GET" or "POST", not {method!r}')
|
|
357
|
+
return {
|
|
358
|
+
"client": self._client,
|
|
359
|
+
"path": path,
|
|
360
|
+
"params": dict(params or {}),
|
|
361
|
+
"method": method.upper(),
|
|
362
|
+
"json_body": None if json_body is None else json.loads(json.dumps(json_body, default=_param_text)),
|
|
363
|
+
"paginator": dict(paginator.spec),
|
|
364
|
+
"select": select,
|
|
365
|
+
"on_status": {str(status): action for status, action in (on_status or {}).items()},
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _key(key: str | None) -> dict[str, Any]:
|
|
370
|
+
"""`key` as a job field, left out when unset so jobs without it are unchanged."""
|
|
371
|
+
return {} if key is None else {"key": key}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _cells(cells: Cells | None) -> dict[str, Any]:
|
|
375
|
+
"""`cells` as a job field, left out when unset so jobs without it are unchanged."""
|
|
376
|
+
return {} if cells is None else {"cells": dict(cells.spec)}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _select_missing(select_missing: str) -> dict[str, Any]:
|
|
380
|
+
"""`select_missing` as a job field, left out at its default so jobs without it are unchanged."""
|
|
381
|
+
if select_missing not in ("fail", "empty"):
|
|
382
|
+
raise ValueError(f'select_missing must be "fail" or "empty", not {select_missing!r}')
|
|
383
|
+
return {} if select_missing == "fail" else {"select_missing": select_missing}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _error_path(error_path: str | None) -> dict[str, Any]:
|
|
387
|
+
"""`error_path` as a job field, left out when unset so jobs without it are unchanged."""
|
|
388
|
+
return {} if error_path is None else {"error_path": error_path}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _key_path(key_path: str | Field | None) -> dict[str, Any]:
|
|
392
|
+
"""`key_path` as a job field, left out when unset so jobs without it are unchanged."""
|
|
393
|
+
if key_path is None:
|
|
394
|
+
return {}
|
|
395
|
+
if isinstance(key_path, str):
|
|
396
|
+
return {"key_path": {"path": key_path}}
|
|
397
|
+
if isinstance(key_path, Field) and key_path.source is not None and key_path.source.get("kind") == "parent":
|
|
398
|
+
return {"key_path": {"path": key_path.path, "from": dict(key_path.source)}}
|
|
399
|
+
raise TypeError(f'key_path takes a path such as "$.issueId" or sl.parent(...), not {key_path!r}')
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _transform(transform: Callable[..., Any] | str | None) -> Callable[..., Any] | str | None:
|
|
403
|
+
"""`transform` as given, refused here when it is neither a function nor a name."""
|
|
404
|
+
if transform is not None and not isinstance(transform, str) and not callable(transform):
|
|
405
|
+
raise TypeError(f"expected a function or the name @sl.transform registered one under, not {type(transform).__name__}")
|
|
406
|
+
return transform
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _projection(fields: Fields | None, keep_record: str | None) -> dict[str, Any]:
|
|
410
|
+
listed = field_list(fields)
|
|
411
|
+
return {
|
|
412
|
+
"fields": listed,
|
|
413
|
+
"keep_record": keep_record,
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def http(
|
|
418
|
+
source: ConnectionOwner | None = None,
|
|
419
|
+
*,
|
|
420
|
+
headers: Mapping[str, str] | None = None,
|
|
421
|
+
connection: str | None = None,
|
|
422
|
+
**moved: Any,
|
|
423
|
+
) -> Http:
|
|
424
|
+
"""Requests to `source`'s HTTP connection (or `connection`, which is all it needs without a source), adding `headers`
|
|
425
|
+
to the connection's. The connection sets how requests authenticate (`auth`), the limits every request to it shares
|
|
426
|
+
in the run (`rate_limit`, `max_in_flight`) and its `retries`. The job is the same whichever way the connection is
|
|
427
|
+
given."""
|
|
428
|
+
return Http(source, headers=headers, connection=connection, **moved)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""The `sl.http` field paths a table function writes as literals, read from its source without calling it.
|
|
2
|
+
|
|
3
|
+
`plan` checks them with load's own path checker, so a bad literal path fails `plan` instead of the load. Only calls whose
|
|
4
|
+
names resolve to sqlload or sqlload_api count: `paginate` and `fan_out` on an `sl.http(...)` client (or, with
|
|
5
|
+
`context_clients`, one the function's context makes, such as `ctx.http()`), and `sl.field`, `sl.parent` and `sl.key` in
|
|
6
|
+
their `fields=`. A `transform=` given as a name must be one `@sl.transform` registered. A path `plan` can't
|
|
7
|
+
read as a literal (a variable, an f-string, a dict built elsewhere), or a function whose source can't be read, is left to
|
|
8
|
+
load, which checks every job before its first request.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import ast
|
|
12
|
+
import inspect
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
import textwrap
|
|
16
|
+
import types
|
|
17
|
+
from collections.abc import Callable, Collection, Iterator, Mapping
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from sqlload_api import _data, _http
|
|
21
|
+
from sqlload_api._transform import TRANSFORMS
|
|
22
|
+
|
|
23
|
+
#: The methods of an `sl.http` client that build a job.
|
|
24
|
+
JOB_METHODS: frozenset[str] = frozenset({"paginate", "fan_out"})
|
|
25
|
+
|
|
26
|
+
#: The packages a name must resolve into for its call to count: `sqlload` re-exports `sqlload_api`'s functions.
|
|
27
|
+
PACKAGES: tuple[str, ...] = ("sqlload", "sqlload_api")
|
|
28
|
+
|
|
29
|
+
#: A name or attribute that doesn't resolve to anything `plan` may look at.
|
|
30
|
+
_UNRESOLVED: Any = object()
|
|
31
|
+
|
|
32
|
+
#: A local name assigned an `sl.http(...)` client inside the table function.
|
|
33
|
+
_LOCAL_CLIENT: Any = object()
|
|
34
|
+
|
|
35
|
+
#: The table function's first parameter, its context, when `context_clients` names methods of it that make clients.
|
|
36
|
+
_CONTEXT: Any = object()
|
|
37
|
+
|
|
38
|
+
#: A context method named in `context_clients`: calling it makes a client.
|
|
39
|
+
_CONTEXT_CLIENT: Any = object()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def literal_paths(function: Callable[..., Any], *, context_clients: Collection[str] = ()) -> dict[str, Any] | None:
|
|
43
|
+
"""The literal paths of the jobs `function` builds that load rows: each `fields=` entry's `[name, path]` and each
|
|
44
|
+
`key_path`; why a `transform=` name can't be looked up; what `plan` can't read as a literal; and whether the source
|
|
45
|
+
can't be read at all. A job passed as another
|
|
46
|
+
job's `over=` is left out: load refuses its `fields` and `key_path` whatever their paths. `None` when the function builds
|
|
47
|
+
no job `plan` can see.
|
|
48
|
+
|
|
49
|
+
`context_clients` names methods of the function's first parameter that return an `sl.http` client (`{"http"}` for
|
|
50
|
+
`api = ctx.http()` or `ctx.http().paginate(...)`); none by default."""
|
|
51
|
+
try:
|
|
52
|
+
tree = ast.parse(textwrap.dedent(inspect.getsource(function)))
|
|
53
|
+
except (OSError, TypeError, SyntaxError):
|
|
54
|
+
return {"fields": [], "key_paths": [], "computed": [], "no_source": True}
|
|
55
|
+
definition = next((node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))), None)
|
|
56
|
+
if definition is None:
|
|
57
|
+
return {"fields": [], "key_paths": [], "computed": [], "no_source": True}
|
|
58
|
+
names = _Names(function, definition, frozenset(context_clients))
|
|
59
|
+
jobs = [call for call in ast.walk(definition) if isinstance(call, ast.Call) and _job_method(call, names)]
|
|
60
|
+
if not jobs:
|
|
61
|
+
return None
|
|
62
|
+
found: dict[str, Any] = {"fields": [], "key_paths": [], "computed": [], "no_source": False, "transform_problems": []}
|
|
63
|
+
over = _over_jobs(definition, jobs)
|
|
64
|
+
for call in jobs:
|
|
65
|
+
if id(call) not in over:
|
|
66
|
+
_read_call(call, names, found)
|
|
67
|
+
return found
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _Names:
|
|
71
|
+
"""What the names a table function uses resolve to: its own imports and `sl.http(...)` clients, else its closure and
|
|
72
|
+
module globals; a name it assigns otherwise shadows them and resolves to nothing."""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self, function: Callable[..., Any], definition: ast.FunctionDef | ast.AsyncFunctionDef, context_clients: frozenset[str]
|
|
76
|
+
) -> None:
|
|
77
|
+
self.context_clients = context_clients
|
|
78
|
+
self.outer: dict[str, Any] = dict(getattr(function, "__globals__", {}))
|
|
79
|
+
code = getattr(function, "__code__", None)
|
|
80
|
+
for name, cell in zip(code.co_freevars if code else (), getattr(function, "__closure__", None) or ()):
|
|
81
|
+
try:
|
|
82
|
+
self.outer[name] = cell.cell_contents
|
|
83
|
+
except ValueError:
|
|
84
|
+
self.outer[name] = _UNRESOLVED
|
|
85
|
+
self.local: dict[str, Any] = {}
|
|
86
|
+
arguments = definition.args
|
|
87
|
+
for argument in [*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs, arguments.vararg, arguments.kwarg]:
|
|
88
|
+
if argument is not None:
|
|
89
|
+
self.local[argument.arg] = _UNRESOLVED
|
|
90
|
+
positional = [*arguments.posonlyargs, *arguments.args]
|
|
91
|
+
if context_clients and positional:
|
|
92
|
+
self.local[positional[0].arg] = _CONTEXT
|
|
93
|
+
for node in ast.walk(definition):
|
|
94
|
+
self._bind(node)
|
|
95
|
+
|
|
96
|
+
def _bind(self, node: ast.AST) -> None:
|
|
97
|
+
if isinstance(node, ast.Import):
|
|
98
|
+
for alias in node.names:
|
|
99
|
+
bound = alias.asname or alias.name.partition(".")[0]
|
|
100
|
+
self.local[bound] = sys.modules.get(alias.name if alias.asname else bound, _UNRESOLVED)
|
|
101
|
+
elif isinstance(node, ast.ImportFrom):
|
|
102
|
+
module = sys.modules.get(node.module or "") if node.level == 0 else None
|
|
103
|
+
for alias in node.names:
|
|
104
|
+
self.local[alias.asname or alias.name] = getattr(module, alias.name, _UNRESOLVED) if _ours(module) else _UNRESOLVED
|
|
105
|
+
elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
|
106
|
+
client = isinstance(node.value, ast.Call) and _makes_client(self.resolve(node.value.func))
|
|
107
|
+
self.local[node.targets[0].id] = _LOCAL_CLIENT if client and self.local.get(node.targets[0].id, _LOCAL_CLIENT) is _LOCAL_CLIENT else _UNRESOLVED
|
|
108
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id not in self.local:
|
|
109
|
+
self.local[node.id] = _UNRESOLVED
|
|
110
|
+
|
|
111
|
+
def resolve(self, node: ast.expr) -> Any:
|
|
112
|
+
"""What a name or a dotted attribute resolves to, looking only into sqlload's modules and clients."""
|
|
113
|
+
if isinstance(node, ast.Name):
|
|
114
|
+
return self.local[node.id] if node.id in self.local else self.outer.get(node.id, _UNRESOLVED)
|
|
115
|
+
if isinstance(node, ast.Call) and self.resolve(node.func) is _CONTEXT_CLIENT:
|
|
116
|
+
return _LOCAL_CLIENT
|
|
117
|
+
if not isinstance(node, ast.Attribute):
|
|
118
|
+
return _UNRESOLVED
|
|
119
|
+
owner = self.resolve(node.value)
|
|
120
|
+
if owner is _CONTEXT:
|
|
121
|
+
return _CONTEXT_CLIENT if node.attr in self.context_clients else _UNRESOLVED
|
|
122
|
+
if isinstance(owner, types.ModuleType) and _ours(owner):
|
|
123
|
+
return getattr(owner, node.attr, _UNRESOLVED)
|
|
124
|
+
if (owner is _LOCAL_CLIENT or isinstance(owner, _http.Http)) and node.attr in JOB_METHODS:
|
|
125
|
+
return node.attr
|
|
126
|
+
return _UNRESOLVED
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _ours(module: Any) -> bool:
|
|
130
|
+
"""Whether `module` is sqlload, sqlload_api or one of their modules."""
|
|
131
|
+
name = getattr(module, "__name__", "") if isinstance(module, types.ModuleType) else ""
|
|
132
|
+
return any(name == package or name.startswith(f"{package}.") for package in PACKAGES)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _makes_client(resolved: Any) -> bool:
|
|
136
|
+
"""Whether calling what a name resolved to makes an `sl.http` client: `sl.http`, `sl.Http`, or a context method
|
|
137
|
+
`context_clients` names."""
|
|
138
|
+
return resolved is _CONTEXT_CLIENT or resolved in (_http.http, _http.Http)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _job_method(call: ast.Call, names: _Names) -> str | None:
|
|
142
|
+
"""`paginate` or `fan_out` when `call` builds a job on an `sl.http` client."""
|
|
143
|
+
method = names.resolve(call.func)
|
|
144
|
+
return method if isinstance(method, str) else None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _over_jobs(definition: ast.AST, jobs: list[ast.Call]) -> set[int]:
|
|
148
|
+
"""The jobs passed as another job's `over=`, directly or through a name assigned them."""
|
|
149
|
+
assigned: dict[str, list[int]] = {}
|
|
150
|
+
for node in ast.walk(definition):
|
|
151
|
+
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and isinstance(node.value, ast.Call):
|
|
152
|
+
assigned.setdefault(node.targets[0].id, []).append(id(node.value))
|
|
153
|
+
over: set[int] = set()
|
|
154
|
+
for call in jobs:
|
|
155
|
+
for keyword in call.keywords:
|
|
156
|
+
if keyword.arg != "over":
|
|
157
|
+
continue
|
|
158
|
+
if isinstance(keyword.value, ast.Call):
|
|
159
|
+
over.add(id(keyword.value))
|
|
160
|
+
elif isinstance(keyword.value, ast.Name):
|
|
161
|
+
over.update(assigned.get(keyword.value.id, []))
|
|
162
|
+
return over
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _read_call(call: ast.Call, names: _Names, found: dict[str, Any]) -> None:
|
|
166
|
+
"""Add `call`'s literal `fields=` and `key_path=` paths to `found`, or what it can't read as literals."""
|
|
167
|
+
for keyword in call.keywords:
|
|
168
|
+
if keyword.arg is None:
|
|
169
|
+
found["computed"].append(f"{_job_method(call, names)}(**...)")
|
|
170
|
+
elif keyword.arg == "fields":
|
|
171
|
+
_read_fields(keyword.value, names, found)
|
|
172
|
+
elif keyword.arg == "transform" and isinstance(keyword.value, ast.Constant) and isinstance(keyword.value.value, str):
|
|
173
|
+
_, problem = TRANSFORMS.lookup(keyword.value.value)
|
|
174
|
+
if problem is not None:
|
|
175
|
+
found["transform_problems"].append(f"transform {keyword.value.value}: {problem}")
|
|
176
|
+
elif keyword.arg == "key_path":
|
|
177
|
+
path = _literal_path(keyword.value, names, (_data.parent,))
|
|
178
|
+
_record(found, "key_path", path, lambda text: found["key_paths"].append(text))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _read_fields(value: ast.expr, names: _Names, found: dict[str, Any]) -> None:
|
|
182
|
+
if isinstance(value, ast.Constant) and value.value is None:
|
|
183
|
+
return
|
|
184
|
+
if not isinstance(value, ast.Dict):
|
|
185
|
+
found["computed"].append("fields")
|
|
186
|
+
return
|
|
187
|
+
for key, spec in zip(value.keys, value.values):
|
|
188
|
+
if not (isinstance(key, ast.Constant) and isinstance(key.value, str)):
|
|
189
|
+
found["computed"].append("fields")
|
|
190
|
+
continue
|
|
191
|
+
name = key.value
|
|
192
|
+
if isinstance(spec, ast.Call) and names.resolve(spec.func) is _data.key:
|
|
193
|
+
continue
|
|
194
|
+
path = _literal_path(spec, names, (_data.field, _data.parent))
|
|
195
|
+
_record(found, f"fields[{json.dumps(name)}]", path, lambda text, name=name: found["fields"].append([name, text]))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _literal_path(value: ast.expr, names: _Names, functions: tuple[Callable[..., Any], ...]) -> str | None:
|
|
199
|
+
"""The path `value` writes as a literal: a string, or the first argument (or `path=`) of one of sqlload's `functions`."""
|
|
200
|
+
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
|
201
|
+
return value.value
|
|
202
|
+
if not (isinstance(value, ast.Call) and names.resolve(value.func) in functions):
|
|
203
|
+
return None
|
|
204
|
+
given = [*value.args[:1], *(keyword.value for keyword in value.keywords if keyword.arg == "path")]
|
|
205
|
+
return next(_strings(given), None)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _strings(values: list[ast.expr]) -> Iterator[str]:
|
|
209
|
+
for value in values:
|
|
210
|
+
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
|
211
|
+
yield value.value
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _record(found: Mapping[str, Any], label: str, path: str | None, add: Callable[[str], None]) -> None:
|
|
215
|
+
if path is None:
|
|
216
|
+
found["computed"].append(label)
|
|
217
|
+
else:
|
|
218
|
+
add(path)
|