Skip to content

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.

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 page
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 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.

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, 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.

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_record adds the whole row as a JSON column. It needs fields, and a table with a mask refuses it.
  • columns, flatten and mask name the projected columns.
  • A table’s cursor_column must be loaded (as a field, keep_record or a flattened field), or it fails before any request or parsing.
  • A fan-out’s over takes no fields or key_path.

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 plan
Errors (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 error

Paths 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.

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"),
)
  • select can pass through several lists.
  • sl.parent(path, levels=1) reads the nearest object select passes through by name, here the issue; levels=2 the next one out, up to the response itself. It takes required, parse and on_error. Too many levels fail before any request.
  • sl.key(name) is the key name the row’s fan-out request was made for, from any level above. A name no level provides fails before any request, as does sl.key with batch=.
  • key_path on fan_out fails 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.ndjson and cells refuse sl.parent and sl.key.

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, for timestamp_ntz). With timezone set, a timestamp_ntz cursor’s values carry the zone too, so compare them with naive times as ctx.cursor_value.replace(tzinfo=None). See Times without an offset.
  • Rows outside the window fail the table, unless on_cursor_out_of_range skips or warns. See Rows outside the window.
  • A source using a connection a target writes to fails plan.
  • Tables sharing a @source.client load one at a time, unless the source sets parallel_tables=True.

sl.http describes REST jobs that run entirely in Rust; for worked examples see HTTP APIs in the guide. Its http connection sets auth, rate_limit, max_in_flight and retries.

Function Meaning
sl.http(source=None, *, headers=None, connection=None) Requests to the source’s connection, or connection, adding headers. Connection settings passed here fail, naming the key to set.
api.paginate(path, *, paginator, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, select_missing="fail", error_path=None, transform=None) Every page of path.
api.fan_out(path, *, over, concurrency=8, paginator=None, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, batch=None, select_missing="fail", error_path=None, key_path=None, transform=None) path once per key of over, concurrency at a time, as keys arrive. One request per key without a paginator.
Argument Meaning
params Query parameters. None values are left out; times go as ISO text.
select Where the rows are: $, or a path such as $.data.items. See A missing select path.
on_status Statuses read as no rows, such as {404: "skip"}.
select_missing "empty" reads a response without select as no rows.
key The placeholder this job’s keys fill as another fan-out’s over.
over A paginate whose select picks keys ($.items[*].id fills {id}), a fan-out, or a list of values (one placeholder) or dicts (by name).

The rest are below: fields, keep_record, key_path, error_path, transform, method, json_body, batch and cells.

Paginator Next page
sl.single() None: one request.
sl.next_link(pointer) The URL at pointer, such as "$.next".
sl.link_header() The Link header’s rel="next".
sl.cursor(pointer, param, *, location="query") The token at pointer, sent back as param.
sl.offset(param="offset", *, limit, limit_param="limit", location="query", read_ahead=None) Counts rows by limit; ends at a short page.
sl.page_number(param="page", *, start=1, page_size=None, page_size_param="page_size", location="query", read_ahead=None) Counts pages; ends at an empty page, or a short page with page_size.

location="body" puts a paginator’s values in a POST body. For read_ahead, see Reading pages ahead.

Cells Columns
sl.cells(pointer="$.cells", *, value="$.value", name) One column per name from each row’s cells at pointer. name is a path in each cell, such as "$.FIELDNAME", or one of the two below.
sl.listed(path, *, key="columnId", id_key="id", name_key="title", by_position=False) The columns listed at path: a cell’s key matches a column’s id_key, or its position; name_key names it.
sl.header_row() The first row names the columns, by position, and doesn’t load.
  • A run’s requests to one connection share its limits, across tables; separate sqlload load processes don’t.
  • Credentials go only to the connection’s origin; OAuth2 secrets only to token_url.
  • Transport errors, 429 and 5xx are retried, honouring Retry-After. Other error statuses fail, unless on_status skips them. Errors name the request, status and start of the body, secrets as ***.
  • Reading a job’s rows in Python fails (rule python_row_loop); use transform.

Without page_size, sl.page_number ends only at an empty page, so a fan-out whose keys fit in one page sends two requests per key. With page_size, a short page ends the run:

api.fan_out(
"/proofs/{id}/activities", over=ids, select="$.items",
paginator=sl.page_number("page", page_size=100, page_size_param="count"),
)

