Sources
Python API
The sqlload package's API for Python sources: declaring tables and their settings, what a table function yields, the run's context, sl.http jobs, logged state and other functions.
The sqlload package declares Python sources: tables whose rows a Python function yields. To set
them up, and for HTTP APIs, see Load from Python and HTTP APIs.
The API at a glance
Section titled “The API at a glance”import sqlload as sl
# A source: the settings its tables share.shop = sl.source("shop", write_strategy="merge")
# A table: one function, one table.@shop.table(unique_key="order_id", cursor_column="updated_at")def orders(ctx: sl.Context): """Orders from the shop, one row per order.""" # ctx.cursor_value is where the last load ended. for page in fetch_orders(updated_after=ctx.cursor_value): # Dicts, Arrow data, JSON bytes or an sl.http job. yield pageDeclaring
Section titled “Declaring”| Function | Returns |
|---|---|
sl.source(name, *, description=None, **settings) |
A Source. settings are its connection, destination, destination_schema and its tables’ defaults. |
@source.table or @source.table(*, name=None, description=None, **settings) |
A Table of the source. |
@sl.table or @sl.table(...) |
A standalone Table in the target’s schema, with its own write_strategy. |
@source.client |
A client the source’s tables share as ctx.client, built once per run. |
Declaring a table never runs its function; it runs when the table loads. A table’s description
(its destination comment) is description=, else the docstring. Unknown settings raise TypeError
at import.
Settings
Section titled “Settings”Settings go on a source, as defaults, or on a table, except as noted.
| Setting | Meaning |
|---|---|
write_strategy, unique_key, on_duplicate_keys, null_keys, newest_by, cursor_column, cursor_start, lookback, append_cursor_inclusive, batch_size, on_cursor_out_of_range |
As in sqlload.toml; no lookahead or lookback_from. Every table needs a write_strategy. merge needs unique_key columns: "{primary_key}" is refused, as Python sources have none. |
contract, on_schema_change, auto_widen, type_change_rebuild |
See Contracts. |
infer_types |
False loads dict rows’ columns as text, except pinned columns, objects and lists. See Loading every column as text. |
on_nonfinite |
"keep" (default) or "null". See NaN and infinities. |
checks |
Such as {"unique": ["order_id"]}. See Checks before publish. |
constant_columns |
Same value in every row: {"tenant_id": "acme"} or {"shard": {"value": "7", "type": "int"}}. A table’s replace its source’s. A yielded field of that name, in any case, fails the table. See Several tenants in one table. |
allow_empty |
Let replace empty a table when the function yields no rows. |
state |
"logged" to keep a position in ctx.state. See Logged state. |
send |
"at_commit" or "per_batch". See Sending rows at commit. |
columns (table) |
Pinned types, such as {"total": "decimal(18,2)"}. |
flatten (table) |
Dotted paths of objects to load as <object>__<key> columns, or "all". See Flattening objects. |
naming, compat, on_duplicate_names |
See Naming. |
rename |
A map such as {"orderId": "order_ref"}, or an @sl.rename function or its name. See rename. |
unnest, max_depth (table) |
List fields to load as child tables (["items"] or "all"), and how deep. See Nested data. |
mask (table), exclude_columns, allow_columns |
As for other sources. |
table_name, destination_path |
Destination name template, and folder in a files target. |
connection, destination, destination_schema, mask_key, parallel_tables (source) |
Connection, target, schema, HMAC key, and whether tables sharing a client load at once. |
What a function yields
Section titled “What a function yields”A table function is a generator, or returns an iterable. It can yield, in any mix:
| Yield | Becomes |
|---|---|
| A dict, or a list of dicts | Rows, typed like JSON. |
| Arrow data: a pyarrow table or batch, a polars or pandas DataFrame | Rows, keeping their Arrow types. |
sl.json(data, path=None, *, fields=None, keep_record=None) |
Rows from a JSON array of objects, at a dotted path such as "data.items", or objects. Parsed in Rust. See Fields. |
sl.ndjson(data, *, fields=None, keep_record=None) |
Rows from newline-delimited JSON. Parsed in Rust. |
An sl.http job |
The rows it fetches, in Rust. See HTTP APIs. |
sl.checkpoint(position) |
A logged position covering the rows yielded before it. |
Dict values are typed like JSON. Nested dicts and lists become JSON columns, or arrays under an
array(T) pin. Also:
| Python value | Column type |
|---|---|
Decimal |
decimal, with room for at least 19 digits before the point. Over 38 digits: text. NaN and infinity: NULL. |
date |
date |
naive datetime |
timestamp_ntz |
datetime with a UTC offset |
timestamp_tz (a column mixing both becomes text) |
bytes, bytearray, memoryview |
binary; base64 text when mixed with text, pinned text, under infer_types=False, or nested. |
Enum |
Its value. |
| dataclass | A JSON object. |
| numpy numbers | Numbers. |
Other values, including subclasses such as pandas.Timestamp |
Text. |
columns overrides inference. A first load with no rows creates nothing unless columns are
declared. Inferred types don’t change by themselves; see
Inferred types.
Nested values stay one JSON column (VARIANT on Snowflake) unless flatten names them:
flatten=["customer", "customer.address"] loads customer__country and customer__address__city.
Dicts, sl.json and Arrow structs flatten alike. See
Flattening objects.
NaN and infinities
Section titled “NaN and infinities”NaN, inf and -inf load as themselves in a float column or an array(float) list. Where the
column can’t hold them, the table fails, naming the column and the row: a decimal or integer pin, a
nested value loading as json, or array(float) on Snowflake. on_nonfinite="null" loads them as
NULL, nested ones too, and plan says so on the schema lines. on_nonfinite doesn’t apply to
Arrow data: its float columns and array(float) lists keep NaN and infinities (failing into
Snowflake), and in nested values that load as json they load as NULL.
Fields
Section titled “Fields”Without fields, each key of a JSON row is a column under its own name, so updated-at needs
quoting in queries. fields loads only the values it names, under the names it gives, on sl.json,
sl.ndjson, paginate and fan_out:
api.paginate( "/accounts", paginator=sl.offset(limit=50), select="$.items", fields={ "id": sl.field("$.id", required=True), "account_code": "$.code", "updated_at": "$.updated-at", "city": "$.address.city", }, keep_record="raw_json",)| Field | Loads |
|---|---|
"$.code" |
The value at the path; NULL when it’s missing. |
sl.field(path, *, required=False, parse=None, on_error="fail") |
The same. required=True fails the table on a missing value, naming the row and path. parse converts it as a table’s parse does ("epoch_ms", {"timestamp": [...], "tz": ...}, …); a value that doesn’t convert fails the table, or loads NULL with on_error="null". Other conversions belong in a transform. |
sl.parent(path, *, levels=1, ...), sl.key(name) |
Values from around the row. See Values from around the row. |
keep_recordadds the whole row as a JSON column. It needsfields, and a table with amaskrefuses it.columns,flattenandmaskname the projected columns.- A table’s
cursor_columnmust be loaded (as a field,keep_recordor a flattened field), or it fails before any request or parsing. - A fan-out’s
overtakes nofieldsorkey_path.
Path syntax
Section titled “Path syntax”Paths in fields, sl.field, sl.parent and key_path, as JSONPath, jq and dlt write them:
| Path | Reads |
|---|---|
$ |
The whole row object. |
$.id, $.address.city |
A key, and keys below it. Keys can’t hold ., [ or ]. |
$.items[0].id |
Item 0 of a list, then a key below it. |
$.statuses[-1].name |
Counting from the end: [-1] is the last item. |
$.grid[1][0] |
A list inside a list. |
A missing key or out-of-range index loads NULL. Anything else is refused, naming the field and path:
[*] and .* (use select to make items rows), filters, slices, .. and ['id']. An sl.http
job fails before any request; sl.json and sl.ndjson when yielded.
plan reads the table function’s source, without calling it, and checks the literal paths of its
sl.http jobs, in every branch:
$ sqlload planErrors (1)└── raw.shop__orders └── reason fields["sku"]: field path "$.lines[*].sku" uses the wildcard [*], which one column can't hold; take one item with [n] or [-1], or select the list's items as rows
✗ Plan failed 1 errorPaths that aren’t literals (a variable, an f-string, a dict built elsewhere) are checked at load,
before any request, and plan lists them on a paths checked at load, … line. Jobs built in
another function the table function calls are checked only at load.
Values from around the row
Section titled “Values from around the row”An sl.http job’s fields can read beyond the row. This loads one row per Jira change history, each
with its issue’s ID:
api.fan_out( "/rest/api/3/changelog/bulkfetch", over=updated, method="POST", json_body={"issueIdsOrKeys": "{id}"}, batch=1000, paginator=sl.cursor( "$.nextPageToken", "$.nextPageToken", location="body" ), select="$.issueChangeLogs[*].changeHistories[*]", fields={ "issue_id": sl.parent("$.issueId", required=True), "history_id": sl.field("$.id", required=True), "created": sl.field("$.created", parse="epoch_ms"), "items": "$.items", }, key_path=sl.parent("$.issueId"),)selectcan pass through several lists.sl.parent(path, levels=1)reads the nearest objectselectpasses through by name, here the issue;levels=2the next one out, up to the response itself. It takesrequired,parseandon_error. Too many levels fail before any request.sl.key(name)is the keynamethe row’s fan-out request was made for, from any level above. A name no level provides fails before any request, as doessl.keywithbatch=.key_pathonfan_outfails the table when a record’s key isn’t among those its request (or batch) sent, for an API that answers for other keys. A request filling several placeholders refuses it.sl.json,sl.ndjsonandcellsrefusesl.parentandsl.key.
The context
Section titled “The context”A table function receives an sl.Context:
| Attribute | Meaning |
|---|---|
ctx.cursor_value |
Where to read from: the destination’s maximum minus lookback, cursor_start, or --start-cursor. None reads everything. |
ctx.cursor_end |
Where the window ends (excluded), with batch_size or --end-cursor; else None. |
ctx.cursor_column, ctx.cursor_inclusive |
The cursor column, and whether the read includes cursor_value (False when append reads after the maximum). |
ctx.is_reload |
True under --reload. |
ctx.state |
The logged position, with state="logged". Assign it to move the position. |
ctx.connection |
The source’s connection settings, as a mapping. ctx.connection("name") gives another’s, except connections a target writes to. |
ctx.client |
The source’s @source.client, built on first use. |
ctx.table, ctx.source, ctx.logger |
The table and source names, and a logger. |
- Cursor times arrive in the table’s
timezone, else UTC (or naive, fortimestamp_ntz). Withtimezoneset, atimestamp_ntzcursor’s values carry the zone too, so compare them with naive times asctx.cursor_value.replace(tzinfo=None). See Times without an offset. - Rows outside the window fail the table, unless
on_cursor_out_of_rangeskips or warns. See Rows outside the window. - A source using a connection a target writes to fails
plan. - Tables sharing a
@source.clientload one at a time, unless the source setsparallel_tables=True.
HTTP APIs
Section titled “HTTP APIs”sl.http declares paginated REST, fan-out, POST, and OAuth2 jobs that run in Rust. See
HTTP APIs for the full reference and
the Python guide for worked examples.
Logged state
Section titled “Logged state”A table whose position the data can’t carry, such as a sync token, sets state="logged", reads
ctx.state, and yields sl.checkpoint(position) (any JSON value) after the rows it covers;
sl.checkpoint(None) clears it. See Logged state, and
sqlload logged-state to inspect or correct it.
Other functions
Section titled “Other functions”| Name | Meaning |
|---|---|
sl.__version__ |
The package version. |
sl.executable() |
The path of the sqlload command installed with the package, else the one on PATH. |
@sl.transform, @sl.transform("name") |
Registers a function, under its name or the one given, as the transform of a files or Google Sheets table or an sl.http job. Returns it unchanged. |
@sl.rename, @sl.rename("name") |
Registers a function for rename. It gets sl.Columns (position, source, default) and an sl.RenameContext (source, table), and returns the names it changes by position. See rename. |
sl.TransformContext |
A transform’s ctx: unit ("file", "range" or "page"), table, and the unit’s details. |
Without the engine
Section titled “Without the engine”sl.http and its paginators, sl.json, sl.ndjson, sl.field, sl.parent, sl.key,
sl.checkpoint and @sl.transform come from sqlload-api,
a pure-Python package that sqlload re-exports. A tool running SQLLoad’s engine in its own process
builds the same items with it, naming the connection:
import sqlload_api
api = sqlload_api.http(connection="shop_api")orders = api.paginate("/orders", select="$.items", paginator=sqlload_api.next_link("$.next"))It’s released with sqlload at the same version; an engine reads items of its own version.
Embedding the Python host
Section titled “Embedding the Python host”A tool with its own pyo3 extension can run its tables on SQLLoad’s engine with the
sqlload-python-host crate. Its tables yield what an
sl.source’s do, declared through a Python runtime module the tool names:
use sqlload_python_host::host::main::module_host::module_host;
let host = module_host("my_tool._sqlload_runtime");The crate’s README lists the functions that module defines, and the pyo3 (0.29, abi3-py310) and
sqlload-api versions it needs. sqlload_api.Context.from_read(read, **extras) builds a table’s
ctx as SQLLoad does; subclass sqlload_api.Context to add the tool’s own fields.