Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/scripts/assert_sdist_sources.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ sha256="$(sed -n 's/^UNIXODBC_SHA256=//p' "$pins")"
name="unixODBC-${version}.tar.gz"

shopt -s nullglob
sdists=("$1"/*.tar.gz)
sdists=()
for sdist in "$1"/*.tar.gz; do
# sqlload-api is pure Python, with no wheel bundling unixODBC, so its sdist carries none of its source.
case "$(basename "$sdist")" in sqlload_api-*) continue ;; esac
sdists+=("$sdist")
done
if [ "${#sdists[@]}" -eq 0 ]; then
echo "no sdists in $1" >&2
exit 1
Expand Down
7 changes: 6 additions & 1 deletion .github/scripts/assert_wheel_notices.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ set -euo pipefail

python="$(command -v python3 || command -v python)"
shopt -s nullglob
wheels=("$1"/*.whl)
wheels=()
for wheel in "$1"/*.whl; do
# sqlload-api is pure Python: it bundles nothing, so it carries no notice of unixODBC.
case "$(basename "$wheel")" in sqlload_api-*) continue ;; esac
wheels+=("$wheel")
done
if [ "${#wheels[@]}" -eq 0 ]; then
echo "no wheels in $1" >&2
exit 1
Expand Down
2 changes: 1 addition & 1 deletion .github/scripts/smoke_mysql_odbc_wheel.sh
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ curl -fsSL --retry 3 --retry-all-errors -o "/tmp/$package" "https://cdn.mysql.co
curl -fsSL --retry 3 --retry-all-errors -o "/tmp/$package" "https://downloads.mysql.com/archives/get/p/10/file/$package"
echo "$MYSQL_ODBC_SHA256 /tmp/$package" | sha256sum -c --quiet -
apt-get -o Acquire::Retries=3 install -y -qq "/tmp/$package" > /dev/null
python -m venv /v && /v/bin/pip install --quiet /dist/sqlload-*.whl
python -m venv /v && /v/bin/pip install --quiet --find-links /dist /dist/sqlload-*.whl
python -m venv /c && /c/bin/pip install --quiet /dist/sqlload_cli-*.whl

# Load into a fresh project with SQLLOAD (and the environment before it); print what it said.
Expand Down
52 changes: 49 additions & 3 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,12 @@ jobs:
manifests = [
("Python package", project_version("packages/sqlload/pyproject.toml")),
("CLI package", project_version("packages/sqlload-cli/pyproject.toml")),
("API package", project_version("packages/sqlload-api/pyproject.toml")),
("Cargo workspace", workspace_version),
]
with Path("packages/sqlload/pyproject.toml").open("rb") as file:
pins = [d for d in tomllib.load(file)["project"]["dependencies"] if d.startswith("sqlload-api")]
manifests.append(("Python package's sqlload-api pin", pins[0].partition("==")[2] if pins else "missing"))
mismatches = [f"{label}={version}" for label, version in manifests if version != expected]
if mismatches:
raise SystemExit(
Expand Down Expand Up @@ -271,10 +275,35 @@ jobs:
name: wheel-${{ matrix.platform.name }}-${{ matrix.package.id }}
path: dist

# sqlload-api is pure Python: one wheel for every platform, and its sdist; every sqlload wheel pins it.
api:
name: Build sqlload-api
needs: [release-tag, release-metadata]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
ref: ${{ needs.release-tag.outputs.tag }}
- uses: astral-sh/setup-uv@v6
with:
version: "0.12.9"
- name: Build the wheel and sdist
run: uv build packages/sqlload-api --out-dir dist
- name: Assert the wheel is pure Python and imports without the engine
run: |
ls dist/sqlload_api-*-py3-none-any.whl
python3 -m venv api
api/bin/pip install --quiet dist/sqlload_api-*.whl
api/bin/python -c "import sys, sqlload_api; assert not any(m.split('.')[0] == 'sqlload' for m in sys.modules)"
- uses: actions/upload-artifact@v5
with:
name: sqlload-api
path: dist

# Each platform's two wheels, installed and run natively: the Intel Mac's on an Intel runner.
wheel-smoke:
name: Smoke-test wheels (${{ matrix.platform.name }})
needs: [release-tag, wheels]
needs: [release-tag, wheels, api]
runs-on: ${{ matrix.platform.runner }}
strategy:
fail-fast: false
Expand Down Expand Up @@ -304,13 +333,18 @@ jobs:
pattern: wheel-${{ matrix.platform.name }}-*
path: dist
merge-multiple: true
# The sqlload wheel pins sqlload-api at its own version, which installs from here.
- uses: actions/download-artifact@v5
with:
name: sqlload-api
path: dist
- name: Smoke-test the wheels
shell: bash
run: |
python -m venv smoke
bin=smoke/bin
if [[ "${RUNNER_OS}" == "Windows" ]]; then bin=smoke/Scripts; fi
"${bin}/python" -m pip install --quiet dist/sqlload-*.whl
"${bin}/python" -m pip install --quiet --find-links dist dist/sqlload-*.whl
"${bin}/sqlload" --help
"${bin}/sqll" --help > /dev/null
"${bin}/python" -c "import sqlload, sqlload._native"
Expand All @@ -326,7 +360,7 @@ jobs:
case "${RUNNER_OS}" in
Linux)
docker run --rm -v "$PWD:/w" -w /w python:3.12-slim bash -c '
python -m venv /v && /v/bin/pip install --quiet dist/sqlload-*.whl &&
python -m venv /v && /v/bin/pip install --quiet --find-links dist dist/sqlload-*.whl &&
python -m venv /c && /c/bin/pip install --quiet dist/sqlload_cli-*.whl &&
/v/bin/python .github/scripts/smoke_odbc_wheel.py /v/bin/sqlload /c/bin/sqlload --default-ini /etc/odbcinst.ini --driver-folder "/usr/lib/$(uname -m)-linux-gnu/odbc"'
;;
Expand Down Expand Up @@ -386,6 +420,7 @@ jobs:
- wheels
- wheel-smoke
- sdist
- api
runs-on: ubuntu-latest
environment: pypi
permissions:
Expand Down Expand Up @@ -416,6 +451,17 @@ jobs:
shell: bash
run: bash .github/scripts/assert_sdist_sources.sh dist

# sqlload pins sqlload-api at its own version, so sqlload-api goes up first: `pip install sqlload==<version>`
# resolves as soon as sqlload is listed.
- name: Set sqlload-api's files apart
run: mkdir dist-api && mv dist/sqlload_api-* dist-api/

- name: Publish sqlload-api to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist-api
skip-existing: true

- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
Expand Down
12 changes: 12 additions & 0 deletions .github/workflows/published-smoke.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ jobs:
echo "PyPI's index still lacks files of ${package} ${VERSION} after 180 attempts"
exit 1
done
# sqlload-api is pure Python: one wheel for every platform, and its sdist.
for attempt in $(seq 1 180); do
listed=$(curl -fsS -H "Accept: application/vnd.pypi.simple.v1+json" "https://pypi.org/simple/sqlload-api/" | jq -r '.files[].filename' || true)
if grep -qx "sqlload_api-${VERSION}-py3-none-any.whl" <<< "$listed" && grep -qx "sqlload_api-${VERSION}.tar.gz" <<< "$listed"; then
echo "PyPI's index lists sqlload-api ${VERSION} (attempt ${attempt})"
exit 0
fi
echo "attempt ${attempt}: sqlload-api ${VERSION} is not listed yet"
sleep 60
done
echo "PyPI's index still lacks sqlload-api ${VERSION} after 180 attempts"
exit 1

smoke:
name: Smoke (${{ matrix.platform.name }})
Expand Down
11 changes: 7 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ test-clickhouse-latest:
test-clickhouse-older:
SQLLOAD_TEST_CLICKHOUSE_TAG=$(CLICKHOUSE_OLDER) AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test cargo test -p sqlload --features container-tests,odbc --test loader --quiet -- to_clickhouse --test-threads=2

# Builds the sqlload extension (debug) into .venv and runs the package's tests.
# Installs sqlload-api (pure Python, which sqlload pins) and builds the sqlload extension (debug) into .venv, and runs
# both packages' tests.
test-python:
uv venv --quiet --allow-existing --python 3.12 .venv
uv pip install --quiet --python .venv/bin/python 'maturin>=1.9,<2' pytest pytest-xdist pyarrow polars pandas orjson duckdb
uv pip install --quiet --python .venv/bin/python -e packages/sqlload-api
cd packages/sqlload && VIRTUAL_ENV=$(CURDIR)/.venv $(CURDIR)/.venv/bin/maturin develop --uv --quiet --features odbc
.venv/bin/python -m pytest packages/sqlload/tests -n auto --dist loadfile
.venv/bin/python -m pytest packages/sqlload-api/tests packages/sqlload/tests -n auto --dist loadfile

test: test-unit test-containers

Expand All @@ -66,12 +68,13 @@ verify: check-ci test
bench-perf:
cargo bench -p sqlload-benches --bench hot_paths --quiet -- $(BENCH_ARGS)

# The sqlload wheel, built from this tree with release settings, in the harness's environment.
# The sqlload wheel, built from this tree with release settings, in the harness's environment, with the sqlload-api it
# pins installed from this tree too (it reaches PyPI only with the release).
bench-wheel:
cd benchmarks && uv sync --quiet --locked $(BENCH_GROUPS)
rm -rf benchmarks/.wheels
cd packages/sqlload && VIRTUAL_ENV=$(CURDIR)/benchmarks/.venv $(CURDIR)/benchmarks/.venv/bin/maturin build --release --quiet --out $(CURDIR)/benchmarks/.wheels
uv pip install --quiet --python benchmarks/.venv/bin/python --reinstall --no-deps benchmarks/.wheels/*.whl
uv pip install --quiet --python benchmarks/.venv/bin/python --reinstall --no-deps ./packages/sqlload-api benchmarks/.wheels/*.whl

# Compares sqlload with dlt and ingestr (needs Docker); on demand, not in CI. Results go to
# BENCH_OUT; BENCH_ARGS takes the harness's options (see benchmarks/README.md).
Expand Down
3 changes: 1 addition & 2 deletions crates/sqlload-python/src/bindings/main/native_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use pyo3::{Bound, PyResult, pymodule, wrap_pyfunction};

use crate::bindings::_helpers::cross::cross;
use crate::bindings::_helpers::run_cli::{run_cli, run_cli_captured, run_stopped};
use crate::bindings::models::{BatchStream, JsonData};
use crate::bindings::models::BatchStream;

/// Register `sqlload._native`'s functions and classes.
#[pymodule]
Expand All @@ -15,7 +15,6 @@ pub fn native_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(run_cli_captured, module)?)?;
module.add_function(wrap_pyfunction!(run_stopped, module)?)?;
module.add_function(wrap_pyfunction!(cross, module)?)?;
module.add_class::<JsonData>()?;
module.add_class::<BatchStream>()?;
Ok(())
}
66 changes: 0 additions & 66 deletions crates/sqlload-python/src/bindings/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,80 +5,14 @@ use arrow_array::RecordBatch;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::SchemaRef;
use pyo3::exceptions::{PyConnectionError, PyRuntimeError, PyValueError};
use pyo3::pybacked::PyBackedBytes;
use pyo3::types::{PyAnyMethods, PyDict, PyDictMethods, PyList, PyListMethods};
use pyo3::{Bound, PyAny, PyRef, PyResult, Python, pyclass, pymethods};
use sqlload::row_batches::main::conform_batch::conform_batch;
use sqlload::row_batches::main::projection::projection;
use sqlload::row_batches::main::settled_schema::settled_schema;
use sqlload::row_batches::models::{FieldSpec, JsonLayout, Projection};

use crate::crossing::errors::CrossError;
use crate::crossing::models::{Polled, TableBatches};

/// JSON or NDJSON bytes yielded by a table function (`sl.json(...)`, `sl.ndjson(...)`), parsed in Rust without the GIL.
#[derive(Debug)]
#[pyclass(frozen, module = "sqlload._native", name = "JsonData")]
pub struct JsonData {
pub(crate) bytes: PyBackedBytes,
pub(crate) layout: JsonLayout,
pub(crate) path: Option<String>,
/// The columns each row loads as, when only some of its values load.
pub(crate) projection: Option<Projection>,
}

#[pymethods]
impl JsonData {
/// `data` as one JSON document (rows at dotted `path`, or the whole document), or as NDJSON when `lines`; `fields` (a JSON list of `sl.field` specs: name, path, required, parse, on_error) and `keep_record` project each row.
#[new]
#[pyo3(signature = (data, *, lines = false, path = None, fields = None, keep_record = None))]
fn new(
data: PyBackedBytes,
lines: bool,
path: Option<String>,
fields: Option<String>,
keep_record: Option<String>,
) -> PyResult<Self> {
let fields = fields
.map(|text| serde_json::from_str::<Vec<FieldSpec>>(&text))
.transpose()
.map_err(|error| PyValueError::new_err(format!("fields: {error}")))?;
let projection =
projection(fields.as_deref(), keep_record.as_deref()).map_err(PyValueError::new_err)?;
let layout = match (lines, &path) {
(true, Some(_)) => {
return Err(PyValueError::new_err(
"path picks rows out of a JSON document; NDJSON has none",
));
}
(true, None) => JsonLayout::Lines,
(false, _) => JsonLayout::Document,
};
Ok(Self {
bytes: data,
layout,
path,
projection,
})
}

/// Whether the bytes are NDJSON.
#[getter]
fn lines(&self) -> bool {
self.layout == JsonLayout::Lines
}

/// The dotted path to the rows inside the document, if any.
#[getter]
fn path(&self) -> Option<String> {
self.path.clone()
}

fn __len__(&self) -> usize {
self.bytes.len()
}
}

/// The Arrow batches of one table generator, as `pyarrow.RecordBatch`es (the crossing's test hook).
#[derive(Debug)]
#[pyclass(module = "sqlload._native", name = "BatchStream")]
Expand Down
21 changes: 9 additions & 12 deletions crates/sqlload-python/src/crossing/_helpers/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@ use std::time::Instant;
use arrow_array::RecordBatch;
use arrow_array::ffi_stream::RecordBatchStreamReader;
use arrow_pyarrow::FromPyArrow;
use pyo3::exceptions::{PyImportError, PyTypeError};
use pyo3::exceptions::{PyImportError, PyTypeError, PyValueError};
use pyo3::pybacked::PyBackedBytes;
use pyo3::types::{
PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, PyTypeMethods,
};
use pyo3::{Bound, Py, PyAny, PyResult, Python};
use sqlload::python_sources::constants::{CHECKPOINT_METHOD, HTTP_JOB_METHOD, JSON_DATA_METHOD};
use sqlload::row_batches::main::json_read_spec::json_read_spec;
use sqlload::row_batches::models::{JsonLayout, JsonRead};

use crate::bindings::models::JsonData;
use crate::crossing::_helpers::parser::{panic_if, panicked};
use crate::crossing::_helpers::walk::{holds_nonfinite, walk_rows};
use crate::crossing::constants::{CHECKPOINT_METHOD, CROSSING_DEFAULT, HTTP_JOB_METHOD};
use crate::crossing::constants::CROSSING_DEFAULT;
use crate::crossing::errors::CrossError;
use crate::crossing::models::{
Crossed, CrossingOptions, CrossingStats, DictCrossing, Dispatch, PanicSite,
Expand Down Expand Up @@ -120,15 +121,11 @@ impl<'py> Producer<'py> {
if let Ok(rows) = item.cast::<PyList>() {
return self.take_list(rows);
}
if let Ok(json) = item.cast::<JsonData>() {
let json = json.get();
let read = JsonRead {
layout: json.layout,
path: json.path.clone(),
batch_rows: self.options.batch_rows,
projection: json.projection.clone(),
};
let bytes = json.bytes.clone_ref(self.py);
if item.hasattr(JSON_DATA_METHOD)? {
let (bytes, spec): (PyBackedBytes, String) =
item.call_method0(JSON_DATA_METHOD)?.extract()?;
let read =
json_read_spec(&spec, self.options.batch_rows).map_err(PyValueError::new_err)?;
return Ok(self.flush()? && self.send(Crossed::Json { bytes, read })?);
}
if item.hasattr(HTTP_JOB_METHOD)? {
Expand Down
6 changes: 0 additions & 6 deletions crates/sqlload-python/src/crossing/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,5 @@ pub(crate) const MICROS_PER_SECOND: i64 = 1_000_000;
/// The `sqlload._runtime` function orjson calls for values it cannot write itself.
pub(crate) const CROSSING_DEFAULT: &str = "crossing_default";

/// The method of an `sl.http` job that returns its definition as JSON.
pub(crate) const HTTP_JOB_METHOD: &str = "__sqlload_http_job__";

/// The method of an `sl.checkpoint` that returns its state as JSON.
pub(crate) const CHECKPOINT_METHOD: &str = "__sqlload_checkpoint__";

/// How long a page `transform`'s crossing is waited on at a time; it polls again until the function's output ends.
pub(crate) const PAGE_POLL: std::time::Duration = std::time::Duration::from_secs(3600);
25 changes: 22 additions & 3 deletions crates/sqlload-testkit/src/doc_pages/_helpers/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use regex::Regex;

use crate::doc_pages::constants::{ELISION, VOLATILE};
use crate::doc_pages::constants::{ELISION, TALLY_VERBS, VOLATILE};

/// What the page should show of `actual`: all of it, or around a `…` line the page's line counts.
pub(crate) fn shown_output(expected: &[String], actual: &[String]) -> Vec<String> {
Expand All @@ -19,7 +19,7 @@ pub(crate) fn shown_output(expected: &[String], actual: &[String]) -> Vec<String
shown
}

/// `lines` without durations, memory, server versions and the spaces that align them.
/// `lines` without durations, memory, server versions and the spaces that align them, each run of a load's tally lines in a fixed order (see [`tally_runs_sorted`]).
pub(crate) fn normalized(lines: &[String]) -> Result<Vec<String>, String> {
let mut patterns: Vec<(Regex, &str)> = Vec::new();
for (pattern, replacement) in VOLATILE {
Expand All @@ -34,7 +34,26 @@ pub(crate) fn normalized(lines: &[String]) -> Result<Vec<String>, String> {
}
normalized.push(text.trim().to_owned());
}
Ok(normalized)
Ok(tally_runs_sorted(normalized))
}

/// `lines` with each run of adjacent tally lines (`loaded`, `failed`, `skipped`) sorted: `load` prints a table's line as the table finishes, so tables loading at once print in no fixed order; which tables, and what each line says, still have to match.
pub(crate) fn tally_runs_sorted(lines: Vec<String>) -> Vec<String> {
let tally = |line: &String| TALLY_VERBS.iter().any(|verb| line.starts_with(verb));
let mut sorted: Vec<String> = Vec::with_capacity(lines.len());
let mut run: Vec<String> = Vec::new();
for line in lines {
if tally(&line) {
run.push(line);
continue;
}
run.sort();
sorted.append(&mut run);
sorted.push(line);
}
run.sort();
sorted.append(&mut run);
sorted
}

/// A difference between the page's lines and a run's, for a failure message.
Expand Down
Loading
Loading