page_size is sent as page_size_param (not in params); page_size_param=None sends nothing. Until the API has shown it sends pages that long, a short page is checked with one more request. If that has rows, the API caps its pages: paging goes on to an empty page and a warning names the page_size to set. sl.offset checks a short first page the same way, but fails, naming the limit to set.

read_ahead=N (at most 100) on sl.offset or sl.page_number keeps up to N page requests open, for an API with slow pages:

api.paginate("/invoices", paginator=sl.offset(limit=50, read_ahead=20))

The first page is read alone; after a full one, open requests double each round up to N. Rows still load in page order, and requests past the last page are dropped. max_in_flight caps every table’s open requests together. sl.cursor, sl.next_link and sl.link_header refuse read_ahead, as each address comes from the page before.

A response without the select path fails the load; an empty list or null there is no rows. This catches an API that answers an error with a 200 status:

GET https://api.shop.example/v1/orders?p=4: select "$.items" is not in the response, which holds the keys error; an API can answer an error with a 200 status, so check the response. For an API that leaves an empty list out, set select_missing="empty" to read such a page as no rows

sl.next_link, sl.cursor and sl.link_header end at a response with no next page, which they can’t tell from an error response; with select set, such a response usually fails as above.

error_path names where a 200 response reports an error, such as EAM’s ErrorAlert, GraphQL’s errors or Slack’s error. Any value there but null, false, "", [] or {} (0 included) fails the table before that page’s rows load, with the value cut at 200 characters:

POST https://eam.example/axis/restservices/grids: the API reported an error at $.ErrorAlert: [{"Message":"Grid WSJOBS: you are not allowed to run this grid"}]

It’s written like select, without [*], and checked on every response with rows or keys, but not OAuth2 token responses.

sl.cursor, sl.next_link and sl.link_header fail when the next position was already requested for the same request or fan-out key, rather than load a page twice:

POST https://eam.example/axis/restservices/grids: cursor 2 repeated after page 2, so paging would read page 2 again; check the paginator's pointer

sl.offset and sl.page_number fail when a page repeats the one before, as when an API ignores the parameter.

transform= calls f(rows, ctx) once per page, in order, on the rows after select, fields and cells; requests stay in Rust. As for a files table’s transform, rows is a pyarrow.Table and it returns or yields dicts, a pyarrow.Table or a DataFrame. Pass the function (registered or not) or its @sl.transform name.

sources/shop.py
import json
import sqlload as sl
shop = sl.source("shop", connection="shop", write_strategy="replace")
api = sl.http(shop)
@sl.transform
def order_lines(rows, ctx):
for order in rows.to_pylist():
for line in json.loads(order["lines"]):
yield {"region": ctx.key["region"], "order_id": order["id"],
**line}
@shop.table(description="Order lines, one row per line, by region.")
def lines(ctx):
return api.fan_out(
"/regions/{region}/orders", over=["north", "south"],
select="$.orders", transform=order_lines,
)
  • ctx.unit is "page", ctx.page its number in the request (from 1), and ctx.key the fan-out key’s fields (None in a paginate or with batch=).

  • Nested values arrive as JSON text: json.loads them, or pick them with fields.

  • Every page goes through, an empty last page included. flatten, columns and mask apply.

  • A function that raises, or returns something else, fails the table: GET .../regions/north/orders: transform order_lines failed: ....

  • plan fails when a literal transform="name" matches no registered function, or two:

    $ sqlload plan
    Errors (1)
    └── raw.shop__lines
    └── reason transform order_line: no function is registered as order_line with @sl.transform; the registered ones are order_lines
    ✗ Plan failed 1 error
  • A fan-out’s over= job refuses transform.

A fan_out whose select picks keys can be another fan_out’s over, as deep as needed. Each key keeps the fields of the keys above it; when they share a name, rename one with key=, as in select="$.items[*].id", key="item_id".

@shop.table(description="Order notes.", write_strategy="append",
cursor_column="order_id")
def notes(ctx):
orders = api.paginate(
"/orders", paginator=sl.page_number("p"),
params={"after": ctx.cursor_value}, select="$.items[*].order_id",
)
items = api.fan_out("/orders/{order_id}/items", over=orders,
select="$.items[*].item_id")
return api.fan_out(
"/orders/{order_id}/items/{item_id}/notes", over=items,
paginator=sl.page_number("page"), select="$.items",
)
  • Each level has its own paginator, concurrency and on_status. At most the levels’ concurrency plus one requests are in flight, within the connection’s limits.
  • Put an incremental cursor on the top level.
  • Only the last level’s rows load, without the keys’ fields, so select an ID the response repeats.
  • Errors name the keys that led to them, such as /orders order_id=5 → /orders/5/items item_id=51 → GET .../notes?page=2: HTTP 500.
  • plan checks that each placeholder comes from a level above.

Keys also fill {placeholders} in json_body’s strings. A value that is only a placeholder, such as "{order_id}", takes the key as returned, so a number stays a number; inside other text it’s text. Braces around a bare name are a placeholder anywhere, "{orders{id}}" included; { id } isn’t.

@shop.table(description="Items of each order.", write_strategy="append",
cursor_column="order_id")
def items(ctx):
orders = api.paginate(
"/orders", paginator=sl.page_number("p"),
params={"after": ctx.cursor_value}, select="$.items[*].order_id",
)
return api.fan_out(
"/items/lookup", over=orders, method="POST",
json_body={"ids": "{order_id}"}, batch=1000, select="$.items",
)

batch=N sends up to N keys per request, so {"ids": "{order_id}"} becomes {"ids": [1, 2, …]}. Each batch is one request, retried whole; concurrency counts batches. A batched fan-out needs json_body, takes keys only as whole body values, and can’t be another fan-out’s over.

Some APIs return each row as a list of cells, such as [{"columnId": 7001, "value": "Bolt"}]. cells=sl.cells(...) turns each into one column per name, in Rust. name says where names are:

name Names come from Example
"$.FIELDNAME" A path in each cell. EAM
sl.listed("$.columns") The listed columns, matching a cell’s columnId to a column’s id, named by title. Smartsheet
sl.listed("$.columns", by_position=True) The listed columns, by position.
sl.header_row() The first row’s cells, by position. Google’s grid data
@eam.table(description="Work orders.")
def work_orders(ctx):
return api.paginate(
"/grids",
method="POST",
json_body={"GRID": {"NAME": "WSJOBS"}},
paginator=sl.cursor(
"$.Result.ResultData.NEXTCURSORPOSITION", "$.CURSORPOSITION",
location="body",
),
select="$.Result.ResultData.DATARECORD",
cells=sl.cells("$.DATAFIELD", value="$.FIELDVALUE",
name="$.FIELDNAME"),
error_path="$.ErrorAlert",
)
  • value is a path, or a list tried in turn, as in value=["$.value", "$.displayValue"].
  • Names go through naming and rename: DueDate loads as due_date. A new name is a new column, under on_schema_change.
  • The load fails on a nameless cell, two cells for one column, names differing only in case, a row field named like a cells column, or (with sl.listed) a non-empty cell whose column isn’t listed. A column with no cell in a row loads NULL.
  • sl.header_row() takes the first row of the first page, per fan-out key; for one sheet split into ranges, use sl.listed.
  • fields= picks pivoted columns by the API’s names ({"qty": "$.Qty"}).

method="POST" sends json_body as JSON with every request. With location="body", sl.offset, sl.page_number and sl.cursor put their values in the body, at paths such as "$.page.cursor". Each request and retry starts from a fresh copy; without json_body, from {}.

@shop.table(description="Orders.", write_strategy="append",
cursor_column="updated_at")
def orders(ctx):
return api.paginate(
"/orders/search",
method="POST",
json_body={"filter": {"updated_after": ctx.cursor_value}},
paginator=sl.cursor("$.meta.next", "$.page.cursor", location="body"),
select="$.items",
)
  • Dates, times and decimals go as text; wrap them in int() or float() for a JSON number.
  • json_body on a GET, location="body" without POST, or a body path through a non-object fails before any request.
  • A POST follows only 307 and 308 redirects; 301, 302 and 303 fail. sl.next_link and sl.link_header resend the body and fail on another origin.

The oauth2_client_credentials, oauth2_refresh_token and oauth2_password kinds of auth fetch tokens from token_url; set them on the http connection. For an example, see OAuth2 in the guide.

  • One token per run serves the connection. It’s renewed before it expires and once on a 401, then the request is retried. With on_status={401: "skip"}, only a token over 30 seconds old is renewed.
  • client_auth = "basic" (default) sends the form-encoded client ID and secret by HTTP basic auth, per RFC 6749; "post" sends them as form fields.
  • token_url must be https (http only on localhost). Token errors name it, the status and the server’s error and error_description.
  • A rotated refresh token isn’t saved, so an API that revokes the old one fails the next run; use client credentials there if offered.
  • oauth2_password renews with the response’s refresh_token, else the password. Wrong credentials end the run with exit 1, without retrying.

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.

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.

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.

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.