From 66749055b238377fac74e0609d4d84b88d0125ba Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:21:33 +0000 Subject: [PATCH 1/5] feat!: publish the Python host as the sqlload-python-host crate Another pyo3 extension can now run its Python tables on SQLLoad's engine without copying the crossing: - The crossing and the host move from the sqlload extension into sqlload-python-host. module_host(runtime) is the engine's PythonHost over a Python runtime module the host provides. table_stream, transform_stream, read_error and error_text are building blocks for a host that implements PythonHost itself. The crate re-exports pyo3 (0.29, abi3-py310) and fails the first read when the interpreter's sqlload-api is not its own version. - Context and Connection move to sqlload_api, with Context.from_read for a host (or a subclass with fields of its own). Transforms and the crossing's callbacks move to sqlload_api._host, so a process has one transform registry. sl.Context is the same object as before. - PythonSource takes an opaque host value that the engine copies unread into each of the source's TableReads. - Publish releases sqlload, then sqlload-python-host, with the same crates.io token, and the release-metadata check covers both exact workspace pins. - An unpublished example host (crates/sqlload-python-host-example, tests/external_host) loads into DuckDB through module_host from make test-python. BREAKING CHANGE: PythonSource, TableRead and ProjectConfig are #[non_exhaustive]; build PythonSource and TableRead with their new constructors. --- .github/workflows/publish.yml | 13 +- .github/workflows/verify.yml | 6 +- .gitignore | 1 + Cargo.lock | 25 ++ Cargo.toml | 6 +- Makefile | 4 +- crates/sqlload-python-host-example/Cargo.toml | 23 ++ .../src/bindings/_helpers/mod.rs | 1 + .../src/bindings/_helpers/run.rs | 11 + .../src/bindings/constants.rs | 2 + .../src/bindings/main/mod.rs | 1 + .../src/bindings/main/native_module.rs | 14 ++ .../src/bindings/mod.rs | 5 + crates/sqlload-python-host-example/src/lib.rs | 5 + crates/sqlload-python-host/Cargo.toml | 38 +++ crates/sqlload-python-host/README.md | 41 ++++ .../src/crossing/_helpers/mod.rs | 0 .../src/crossing/_helpers/parser.rs | 6 +- .../src/crossing/_helpers/producer.rs | 4 +- .../src/crossing/_helpers/walk.rs | 0 .../src/crossing/constants.rs | 37 +++ .../src/crossing/errors.rs | 0 .../src/crossing/main/crossing_options.rs | 2 +- .../crossing/main/default_parse_threads.rs | 2 +- .../src/crossing/main/mod.rs | 0 .../src/crossing/main/returned_batches.rs | 4 +- .../src/crossing/main/table_batches.rs | 0 .../src/crossing/mod.rs | 2 +- .../src/crossing/models.rs | 0 .../src/host/_helpers/api_version.rs | 28 +++ .../src/host/_helpers/mod.rs | 2 + .../src/host/_helpers/read_context.rs | 18 ++ .../sqlload-python-host/src/host/constants.rs | 5 + .../src/host/main/error_text.rs} | 17 +- .../sqlload-python-host/src/host/main/mod.rs | 5 + .../src/host/main/module_host.rs | 14 ++ .../src/host/main/read_error.rs | 18 ++ .../src/host/main/table_stream.rs | 29 +++ .../src/host/main/transform_stream.rs | 31 +++ crates/sqlload-python-host/src/host/mod.rs | 6 + .../src/host/models.rs | 81 +++---- crates/sqlload-python-host/src/lib.rs | 8 + crates/sqlload-python/Cargo.toml | 7 +- .../src/bindings/_helpers/cross.rs | 12 +- .../src/bindings/_helpers/extension_host.rs | 13 + .../src/bindings/_helpers/mod.rs | 1 + .../src/bindings/_helpers/run_cli.rs | 2 +- .../sqlload-python/src/bindings/constants.rs | 18 +- crates/sqlload-python/src/bindings/models.rs | 4 +- .../sqlload-python/src/crossing/constants.rs | 20 -- .../sqlload-python/src/host/_helpers/mod.rs | 1 - crates/sqlload-python/src/host/constants.rs | 2 - .../src/host/main/extension_host.rs | 12 - crates/sqlload-python/src/host/main/mod.rs | 1 - crates/sqlload-python/src/host/mod.rs | 6 - crates/sqlload-python/src/lib.rs | 4 +- crates/sqlload/src/loader/_helpers/python.rs | 1 + .../src/project/main/parse_python_project.rs | 4 + crates/sqlload/src/project/models.rs | 4 + crates/sqlload/src/python_sources/models.rs | 50 +++- fensu.toml | 22 +- .../python/sqlload_api/__init__.py | 7 + .../python/sqlload_api/_context.py | 225 ++++++++++++++++++ .../sqlload-api/python/sqlload_api/_host.py | 139 +++++++++++ packages/sqlload-api/tests/test_host.py | 143 +++++++++++ packages/sqlload/python/sqlload/_declare.py | 125 +--------- packages/sqlload/python/sqlload/_runtime.py | 204 +--------------- packages/sqlload/tests/test_transforms.py | 34 --- tests/external_host/pyproject.toml | 14 ++ .../python/example_host/__init__.py | 5 + .../python/example_host/example_runtime.py | 84 +++++++ tests/external_host/test_external_host.py | 129 ++++++++++ .../src/content/docs/docs/sources/python.mdx | 40 ++++ 73 files changed, 1351 insertions(+), 497 deletions(-) create mode 100644 crates/sqlload-python-host-example/Cargo.toml create mode 100644 crates/sqlload-python-host-example/src/bindings/_helpers/mod.rs create mode 100644 crates/sqlload-python-host-example/src/bindings/_helpers/run.rs create mode 100644 crates/sqlload-python-host-example/src/bindings/constants.rs create mode 100644 crates/sqlload-python-host-example/src/bindings/main/mod.rs create mode 100644 crates/sqlload-python-host-example/src/bindings/main/native_module.rs create mode 100644 crates/sqlload-python-host-example/src/bindings/mod.rs create mode 100644 crates/sqlload-python-host-example/src/lib.rs create mode 100644 crates/sqlload-python-host/Cargo.toml create mode 100644 crates/sqlload-python-host/README.md rename crates/{sqlload-python => sqlload-python-host}/src/crossing/_helpers/mod.rs (100%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/_helpers/parser.rs (99%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/_helpers/producer.rs (99%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/_helpers/walk.rs (100%) create mode 100644 crates/sqlload-python-host/src/crossing/constants.rs rename crates/{sqlload-python => sqlload-python-host}/src/crossing/errors.rs (100%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/main/crossing_options.rs (95%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/main/default_parse_threads.rs (85%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/main/mod.rs (100%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/main/returned_batches.rs (96%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/main/table_batches.rs (100%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/mod.rs (88%) rename crates/{sqlload-python => sqlload-python-host}/src/crossing/models.rs (100%) create mode 100644 crates/sqlload-python-host/src/host/_helpers/api_version.rs create mode 100644 crates/sqlload-python-host/src/host/_helpers/mod.rs create mode 100644 crates/sqlload-python-host/src/host/_helpers/read_context.rs create mode 100644 crates/sqlload-python-host/src/host/constants.rs rename crates/{sqlload-python/src/host/_helpers/python_errors.rs => sqlload-python-host/src/host/main/error_text.rs} (56%) create mode 100644 crates/sqlload-python-host/src/host/main/mod.rs create mode 100644 crates/sqlload-python-host/src/host/main/module_host.rs create mode 100644 crates/sqlload-python-host/src/host/main/read_error.rs create mode 100644 crates/sqlload-python-host/src/host/main/table_stream.rs create mode 100644 crates/sqlload-python-host/src/host/main/transform_stream.rs create mode 100644 crates/sqlload-python-host/src/host/mod.rs rename crates/{sqlload-python => sqlload-python-host}/src/host/models.rs (69%) create mode 100644 crates/sqlload-python-host/src/lib.rs create mode 100644 crates/sqlload-python/src/bindings/_helpers/extension_host.rs delete mode 100644 crates/sqlload-python/src/crossing/constants.rs delete mode 100644 crates/sqlload-python/src/host/_helpers/mod.rs delete mode 100644 crates/sqlload-python/src/host/constants.rs delete mode 100644 crates/sqlload-python/src/host/main/extension_host.rs delete mode 100644 crates/sqlload-python/src/host/main/mod.rs delete mode 100644 crates/sqlload-python/src/host/mod.rs create mode 100644 packages/sqlload-api/python/sqlload_api/_context.py create mode 100644 packages/sqlload-api/python/sqlload_api/_host.py create mode 100644 packages/sqlload-api/tests/test_host.py create mode 100644 tests/external_host/pyproject.toml create mode 100644 tests/external_host/python/example_host/__init__.py create mode 100644 tests/external_host/python/example_host/example_runtime.py create mode 100644 tests/external_host/test_external_host.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6db63b03e..c78e939c6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -26,6 +26,7 @@ on: - Cargo.lock - crates/sqlload/Cargo.toml - crates/sqlload-python/Cargo.toml + - crates/sqlload-python-host/Cargo.toml # A new push to a pull request cancels its older wheel builds; a release run is a group of its own, # so releases never cancel each other. @@ -84,7 +85,8 @@ jobs: with Path(path).open("rb") as file: return tomllib.load(file)["project"]["version"] with Path("Cargo.toml").open("rb") as file: - workspace_version = tomllib.load(file)["workspace"]["package"]["version"] + workspace = tomllib.load(file)["workspace"] + workspace_version = workspace["package"]["version"] manifests = [ ("Python package", project_version("packages/sqlload/pyproject.toml")), ("CLI package", project_version("packages/sqlload-cli/pyproject.toml")), @@ -94,6 +96,10 @@ jobs: 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")) + # sqlload-python-host publishes with exact requirements on these, so they must name the release. + for crate in ("sqlload", "sqlload-python-host"): + pin = workspace["dependencies"][crate].get("version", "missing") + manifests.append((f"Cargo workspace's {crate} pin", pin.removeprefix("="))) mismatches = [f"{label}={version}" for label, version in manifests if version != expected] if mismatches: raise SystemExit( @@ -491,7 +497,12 @@ jobs: - name: Exchange the OIDC token for a crates.io token id: crates-io-auth uses: rust-lang/crates-io-auth-action@v1 + # sqlload first: sqlload-python-host requires it at exactly this version, so crates.io must have it already. - name: Publish sqlload env: CARGO_REGISTRY_TOKEN: ${{ steps.crates-io-auth.outputs.token }} run: cargo publish --locked -p sqlload + - name: Publish sqlload-python-host + env: + CARGO_REGISTRY_TOKEN: ${{ steps.crates-io-auth.outputs.token }} + run: cargo publish --locked -p sqlload-python-host diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 000b25d64..bfad55c27 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -95,8 +95,10 @@ jobs: # Checks what crates.io would receive (files, metadata, lockfile) without compiling it again: # the steps above already build it, and recompiling the packaged copy re-unpacks DuckDB's # bundled sources into a cached build folder, which fails when that folder is not empty. - - name: Package the crate as crates.io would - run: cargo publish --dry-run --no-verify --locked -p sqlload + # `cargo package` with both crates resolves sqlload-python-host's exact sqlload requirement against the sqlload + # packaged beside it, which `cargo publish --dry-run` can't before that version is on crates.io. + - name: Package the crates as crates.io would + run: cargo package --no-verify --locked -p sqlload -p sqlload-python-host containers: name: Container tests diff --git a/.gitignore b/.gitignore index 7fa2555af..61f665283 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ __pycache__/ # Native extension built in place by maturin develop packages/sqlload/python/sqlload/*.so +tests/external_host/python/example_host/*.so packages/sqlload/python/sqlload/*.pyd benchmarks/results/ benchmarks/.wheels/ diff --git a/Cargo.lock b/Cargo.lock index 78fa0dcd3..e8526f54d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6112,9 +6112,34 @@ dependencies = [ "pyo3", "serde_json", "sqlload", + "sqlload-python-host", "tracing", ] +[[package]] +name = "sqlload-python-host" +version = "0.85.0" +dependencies = [ + "arrow-array", + "arrow-pyarrow", + "arrow-schema", + "base64 0.22.1", + "chrono-tz", + "pyo3", + "serde_json", + "sqlload", + "tracing", +] + +[[package]] +name = "sqlload-python-host-example" +version = "0.0.0" +dependencies = [ + "pyo3", + "sqlload", + "sqlload-python-host", +] + [[package]] name = "sqlload-testkit" version = "0.85.0" diff --git a/Cargo.toml b/Cargo.toml index 5ac21d8da..b9b5193b7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,8 @@ members = [ "crates/sqlload", "crates/sqlload-benches", "crates/sqlload-python", + "crates/sqlload-python-host", + "crates/sqlload-python-host-example", "crates/sqlload-testkit", ] resolver = "2" @@ -73,7 +75,9 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["raw_value", "arbitrary_precision"] } sha2 = "0.10" shake = "0.1" -sqlload = { path = "crates/sqlload", default-features = false } +# Exact: sqlload-python-host publishes with this requirement, and its public types are sqlload's. +sqlload = { path = "crates/sqlload", version = "=0.85.0", default-features = false } # x-release-please-version +sqlload-python-host = { path = "crates/sqlload-python-host", version = "=0.85.0" } # x-release-please-version sqlload-testkit = { path = "crates/sqlload-testkit" } tempfile = "3" testcontainers = "0.28" diff --git a/Makefile b/Makefile index f9ec1bd3a..0426fe977 100644 --- a/Makefile +++ b/Makefile @@ -57,7 +57,9 @@ test-python: 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-api/tests packages/sqlload/tests -n auto --dist loadfile + # A host of its own on sqlload-python-host, which loads through the same engine (never published). + cd tests/external_host && VIRTUAL_ENV=$(CURDIR)/.venv $(CURDIR)/.venv/bin/maturin develop --uv --quiet + .venv/bin/python -m pytest packages/sqlload-api/tests packages/sqlload/tests tests/external_host -n auto --dist loadfile test: test-unit test-containers diff --git a/crates/sqlload-python-host-example/Cargo.toml b/crates/sqlload-python-host-example/Cargo.toml new file mode 100644 index 000000000..a273fc667 --- /dev/null +++ b/crates/sqlload-python-host-example/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "sqlload-python-host-example" +version = "0.0.0" +description = "A host of SQLLoad's engine with a Python runtime of its own, built on sqlload-python-host, for its tests." +edition.workspace = true +license.workspace = true +publish = false +rust-version.workspace = true + +[lib] +name = "example_host" +crate-type = ["cdylib"] +# Tested from Python (tests/external_host). +test = false +doctest = false + +[dependencies] +pyo3.workspace = true +sqlload = { workspace = true, default-features = true } +sqlload-python-host.workspace = true + +[lints] +workspace = true diff --git a/crates/sqlload-python-host-example/src/bindings/_helpers/mod.rs b/crates/sqlload-python-host-example/src/bindings/_helpers/mod.rs new file mode 100644 index 000000000..bcb3b3839 --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod run; diff --git a/crates/sqlload-python-host-example/src/bindings/_helpers/run.rs b/crates/sqlload-python-host-example/src/bindings/_helpers/run.rs new file mode 100644 index 000000000..f156cee8a --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/_helpers/run.rs @@ -0,0 +1,11 @@ +use pyo3::{Python, pyfunction}; +use sqlload::command::main::run_args_with_host::run_args_with_host; +use sqlload_python_host::host::main::module_host::module_host; + +use crate::bindings::constants::RUNTIME_MODULE; + +/// Run the `sqlload` command line `argv` (the program name first) with the example host, and return its exit code. +#[pyfunction] +pub(crate) fn run(py: Python<'_>, argv: Vec) -> u8 { + py.detach(|| run_args_with_host(argv, Some(module_host(RUNTIME_MODULE)), false).0) +} diff --git a/crates/sqlload-python-host-example/src/bindings/constants.rs b/crates/sqlload-python-host-example/src/bindings/constants.rs new file mode 100644 index 000000000..cf80a5190 --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/constants.rs @@ -0,0 +1,2 @@ +/// The example host's Python runtime module, which `sqlload-python-host`'s `ModuleHost` calls. +pub const RUNTIME_MODULE: &str = "example_host.example_runtime"; diff --git a/crates/sqlload-python-host-example/src/bindings/main/mod.rs b/crates/sqlload-python-host-example/src/bindings/main/mod.rs new file mode 100644 index 000000000..fc4aa77a4 --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/main/mod.rs @@ -0,0 +1 @@ +pub mod native_module; diff --git a/crates/sqlload-python-host-example/src/bindings/main/native_module.rs b/crates/sqlload-python-host-example/src/bindings/main/native_module.rs new file mode 100644 index 000000000..e47519a15 --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/main/native_module.rs @@ -0,0 +1,14 @@ +//! The `example_host._native` module definition. + +use pyo3::types::{PyModule, PyModuleMethods}; +use pyo3::{Bound, PyResult, pymodule, wrap_pyfunction}; + +use crate::bindings::_helpers::run::run; + +/// Register `example_host._native`'s functions. +#[pymodule] +#[pyo3(name = "_native")] +pub fn native_module(module: &Bound<'_, PyModule>) -> PyResult<()> { + module.add_function(wrap_pyfunction!(run, module)?)?; + Ok(()) +} diff --git a/crates/sqlload-python-host-example/src/bindings/mod.rs b/crates/sqlload-python-host-example/src/bindings/mod.rs new file mode 100644 index 000000000..788387bc0 --- /dev/null +++ b/crates/sqlload-python-host-example/src/bindings/mod.rs @@ -0,0 +1,5 @@ +//! The functions `example_host._native` exposes to Python. + +pub(crate) mod _helpers; +pub mod constants; +pub mod main; diff --git a/crates/sqlload-python-host-example/src/lib.rs b/crates/sqlload-python-host-example/src/lib.rs new file mode 100644 index 000000000..2d5316b6c --- /dev/null +++ b/crates/sqlload-python-host-example/src/lib.rs @@ -0,0 +1,5 @@ +//! `example_host._native`: the `sqlload` command line on a host of its own, built on `sqlload-python-host`, for its tests. + +#![forbid(unsafe_code)] + +pub mod bindings; diff --git a/crates/sqlload-python-host/Cargo.toml b/crates/sqlload-python-host/Cargo.toml new file mode 100644 index 000000000..9c6da1b36 --- /dev/null +++ b/crates/sqlload-python-host/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "sqlload-python-host" +version.workspace = true +description = "The Python host of SQLLoad's engine: runs Python tables and crosses what they yield into the engine, for a pyo3 extension of your own." +edition.workspace = true +publish = true +license.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +keywords = ["sqlload", "python", "pyo3", "arrow", "etl"] +categories = ["database", "api-bindings"] + +[lib] +name = "sqlload_python_host" +# Tested from Python (packages/sqlload/tests and tests/external_host); a Rust test binary would have to link libpython. +test = false +doctest = false + +[features] +# TLS with OpenSSL built in, as in the sqlload-cli wheels. +ssl-vendored = ["sqlload/ssl-vendored"] +# ODBC sources, as in the sqlload-cli wheels. +odbc = ["sqlload/odbc"] + +[dependencies] +arrow-array.workspace = true +arrow-pyarrow.workspace = true +arrow-schema.workspace = true +base64.workspace = true +chrono-tz.workspace = true +pyo3.workspace = true +serde_json.workspace = true +sqlload.workspace = true +tracing.workspace = true + +[lints] +workspace = true diff --git a/crates/sqlload-python-host/README.md b/crates/sqlload-python-host/README.md new file mode 100644 index 000000000..81e9a57f8 --- /dev/null +++ b/crates/sqlload-python-host/README.md @@ -0,0 +1,41 @@ +# sqlload-python-host + +The Python host of [SQLLoad](https://github.com/sqlstack-io/sqlload)'s engine, for a program that runs the engine in a +pyo3 extension of its own. It runs Python tables and turns what they yield into the engine's batches exactly as SQLLoad's +`sqlload` package does: dicts and lists of dicts, Arrow data (pyarrow, polars, pandas), `sqlload_api.json` / `ndjson`, +`sqlload_api.http` jobs (run in Rust, page transforms included) and `sqlload_api.checkpoint`s. The generator runs on its +own thread, and its rows are parsed on others without the GIL. + +- `host::main::module_host::module_host(runtime)` is the engine's `PythonHost` over a Python runtime module of the + host's own; SQLLoad's is `sqlload._runtime`. +- `host::main::table_stream::table_stream` and `host::main::transform_stream::transform_stream` cross one table's + yields, or one transform's result, for a host that implements `PythonHost` itself. + +```rust,ignore +use sqlload_python_host::host::main::module_host::module_host; + +let host = module_host("my_tool._sqlload_runtime"); +``` + +## The runtime module + +| Function | What it does | +| --- | --- | +| `discover(root, python_paths) -> str` | The sources found, as the JSON list of `PythonSource`s: `name`, `module`, `settings` (TOML keys, tables under `tables`) and an optional `host` value of the host's own, which the engine copies unread into each of the source's reads. | +| `start_table(read) -> Iterable` | Call the table `read` (a `TableRead`, as JSON) names and return what it yields. | +| `current_state(table)`, `table_state(table) -> str \| None` | A logged table's `ctx.state` as JSON while its rows cross, and once its function has finished; `sqlload_api._host.current_state` and `final_state` answer both for a `Context`. | +| `rename(name, columns, context) -> (str \| None, str \| None)` | A table's `rename`: the names, or why there are none. | +| `finish_run() -> None` | The run is over: close clients. | + +`sqlload_api.Context.from_read(read, **extras)` builds a table's `ctx` as SQLLoad does; a host with fields of its own +subclasses `sqlload_api.Context`. Transforms and the crossing's callbacks are `sqlload_api._host`'s, never the +runtime's, so one transform registry serves the whole process. + +## Versions + +- **pyo3 0.29** (any patch), with `abi3-py310` (a host may raise the floor). pyo3 types are part of this crate's + interface, so your extension uses the same pyo3. Cargo refuses a build with two pyo3 minors, as `pyo3-ffi` links the + `python` library; `sqlload_python_host::pyo3` re-exports the one in use. +- **`sqlload-api`** at exactly this crate's version in the interpreter. A different version fails the first read, naming + the version to install. +- This crate, `sqlload` and `sqlload-api` are released together, at one version. diff --git a/crates/sqlload-python/src/crossing/_helpers/mod.rs b/crates/sqlload-python-host/src/crossing/_helpers/mod.rs similarity index 100% rename from crates/sqlload-python/src/crossing/_helpers/mod.rs rename to crates/sqlload-python-host/src/crossing/_helpers/mod.rs diff --git a/crates/sqlload-python/src/crossing/_helpers/parser.rs b/crates/sqlload-python-host/src/crossing/_helpers/parser.rs similarity index 99% rename from crates/sqlload-python/src/crossing/_helpers/parser.rs rename to crates/sqlload-python-host/src/crossing/_helpers/parser.rs index 69e0bb6ce..213167342 100644 --- a/crates/sqlload-python/src/crossing/_helpers/parser.rs +++ b/crates/sqlload-python-host/src/crossing/_helpers/parser.rs @@ -30,7 +30,7 @@ use crate::crossing::models::{ Crossed, CrossingOptions, CrossingStats, Dispatch, PanicSite, ParseJob, Parsed, Polled, ReadContext, TableBatches, }; -use crate::host::constants::RUNTIME_MODULE; +use crate::host::constants::API_HOST_MODULE; /// Where one piece's batches go, and the read's counters. struct Output { @@ -366,7 +366,7 @@ impl Output { .map_err(|error| PyValueError::new_err(error.to_string()))? .into_pyarrow(py)?; let (returned, problem): (Option>, Option) = py - .import(RUNTIME_MODULE)? + .import(API_HOST_MODULE)? .call_method1("call_transform", (function.as_str(), table, page.context))? .extract()?; match returned { @@ -382,7 +382,7 @@ impl Output { } })?; let items = py - .import(RUNTIME_MODULE)? + .import(API_HOST_MODULE)? .call_method1("page_items", (feed,))?; let snapshot = PyCFunction::new_closure(py, None, None, |_, _| PyResult::Ok(None::))?; diff --git a/crates/sqlload-python/src/crossing/_helpers/producer.rs b/crates/sqlload-python-host/src/crossing/_helpers/producer.rs similarity index 99% rename from crates/sqlload-python/src/crossing/_helpers/producer.rs rename to crates/sqlload-python-host/src/crossing/_helpers/producer.rs index 99e99473e..2cf3031c9 100644 --- a/crates/sqlload-python/src/crossing/_helpers/producer.rs +++ b/crates/sqlload-python-host/src/crossing/_helpers/producer.rs @@ -22,7 +22,7 @@ use crate::crossing::errors::CrossError; use crate::crossing::models::{ Crossed, CrossingOptions, CrossingStats, DictCrossing, Dispatch, PanicSite, }; -use crate::host::constants::RUNTIME_MODULE; +use crate::host::constants::API_HOST_MODULE; /// Where the generator's items go: dict yields gather in `pending` until a batch is full. struct Producer<'py> { @@ -253,7 +253,7 @@ fn orjson_dumps( let options = PyDict::new(py); options.set_item( "default", - py.import(RUNTIME_MODULE)?.getattr(CROSSING_DEFAULT)?, + py.import(API_HOST_MODULE)?.getattr(CROSSING_DEFAULT)?, )?; let numpy = orjson.getattr("OPT_SERIALIZE_NUMPY")?; let passthrough = orjson.getattr("OPT_PASSTHROUGH_DATETIME")?; diff --git a/crates/sqlload-python/src/crossing/_helpers/walk.rs b/crates/sqlload-python-host/src/crossing/_helpers/walk.rs similarity index 100% rename from crates/sqlload-python/src/crossing/_helpers/walk.rs rename to crates/sqlload-python-host/src/crossing/_helpers/walk.rs diff --git a/crates/sqlload-python-host/src/crossing/constants.rs b/crates/sqlload-python-host/src/crossing/constants.rs new file mode 100644 index 000000000..c004b58a8 --- /dev/null +++ b/crates/sqlload-python-host/src/crossing/constants.rs @@ -0,0 +1,37 @@ +use crate::crossing::models::DictCrossing; + +/// Dict rows gathered before they cross into Rust (and the most rows per batch parsed from bytes): as fast as 10,000 in the crossing benchmark, with a third of the memory. +pub const DEFAULT_BATCH_ROWS: usize = 1_000; + +/// Batches queued between the generator, the parser and the consumer. +pub const DEFAULT_MAX_QUEUED: usize = 4; + +/// How dicts cross by default: serialised by orjson and parsed in parallel without the GIL, which the crossing benchmark found faster than walking them and holding the GIL a third as long. +pub const DEFAULT_DICT_CROSSING: DictCrossing = DictCrossing::Serialise; + +/// The most threads parsing one table's batches by default. +pub const MAX_DEFAULT_PARSE_THREADS: usize = 4; + +/// Bytes of crossed data waiting to be parsed before the generator pauses. +pub const DEFAULT_MAX_QUEUED_BYTES: usize = 256 * 1024 * 1024; + +/// The module of numpy's scalar and array types, which orjson writes by their own rules. +pub(crate) const NUMPY_MODULE: &str = "numpy"; + +/// numpy's array type, written as a list when its values are numbers or booleans. +pub(crate) const NUMPY_ARRAY: &str = "ndarray"; + +/// `date(1970, 1, 1).toordinal()`. +pub(crate) const EPOCH_ORDINAL: i64 = 719_163; + +/// Microseconds in a day. +pub(crate) const MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Microseconds in a second. +pub(crate) const MICROS_PER_SECOND: i64 = 1_000_000; + +/// The `sqlload_api._host` function orjson calls for values it cannot write itself. +pub(crate) const CROSSING_DEFAULT: &str = "crossing_default"; + +/// 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); diff --git a/crates/sqlload-python/src/crossing/errors.rs b/crates/sqlload-python-host/src/crossing/errors.rs similarity index 100% rename from crates/sqlload-python/src/crossing/errors.rs rename to crates/sqlload-python-host/src/crossing/errors.rs diff --git a/crates/sqlload-python/src/crossing/main/crossing_options.rs b/crates/sqlload-python-host/src/crossing/main/crossing_options.rs similarity index 95% rename from crates/sqlload-python/src/crossing/main/crossing_options.rs rename to crates/sqlload-python-host/src/crossing/main/crossing_options.rs index 638c73367..77d353f9b 100644 --- a/crates/sqlload-python/src/crossing/main/crossing_options.rs +++ b/crates/sqlload-python-host/src/crossing/main/crossing_options.rs @@ -1,6 +1,6 @@ //! The crossing settings every Python read uses. -use crate::bindings::constants::{ +use crate::crossing::constants::{ DEFAULT_BATCH_ROWS, DEFAULT_DICT_CROSSING, DEFAULT_MAX_QUEUED, DEFAULT_MAX_QUEUED_BYTES, }; use crate::crossing::main::default_parse_threads::default_parse_threads; diff --git a/crates/sqlload-python/src/crossing/main/default_parse_threads.rs b/crates/sqlload-python-host/src/crossing/main/default_parse_threads.rs similarity index 85% rename from crates/sqlload-python/src/crossing/main/default_parse_threads.rs rename to crates/sqlload-python-host/src/crossing/main/default_parse_threads.rs index 8a12c36de..0049ad4fe 100644 --- a/crates/sqlload-python/src/crossing/main/default_parse_threads.rs +++ b/crates/sqlload-python-host/src/crossing/main/default_parse_threads.rs @@ -1,6 +1,6 @@ //! How many threads parse one table's batches by default. -use crate::bindings::constants::MAX_DEFAULT_PARSE_THREADS; +use crate::crossing::constants::MAX_DEFAULT_PARSE_THREADS; /// One parser per core but one, which the generator's thread keeps, capped at the default. pub fn default_parse_threads() -> usize { diff --git a/crates/sqlload-python/src/crossing/main/mod.rs b/crates/sqlload-python-host/src/crossing/main/mod.rs similarity index 100% rename from crates/sqlload-python/src/crossing/main/mod.rs rename to crates/sqlload-python-host/src/crossing/main/mod.rs diff --git a/crates/sqlload-python/src/crossing/main/returned_batches.rs b/crates/sqlload-python-host/src/crossing/main/returned_batches.rs similarity index 96% rename from crates/sqlload-python/src/crossing/main/returned_batches.rs rename to crates/sqlload-python-host/src/crossing/main/returned_batches.rs index b841ffb44..21004fe01 100644 --- a/crates/sqlload-python/src/crossing/main/returned_batches.rs +++ b/crates/sqlload-python-host/src/crossing/main/returned_batches.rs @@ -11,7 +11,7 @@ use sqlload::row_batches::models::Flatten; use crate::crossing::main::table_batches::table_batches; use crate::crossing::models::{CrossingOptions, ReadContext, TableBatches}; -use crate::host::constants::RUNTIME_MODULE; +use crate::host::constants::API_HOST_MODULE; /// Call `call`'s transform on `rows` (in `schema`) and start crossing what it returned or yielded with `options`, as a table function's yields cross, expanding the objects `flatten` flattens: the batches, and what it returned (whose `dicts` says whether any item was dicts); or why it failed, or what it returned cannot load. pub fn returned_batches( @@ -26,7 +26,7 @@ pub fn returned_batches( .map_err(|error| PyValueError::new_err(error.to_string()))? .into_pyarrow(py)?; let (returned, problem): (Option>, Option) = py - .import(RUNTIME_MODULE)? + .import(API_HOST_MODULE)? .call_method1("call_transform", (call.function.as_str(), table, context))? .extract()?; let Some(returned) = returned else { diff --git a/crates/sqlload-python/src/crossing/main/table_batches.rs b/crates/sqlload-python-host/src/crossing/main/table_batches.rs similarity index 100% rename from crates/sqlload-python/src/crossing/main/table_batches.rs rename to crates/sqlload-python-host/src/crossing/main/table_batches.rs diff --git a/crates/sqlload-python/src/crossing/mod.rs b/crates/sqlload-python-host/src/crossing/mod.rs similarity index 88% rename from crates/sqlload-python/src/crossing/mod.rs rename to crates/sqlload-python-host/src/crossing/mod.rs index 2b3ca043b..e72bdeb71 100644 --- a/crates/sqlload-python/src/crossing/mod.rs +++ b/crates/sqlload-python-host/src/crossing/mod.rs @@ -1,7 +1,7 @@ //! Table generators into Arrow: yielded dicts, lists of dicts, JSON bytes and Arrow data become a stream of record batches. pub(crate) mod _helpers; -pub(crate) mod constants; +pub mod constants; pub mod errors; pub mod main; pub mod models; diff --git a/crates/sqlload-python/src/crossing/models.rs b/crates/sqlload-python-host/src/crossing/models.rs similarity index 100% rename from crates/sqlload-python/src/crossing/models.rs rename to crates/sqlload-python-host/src/crossing/models.rs diff --git a/crates/sqlload-python-host/src/host/_helpers/api_version.rs b/crates/sqlload-python-host/src/host/_helpers/api_version.rs new file mode 100644 index 000000000..90719dbc3 --- /dev/null +++ b/crates/sqlload-python-host/src/host/_helpers/api_version.rs @@ -0,0 +1,28 @@ +use std::sync::OnceLock; + +use pyo3::types::PyAnyMethods; +use pyo3::{PyResult, Python}; + +use crate::host::constants::API_PACKAGE; + +/// Whether this interpreter's `sqlload_api` is this crate's version, checked once per process; the crossing calls `sqlload_api._host` and reads what `sqlload_api` builds, both of one version with the engine. +pub(crate) fn api_version_problem() -> Option { + static CHECKED: OnceLock> = OnceLock::new(); + CHECKED + .get_or_init(|| { + let expected = env!("CARGO_PKG_VERSION"); + let found = Python::attach(|py| -> PyResult { + py.import(API_PACKAGE)?.getattr("__version__")?.extract() + }); + match found { + Ok(found) if found == expected => None, + Ok(found) => Some(format!( + "sqlload-api {found} is installed, but this engine reads sqlload-api {expected}: pip install \"sqlload-api=={expected}\"" + )), + Err(_) => Some(format!( + "sqlload-api is not installed in this Python, and this engine reads what it builds: pip install \"sqlload-api=={expected}\"" + )), + } + }) + .clone() +} diff --git a/crates/sqlload-python-host/src/host/_helpers/mod.rs b/crates/sqlload-python-host/src/host/_helpers/mod.rs new file mode 100644 index 000000000..14afda8fb --- /dev/null +++ b/crates/sqlload-python-host/src/host/_helpers/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod api_version; +pub(crate) mod read_context; diff --git a/crates/sqlload-python-host/src/host/_helpers/read_context.rs b/crates/sqlload-python-host/src/host/_helpers/read_context.rs new file mode 100644 index 000000000..66b7b685e --- /dev/null +++ b/crates/sqlload-python-host/src/host/_helpers/read_context.rs @@ -0,0 +1,18 @@ +use sqlload::python_sources::models::TableRead; + +use crate::crossing::models::ReadContext; + +/// What the crossing needs of the table `request` reads, besides its data. +pub(crate) fn read_context(request: &TableRead) -> ReadContext { + ReadContext { + table: request.table.clone(), + flatten: request.flatten.clone(), + connections: request.connections.clone(), + cursor_column: request.cursor.as_ref().map(|cursor| cursor.column.clone()), + masked: request.masked.clone(), + arrays: request.arrays.clone(), + naming: request.naming, + zone: request.zone, + source_part: request.source_part, + } +} diff --git a/crates/sqlload-python-host/src/host/constants.rs b/crates/sqlload-python-host/src/host/constants.rs new file mode 100644 index 000000000..b0935c488 --- /dev/null +++ b/crates/sqlload-python-host/src/host/constants.rs @@ -0,0 +1,5 @@ +/// The `sqlload-api` module every host's crossing calls for what transforms and crossing need (`crossing_default`, `transform_version`, `call_transform`, `page_items`, `finish`), so a process has one transform registry whichever host runs. +pub const API_HOST_MODULE: &str = "sqlload_api._host"; + +/// The `sqlload-api` package, whose version must be this crate's. +pub const API_PACKAGE: &str = "sqlload_api"; diff --git a/crates/sqlload-python/src/host/_helpers/python_errors.rs b/crates/sqlload-python-host/src/host/main/error_text.rs similarity index 56% rename from crates/sqlload-python/src/host/_helpers/python_errors.rs rename to crates/sqlload-python-host/src/host/main/error_text.rs index 8ab09ffdd..9783fb3f8 100644 --- a/crates/sqlload-python/src/host/_helpers/python_errors.rs +++ b/crates/sqlload-python-host/src/host/main/error_text.rs @@ -1,10 +1,10 @@ -use pyo3::exceptions::{PyConnectionError, PyTimeoutError}; +//! A Python exception as the engine reports it. + use pyo3::types::{PyStringMethods, PyTracebackMethods, PyTypeMethods}; use pyo3::{PyErr, Python}; -use sqlload::python_sources::errors::ReadError; /// A Python exception as one line: its type and message, then where in the user's code it was raised. -pub(crate) fn error_text(error: &PyErr) -> String { +pub fn error_text(error: &PyErr) -> String { Python::attach(|py| { let place = error .traceback(py) @@ -23,14 +23,3 @@ pub(crate) fn error_text(error: &PyErr) -> String { format!("{kind}: {}{place}", error.value(py)) }) } - -/// A table function's exception as a read error, retryable when it is a `ConnectionError` or `TimeoutError` (or a subclass), as a dropped connection or an `sl.http` job that outlasted its retries raises. -pub(crate) fn read_error(error: &PyErr) -> ReadError { - let retryable = Python::attach(|py| { - error.is_instance_of::(py) || error.is_instance_of::(py) - }); - ReadError { - message: error_text(error), - retryable, - } -} diff --git a/crates/sqlload-python-host/src/host/main/mod.rs b/crates/sqlload-python-host/src/host/main/mod.rs new file mode 100644 index 000000000..147943991 --- /dev/null +++ b/crates/sqlload-python-host/src/host/main/mod.rs @@ -0,0 +1,5 @@ +pub mod error_text; +pub mod module_host; +pub mod read_error; +pub mod table_stream; +pub mod transform_stream; diff --git a/crates/sqlload-python-host/src/host/main/module_host.rs b/crates/sqlload-python-host/src/host/main/module_host.rs new file mode 100644 index 000000000..4039a475e --- /dev/null +++ b/crates/sqlload-python-host/src/host/main/module_host.rs @@ -0,0 +1,14 @@ +//! A host whose Python side is a module of the host's own. + +use std::sync::Arc; + +use sqlload::python_sources::types::PythonHost; + +use crate::host::models::ModuleHost; + +/// A [`PythonHost`] that calls `runtime`, a Python module the host provides (see [`ModuleHost`] for what it defines), and `sqlload_api._host` for transforms. +pub fn module_host(runtime: &str) -> Arc { + Arc::new(ModuleHost { + runtime: runtime.to_owned(), + }) +} diff --git a/crates/sqlload-python-host/src/host/main/read_error.rs b/crates/sqlload-python-host/src/host/main/read_error.rs new file mode 100644 index 000000000..f267cbe31 --- /dev/null +++ b/crates/sqlload-python-host/src/host/main/read_error.rs @@ -0,0 +1,18 @@ +//! A table function's exception as the engine's read error. + +use pyo3::exceptions::{PyConnectionError, PyTimeoutError}; +use pyo3::{PyErr, Python}; +use sqlload::python_sources::errors::ReadError; + +use crate::host::main::error_text::error_text; + +/// A table function's exception as a read error, retryable when it is a `ConnectionError` or `TimeoutError` (or a subclass), as a dropped connection or an `sl.http` job that outlasted its retries raises. +pub fn read_error(error: &PyErr) -> ReadError { + let retryable = Python::attach(|py| { + error.is_instance_of::(py) || error.is_instance_of::(py) + }); + ReadError { + message: error_text(error), + retryable, + } +} diff --git a/crates/sqlload-python-host/src/host/main/table_stream.rs b/crates/sqlload-python-host/src/host/main/table_stream.rs new file mode 100644 index 000000000..46dcc5627 --- /dev/null +++ b/crates/sqlload-python-host/src/host/main/table_stream.rs @@ -0,0 +1,29 @@ +//! Cross a table function's yields into the engine's batches. + +use pyo3::{Bound, PyAny}; +use sqlload::python_sources::models::TableRead; +use sqlload::python_sources::types::BatchStream; + +use crate::crossing::main::crossing_options::crossing_options; +use crate::crossing::main::table_batches::table_batches; +use crate::host::_helpers::api_version::api_version_problem; +use crate::host::_helpers::read_context::read_context; +use crate::host::models::PythonBatches; + +/// What `iterable` (what the table function `request` reads returned or yields) yields, as the engine's batches: dicts, Arrow data, `sl.json`/`sl.ndjson`, `sl.http` jobs and `sl.checkpoint`s cross as SQLLoad's own tables' do, with the table's flatten, naming, masked columns, cursor and connections from `request`. `snapshot`, for a logged table, returns its `ctx.state` as JSON as each piece crosses. Fails when this interpreter's `sqlload_api` is not this crate's version. +pub fn table_stream( + iterable: &Bound<'_, PyAny>, + snapshot: Option<&Bound<'_, PyAny>>, + request: &TableRead, +) -> Result, String> { + if let Some(problem) = api_version_problem() { + return Err(problem); + } + let batches = table_batches( + iterable, + snapshot, + crossing_options(), + read_context(request), + ); + Ok(Box::new(PythonBatches(batches))) +} diff --git a/crates/sqlload-python-host/src/host/main/transform_stream.rs b/crates/sqlload-python-host/src/host/main/transform_stream.rs new file mode 100644 index 000000000..c02766575 --- /dev/null +++ b/crates/sqlload-python-host/src/host/main/transform_stream.rs @@ -0,0 +1,31 @@ +//! Run a `transform` on rows and cross what it returns. + +use arrow_array::RecordBatch; +use arrow_schema::SchemaRef; +use sqlload::python_sources::models::TransformCall; +use sqlload::python_sources::types::BatchStream; + +use crate::crossing::main::crossing_options::crossing_options; +use crate::crossing::main::returned_batches::returned_batches; +use crate::host::_helpers::api_version::api_version_problem; +use crate::host::models::{PythonBatches, TransformBatches}; + +/// What `call`'s transform (looked up in `sqlload_api`'s one registry) returns for `rows`, in `schema`, as the engine's batches, or why it can't run. +pub fn transform_stream( + call: &TransformCall, + rows: Vec, + schema: SchemaRef, +) -> Result, String> { + if let Some(problem) = api_version_problem() { + return Err(problem); + } + let (batches, returned) = returned_batches( + call, + (rows, schema), + (crossing_options(), call.flatten.clone()), + )?; + Ok(Box::new(TransformBatches { + batches: PythonBatches(batches), + returned, + })) +} diff --git a/crates/sqlload-python-host/src/host/mod.rs b/crates/sqlload-python-host/src/host/mod.rs new file mode 100644 index 000000000..5646b39f9 --- /dev/null +++ b/crates/sqlload-python-host/src/host/mod.rs @@ -0,0 +1,6 @@ +//! The engine's [`PythonHost`](sqlload::python_sources::types::PythonHost) over a Python runtime module the host provides, and the building blocks for a host of its own. + +pub(crate) mod _helpers; +pub mod constants; +pub mod main; +pub mod models; diff --git a/crates/sqlload-python/src/host/models.rs b/crates/sqlload-python-host/src/host/models.rs similarity index 69% rename from crates/sqlload-python/src/host/models.rs rename to crates/sqlload-python-host/src/host/models.rs index f8a65196d..dd1788794 100644 --- a/crates/sqlload-python/src/host/models.rs +++ b/crates/sqlload-python-host/src/host/models.rs @@ -10,25 +10,33 @@ use sqlload::python_sources::models::{PythonSource, TableRead, TransformCall}; use sqlload::python_sources::types::{BatchStream, PythonHost, Streamed}; use crate::crossing::errors::CrossError; -use crate::crossing::main::crossing_options::crossing_options; -use crate::crossing::main::returned_batches::returned_batches; -use crate::crossing::main::table_batches::table_batches; -use crate::crossing::models::{Polled, ReadContext, TableBatches}; -use crate::host::_helpers::python_errors::{error_text, read_error}; -use crate::host::constants::RUNTIME_MODULE; +use crate::crossing::models::{Polled, TableBatches}; +use crate::host::_helpers::api_version::api_version_problem; +use crate::host::constants::API_HOST_MODULE; +use crate::host::main::error_text::error_text; +use crate::host::main::read_error::read_error; +use crate::host::main::table_stream::table_stream; +use crate::host::main::transform_stream::transform_stream; -/// Runs Python sources in this interpreter through `sqlload._runtime`. -#[derive(Debug, Clone, Copy, Default)] -pub struct ExtensionHost; +/// Runs Python sources in this interpreter through `runtime`, a Python module the host provides (what it defines: the crate's "The runtime module"). +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct ModuleHost { + /// The runtime module's import name, such as `sqlload._runtime`. + pub runtime: String, +} -impl PythonHost for ExtensionHost { +impl PythonHost for ModuleHost { fn discover(&self, root: &Path, python_paths: &[PathBuf]) -> Result, String> { + if let Some(problem) = api_version_problem() { + return Err(problem); + } let paths: Vec = python_paths .iter() .map(|path| path.to_string_lossy().into_owned()) .collect(); let text = Python::attach(|py| -> PyResult { - py.import(RUNTIME_MODULE)? + py.import(self.runtime.as_str())? .call_method1("discover", (root.to_string_lossy().into_owned(), paths))? .extract() }) @@ -39,9 +47,8 @@ impl PythonHost for ExtensionHost { fn read_table(&self, request: &TableRead) -> Result, String> { let text = serde_json::to_string(request).map_err(|error| error.to_string())?; - let options = crossing_options(); - Python::attach(|py| -> PyResult { - let runtime = py.import(RUNTIME_MODULE)?; + Python::attach(|py| -> PyResult, String>> { + let runtime = py.import(self.runtime.as_str())?; let iterator = runtime.call_method1("start_table", (text,))?; let snapshot = match request.logged { true => Some( @@ -51,30 +58,14 @@ impl PythonHost for ExtensionHost { ), false => None, }; - Ok(table_batches( - &iterator, - snapshot.as_ref(), - options, - ReadContext { - table: request.table.clone(), - flatten: request.flatten.clone(), - connections: request.connections.clone(), - cursor_column: request.cursor.as_ref().map(|cursor| cursor.column.clone()), - masked: request.masked.clone(), - arrays: request.arrays.clone(), - naming: request.naming, - zone: request.zone, - source_part: request.source_part, - }, - )) + Ok(table_stream(&iterator, snapshot.as_ref(), request)) }) - .map(|batches| Box::new(PythonBatches(batches)) as Box) - .map_err(|error| error_text(&error)) + .map_err(|error| error_text(&error))? } fn table_state(&self, table: &str) -> Result, String> { Python::attach(|py| -> PyResult> { - py.import(RUNTIME_MODULE)? + py.import(self.runtime.as_str())? .call_method1("table_state", (table,))? .extract() }) @@ -83,7 +74,7 @@ impl PythonHost for ExtensionHost { fn transform_version(&self, name: &str) -> Result { let checked = Python::attach(|py| -> PyResult<(Option, Option)> { - py.import(RUNTIME_MODULE)? + py.import(API_HOST_MODULE)? .call_method1("transform_version", (name,))? .extract() }) @@ -100,20 +91,12 @@ impl PythonHost for ExtensionHost { rows: Vec, schema: SchemaRef, ) -> Result, String> { - let (batches, returned) = returned_batches( - call, - (rows, schema), - (crossing_options(), call.flatten.clone()), - )?; - Ok(Box::new(TransformBatches { - batches: PythonBatches(batches), - returned, - })) + transform_stream(call, rows, schema) } fn rename(&self, name: &str, columns: Option<&str>, context: &str) -> Result { let called = Python::attach(|py| -> PyResult<(Option, Option)> { - py.import(RUNTIME_MODULE)? + py.import(self.runtime.as_str())? .call_method1("rename", (name, columns, context))? .extract() }) @@ -126,7 +109,9 @@ impl PythonHost for ExtensionHost { fn finish(&self) { let closed = Python::attach(|py| -> PyResult<()> { - py.import(RUNTIME_MODULE)?.call_method0("finish_run")?; + py.import(self.runtime.as_str())? + .call_method0("finish_run")?; + py.import(API_HOST_MODULE)?.call_method0("finish")?; Ok(()) }); if let Err(error) = closed { @@ -137,7 +122,7 @@ impl PythonHost for ExtensionHost { /// A table function's batches as the engine reads them. #[derive(Debug)] -pub struct PythonBatches(TableBatches); +pub struct PythonBatches(pub(crate) TableBatches); impl BatchStream for PythonBatches { fn next_batch(&mut self) -> Option> { @@ -158,8 +143,8 @@ impl BatchStream for PythonBatches { /// What a `transform` returned or yielded, as the engine reads it, and the Python object noting whether any of it was dicts. #[derive(Debug)] pub struct TransformBatches { - batches: PythonBatches, - returned: Py, + pub(crate) batches: PythonBatches, + pub(crate) returned: Py, } impl BatchStream for TransformBatches { diff --git a/crates/sqlload-python-host/src/lib.rs b/crates/sqlload-python-host/src/lib.rs new file mode 100644 index 000000000..3c301463c --- /dev/null +++ b/crates/sqlload-python-host/src/lib.rs @@ -0,0 +1,8 @@ +//! The Python host of SQLLoad's engine, for a pyo3 extension of its own: the README gives the runtime module and versions. +#![forbid(unsafe_code)] + +pub mod crossing; +pub mod host; + +/// The pyo3 this crate is built with, which a host's extension must use. +pub use pyo3; diff --git a/crates/sqlload-python/Cargo.toml b/crates/sqlload-python/Cargo.toml index 5ccdb1a21..b4785a851 100644 --- a/crates/sqlload-python/Cargo.toml +++ b/crates/sqlload-python/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "sqlload-python" version.workspace = true -description = "The native module of the sqlload Python package: the command line in-process and the Python-to-Arrow crossing." +description = "The native module of the sqlload Python package: the command line in-process, with the Python host of sqlload-python-host." edition.workspace = true license.workspace = true publish = false @@ -17,9 +17,9 @@ doctest = false [features] # TLS with OpenSSL built in, as in the sqlload-cli wheels. -ssl-vendored = ["sqlload/ssl-vendored"] +ssl-vendored = ["sqlload/ssl-vendored", "sqlload-python-host/ssl-vendored"] # ODBC sources, as in the sqlload-cli wheels. -odbc = ["sqlload/odbc"] +odbc = ["sqlload/odbc", "sqlload-python-host/odbc"] [dependencies] arrow-array.workspace = true @@ -30,6 +30,7 @@ chrono-tz.workspace = true pyo3.workspace = true serde_json.workspace = true sqlload = { workspace = true, default-features = true } +sqlload-python-host.workspace = true tracing.workspace = true [lints] diff --git a/crates/sqlload-python/src/bindings/_helpers/cross.rs b/crates/sqlload-python/src/bindings/_helpers/cross.rs index 05ad20f0b..e4ba5d090 100644 --- a/crates/sqlload-python/src/bindings/_helpers/cross.rs +++ b/crates/sqlload-python/src/bindings/_helpers/cross.rs @@ -3,13 +3,15 @@ use std::sync::Mutex; use pyo3::exceptions::PyValueError; use pyo3::{Bound, PyAny, PyResult, pyfunction}; -use crate::bindings::constants::{ +use crate::bindings::models::BatchStream; +use sqlload_python_host::crossing::constants::{ DEFAULT_BATCH_ROWS, DEFAULT_DICT_CROSSING, DEFAULT_MAX_QUEUED, DEFAULT_MAX_QUEUED_BYTES, }; -use crate::bindings::models::BatchStream; -use crate::crossing::main::default_parse_threads::default_parse_threads; -use crate::crossing::main::table_batches::table_batches; -use crate::crossing::models::{CrossingOptions, DictCrossing, PanicSite, ReadContext}; +use sqlload_python_host::crossing::main::default_parse_threads::default_parse_threads; +use sqlload_python_host::crossing::main::table_batches::table_batches; +use sqlload_python_host::crossing::models::{ + CrossingOptions, DictCrossing, PanicSite, ReadContext, +}; /// Start reading `source` (any iterable of table data); `crossing` is `auto`, `walk` or `serialise`; at most `max_queued + parse_threads` batches (a yielded JSON or Arrow object counting as one) wait between the generator and the consumer, besides the one being gathered; `panic_at` (`producer` or `parser`) makes a crossing thread panic, for tests; crossed data waiting to be parsed stays under `max_queued_bytes` (one larger piece still crosses alone). When the read ends (finished, failed or dropped), the iterator's `close()` is called if it has one, including an iterator passed in directly (`iter(x) is x`, such as a database cursor or a file). #[pyfunction] diff --git a/crates/sqlload-python/src/bindings/_helpers/extension_host.rs b/crates/sqlload-python/src/bindings/_helpers/extension_host.rs new file mode 100644 index 000000000..13ab04acb --- /dev/null +++ b/crates/sqlload-python/src/bindings/_helpers/extension_host.rs @@ -0,0 +1,13 @@ +//! The host the `sqlload` command of the Python package gives the loader. + +use std::sync::Arc; + +use sqlload::python_sources::types::PythonHost; +use sqlload_python_host::host::main::module_host::module_host; + +use crate::bindings::constants::RUNTIME_MODULE; + +/// A host that runs `sl.source`s in this interpreter, through `sqlload._runtime`. +pub(crate) fn extension_host() -> Arc { + module_host(RUNTIME_MODULE) +} diff --git a/crates/sqlload-python/src/bindings/_helpers/mod.rs b/crates/sqlload-python/src/bindings/_helpers/mod.rs index 81392d947..a30369289 100644 --- a/crates/sqlload-python/src/bindings/_helpers/mod.rs +++ b/crates/sqlload-python/src/bindings/_helpers/mod.rs @@ -1,2 +1,3 @@ pub(crate) mod cross; +pub(crate) mod extension_host; pub(crate) mod run_cli; diff --git a/crates/sqlload-python/src/bindings/_helpers/run_cli.rs b/crates/sqlload-python/src/bindings/_helpers/run_cli.rs index 2879cf0f5..f9e069839 100644 --- a/crates/sqlload-python/src/bindings/_helpers/run_cli.rs +++ b/crates/sqlload-python/src/bindings/_helpers/run_cli.rs @@ -2,7 +2,7 @@ use pyo3::{Python, pyfunction}; use sqlload::command::main::run_args_with_host::run_args_with_host; use sqlload::memory_budget::main::run_stopped::run_stopped as stopped; -use crate::host::main::extension_host::extension_host; +use crate::bindings::_helpers::extension_host::extension_host; /// Run the `sqlload` command line `argv` (the program name first) with the GIL released, Python sources included, and return its exit code. #[pyfunction] diff --git a/crates/sqlload-python/src/bindings/constants.rs b/crates/sqlload-python/src/bindings/constants.rs index efddfee82..3e0344a56 100644 --- a/crates/sqlload-python/src/bindings/constants.rs +++ b/crates/sqlload-python/src/bindings/constants.rs @@ -1,16 +1,2 @@ -use crate::crossing::models::DictCrossing; - -/// Dict rows gathered before they cross into Rust (and the most rows per batch parsed from bytes): as fast as 10,000 in the crossing benchmark, with a third of the memory. -pub const DEFAULT_BATCH_ROWS: usize = 1_000; - -/// Batches queued between the generator, the parser and the consumer. -pub const DEFAULT_MAX_QUEUED: usize = 4; - -/// How dicts cross by default: serialised by orjson and parsed in parallel without the GIL, which the crossing benchmark found faster than walking them and holding the GIL a third as long. -pub const DEFAULT_DICT_CROSSING: DictCrossing = DictCrossing::Serialise; - -/// The most threads parsing one table's batches by default. -pub const MAX_DEFAULT_PARSE_THREADS: usize = 4; - -/// Bytes of crossed data waiting to be parsed before the generator pauses. -pub const DEFAULT_MAX_QUEUED_BYTES: usize = 256 * 1024 * 1024; +/// The Python module that discovers `sl.source`s and calls their table functions: the runtime `sqlload`'s host runs. +pub const RUNTIME_MODULE: &str = "sqlload._runtime"; diff --git a/crates/sqlload-python/src/bindings/models.rs b/crates/sqlload-python/src/bindings/models.rs index 7746348d2..4cb84ffd9 100644 --- a/crates/sqlload-python/src/bindings/models.rs +++ b/crates/sqlload-python/src/bindings/models.rs @@ -10,8 +10,8 @@ use pyo3::{Bound, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; use sqlload::row_batches::main::conform_batch::conform_batch; use sqlload::row_batches::main::settled_schema::settled_schema; -use crate::crossing::errors::CrossError; -use crate::crossing::models::{Polled, TableBatches}; +use sqlload_python_host::crossing::errors::CrossError; +use sqlload_python_host::crossing::models::{Polled, TableBatches}; /// The Arrow batches of one table generator, as `pyarrow.RecordBatch`es (the crossing's test hook). #[derive(Debug)] diff --git a/crates/sqlload-python/src/crossing/constants.rs b/crates/sqlload-python/src/crossing/constants.rs deleted file mode 100644 index cca0a93c5..000000000 --- a/crates/sqlload-python/src/crossing/constants.rs +++ /dev/null @@ -1,20 +0,0 @@ -/// The module of numpy's scalar and array types, which orjson writes by their own rules. -pub(crate) const NUMPY_MODULE: &str = "numpy"; - -/// numpy's array type, written as a list when its values are numbers or booleans. -pub(crate) const NUMPY_ARRAY: &str = "ndarray"; - -/// `date(1970, 1, 1).toordinal()`. -pub(crate) const EPOCH_ORDINAL: i64 = 719_163; - -/// Microseconds in a day. -pub(crate) const MICROS_PER_DAY: i64 = 86_400_000_000; - -/// Microseconds in a second. -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"; - -/// 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); diff --git a/crates/sqlload-python/src/host/_helpers/mod.rs b/crates/sqlload-python/src/host/_helpers/mod.rs deleted file mode 100644 index 2d5d19db8..000000000 --- a/crates/sqlload-python/src/host/_helpers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod python_errors; diff --git a/crates/sqlload-python/src/host/constants.rs b/crates/sqlload-python/src/host/constants.rs deleted file mode 100644 index f5f9d76ab..000000000 --- a/crates/sqlload-python/src/host/constants.rs +++ /dev/null @@ -1,2 +0,0 @@ -/// The Python module that imports `python_paths` and calls table functions. -pub const RUNTIME_MODULE: &str = "sqlload._runtime"; diff --git a/crates/sqlload-python/src/host/main/extension_host.rs b/crates/sqlload-python/src/host/main/extension_host.rs deleted file mode 100644 index f38eee95f..000000000 --- a/crates/sqlload-python/src/host/main/extension_host.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! The host the `sqlload` command of the Python package gives the loader. - -use std::sync::Arc; - -use sqlload::python_sources::types::PythonHost; - -use crate::host::models::ExtensionHost; - -/// A host that runs Python sources in this interpreter. -pub fn extension_host() -> Arc { - Arc::new(ExtensionHost) -} diff --git a/crates/sqlload-python/src/host/main/mod.rs b/crates/sqlload-python/src/host/main/mod.rs deleted file mode 100644 index dd552b94d..000000000 --- a/crates/sqlload-python/src/host/main/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod extension_host; diff --git a/crates/sqlload-python/src/host/mod.rs b/crates/sqlload-python/src/host/mod.rs deleted file mode 100644 index 105d86d0c..000000000 --- a/crates/sqlload-python/src/host/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! The host that discovers and runs Python sources for the engine's loader. - -pub(crate) mod _helpers; -pub mod constants; -pub mod main; -pub mod models; diff --git a/crates/sqlload-python/src/lib.rs b/crates/sqlload-python/src/lib.rs index 8140df49d..4949edb74 100644 --- a/crates/sqlload-python/src/lib.rs +++ b/crates/sqlload-python/src/lib.rs @@ -1,7 +1,5 @@ -//! The `sqlload._native` extension module: the `sqlload` command line in-process, and table generators crossing into Arrow. +//! The `sqlload._native` extension module: the `sqlload` command line in-process, with the Python host from `sqlload-python-host`. #![forbid(unsafe_code)] pub mod bindings; -pub mod crossing; -pub mod host; diff --git a/crates/sqlload/src/loader/_helpers/python.rs b/crates/sqlload/src/loader/_helpers/python.rs index 1056de7da..216953bef 100644 --- a/crates/sqlload/src/loader/_helpers/python.rs +++ b/crates/sqlload/src/loader/_helpers/python.rs @@ -1277,6 +1277,7 @@ fn table_read( zone: spec.timezone.map(|(zone, _)| zone), source_part: (load.project.memory.budget.as_ref()) .map(|budget| budget.table_share / TABLE_SHARE_PARTS), + host: load.project.python_hosts.get(&spec.source_name).cloned(), } } diff --git a/crates/sqlload/src/project/main/parse_python_project.rs b/crates/sqlload/src/project/main/parse_python_project.rs index 9d2252d8e..ab303574f 100644 --- a/crates/sqlload/src/project/main/parse_python_project.rs +++ b/crates/sqlload/src/project/main/parse_python_project.rs @@ -41,6 +41,10 @@ pub fn parse_python_project( .iter() .map(|source| (source.name.clone(), source.http_paths.clone())) .collect(); + project.python_hosts = python + .iter() + .filter_map(|source| Some((source.name.clone(), source.host.clone()?))) + .collect(); project.connection_variables = variables; let project = attach_sessions(project, sessions).map_err(ProjectError::Invalid)?; let problems = reference_problems(&project); diff --git a/crates/sqlload/src/project/models.rs b/crates/sqlload/src/project/models.rs index 8af3dc88f..a71b140b8 100644 --- a/crates/sqlload/src/project/models.rs +++ b/crates/sqlload/src/project/models.rs @@ -26,6 +26,7 @@ use crate::row_batches::models::Flatten; /// A loader project: `sqlload.toml` with `[connections]`, `[targets]` and `[sources]`. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] +#[non_exhaustive] pub struct ProjectConfig { /// Folders scanned for Python sources; none when omitted. #[serde(default)] @@ -57,6 +58,9 @@ pub struct ProjectConfig { /// The `sl.http` paths each Python table writes as literals, by source name and table name. #[serde(skip)] pub python_http_paths: BTreeMap>, + /// Each Python source's host data ([`PythonSource::host`](crate::python_sources::models::PythonSource::host)), by source name, for its tables' reads; sources without any are left out. + #[serde(skip)] + pub python_hosts: BTreeMap, /// The `${ENV:NAME}` variables each connection's settings read, by connection name, for hints. #[serde(skip)] pub connection_variables: BTreeMap>, diff --git a/crates/sqlload/src/python_sources/models.rs b/crates/sqlload/src/python_sources/models.rs index 65a1b33f1..5098a8883 100644 --- a/crates/sqlload/src/python_sources/models.rs +++ b/crates/sqlload/src/python_sources/models.rs @@ -2,9 +2,10 @@ use serde::{Deserialize, Serialize}; use crate::row_batches::models::Flatten; -/// One `sl.source(...)` (or a standalone `@sl.table`, as a source of its own) found under `python_paths`. +/// One `sl.source(...)` (or a standalone `@sl.table`, as a source of its own) found under `python_paths`, or one a host declares itself ([`PythonSource::new`]). #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] +#[non_exhaustive] pub struct PythonSource { pub name: String, /// The file that declares it, relative to the project directory. @@ -14,10 +15,31 @@ pub struct PythonSource { /// The `sl.http` paths each table function writes as literals, by table name; tables that build no job are left out. #[serde(default)] pub http_paths: std::collections::BTreeMap, + /// The host's own data about the source (its loader, run or model), which the engine never reads and copies into every [`TableRead`] of the source's tables; SQLLoad's sources set none. + #[serde(default)] + pub host: Option, +} + +impl PythonSource { + /// Source `name`, declared in `module` (as error messages name it), with its `settings` as TOML keys and its tables under `tables`; no literal `sl.http` paths and no host data. + pub fn new( + name: impl Into, + module: impl Into, + settings: serde_json::Map, + ) -> Self { + Self { + name: name.into(), + module: module.into(), + settings, + http_paths: std::collections::BTreeMap::new(), + host: None, + } + } } /// What one table function is called with: its connection, the cursor window and the run. #[derive(Debug, Clone, PartialEq, Serialize)] +#[non_exhaustive] pub struct TableRead { pub source: String, pub table: String, @@ -49,6 +71,32 @@ pub struct TableRead { /// The most the table's `sl.http` jobs hold in pages requested ahead: a quarter of its share of the run's memory budget; `None` without a budget. Not sent to the table function. #[serde(skip)] pub source_part: Option, + /// The source's [`PythonSource::host`] data, as the host declared it. + pub host: Option, +} + +impl TableRead { + /// A read of `table` from `source` with nothing else set: no connection, cursor or state, nothing masked or flattened; for a host's tests and its own reads. + pub fn new(source: impl Into, table: impl Into) -> Self { + Self { + source: source.into(), + table: table.into(), + connection: None, + connections: serde_json::Map::new(), + withheld: Vec::new(), + cursor: None, + logged: false, + state: None, + is_reload: false, + flatten: Flatten::default(), + masked: Vec::new(), + arrays: Vec::new(), + naming: (crate::load_naming::models::Naming::default(), None), + zone: None, + source_part: None, + host: None, + } + } } /// The cursor window a table function may use to read only new data. diff --git a/fensu.toml b/fensu.toml index f671640f5..882b9faf2 100644 --- a/fensu.toml +++ b/fensu.toml @@ -117,6 +117,26 @@ path = "crates/sqlload/src/odbc_source/_helpers/catalog.rs" symbols = ["listed_keys"] reason = "The keys INFORMATION_SCHEMA lists only explain plan's error for a table whose driver reports no primary key; a database without INFORMATION_SCHEMA, or one answering with an error or a name that is not UTF-8, gets the error without them rather than failing the catalog read." +[[targets.rust.rule_exceptions]] +rule = "FPRSL105" +path = "crates/sqlload-python-host/src/host/main/error_text.rs" +reason = "Part of sqlload-python-host's public interface, for a host that implements PythonHost itself; its importers are other projects' extensions." + +[[targets.rust.rule_exceptions]] +rule = "FPRSL105" +path = "crates/sqlload-python-host/src/host/main/read_error.rs" +reason = "Part of sqlload-python-host's public interface, for a host that implements PythonHost itself; its importers are other projects' extensions." + +[[targets.rust.rule_exceptions]] +rule = "FPRSL105" +path = "crates/sqlload-python-host/src/host/main/table_stream.rs" +reason = "Part of sqlload-python-host's public interface, for a host that implements PythonHost itself; its importers are other projects' extensions." + +[[targets.rust.rule_exceptions]] +rule = "FPRSL105" +path = "crates/sqlload-python-host/src/host/main/transform_stream.rs" +reason = "Part of sqlload-python-host's public interface, for a host that implements PythonHost itself; its importers are other projects' extensions." + [[targets.rust.rule_exceptions]] rule = "FPRSL105" path = "crates/sqlload-testkit/src/parity/main/comparison_sql.rs" @@ -311,7 +331,7 @@ reason = "PyO3 maps each of the Python function's keyword-only arguments to one [[targets.rust.rule_exceptions]] rule = "FPRSH003" -path = "crates/sqlload-python/src/crossing/_helpers/parser.rs" +path = "crates/sqlload-python-host/src/crossing/_helpers/parser.rs" symbols = ["panic_if"] reason = "The crossing's test hook panics on purpose, to prove a panicking crossing thread fails the read instead of ending it early." diff --git a/packages/sqlload-api/python/sqlload_api/__init__.py b/packages/sqlload-api/python/sqlload_api/__init__.py index ad294319f..3c506d77a 100644 --- a/packages/sqlload-api/python/sqlload_api/__init__.py +++ b/packages/sqlload-api/python/sqlload_api/__init__.py @@ -9,10 +9,15 @@ Each crosses as plain data through a method the engine looks for (`__sqlload_http_job__`, `__sqlload_json__`, `__sqlload_checkpoint__`), so this package holds no compiled code. `sqlload` re-exports it: `import sqlload as sl; sl.http` is `sqlload_api.http`. Without a SQLLoad source, name the connection: `http(connection="shop_api")`. + +A host that runs table functions on SQLLoad's engine (through the `sqlload-python-host` crate) builds each table's +`Context` with `Context.from_read(read)`, or a subclass of it with fields of its own; `sqlload_api._host` holds what every +host's crossing calls, so a process has one transform registry. """ from importlib.metadata import version +from sqlload_api._context import Connection, Context from sqlload_api._data import Checkpoint, Field, JsonData, checkpoint, field, json, key, ndjson, parent from sqlload_api._http import ( CellName, @@ -40,7 +45,9 @@ "CellName", "Cells", "Checkpoint", + "Connection", "ConnectionOwner", + "Context", "Field", "Http", "Job", diff --git a/packages/sqlload-api/python/sqlload_api/_context.py b/packages/sqlload-api/python/sqlload_api/_context.py new file mode 100644 index 000000000..e1cbff6b0 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_context.py @@ -0,0 +1,225 @@ +"""What a table function receives: `Context`, and the connections it reaches through `Connection`. + +A host builds a table's context from the engine's read (`Context.from_read`), as SQLLoad does; a host with fields of its +own subclasses `Context`, so the rules that fill it (connections, cursor types, time zones, logged state) are SQLLoad's. +""" + +import json +import logging +from collections.abc import Callable, Collection, Iterator, Mapping +from datetime import date, datetime, timezone +from decimal import Decimal +from logging import Logger +from typing import Any +from zoneinfo import ZoneInfo + + +class Connection(Mapping[str, Any]): + """A connection's resolved settings; calling it looks up another connection by name. + + Connections that `[targets]` write to are not available to table functions (except a source's + own connection), so a table function cannot reach a destination's credentials. + """ + + def __init__( + self, + settings: Mapping[str, Any], + named: Mapping[str, Mapping[str, Any]], + withheld: Collection[str] = (), + ) -> None: + self._settings = dict(settings) + self._named = named + self._withheld = frozenset(withheld) + + def __getitem__(self, key: str) -> Any: + return self._settings[key] + + def __iter__(self) -> Iterator[str]: + return iter(self._settings) + + def __len__(self) -> int: + return len(self._settings) + + def __call__(self, name: str) -> "Connection": + if name in self._withheld: + raise PermissionError( + f"connection {name} is used by a [targets] entry; table functions only get connections" + " that no target writes to, so they cannot reach a destination's credentials" + ) + if name not in self._named: + raise KeyError(f"no connection named {name}") + return Connection(self._named[name], self._named, self._withheld) + + +class Context: + """What a table function receives: its connection and client, the cursor window, and a logger. + + `cursor_value` is where to read from (the destination's maximum of `cursor_column` minus + `lookback`, `cursor_start` on a first run, or `--start-cursor-*`), and `cursor_end` where to stop + (not included); `None` means open. Times arrive in the table's `timezone`, else UTC. Rows the + function returns outside the window fail the table, unless `on_cursor_out_of_range` says to skip + them or load them with a warning. + + With `state="logged"`, `state` is the position the last successful run left (`None` on the + first run, after `--reload` or `sqlload logged-state reset --clear`); set `ctx.state` to the new + position (any JSON value, such as an API sync token) and SQLLoad records it with the data. + """ + + def __init__( + self, + *, + table: str, + source: str, + connection: Connection, + logger: Logger, + cursor_column: str | None = None, + cursor_value: Any = None, + cursor_end: Any = None, + cursor_inclusive: bool = True, + is_reload: bool = False, + client_factory: Callable[["Context"], Any] | None = None, + logged: bool = False, + state: Any = None, + ) -> None: + self.table = table + self.source = source + self._connection = connection + self.logger = logger + self.cursor_column = cursor_column + self.cursor_value = cursor_value + self.cursor_end = cursor_end + self.cursor_inclusive = cursor_inclusive + self.is_reload = is_reload + self._client_factory = client_factory + self._client: Any = None + self._logged = logged + self._state = state + self.started_state = json.dumps(state) + self._assigned_state = self.started_state + self._previous_assigned_state = self.started_state + + @classmethod + def from_read( + cls, + read: Mapping[str, Any], + *, + client_factory: "Callable[[Context], Any] | None" = None, + logger: Logger | None = None, + **extras: Any, + ) -> "Context": + """The context of the table the engine's read `read` (its `TableRead`, as JSON parsed) names, filled as SQLLoad + fills it: the source's connection with the others no target writes to, the cursor window in its Python type and the + table's `timezone`, the logged state, and whether it is a reload. `extras` go to the constructor, for a subclass's + own fields (`class LoaderContext(Context)`).""" + connections: Mapping[str, Any] = read.get("connections") or {} + name = read.get("connection") + connection = Connection(connections.get(name, {}) if name else {}, connections, read.get("withheld") or ()) + cursor = read.get("cursor") or {} + zone = cursor.get("timezone") + return cls( + table=read["table"], + source=read["source"], + connection=connection, + logger=logger or logging.getLogger(f"sqlload.{read['source']}.{read['table']}"), + cursor_column=cursor.get("column"), + cursor_value=cursor_value(cursor.get("start"), cursor.get("column_type"), zone), + cursor_end=cursor_value(cursor.get("end"), cursor.get("column_type"), zone), + cursor_inclusive=cursor.get("inclusive", True), + is_reload=read.get("is_reload", False), + client_factory=client_factory, + logged=read.get("logged", False), + state=json.loads(read["state"]) if read.get("state") is not None else None, + **extras, + ) + + @property + def state(self) -> Any: + """The logged position (`state="logged"` tables): where the last successful run left off.""" + return self._state + + @state.setter + def state(self, value: Any) -> None: + if not self._logged: + raise AttributeError(f"ctx.state needs state='logged' on table {self.table}") + try: + assigned = json.dumps(value) + except (TypeError, ValueError) as error: + raise TypeError(f"ctx.state of table {self.table} is not JSON: {error}") from error + self._previous_assigned_state = self._assigned_state + self._assigned_state = assigned + self._state = value + + @property + def connection(self) -> Connection: + """The source's connection settings (empty when it names none); call it with a name for another connection.""" + return self._connection + + @property + def client(self) -> Any: + """The source's client (`@source.client`), built on first use and shared by its tables for the run.""" + if self._client is None: + if self._client_factory is None: + raise LookupError(f"the source of table {self.table} declares no @source.client") + self._client = self._client_factory(self) + return self._client + + +def cursor_value(text: str | None, column_type: str | None, zone: str | None = None) -> Any: + """A cursor bound in its Python type: int, float, Decimal, date, or datetime: aware for `timestamp_tz`, in the + table's `timezone` (`zone`) or UTC; for `timestamp_ntz`, aware in `zone` when it is set, its wall-clock time kept. + + Before the first load shows the cursor's type (`unknown`), ISO dates and timestamps and integers + are read as such, so the value's type matches later runs. + """ + if text is None: + return None + kind = column_type or "unknown" + if kind.startswith("decimal"): + kind = "decimal" + try: + if kind == "unknown": + return zoned(_guessed_value(text), zone) + if kind in ("int", "smallint"): + return int(text) + if kind == "float": + return float(text) + if kind == "decimal": + return Decimal(text) + if kind == "date": + return date.fromisoformat(text[:10]) + if kind in ("timestamp_tz", "timestamp_ntz"): + return zoned(_timestamp(text, aware=kind == "timestamp_tz"), zone) + except (ValueError, ArithmeticError): + return text + return text + + +def _guessed_value(text: str) -> Any: + if text.lstrip("-").isdigit(): + return int(text) + if len(text) == 10: + return date.fromisoformat(text) + value = datetime.fromisoformat(offset_text(text)) + return value.astimezone(timezone.utc) if value.tzinfo is not None else value + + +def offset_text(text: str) -> str: + """`text` with a `Z` or `+00` offset written as `+00:00`, which `fromisoformat` reads on Python 3.10.""" + normal = text.replace("Z", "+00:00") + return normal + ":00" if normal.endswith("+00") else normal + + +def zoned(value: Any, zone: str | None) -> Any: + """`value` in the IANA zone `zone` when it is a datetime and `zone` is set: an aware one converted, a naive one (a + wall-clock time declared to be in that zone) given it; anything else as it is.""" + if zone is None or not isinstance(value, datetime): + return value + where = ZoneInfo(zone) + return value.astimezone(where) if value.tzinfo is not None else value.replace(tzinfo=where) + + +def _timestamp(text: str, *, aware: bool) -> datetime: + value = datetime.fromisoformat(offset_text(text)) + if not aware: + return value.replace(tzinfo=None) + return value.astimezone(timezone.utc) if value.tzinfo is not None else value.replace(tzinfo=timezone.utc) diff --git a/packages/sqlload-api/python/sqlload_api/_host.py b/packages/sqlload-api/python/sqlload_api/_host.py new file mode 100644 index 000000000..54b3cb381 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_host.py @@ -0,0 +1,139 @@ +"""What every host's crossing calls in Python: transforms (one registry per process, whichever host runs) and the crossing's +own callbacks; and the logged-state bookkeeping a host's runtime answers the engine with. + +SQLLoad's engine (`sqlload-python-host`) imports this module by name. A host's own runtime module defines discovery and how +it calls its table functions; nothing here depends on the host. +""" + +import hashlib +import importlib +import json +import types +from collections.abc import Callable, Iterator +from datetime import date, datetime, time +from decimal import Decimal +from pathlib import Path +from typing import Any + +from sqlload_api._context import Context, offset_text +from sqlload_api._data import checkpoint +from sqlload_api._transform import TRANSFORMS, TransformContext, returned_items + +#: What `page_items` yields after each page's items. +PAGE_END = checkpoint(None) + +#: How long a transform's version hash is, in hex digits. +VERSION_DIGITS = 16 + +#: The project folder the host imported from, which errors name files relative to. +_root: list[Path] = [] + + +def set_root(root: Path) -> None: + """Name files relative to `root` (the project folder) in transforms' errors.""" + _root[:] = [root] + + +def crossing_default(value: Any) -> Any: + """orjson's `default` for yielded rows: `str()`, a `time` as ISO text; a `Decimal`, `date`, `datetime` or bytes refuses, so the batch is walked and keeps its type.""" + if isinstance(value, (Decimal, bytes, bytearray, memoryview)) or type(value) in (date, datetime): + raise TypeError("typed value") + if type(value) is time: + return value.isoformat() + return str(value) + + +def transform_version(name: str) -> tuple[str | None, str | None]: + """Look up the transform registered as `name` and check it can run. + + Returns its version, `name@` and a hash of the file it is defined in (an edit to the file, not only to the function, + changes it; when the file can't be read, as for a function defined in a notebook, a hash of the function's code), or + why it cannot run: no function or two are registered as `name`, or pyarrow is missing. + """ + function, problem = TRANSFORMS.lookup(name, _root[0] if _root else None) + if function is None: + return None, problem + try: + importlib.import_module("pyarrow") + except ImportError: + return None, "transform needs pyarrow: pip install pyarrow" + source = TRANSFORMS.source_file(name) or "" + contents = Path(source).read_bytes() if source and Path(source).is_file() else _code_bytes(function) + return f"{name}@{hashlib.sha256(contents).hexdigest()[:VERSION_DIGITS]}", None + + +def call_transform(name: str, table: Any, context: str) -> tuple[Any, str | None]: + """Call the transform `name` on one unit's rows, a pyarrow Table, with its `ctx` (JSON). + + Returns what crosses, item by item as a generator yields them (its `dicts` says whether any were dicts), or why the + returned value cannot load. + """ + function, problem = TRANSFORMS.lookup(name) + if function is None: + raise LookupError(problem) + fields: dict[str, Any] = json.loads(context) + modified_at = fields.get("modified_at") + ctx = TransformContext(**{**fields, "modified_at": datetime.fromisoformat(offset_text(modified_at)) if modified_at else None}) + return returned_items(TRANSFORMS.shown(name), function(table, ctx)) + + +def page_items(next_page: Callable[[], Any]) -> Iterator[Any]: + """Yield what an `sl.http` job's transform returns for each page `next_page` hands over, item by item, and + `sl.checkpoint(None)` after each page's items to mark where they end, until it hands over `None`.""" + while (returned := next_page()) is not None: + yield from returned + yield PAGE_END + + +def finish() -> None: + """The run is over: let go of the functions passed to jobs as themselves (`transform=page`).""" + TRANSFORMS.release() + + +def current_state(ctx: Context | None) -> str | None: + """The JSON `ctx.state` was assigned one assignment before its latest, while the table function runs: rows crossing now commit with it. + + Rows a function yields may cross before or after it moves `ctx.state` past them, so only the + previous value is sure to cover every row crossed so far, whether the state is set before or + after the rows it covers; a resumed run then never skips rows, and may load up to about two + pages again. Each assignment is kept as JSON, so re-assigning a mutated object leaves the + previous value as it was.""" + if ctx is None or not ctx._logged: + return None + return ctx._previous_assigned_state + + +def final_state(ctx: Context | None) -> str | None: + """The position the table function left in `ctx.state`, as JSON, when it differs from the one it started with. + + It is read once the function finished, so a position changed in place (`ctx.state["token"] = ...`) + counts like one assigned. + """ + if ctx is None or not ctx._logged: + return None + try: + final = json.dumps(ctx.state) + except (TypeError, ValueError) as error: + raise TypeError(f"ctx.state of table {ctx.table} is not JSON: {error}") from error + return final if final != ctx.started_state else None + + +def _code_bytes(function: Any) -> bytes: + """What a function does, for its version when its file can't be read: its bytecode, constants (nested functions' code + included) and the names it uses, without its file name or line numbers. A callable without code, by its type's name.""" + code = getattr(function, "__code__", None) + return _code_parts(code) if isinstance(code, types.CodeType) else type(function).__qualname__.encode() + + +def _code_parts(code: types.CodeType) -> bytes: + constants = [_code_parts(constant) if isinstance(constant, types.CodeType) else _constant_text(constant) for constant in code.co_consts] + return b"\0".join([code.co_code, repr(code.co_names).encode(), *constants]) + + +def _constant_text(constant: Any) -> bytes: + """A code constant as text that is the same in every process: a frozenset's items sorted, as its order follows string hashing.""" + if isinstance(constant, frozenset): + return repr(sorted(repr(item) for item in constant)).encode() + if isinstance(constant, tuple): + return b"(" + b",".join(_constant_text(item) for item in constant) + b")" + return repr(constant).encode() diff --git a/packages/sqlload-api/tests/test_host.py b/packages/sqlload-api/tests/test_host.py new file mode 100644 index 000000000..edcbba1fa --- /dev/null +++ b/packages/sqlload-api/tests/test_host.py @@ -0,0 +1,143 @@ +"""What every host shares: `Context.from_read`, the state bookkeeping, and the transform callbacks of one registry.""" + +import gc +import json +import weakref +from datetime import date, datetime, time, timezone +from decimal import Decimal +from typing import Any +from zoneinfo import ZoneInfo + +import pytest + +import sqlload_api as sl +from sqlload_api import _host + +#: A read as the engine sends it (`TableRead` as JSON, parsed): one connection withheld, a timestamp cursor in a zone. +READ: dict[str, Any] = { + "source": "shop", + "table": "orders", + "connection": "shop_api", + "connections": {"shop_api": {"base_url": "https://api.example.com"}, "other": {"token": "t"}}, + "withheld": ["warehouse"], + "cursor": { + "column": "updated_at", + "column_type": "timestamp_tz", + "start": "2026-11-01T10:00:00Z", + "end": None, + "inclusive": True, + "timezone": "Europe/Paris", + }, + "logged": True, + "state": '{"page": 2}', + "is_reload": False, + "masked": [], + "arrays": [], + "host": {"model": "orders_model"}, +} + + +class LoaderContext(sl.Context): + """A host's context: SQLLoad's, with a field of its own.""" + + def __init__(self, *, model: str, **fields: Any) -> None: + super().__init__(**fields) + self.model = model + + +def test_given_a_read_when_building_its_context_then_it_is_filled_as_sqlload_fills_it() -> None: + ctx = sl.Context.from_read(READ) + assert (ctx.table, ctx.source, ctx.cursor_column, ctx.is_reload, ctx.state) == ("orders", "shop", "updated_at", False, {"page": 2}) + assert ctx.cursor_value == datetime(2026, 11, 1, 11, 0, tzinfo=ZoneInfo("Europe/Paris")) + assert ctx.cursor_end is None + assert dict(ctx.connection) == {"base_url": "https://api.example.com"} + assert dict(ctx.connection("other")) == {"token": "t"} + with pytest.raises(PermissionError, match="connection warehouse is used by a \\[targets\\] entry"): + ctx.connection("warehouse") + + +def test_given_a_subclass_with_a_field_of_its_own_when_building_from_a_read_then_both_are_set() -> None: + ctx = LoaderContext.from_read(READ, model=READ["host"]["model"]) + assert isinstance(ctx, LoaderContext) + assert (ctx.model, ctx.table, ctx.state) == ("orders_model", "orders", {"page": 2}) + + +def test_given_a_logged_context_when_its_state_moves_then_the_crossing_and_final_states_follow() -> None: + ctx = sl.Context.from_read(READ) + assert (_host.current_state(ctx), _host.final_state(ctx)) == ('{"page": 2}', None) + ctx.state = {"page": 3} + ctx.state = {"page": 4} + assert (_host.current_state(ctx), _host.final_state(ctx)) == ('{"page": 3}', '{"page": 4}') + assert (_host.current_state(None), _host.final_state(None)) == (None, None) + + +@pytest.mark.parametrize( + ("value", "expected"), + [(time(9, 30), "09:30:00"), (Decimal("1.5"), TypeError), (date(2026, 1, 1), TypeError), (b"x", TypeError), (object, "")], + ids=["time", "decimal", "date", "bytes", "other"], +) +def test_given_a_value_orjson_cannot_write_when_crossing_dicts_then_the_default_writes_it_or_refuses(value: Any, expected: Any) -> None: + if expected is TypeError: + with pytest.raises(TypeError): + _host.crossing_default(value) + else: + assert _host.crossing_default(value) == expected + + +def test_given_pages_a_transform_returned_when_listing_items_then_each_page_ends_with_a_marker() -> None: + pages = iter([[{"a": 1}, {"a": 2}], [{"a": 3}], None]) + items = list(_host.page_items(lambda: next(pages))) + markers = [item for item in items if hasattr(item, "__sqlload_checkpoint__")] + assert [item for item in items if isinstance(item, dict)] == [{"a": 1}, {"a": 2}, {"a": 3}] + assert [json.loads(marker.__sqlload_checkpoint__()) for marker in markers] == [None, None] + + +def test_given_a_registered_transform_when_called_through_the_host_then_it_gets_its_context() -> None: + pa = pytest.importorskip("pyarrow") + + @sl.transform("host_test_page") + def page(rows: Any, ctx: sl.TransformContext) -> Any: + return [{"n": rows.num_rows, "unit": ctx.unit, "page": ctx.page, "at": ctx.modified_at}] + + returned, problem = _host.call_transform( + "host_test_page", pa.table({"x": [1, 2]}), json.dumps({"unit": "page", "table": "t", "page": 3, "modified_at": "2026-11-01T00:00:00Z"}) + ) + assert (problem, list(returned)) == (None, [[{"n": 2, "unit": "page", "page": 3, "at": datetime(2026, 11, 1, tzinfo=timezone.utc)}]]) + + +def test_a_function_passed_as_transform_is_released_when_the_run_finishes() -> None: + from sqlload_api._host import finish + from sqlload_api._transform import TRANSFORMS + + def page_transform() -> Any: + return lambda rows, ctx: rows + + function = page_transform() + released = weakref.ref(function) + key, _ = TRANSFORMS.key(function) + assert TRANSFORMS.lookup(key)[0] is function + del function + finish() + gc.collect() + assert released() is None + assert TRANSFORMS.lookup(key)[0] is None + + +def test_a_transform_whose_file_cant_be_read_is_versioned_by_its_code() -> None: + from sqlload_api._host import transform_version + from sqlload_api._transform import TRANSFORMS + + def version_of(body: str) -> str | None: + namespace: dict[str, Any] = {} + exec(compile(f"def unread_file_transform(rows, ctx):\n\t{body}\n", "", "exec"), namespace) + TRANSFORMS.register("unread_file_transform", namespace["unread_file_transform"]) + return transform_version("unread_file_transform")[0] + + first = version_of("return rows") + assert first is not None and first.startswith("unread_file_transform@") + assert version_of("return rows.slice(1)") != first + assert version_of("return rows") == first + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/packages/sqlload/python/sqlload/_declare.py b/packages/sqlload/python/sqlload/_declare.py index 0d621921c..822d387fc 100644 --- a/packages/sqlload/python/sqlload/_declare.py +++ b/packages/sqlload/python/sqlload/_declare.py @@ -5,12 +5,15 @@ """ import inspect -import json -from collections.abc import Callable, Collection, Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field -from logging import Logger from typing import Any, TypeVar, overload +# What a table function receives lives in sqlload_api, which other hosts share; re-exported here unchanged. +from sqlload_api._context import Connection, Context + +__all__ = ["Connection", "Context", "Source", "Table", "source", "table"] + TableFunction = Callable[["Context"], Iterator[Any]] ClientFactory = Callable[["Context"], Any] _Function = TypeVar("_Function", bound=TableFunction) @@ -207,122 +210,6 @@ def declare(table_function: TableFunction) -> Table: return declare(function) if function is not None else declare -class Connection(Mapping[str, Any]): - """A connection's resolved settings; calling it looks up another connection by name. - - Connections that `[targets]` write to are not available to table functions (except a source's - own connection), so a table function cannot reach a destination's credentials. - """ - - def __init__( - self, - settings: Mapping[str, Any], - named: Mapping[str, Mapping[str, Any]], - withheld: Collection[str] = (), - ) -> None: - self._settings = dict(settings) - self._named = named - self._withheld = frozenset(withheld) - - def __getitem__(self, key: str) -> Any: - return self._settings[key] - - def __iter__(self) -> Iterator[str]: - return iter(self._settings) - - def __len__(self) -> int: - return len(self._settings) - - def __call__(self, name: str) -> "Connection": - if name in self._withheld: - raise PermissionError( - f"connection {name} is used by a [targets] entry; table functions only get connections" - " that no target writes to, so they cannot reach a destination's credentials" - ) - if name not in self._named: - raise KeyError(f"no connection named {name}") - return Connection(self._named[name], self._named, self._withheld) - - -class Context: - """What a table function receives: its connection and client, the cursor window, and a logger. - - `cursor_value` is where to read from (the destination's maximum of `cursor_column` minus - `lookback`, `cursor_start` on a first run, or `--start-cursor-*`), and `cursor_end` where to stop - (not included); `None` means open. Times arrive in the table's `timezone`, else UTC. Rows the - function returns outside the window fail the table, unless `on_cursor_out_of_range` says to skip - them or load them with a warning. - - With `state="logged"`, `state` is the position the last successful run left (`None` on the - first run, after `--reload` or `sqlload logged-state reset --clear`); set `ctx.state` to the new - position (any JSON value, such as an API sync token) and SQLLoad records it with the data. - """ - - def __init__( - self, - *, - table: str, - source: str, - connection: Connection, - logger: Logger, - cursor_column: str | None = None, - cursor_value: Any = None, - cursor_end: Any = None, - cursor_inclusive: bool = True, - is_reload: bool = False, - client_factory: Callable[["Context"], Any] | None = None, - logged: bool = False, - state: Any = None, - ) -> None: - self.table = table - self.source = source - self._connection = connection - self.logger = logger - self.cursor_column = cursor_column - self.cursor_value = cursor_value - self.cursor_end = cursor_end - self.cursor_inclusive = cursor_inclusive - self.is_reload = is_reload - self._client_factory = client_factory - self._client: Any = None - self._logged = logged - self._state = state - self.started_state = json.dumps(state) - self._assigned_state = self.started_state - self._previous_assigned_state = self.started_state - - @property - def state(self) -> Any: - """The logged position (`state="logged"` tables): where the last successful run left off.""" - return self._state - - @state.setter - def state(self, value: Any) -> None: - if not self._logged: - raise AttributeError(f"ctx.state needs state='logged' on table {self.table}") - try: - assigned = json.dumps(value) - except (TypeError, ValueError) as error: - raise TypeError(f"ctx.state of table {self.table} is not JSON: {error}") from error - self._previous_assigned_state = self._assigned_state - self._assigned_state = assigned - self._state = value - - @property - def connection(self) -> Connection: - """The source's connection settings (empty when it names none); call it with a name for another connection.""" - return self._connection - - @property - def client(self) -> Any: - """The source's client (`@source.client`), built on first use and shared by its tables for the run.""" - if self._client is None: - if self._client_factory is None: - raise LookupError(f"the source of table {self.table} declares no @source.client") - self._client = self._client_factory(self) - return self._client - - def _check_settings(settings: Mapping[str, Any], allowed: frozenset[str], what: str) -> None: unknown = sorted(set(settings) - allowed) if unknown: diff --git a/packages/sqlload/python/sqlload/_runtime.py b/packages/sqlload/python/sqlload/_runtime.py index 6c4da34a9..32b27aed1 100644 --- a/packages/sqlload/python/sqlload/_runtime.py +++ b/packages/sqlload/python/sqlload/_runtime.py @@ -4,30 +4,21 @@ `load` and the other commands; they are not a public API. """ -import hashlib import importlib import json -import logging import sys import threading import traceback -import types -from collections.abc import Callable, Iterator -from datetime import date, datetime, time, timedelta, timezone -from decimal import Decimal +from collections.abc import Iterator +from datetime import date, datetime, timedelta from pathlib import Path from typing import Any -from zoneinfo import ZoneInfo -from sqlload._declare import Connection, Context, Source, Table +from sqlload._declare import Context, Source, Table from sqlload._rename import RENAMES, Column, RenameContext, renamed -from sqlload_api._data import checkpoint +from sqlload_api import _host from sqlload_api._http import Job from sqlload_api._http_paths import literal_paths -from sqlload_api._transform import TRANSFORMS, TransformContext, returned_items - -#: What `page_items` yields after each page's items. -PAGE_END = checkpoint(None) #: Folders under `python_paths` never imported: virtual environments, build output and caches. SKIPPED_FOLDERS: frozenset[str] = frozenset({"venv", "build", "dist", "site-packages", "node_modules"}) @@ -35,9 +26,6 @@ #: The destination name of a table declared without a source: its own name. STANDALONE_TABLE_NAME = "{table}" -#: How long a transform's version hash is, in hex digits. -VERSION_DIGITS = 16 - _tables: dict[str, Table] = {} #: The project folder `discover` imported from, which errors name files relative to. _root: list[Path] = [] @@ -69,6 +57,7 @@ def discover(root: str, python_paths: list[str]) -> str: elif isinstance(value, Table) and value.source is not None: sources.setdefault(id(value.source), (value.source, relative)) _root[:] = [root_path] + _host.set_root(root_path) _tables.clear() declared: list[dict[str, Any]] = [] for source, relative in sources.values(): @@ -90,39 +79,13 @@ def discover(root: str, python_paths: list[str]) -> str: return json.dumps(declared) -def crossing_default(value: Any) -> Any: - """orjson's `default` for yielded rows: `str()`, a `time` as ISO text; a `Decimal`, `date`, `datetime` or bytes refuses, so the batch is walked and keeps its type.""" - if isinstance(value, (Decimal, bytes, bytearray, memoryview)) or type(value) in (date, datetime): - raise TypeError("typed value") - if type(value) is time: - return value.isoformat() - return str(value) - - def start_table(request: str) -> Iterator[Any]: """Call a table function with its context; returns what it yields.""" read = json.loads(request) table = _tables[read["table"]] - connections: dict[str, Any] = read["connections"] - connection_name = read.get("connection") - withheld: list[str] = read["withheld"] - connection = Connection(connections.get(connection_name, {}) if connection_name else {}, connections, withheld) - cursor = read.get("cursor") or {} source = table.source - ctx = Context( - table=table.name, - source=read["source"], - connection=connection, - logger=logging.getLogger(f"sqlload.{read['source']}.{table.name}"), - cursor_column=cursor.get("column"), - cursor_value=_cursor_value(cursor.get("start"), cursor.get("column_type"), cursor.get("timezone")), - cursor_end=_cursor_value(cursor.get("end"), cursor.get("column_type"), cursor.get("timezone")), - cursor_inclusive=cursor.get("inclusive", True), - is_reload=read["is_reload"], - client_factory=_shared_client(source) if source is not None and source.client_factory else None, - logged=read.get("logged", False), - state=json.loads(read["state"]) if read.get("state") is not None else None, - ) + shared = _shared_client(source) if source is not None and source.client_factory else None + ctx = Context.from_read(read, client_factory=shared) _contexts[table.name] = ctx yielded = table.function(ctx) if yielded is None: @@ -131,75 +94,13 @@ def start_table(request: str) -> Iterator[Any]: def current_state(table: str) -> str | None: - """The JSON `ctx.state` was assigned one assignment before its latest, while the table function runs: rows crossing now commit with it. - - Rows a function yields may cross before or after it moves `ctx.state` past them, so only the - previous value is sure to cover every row crossed so far, whether the state is set before or - after the rows it covers; a resumed run then never skips rows, and may load up to about two - pages again. Each assignment is kept as JSON, so re-assigning a mutated object leaves the - previous value as it was.""" - ctx = _contexts.get(table) - if ctx is None or not ctx._logged: - return None - return ctx._previous_assigned_state + """The JSON `ctx.state` was assigned one assignment before its latest, while the table function runs (see `sqlload_api._host.current_state`).""" + return _host.current_state(_contexts.get(table)) def table_state(table: str) -> str | None: - """The position the table function left in `ctx.state`, as JSON, when it differs from the one it started with. - - It is read once the function finished, so a position changed in place (`ctx.state["token"] = ...`) - counts like one assigned. - """ - ctx = _contexts.pop(table, None) - if ctx is None or not ctx._logged: - return None - try: - final = json.dumps(ctx.state) - except (TypeError, ValueError) as error: - raise TypeError(f"ctx.state of table {table} is not JSON: {error}") from error - return final if final != ctx.started_state else None - - -def transform_version(name: str) -> tuple[str | None, str | None]: - """Look up the transform registered as `name` and check it can run. - - Returns its version, `name@` and a hash of the file it is defined in (an edit to the file, not only to the function, - changes it; when the file can't be read, as for a function defined in a notebook, a hash of the function's code), or - why it cannot run: no function or two are registered as `name`, or pyarrow is missing. - """ - function, problem = TRANSFORMS.lookup(name, _root[0] if _root else None) - if function is None: - return None, problem - try: - importlib.import_module("pyarrow") - except ImportError: - return None, "transform needs pyarrow: pip install pyarrow" - source = TRANSFORMS.source_file(name) or "" - contents = Path(source).read_bytes() if source and Path(source).is_file() else _code_bytes(function) - return f"{name}@{hashlib.sha256(contents).hexdigest()[:VERSION_DIGITS]}", None - - -def call_transform(name: str, table: Any, context: str) -> tuple[Any, str | None]: - """Call the transform `name` on one unit's rows, a pyarrow Table, with its `ctx` (JSON). - - Returns what crosses, item by item as a generator yields them (its `dicts` says whether any were dicts), or why the - returned value cannot load. - """ - function, problem = TRANSFORMS.lookup(name) - if function is None: - raise LookupError(problem) - fields: dict[str, Any] = json.loads(context) - modified_at = fields.get("modified_at") - ctx = TransformContext(**{**fields, "modified_at": datetime.fromisoformat(_offset_text(modified_at)) if modified_at else None}) - return returned_items(TRANSFORMS.shown(name), function(table, ctx)) - - -def page_items(next_page: Callable[[], Any]) -> Iterator[Any]: - """Yield what an `sl.http` job's transform returns for each page `next_page` hands over, item by item, and - `sl.checkpoint(None)` after each page's items to mark where they end, until it hands over `None`.""" - while (returned := next_page()) is not None: - yield from returned - yield PAGE_END + """The position the table function left in `ctx.state`, as JSON, when it differs from the one it started with (see `sqlload_api._host.final_state`).""" + return _host.final_state(_contexts.pop(table, None)) def rename(name: str, columns: str | None, context: str) -> tuple[str | None, str | None]: @@ -224,7 +125,6 @@ def rename(name: str, columns: str | None, context: str) -> tuple[str | None, st def finish_run() -> None: """Close every client the run built (their `close()`, when they have one).""" - TRANSFORMS.release() RENAMES.release() clients = list(_clients.values()) _clients.clear() @@ -325,85 +225,3 @@ def build(ctx: Context) -> Any: return _clients[source.name] return build - - -def _cursor_value(text: str | None, column_type: str | None, zone: str | None = None) -> Any: - """A cursor bound in its Python type: int, float, Decimal, date, or datetime: aware for `timestamp_tz`, in the - table's `timezone` (`zone`) or UTC; for `timestamp_ntz`, aware in `zone` when it is set, its wall-clock time kept. - - Before the first load shows the cursor's type (`unknown`), ISO dates and timestamps and integers - are read as such, so the value's type matches later runs. - """ - if text is None: - return None - kind = column_type or "unknown" - if kind.startswith("decimal"): - kind = "decimal" - try: - if kind == "unknown": - return _zoned(_guessed_value(text), zone) - if kind in ("int", "smallint"): - return int(text) - if kind == "float": - return float(text) - if kind == "decimal": - return Decimal(text) - if kind == "date": - return date.fromisoformat(text[:10]) - if kind in ("timestamp_tz", "timestamp_ntz"): - return _zoned(_timestamp(text, aware=kind == "timestamp_tz"), zone) - except (ValueError, ArithmeticError): - return text - return text - - -def _guessed_value(text: str) -> Any: - if text.lstrip("-").isdigit(): - return int(text) - if len(text) == 10: - return date.fromisoformat(text) - value = datetime.fromisoformat(_offset_text(text)) - return value.astimezone(timezone.utc) if value.tzinfo is not None else value - - -def _offset_text(text: str) -> str: - """`text` with a `Z` or `+00` offset written as `+00:00`, which `fromisoformat` reads on Python 3.10.""" - normal = text.replace("Z", "+00:00") - return normal + ":00" if normal.endswith("+00") else normal - - -def _zoned(value: Any, zone: str | None) -> Any: - """`value` in the IANA zone `zone` when it is a datetime and `zone` is set: an aware one converted, a naive one (a - wall-clock time declared to be in that zone) given it; anything else as it is.""" - if zone is None or not isinstance(value, datetime): - return value - where = ZoneInfo(zone) - return value.astimezone(where) if value.tzinfo is not None else value.replace(tzinfo=where) - - -def _timestamp(text: str, *, aware: bool) -> datetime: - value = datetime.fromisoformat(_offset_text(text)) - if not aware: - return value.replace(tzinfo=None) - return value.astimezone(timezone.utc) if value.tzinfo is not None else value.replace(tzinfo=timezone.utc) - - -def _code_bytes(function: Any) -> bytes: - """What a function does, for its version when its file can't be read: its bytecode, constants (nested functions' code - included) and the names it uses, without its file name or line numbers. A callable without code, by its type's name.""" - code = getattr(function, "__code__", None) - return _code_parts(code) if isinstance(code, types.CodeType) else type(function).__qualname__.encode() - - -def _code_parts(code: types.CodeType) -> bytes: - constants = [_code_parts(constant) if isinstance(constant, types.CodeType) else _constant_text(constant) for constant in code.co_consts] - return b"\0".join([code.co_code, repr(code.co_names).encode(), *constants]) - - -def _constant_text(constant: Any) -> bytes: - """A code constant as text that is the same in every process: a frozenset's items sorted, as its order follows string hashing.""" - if isinstance(constant, frozenset): - return repr(sorted(repr(item) for item in constant)).encode() - if isinstance(constant, tuple): - return b"(" + b",".join(_constant_text(item) for item in constant) + b")" - return repr(constant).encode() diff --git a/packages/sqlload/tests/test_transforms.py b/packages/sqlload/tests/test_transforms.py index 1d0a43d8c..6c41a2c49 100644 --- a/packages/sqlload/tests/test_transforms.py +++ b/packages/sqlload/tests/test_transforms.py @@ -1,6 +1,5 @@ """Transforms end to end: `transform` on files tables (each file or ZIP member) and on `google_sheets` tables (each range), into DuckDB.""" -import gc import importlib.util import json import os @@ -9,7 +8,6 @@ import textwrap import threading import time -import weakref import zipfile from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -561,35 +559,3 @@ def test_a_function_passed_as_transform_resolves_to_itself_when_two_files_regist assert shown == "clean" -def test_a_function_passed_as_transform_is_released_when_the_run_finishes() -> None: - from sqlload._runtime import finish_run - from sqlload_api._transform import TRANSFORMS - - def page_transform() -> Any: - return lambda rows, ctx: rows - - function = page_transform() - released = weakref.ref(function) - key, _ = TRANSFORMS.key(function) - assert TRANSFORMS.lookup(key)[0] is function - del function - finish_run() - gc.collect() - assert released() is None - assert TRANSFORMS.lookup(key)[0] is None - - -def test_a_transform_whose_file_cant_be_read_is_versioned_by_its_code() -> None: - from sqlload._runtime import transform_version - from sqlload_api._transform import TRANSFORMS - - def version_of(body: str) -> str | None: - namespace: dict[str, Any] = {} - exec(compile(f"def unread_file_transform(rows, ctx):\n\t{body}\n", "", "exec"), namespace) - TRANSFORMS.register("unread_file_transform", namespace["unread_file_transform"]) - return transform_version("unread_file_transform")[0] - - first = version_of("return rows") - assert first is not None and first.startswith("unread_file_transform@") - assert version_of("return rows.slice(1)") != first - assert version_of("return rows") == first diff --git a/tests/external_host/pyproject.toml b/tests/external_host/pyproject.toml new file mode 100644 index 000000000..efeaa1618 --- /dev/null +++ b/tests/external_host/pyproject.toml @@ -0,0 +1,14 @@ +[build-system] +requires = ["maturin>=1.9,<2"] +build-backend = "maturin" + +[project] +name = "example-host" +version = "0.0.0" +description = "A host of SQLLoad's engine with a Python runtime of its own, for sqlload-python-host's tests; never published." +requires-python = ">=3.10" + +[tool.maturin] +manifest-path = "../../crates/sqlload-python-host-example/Cargo.toml" +module-name = "example_host._native" +python-source = "python" diff --git a/tests/external_host/python/example_host/__init__.py b/tests/external_host/python/example_host/__init__.py new file mode 100644 index 000000000..2b9d523eb --- /dev/null +++ b/tests/external_host/python/example_host/__init__.py @@ -0,0 +1,5 @@ +"""A host of SQLLoad's engine with a Python runtime of its own: tables are `@model` functions, and each gets an `ExampleContext`.""" + +from example_host.example_runtime import ExampleContext, model + +__all__ = ["ExampleContext", "model"] diff --git a/tests/external_host/python/example_host/example_runtime.py b/tests/external_host/python/example_host/example_runtime.py new file mode 100644 index 000000000..9d2b977fa --- /dev/null +++ b/tests/external_host/python/example_host/example_runtime.py @@ -0,0 +1,84 @@ +"""The example host's runtime, which `sqlload-python-host`'s `ModuleHost` calls. + +It declares tables its own way (`@model(source)`), passes data of its own through the engine (each source's `host`), and +builds each table's context as a subclass of `sqlload_api.Context`. Transforms, `sqlload_api.http` jobs and the +crossing are SQLLoad's, through `sqlload_api._host`. +""" + +import importlib.util +import json +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import sqlload_api +from sqlload_api import _host + +#: Each declared table: its source and function, by table name. +_tables: dict[str, tuple[str, Callable[["ExampleContext"], Any]]] = {} +#: The context of each table running, by table name. +_contexts: dict[str, "ExampleContext"] = {} + + +class ExampleContext(sqlload_api.Context): + """SQLLoad's context, with the model the host's own data names for the table.""" + + def __init__(self, *, model: str, **fields: Any) -> None: + super().__init__(**fields) + self.model = model + + +def model(source: str) -> Callable[[Callable[[ExampleContext], Any]], Callable[[ExampleContext], Any]]: + """Declare the decorated function as a table of `source`, named after it.""" + + def declare(function: Callable[[ExampleContext], Any]) -> Callable[[ExampleContext], Any]: + _tables[function.__name__] = (source, function) + return function + + return declare + + +def discover(root: str, python_paths: list[str]) -> str: + """Import the `.py` files in `python_paths` and describe their sources, each with the host's data: its tables' models.""" + root_path = Path(root or ".").resolve() + _host.set_root(root_path) + modules: dict[str, str] = {} + for folder in python_paths: + for path in sorted((root_path / folder).glob("*.py")): + before = set(_tables) + spec = importlib.util.spec_from_file_location(f"example_models_{path.stem}", path) + assert spec is not None and spec.loader is not None + spec.loader.exec_module(importlib.util.module_from_spec(spec)) + modules.update({name: str(path.relative_to(root_path)) for name in set(_tables) - before}) + sources: dict[str, dict[str, Any]] = {} + for name, (source, _) in _tables.items(): + declared = sources.setdefault(source, {"name": source, "module": modules.get(name, ""), "settings": {"write_strategy": "replace", "tables": {}}, "host": {"models": {}}}) + declared["settings"]["tables"][name] = {"description": f"The {name} model."} + declared["host"]["models"][name] = f"{source}.{name}" + return json.dumps(list(sources.values())) + + +def start_table(request: str) -> Iterator[Any]: + """Call the table the read names with an `ExampleContext`; returns what it yields.""" + read = json.loads(request) + _, function = _tables[read["table"]] + ctx = ExampleContext.from_read(read, model=read["host"]["models"][read["table"]]) + _contexts[ctx.table] = ctx + yielded = function(ctx) + return iter([yielded]) if isinstance(yielded, sqlload_api.Job) else iter(yielded) + + +def current_state(table: str) -> str | None: + return _host.current_state(_contexts.get(table)) + + +def table_state(table: str) -> str | None: + return _host.final_state(_contexts.pop(table, None)) + + +def rename(name: str, columns: str | None, context: str) -> tuple[str | None, str | None]: + return None, "the example host has no renames" + + +def finish_run() -> None: + _contexts.clear() diff --git a/tests/external_host/test_external_host.py b/tests/external_host/test_external_host.py new file mode 100644 index 000000000..b9ee92c42 --- /dev/null +++ b/tests/external_host/test_external_host.py @@ -0,0 +1,129 @@ +"""A host of its own on SQLLoad's engine: tables declared its way, its data reaching each table's context, and SQLLoad's +`sqlload_api.http` jobs and page transforms, through `sqlload-python-host`.""" + +import json +import os +import subprocess +import sys +import textwrap +import threading +from collections.abc import Iterator +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, urlparse + +import duckdb +import pytest + +#: The orders the stub API serves, two a page. +ORDERS = [{"order_id": n, "status": "open"} for n in range(1, 5)] + +#: Run the example host's `sqlload` with this script's arguments. +RUN = "import sys; from example_host._native import run; sys.exit(run(['sqlload', *sys.argv[1:]]))" + + +class Api(BaseHTTPRequestHandler): + """`/v1/pages?p=N`: the orders, two a page, then an empty page.""" + + def log_message(self, *args: Any) -> None: + pass + + def do_GET(self) -> None: + page = int(parse_qs(urlparse(self.path).query).get("p", ["1"])[0]) + body = json.dumps({"items": ORDERS[(page - 1) * 2 : page * 2]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + +@pytest.fixture +def api() -> Iterator[ThreadingHTTPServer]: + server = ThreadingHTTPServer(("127.0.0.1", 0), Api) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield server + server.shutdown() + + +def make_project(tmp_path: Path, api: ThreadingHTTPServer) -> Path: + host, port = api.server_address[:2] + (tmp_path / "models").mkdir() + (tmp_path / "sqlload.toml").write_text( + textwrap.dedent(f"""\ + python_paths = ["models"] + + [connections.wh] + kind = "duckdb" + database = "wh.duckdb" + + [connections.shop] + kind = "http" + base_url = "http://{host}:{port}/v1" + + [targets.dev] + connection = "wh" + loader_schema = "RAW" + """) + ) + (tmp_path / "models" / "shop.py").write_text( + textwrap.dedent("""\ + import sqlload_api as sl + from example_host import model + + api = sl.http(connection="shop") + + + @sl.transform + def tag_page(rows, ctx): + return [{**row, "page": ctx.page} for row in rows.to_pylist()] + + + @model("shop") + def orders(ctx): + return api.paginate("/pages", paginator=sl.page_number("p"), select="$.items", transform=tag_page) + + + @model("shop") + def models(ctx): + yield {"model": ctx.model, "source": ctx.source, "kind": type(ctx).__name__} + """) + ) + return tmp_path + + +def sqlload(project: Path, *args: str, before: str = "") -> subprocess.CompletedProcess[str]: + home = project / "home" + home.mkdir(exist_ok=True) + env = {**os.environ, "HOME": str(home), "XDG_CONFIG_HOME": str(home / ".config")} + return subprocess.run([sys.executable, "-c", before + RUN, *args], cwd=project, env=env, capture_output=True, text=True, timeout=120) + + +def query(project: Path, sql: str) -> list[tuple[Any, ...]]: + with duckdb.connect(str(project / "wh.duckdb"), read_only=True) as connection: + return connection.execute(sql).fetchall() + + +def test_given_a_host_of_its_own_when_loading_then_its_tables_jobs_and_transforms_load(tmp_path: Path, api: ThreadingHTTPServer) -> None: + project = make_project(tmp_path, api) + done = sqlload(project, "load") + assert done.returncode == 0, done.stdout + done.stderr + assert query(project, 'select order_id, status, page from "RAW".shop__orders order by order_id') == [(1, "open", 1), (2, "open", 1), (3, "open", 2), (4, "open", 2)] + assert query(project, 'select model, source, kind from "RAW".shop__models') == [("shop.models", "shop", "ExampleContext")] + + +def test_given_another_sqlload_api_when_loading_then_the_host_says_which_to_install(tmp_path: Path, api: ThreadingHTTPServer) -> None: + project = make_project(tmp_path, api) + done = sqlload(project, "load", before="import sqlload_api; sqlload_api.__version__ = '0.0.1'; ") + expected = f'sqlload-api 0.0.1 is installed, but this engine reads sqlload-api {_engine_version()}: pip install "sqlload-api=={_engine_version()}"' + assert (done.returncode != 0, expected in done.stdout + done.stderr) == (True, True), done.stdout + done.stderr + + +def _engine_version() -> str: + from importlib.metadata import version + + return version("sqlload-api") + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/website/src/content/docs/docs/sources/python.mdx b/website/src/content/docs/docs/sources/python.mdx index dfdf21b8a..1716b00b5 100644 --- a/website/src/content/docs/docs/sources/python.mdx +++ b/website/src/content/docs/docs/sources/python.mdx @@ -835,3 +835,43 @@ A job built this way is the same, byte for byte, as one built with `sl.http(sour `shop_api`. `sqlload-api` is released with `sqlload`, at the same version, and `sqlload` pins it exactly: an engine reads the items of its own version. A field path in `sl.json(..., fields=...)` is checked by the engine when the item is yielded, and fails the table naming the field. + +### Embedding the Python host + +A tool with a pyo3 extension of its own can run its tables on SQLLoad's engine with the +[`sqlload-python-host`](https://crates.io/crates/sqlload-python-host) crate. What its tables yield crosses as an +`sl.source`'s does: dicts, Arrow data, `json`/`ndjson` items, `http` jobs with their page transforms, and checkpoints. +The tool declares its tables its own way, in a Python runtime module it names: + +```rust +let host = sqlload_python_host::host::main::module_host::module_host("my_tool._sqlload_runtime"); +``` + +The runtime module defines these functions: + +| Function | What it does | +| --- | --- | +| `discover(root, python_paths)` | Returns the sources found, as JSON: each with `name`, `module`, `settings` (TOML keys, tables under `tables`) and an optional `host` value of the tool's own. | +| `start_table(read)` | Calls the table `read` (JSON) names and returns what it yields. `read["host"]` is its source's `host` value. | +| `current_state(table)`, `table_state(table)` | A logged table's `ctx.state` as JSON while its rows cross, and once it has finished. | +| `rename(name, columns, context)` | Runs a table's `rename`; returns `(names, None)` or `(None, problem)`. | +| `finish_run()` | Runs when the run is over, to close clients. | + +`sqlload_api.Context.from_read(read, **extras)` builds a table's `ctx` as SQLLoad builds it: connections, cursor +window and types, logged state. A tool adds fields of its own with a subclass: + +```python +import sqlload_api + + +class ToolContext(sqlload_api.Context): + def __init__(self, *, model: str, **fields): + super().__init__(**fields) + self.model = model + + +ctx = ToolContext.from_read(read, model=read["host"]["model"]) +``` + +The extension uses the crate's pyo3, 0.29, with `abi3-py310`. The interpreter needs `sqlload-api` at the crate's +version: a different one fails the first read with the version to install. From f5cb45b4b582022b8559edddc6b48953aa7383b9 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:20:10 +0000 Subject: [PATCH 2/5] fix(motherduck): a command returns only once its MotherDuck bridges have exited The last handle of a bridge closed its stdin and left the exit to a detached thread, so sqlload could return while the bridge still held the database it opened, and the next command (or a reader) hit DuckDB's file lock. Dropping the last handle now waits for the bridge to exit, ending it after 10 s. The memory watchdog's interrupt thread holds a weak handle, so that wait happens on the command's own path, not on that thread. make test-python roots pytest at the repository, so test IDs name their real paths instead of sqlload-api's folder. --- Makefile | 3 +- .../adapters/duckdb/main/_own_connection.rs | 7 +++-- .../motherduck_bridge/_helpers/process.rs | 29 +++++++++++++++---- .../adapters/motherduck_bridge/constants.rs | 4 +++ .../src/adapters/motherduck_bridge/models.rs | 14 ++++++++- 5 files changed, 48 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index 0426fe977..6650f2cbb 100644 --- a/Makefile +++ b/Makefile @@ -59,7 +59,8 @@ test-python: cd packages/sqlload && VIRTUAL_ENV=$(CURDIR)/.venv $(CURDIR)/.venv/bin/maturin develop --uv --quiet --features odbc # A host of its own on sqlload-python-host, which loads through the same engine (never published). cd tests/external_host && VIRTUAL_ENV=$(CURDIR)/.venv $(CURDIR)/.venv/bin/maturin develop --uv --quiet - .venv/bin/python -m pytest packages/sqlload-api/tests packages/sqlload/tests tests/external_host -n auto --dist loadfile + # The repository root as rootdir: otherwise pytest roots at the first argument's pyproject.toml (sqlload-api's), and names the other tests from there. + .venv/bin/python -m pytest --rootdir $(CURDIR) packages/sqlload-api/tests packages/sqlload/tests tests/external_host -n auto --dist loadfile test: test-unit test-containers diff --git a/crates/sqlload/src/adapters/duckdb/main/_own_connection.rs b/crates/sqlload/src/adapters/duckdb/main/_own_connection.rs index 9ae09f8f6..139a7a555 100644 --- a/crates/sqlload/src/adapters/duckdb/main/_own_connection.rs +++ b/crates/sqlload/src/adapters/duckdb/main/_own_connection.rs @@ -7,7 +7,7 @@ use crate::adapters::duckdb::models::{DuckDbConnection, DuckDbDestination}; use crate::adapters::motherduck_bridge::main::fork_connection::fork_connection; use crate::memory_budget::main::table_memory::table_memory; -/// A new connection to the same database, so one table's transaction never mixes with another table's loading at the same time. Under the memory watchdog, the table it loads can have the connection's running statement interrupted. +/// A new connection to the same database, so one table's transaction never mixes with another table's loading at the same time. Under the memory watchdog, the table it loads can have the connection's running statement interrupted; on a MotherDuck bridge, the thread that interrupts it holds the bridge weakly, so the connection keeps its last handle and the bridge exits on the command's own path. pub(in crate::adapters) fn own_connection( destination: &DuckDbDestination, ) -> Result { @@ -32,9 +32,12 @@ pub(in crate::adapters) fn own_connection( DuckDbConnection::Bridge(bridge) => { let forked = fork_connection(bridge); if watched.is_some() { - let (process, cursor) = (forked.cursor.process.clone(), forked.cursor.id); + let (process, cursor) = (Arc::downgrade(&forked.cursor.process), forked.cursor.id); std::thread::spawn(move || { for () in receiver { + let Some(process) = process.upgrade() else { + break; + }; let interrupt = serde_json::json!({"op": "interrupt", "cursor": cursor}); let _ = process.lines.send(interrupt.to_string()); } diff --git a/crates/sqlload/src/adapters/motherduck_bridge/_helpers/process.rs b/crates/sqlload/src/adapters/motherduck_bridge/_helpers/process.rs index b5da57011..29cd60199 100644 --- a/crates/sqlload/src/adapters/motherduck_bridge/_helpers/process.rs +++ b/crates/sqlload/src/adapters/motherduck_bridge/_helpers/process.rs @@ -1,18 +1,20 @@ //! The bridge process: starting it, sending it requests, and routing its replies. use std::io::{BufRead, BufReader, Read, Write}; -use std::process::{Command, Stdio}; +use std::process::{Child, Command, Stdio}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, channel}; use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Instant; use crate::adapters::motherduck_bridge::constants::{ - BRIDGE_SCRIPT, PYTHON_VARIABLE, STDERR_TAIL_BYTES, SUPPORTED_DUCKDB, + BRIDGE_EXIT_POLL, BRIDGE_EXIT_WAIT, BRIDGE_SCRIPT, PYTHON_VARIABLE, STDERR_TAIL_BYTES, + SUPPORTED_DUCKDB, }; use crate::adapters::motherduck_bridge::errors::BridgeError; use crate::adapters::motherduck_bridge::models::{BridgeCursor, BridgeProcess, Replies}; -/// Start the bridge on `python`: a writer thread feeding its stdin (closing it, and reaping the process, once every handle is gone), a reader thread routing its replies and, once stdout and stderr have both closed or a reply is unreadable, failing what still waits, and one keeping its stderr's tail with each of `hidden` taken out. +/// Start the bridge on `python`: a writer thread feeding its stdin (closing it, and reaping the process, once the last handle drops, which waits for it), a reader thread routing its replies and, once stdout and stderr have both closed or a reply is unreadable, failing what still waits, and one keeping its stderr's tail with each of `hidden` taken out. pub(crate) fn start(python: &str, hidden: Vec) -> Result, BridgeError> { let mut child = Command::new(python) .args(["-c", BRIDGE_SCRIPT]) @@ -36,7 +38,7 @@ pub(crate) fn start(python: &str, hidden: Vec) -> Result(); let replies = Arc::new(Mutex::new(Replies::default())); let tail = Arc::new(Mutex::new(String::new())); - std::thread::spawn(move || { + let writer = std::thread::spawn(move || { for line in outgoing { if stdin .write_all(format!("{line}\n").as_bytes()) @@ -47,7 +49,7 @@ pub(crate) fn start(python: &str, hidden: Vec) -> Result) -> Result return, + Ok(None) if Instant::now() >= deadline => { + let _ = child.kill(); + let _ = child.wait(); + return; + } + Ok(None) => std::thread::sleep(BRIDGE_EXIT_POLL), + } + } +} + /// Send `request` with an id of its own; the receiver gets its reply, or why the bridge stopped first. pub(crate) fn send( process: &BridgeProcess, diff --git a/crates/sqlload/src/adapters/motherduck_bridge/constants.rs b/crates/sqlload/src/adapters/motherduck_bridge/constants.rs index 0799253f3..d8b1b20cc 100644 --- a/crates/sqlload/src/adapters/motherduck_bridge/constants.rs +++ b/crates/sqlload/src/adapters/motherduck_bridge/constants.rs @@ -10,6 +10,10 @@ pub const DEFAULT_PYTHON: &str = "python3"; pub const DEFAULT_PYTHON: &str = "python"; /// The duckdb package versions MotherDuck accepts, as the bridge's install hints name them. pub const SUPPORTED_DUCKDB: &str = "duckdb 1.4.1 to 1.5.6"; +/// How long the last handle of a bridge waits for it to exit once its stdin closes, before ending it: it exits as soon as it reads the end of stdin, releasing the database it opened. +pub const BRIDGE_EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(10); +/// How often that wait checks whether the bridge has exited. +pub const BRIDGE_EXIT_POLL: std::time::Duration = std::time::Duration::from_millis(5); /// How many bytes of the bridge's last stderr output a failure quotes. pub const STDERR_TAIL_BYTES: usize = 2048; /// The error types the bridge replies with when its Python has no duckdb package. diff --git a/crates/sqlload/src/adapters/motherduck_bridge/models.rs b/crates/sqlload/src/adapters/motherduck_bridge/models.rs index f1ebc98d3..86bd6c039 100644 --- a/crates/sqlload/src/adapters/motherduck_bridge/models.rs +++ b/crates/sqlload/src/adapters/motherduck_bridge/models.rs @@ -25,7 +25,7 @@ impl Drop for BridgeCursor { } } -/// A running bridge process: the lines going to its stdin, the requests waiting for its replies, and the tail of its stderr. The process ends when the last handle drops, which closes its stdin. +/// A running bridge process: the lines going to its stdin, the requests waiting for its replies, and the tail of its stderr. The process ends when the last handle drops, which closes its stdin and waits for it to exit, so the database it holds is free before the command goes on. #[derive(Debug)] pub struct BridgeProcess { /// The Python it runs on, as messages name it. @@ -37,6 +37,18 @@ pub struct BridgeProcess { pub next_request: AtomicU64, pub next_cursor: AtomicU64, pub stderr: Arc>, + /// The thread feeding its stdin, which reaps the process once stdin closes. + pub writer: Option>, +} + +impl Drop for BridgeProcess { + /// Close the bridge's stdin, by replacing `lines`, the writer's only sender, which ends the writer's loop; then wait for the writer, which reaps the bridge. + fn drop(&mut self) { + self.lines = std::sync::mpsc::channel().0; + if let Some(writer) = self.writer.take() { + let _ = writer.join(); + } + } } /// The requests waiting for a reply, by id, each with where its reply goes; once the process has ended, why, which every later request fails with. From 62bc7b0619dc114b65c5c4026c8cf5aff2060f8e Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:55:08 +0000 Subject: [PATCH 3/5] feat: check how a table's options combine when the project is parsed The rules for how a table's options combine (merge needs a unique_key, replace takes no cursor, append takes no lookback, a setting for another strategy, and the rest the loader enforced from settings alone) ran only when a table was planned. A tool that validates a project offline, such as one calling parse_python_project, never saw them. They now live in one place, the table_options module. The loader's build_spec calls it as it plans a table, and parse_project and parse_python_project call it for every table entry, Python tables included, before anything connects. A source that lists no tables is checked with its own settings, which every table it finds takes. Parse reports each problem at the table's entry with plan's wording. Rules that need the discovered table (its columns, its primary key and its nullability, constants, a missing write_strategy) stay at plan. The integration test cases that expected plan to refuse settings-only combinations moved to a parse test covering every rule, for TOML and Python sources. --- crates/sqlload/src/lib.rs | 1 + crates/sqlload/src/loader/_helpers/resolve.rs | 6 +- crates/sqlload/src/loader/_helpers/run_log.rs | 22 - crates/sqlload/src/loader/_helpers/sources.rs | 6 +- crates/sqlload/src/loader/_helpers/specs.rs | 827 ++---------------- .../src/loader/tests/test_table_parses.rs | 4 +- .../src/project/_helpers/references.rs | 4 +- .../src/project/main/parse_python_project.rs | 2 +- crates/sqlload/src/project/tests/helpers.rs | 5 +- .../sqlload/src/table_options/_helpers/mod.rs | 5 + .../src/table_options/_helpers/nesting.rs | 192 ++++ .../table_options/_helpers/option_target.rs | 27 + .../src/table_options/_helpers/options.rs | 175 ++++ .../src/table_options/_helpers/rules.rs | 273 ++++++ .../src/table_options/_helpers/settings.rs | 124 +++ .../sqlload/src/table_options/main/layered.rs | 12 + crates/sqlload/src/table_options/main/mod.rs | 7 + .../src/table_options/main/option_problems.rs | 82 ++ .../table_options/main/placeholder_problem.rs | 33 + .../src/table_options/main/table_compat.rs | 16 + .../src/table_options/main/table_naming.rs | 16 + .../src/table_options/main/table_options.rs | 56 ++ .../src/table_options/main/table_strategy.rs | 46 + crates/sqlload/src/table_options/mod.rs | 8 + crates/sqlload/src/table_options/models.rs | 69 ++ crates/sqlload/src/table_options/tests.rs | 6 + .../src/table_options/tests/helpers.rs | 50 ++ .../tests/test_option_problems.rs | 393 +++++++++ .../src/table_options/tests/test_types.rs | 17 + .../tests/loader/test_files_to_duckdb.rs | 94 -- .../tests/loader/test_loader_edge_cases.rs | 35 - .../sqlload/tests/loader/test_sync_deletes.rs | 20 +- .../tests/loader/test_typed_cursors.rs | 26 - website/src/content/docs/docs/cli/plan.mdx | 21 + .../src/content/docs/docs/configuration.mdx | 2 + 35 files changed, 1724 insertions(+), 958 deletions(-) create mode 100644 crates/sqlload/src/table_options/_helpers/mod.rs create mode 100644 crates/sqlload/src/table_options/_helpers/nesting.rs create mode 100644 crates/sqlload/src/table_options/_helpers/option_target.rs create mode 100644 crates/sqlload/src/table_options/_helpers/options.rs create mode 100644 crates/sqlload/src/table_options/_helpers/rules.rs create mode 100644 crates/sqlload/src/table_options/_helpers/settings.rs create mode 100644 crates/sqlload/src/table_options/main/layered.rs create mode 100644 crates/sqlload/src/table_options/main/mod.rs create mode 100644 crates/sqlload/src/table_options/main/option_problems.rs create mode 100644 crates/sqlload/src/table_options/main/placeholder_problem.rs create mode 100644 crates/sqlload/src/table_options/main/table_compat.rs create mode 100644 crates/sqlload/src/table_options/main/table_naming.rs create mode 100644 crates/sqlload/src/table_options/main/table_options.rs create mode 100644 crates/sqlload/src/table_options/main/table_strategy.rs create mode 100644 crates/sqlload/src/table_options/mod.rs create mode 100644 crates/sqlload/src/table_options/models.rs create mode 100644 crates/sqlload/src/table_options/tests.rs create mode 100644 crates/sqlload/src/table_options/tests/helpers.rs create mode 100644 crates/sqlload/src/table_options/tests/test_option_problems.rs create mode 100644 crates/sqlload/src/table_options/tests/test_types.rs diff --git a/crates/sqlload/src/lib.rs b/crates/sqlload/src/lib.rs index eb8b2985e..ba185c87e 100644 --- a/crates/sqlload/src/lib.rs +++ b/crates/sqlload/src/lib.rs @@ -66,4 +66,5 @@ pub mod status; pub mod store_paths; pub mod streaming_api; pub mod table_lease; +pub mod table_options; pub mod time_text; diff --git a/crates/sqlload/src/loader/_helpers/resolve.rs b/crates/sqlload/src/loader/_helpers/resolve.rs index 4aa5f9331..a3ea84bcb 100644 --- a/crates/sqlload/src/loader/_helpers/resolve.rs +++ b/crates/sqlload/src/loader/_helpers/resolve.rs @@ -24,8 +24,7 @@ use crate::loader::_helpers::sources::scoped_tables; use crate::loader::_helpers::specs::ColumnSelection; use crate::loader::_helpers::specs::table_name; use crate::loader::_helpers::specs::{ - ColumnChoices, SourceContext, build_spec, column_selection, layered, pinned_types, - table_compat, table_naming, + ColumnChoices, SourceContext, build_spec, column_selection, pinned_types, }; #[cfg(feature = "odbc")] use crate::loader::_helpers::table_plan::block_refused_bounds; @@ -52,6 +51,9 @@ use crate::python_sources::types::PythonHost; use crate::schema_plan::models::SchemaPlan; use crate::similar_names::main::nearest_name::nearest_name; use crate::ssh_tunnel::models::SshTunnel; +use crate::table_options::main::layered::layered; +use crate::table_options::main::table_compat::table_compat; +use crate::table_options::main::table_naming::table_naming; use std::collections::BTreeMap; /// The specs for `discovered` tables of source `source_name`, with problems and skipped tables, including each table listed under `[sources.NAME.tables]` that discovery didn't find. diff --git a/crates/sqlload/src/loader/_helpers/run_log.rs b/crates/sqlload/src/loader/_helpers/run_log.rs index 4e7e42997..f9f8f2092 100644 --- a/crates/sqlload/src/loader/_helpers/run_log.rs +++ b/crates/sqlload/src/loader/_helpers/run_log.rs @@ -1052,28 +1052,6 @@ pub(crate) fn listed_sources( )) } -/// Why `on_overlapping_files` does not apply to a table loaded by `strategy`: it is for a `delete_insert` by `replace_key` (`keyed`) of a source of `files`, where two files of the folder can hold one key value. -pub(crate) fn overlapping_files_problem( - files: bool, - strategy: WriteStrategy, - keyed: bool, -) -> Option { - const FOR: &str = "on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value"; - match (files, strategy, keyed) { - (true, _, true) => None, - (false, _, _) => Some(format!("{FOR}; this source reads no files, so remove it")), - (true, WriteStrategy::Merge, _) => Some(format!( - "{FOR}; a merge already lets the last file win each unique_key; remove it" - )), - (true, WriteStrategy::DeleteInsert, false) => Some(format!( - "{FOR}; this delete_insert replaces a cursor range, not key values, so remove it, or set replace_key" - )), - (true, strategy, false) => Some(format!( - "{FOR}; {strategy} replaces no key values, so remove it" - )), - } -} - /// How `plan` describes the commits of a files table whose files, in `groups`, are each recorded in the run log: how many commits, their order, and what `on_overlapping_files = "last_wins"` adds. pub(crate) fn recorded_commits(groups: &[FileGroup], spec: &TableSpec) -> String { let files = match groups.iter().map(|group| group.files.len()).sum::() { diff --git a/crates/sqlload/src/loader/_helpers/sources.rs b/crates/sqlload/src/loader/_helpers/sources.rs index 8effa9a22..b4e85e938 100644 --- a/crates/sqlload/src/loader/_helpers/sources.rs +++ b/crates/sqlload/src/loader/_helpers/sources.rs @@ -67,9 +67,7 @@ use crate::loader::_helpers::run_log::{ file_column_problem, loaded_file, logs_files, merge_ledger, reload_order, }; use crate::loader::_helpers::specs::integer_cursor; -use crate::loader::_helpers::specs::{ - flattened_object_problems, referenced_columns, table_compat, table_name, table_naming, -}; +use crate::loader::_helpers::specs::{flattened_object_problems, referenced_columns, table_name}; use crate::loader::_helpers::specs::{path_values, pinned_unsampled}; use crate::loader::_helpers::specs::{returned_columns, runnable_transform, transform_input}; #[cfg(not(feature = "duckdb"))] @@ -132,6 +130,8 @@ use crate::snowflake_source::models::{UnloadRequest, UnloadedFiles}; use crate::store_paths::main::connection_store::connection_store; use crate::store_paths::main::resolve_location::resolve_location; use crate::store_paths::models::Location; +use crate::table_options::main::table_compat::table_compat; +use crate::table_options::main::table_naming::table_naming; /// The sources the plan running now has finished checking, which only the line `plan` shows on a terminal reads. pub(crate) static PLANNED_SOURCES: std::sync::atomic::AtomicUsize = diff --git a/crates/sqlload/src/loader/_helpers/specs.rs b/crates/sqlload/src/loader/_helpers/specs.rs index dad30b242..e49ebe312 100644 --- a/crates/sqlload/src/loader/_helpers/specs.rs +++ b/crates/sqlload/src/loader/_helpers/specs.rs @@ -3,16 +3,9 @@ use std::sync::Arc; use arrow_array::RecordBatch; use arrow_schema::{DataType, Schema}; -use crate::adapters::contract::models::{ChangeApply, TableName, WriteMode}; +use crate::adapters::contract::models::{TableName, WriteMode}; use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; -use crate::adapters::files::constants::{CURSOR_PLACEHOLDER_START, TABLE_PLACEHOLDER}; use crate::bigquery_source::constants::BIGQUERY_SOURCE; -use crate::cdc::constants::{ - BATCH_INTERVAL, CDC_FILES_PROBLEM, CDC_TARGETS_PROBLEM, FILES_BATCH_INTERVAL, -}; -use crate::column_parse::main::column_parse::column_parse; -use crate::column_parse::main::time_zone::time_zone; -use crate::column_parse::models::ColumnParse; use crate::column_types::main::arrow_field::arrow_field; use crate::column_types::main::is_variant::is_variant; use crate::column_types::main::parse_type::parse_type; @@ -22,15 +15,12 @@ use crate::duckdb_source::constants::{DUCKDB_SOURCE, MOTHERDUCK_SOURCE}; use crate::files_source::main::constant_columns::constant_columns; use crate::files_source::main::path_template::path_template; use crate::files_source::models::FileColumn; -use crate::files_source::models::{ - AfterLoad, FilesOrder, FilesTable, PathValues, SourceFormat, StoredRead, TextChecks, -}; +use crate::files_source::models::{FilesTable, PathValues, SourceFormat, StoredRead, TextChecks}; use crate::load_naming::main::loaded_name::loaded_name; -use crate::load_naming::models::{Compat, LoadedNames, NameRules, Naming}; +use crate::load_naming::models::{LoadedNames, NameRules, Naming}; use crate::loader::_helpers::destination::read_as_text; use crate::loader::_helpers::python::field_type; use crate::loader::_helpers::resolve::{NameRule, ResolvedTarget}; -use crate::loader::_helpers::run_log::overlapping_files_problem; use crate::loader::_helpers::sources::sheet_rule; use crate::loader::_helpers::table_plan::source_cursor; use crate::loader::constants::{ @@ -39,27 +29,20 @@ use crate::loader::constants::{ }; use crate::loader::errors::LoaderError; use crate::loader::models::{ - CdcSpec, CursorSpec, FilesTransform, SettingOrigin, TableLayout, TableSpec, WarehouseRoute, - WarehouseSource, + CursorSpec, FilesTransform, TableSpec, WarehouseRoute, WarehouseSource, }; use crate::loader::models::{SourceReader, TablePlan}; use crate::masking::models::MaskRules; use crate::postgres_source::models::{PgType, SourceColumn, SourceTable}; use crate::postgres_source::models::{ReadColumn, WireType}; -use crate::project::constants::DEFAULT_MAX_DEPTH; -use crate::project::main::table_flatten::table_flatten; use crate::project::models::{ - CdcMode, CursorBounds, Deletes, Lookback, LookbackFrom, MaskMethod, NullCursor, NullKeys, - OnDuplicateKeys, PathsSetting, ProjectConfig, SourceConfig, SourceKind, StateMode, + NullCursor, NullKeys, PathsSetting, ProjectConfig, SourceConfig, SourceKind, StateMode, TableOverride, TableSettings, UnloadStage, WriteStrategy, }; -use crate::publish_checks::main::check_problems::check_problems; use crate::python_sources::types::PythonHost; use crate::routing::models::Store; use crate::row_batches::constants::FLATTEN_SEPARATOR; use crate::row_batches::main::merge_schema::merge_schema; -use crate::row_batches::models::{Flatten, Unnest}; -use crate::row_deletes::main::deletes_problems::deletes_problems; use crate::row_deletes::main::deletes_spec::deletes_spec; use crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings; use crate::schema_plan::models::{ColumnOrigin, DesiredColumn}; @@ -67,6 +50,11 @@ use crate::sheets_source::models::SheetRead; use crate::similar_names::main::close_name::close_name; use crate::similar_names::main::nearest_name::nearest_name; use crate::snowflake_source::constants::USER_STAGE_FOLDER; +use crate::table_options::main::layered::layered; +use crate::table_options::main::placeholder_problem::placeholder_problem; +use crate::table_options::main::table_options::table_options; +use crate::table_options::main::table_strategy::table_strategy; +use crate::table_options::models::{OptionContext, OptionTarget, TableOptions, TableStrategy}; use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder}; use std::collections::{BTreeMap, BTreeSet}; @@ -225,64 +213,44 @@ pub(crate) fn build_spec( ) -> Result> { let settings = &overrides.settings; let defaults = &context.source.defaults; - let cursor = cursor(settings, defaults); - let deletes = layered(&settings.deletes, &defaults.deletes); - let cdc = cdc_spec(context, deletes.map(|(value, _)| value)); - let (strategy, strategy_origin) = match ( - layered(&settings.write_strategy, &defaults.write_strategy), - &cdc, - ) { - (Some(set), _) => set, - (None, Some(_)) => (WriteStrategy::Append, SettingOrigin::Source), - (None, None) => { + let target = option_target(context.target); + let options_context = OptionContext { + name: context.name, + source: context.source, + target: &target, + }; + let chosen = match table_strategy(&options_context, overrides) { + Ok(chosen) => chosen, + Err(cursor) => { return Err(vec![missing_strategy_problem( context, table, - cursor.as_ref(), + cursor.as_deref(), )]); } }; - let merges = strategy == WriteStrategy::Merge && cdc.is_none(); - let replace_key: Vec = layered(&settings.replace_key, &defaults.replace_key) - .filter(|(_, origin)| { - *origin == SettingOrigin::Table - || strategy == WriteStrategy::DeleteInsert - || strategy_origin != SettingOrigin::Table - }) - .map(|(key, _)| key) - .unwrap_or_default(); - let keyed = strategy == WriteStrategy::DeleteInsert && !replace_key.is_empty(); let (unique_key, key_from_primary_key) = - match table_key(context, table, (settings, defaults), merges) { + match table_key(context, table, (settings, defaults), chosen.merges) { Ok(key) => key, Err(problem) => return Err(vec![problem]), }; - let (strategy, mut problems) = match &cdc { - Some(cdc) if !sql_adapter(context.target.warehouse).captures_changes(cdc.apply) => ( - WriteStrategy::Append, - vec![ - match sql_adapter(context.target.warehouse).runs_sql() { - true => CDC_TARGETS_PROBLEM, - false => CDC_FILES_PROBLEM, - } - .to_owned(), - ], - ), - Some(_) => (WriteStrategy::Append, cdc_key_problems(table, &unique_key)), - None => ( - strategy, - strategy_problems(strategy, (&unique_key, &replace_key), cursor.as_ref()), - ), - }; - problems.extend(replace_key_problems(context, cursor.as_ref(), keyed)); + let (options, mut problems) = table_options(&options_context, overrides, &chosen, &unique_key); + if let Some(cdc) = &chosen.cdc + && sql_adapter(context.target.warehouse).captures_changes(cdc.apply) + { + problems.extend(cdc_key_problems(table, &unique_key)); + } + let TableStrategy { + cursor, + cdc, + strategy_origin, + replace_key, + keyed, + .. + } = chosen; + let strategy = options.strategy; problems.extend(column_reference_problems(table, overrides)); problems.extend(typed_parse_problems(context.source.kind, table, overrides)); - problems.extend(cursor_problems( - context, - (settings, defaults), - strategy, - cursor.as_ref(), - )); let constants = match table_constants(context, table, (settings, defaults), &columns.excluded) { Ok(constants) => constants, Err(found) => { @@ -301,76 +269,12 @@ pub(crate) fn build_spec( format!("constant column {name} cannot be the cursor_column: it holds one value") }), ); - let table_sorts = settings.newest_by.is_some(); - let on_duplicate_keys = layered(&settings.on_duplicate_keys, &defaults.on_duplicate_keys) - .filter(|(_, origin)| *origin == SettingOrigin::Table || (merges && !table_sorts)); - let table_fails = on_duplicate_keys == Some((OnDuplicateKeys::Fail, SettingOrigin::Table)); - let newest_by = layered(&settings.newest_by, &defaults.newest_by) - .filter(|(_, origin)| *origin == SettingOrigin::Table || (merges && !table_fails)) - .map(|(value, _)| value); - let (newest_by, found) = dedupe_settings( - strategy, - &unique_key, - ( - on_duplicate_keys.map(|(value, _)| value), - newest_by.as_deref(), - ), - overrides, - ); - problems.extend(found); - if context.source.order == FilesOrder::Path - && !(strategy == WriteStrategy::Merge - || (strategy == WriteStrategy::DeleteInsert && !replace_key.is_empty())) - { - problems.push(format!("order = \"path\" orders the files a merge or a delete_insert by replace_key applies in turn; {strategy} loads them without an order, so remove it")); - } - let own_strategy = strategy_origin == SettingOrigin::Table && !keyed; - let overlapping = layered( - &settings.on_overlapping_files, - &defaults.on_overlapping_files, - ); - let overlapping = overlapping - .filter(|(_, origin)| !own_strategy || *origin == SettingOrigin::Table) - .map(|(value, _)| value); - let files = context.source.kind == SourceKind::Files; - problems.extend(overlapping.and_then(|_| overlapping_files_problem(files, strategy, keyed))); let matched_key = match keyed { true => &replace_key, false => &unique_key, }; - let (null_keys, not_null_keys, found) = key_nulls( - (table, &constants), - (strategy, matched_key, keyed), - layered(&settings.null_keys, &defaults.null_keys) - .filter(|(_, origin)| *origin == SettingOrigin::Table || merges || keyed) - .map(|(value, _)| value), - ); - problems.extend(found); - let deletes = deletes - .filter(|(_, origin)| *origin == SettingOrigin::Table || merges || cdc.is_some()) - .map(|(value, _)| value); - let checks = layered(&settings.checks, &defaults.checks).map(|(value, _)| value); - problems.extend(checks.iter().flat_map(|checks| { - let target = (context.target.path.is_some(), deletes.is_some()); - check_problems(checks, (strategy, target.0, target.1)) - })); + let (null_keys, not_null_keys) = key_nulls((table, &constants), matched_key, options.null_keys); let batch = layered(&settings.batch_size, &defaults.batch_size).map(|(value, _)| value); - let uses_key = strategy == WriteStrategy::Merge; - problems.extend(overrides.mask.keys().filter_map(|masked| { - let is_cursor = cursor.as_ref().is_some_and(|cursor| cursor.names(masked)); - let is_key = (uses_key && unique_key.contains(masked)) || replace_key.contains(masked); - (is_cursor || is_key).then(|| { - format!("mask {masked}: a masked column cannot be the cursor_column or part of the unique_key or replace_key") - }) - })); - if context.source.mask_key.is_none() - && overrides - .mask - .values() - .any(|method| *method == MaskMethod::Hmac) - { - problems.push("mask uses \"hmac\" but the source sets no mask_key (for example mask_key = \"${ENV:MASK_KEY}\")".to_owned()); - } let files_description = match context.source.kind { SourceKind::Files | SourceKind::GoogleSheets => context.source.description.as_deref(), _ => None, @@ -385,33 +289,22 @@ pub(crate) fn build_spec( let contract = layered(&settings.contract, &defaults.contract) .map(|(value, _)| value) .unwrap_or_default(); - let (nesting, found) = nesting(context, overrides, strategy); - problems.extend(found); - let unnests = !matches!(nesting.unnest, Unnest::None); - let kind = (strategy, context.source.kind); - problems.extend(deletes_problems( - deletes, - kind, - context.target.warehouse, - unnests, - )); let from = overrides.deletes_from.as_ref(); - let (deletes, checks) = deletes_spec((deletes.filter(|_| cdc.is_none()), from), checks); - if keyed && !matches!(nesting.unnest, Unnest::None) { - problems.push("replace_key does not carry child tables yet, whose rows hang off the replaced rows by their ids. Fix: drop unnest, or use write_strategy = \"merge\" on a unique_key".to_owned()); - } - problems.extend(after_load_problems(context, (strategy, keyed))); - let layout = table_layout(settings, defaults); + let (deletes, checks) = deletes_spec( + (options.deletes.filter(|_| cdc.is_none()), from), + options.checks, + ); let is_duckdb = sql_adapter(context.target.warehouse).parses_variant_pins(); - problems.extend(sql_adapter(context.target.warehouse).layout_problems(&layout)); - let parses = table_parses(overrides).unwrap_or_else(|found| { - problems.extend(found); - BTreeMap::new() - }); - let timezone = table_timezone((settings, defaults)).unwrap_or_else(|problem| { - problems.push(problem); - None - }); + let TableOptions { + on_duplicate_keys, + newest_by, + overlapping, + nesting, + layout, + parses, + timezone, + .. + } = options; if !problems.is_empty() { return Err(problems); } @@ -575,39 +468,6 @@ pub(crate) fn build_spec( }) } -/// The table's `parse` entries read, or their problems; a column cannot be both pinned in `columns` and parsed, as `parse` gives its type. -fn table_parses(overrides: &TableOverride) -> Result, Vec> { - let mut problems: Vec = Vec::new(); - let mut parses: BTreeMap = BTreeMap::new(); - for (column, setting) in &overrides.parse { - match column_parse(setting) { - Ok(_) if overrides.columns.contains_key(column) => problems.push(format!( - "parse {column}: the column is also pinned in columns, and parse gives its type; drop the pin" - )), - Ok(parse) => { - parses.insert(column.clone(), parse); - } - Err(problem) => problems.push(format!("parse {column}: {problem}")), - } - } - match problems.is_empty() { - true => Ok(parses), - false => Err(problems), - } -} - -/// The table's `timezone` (its own, else its source's) and where it is set, or why it is not an IANA zone. -fn table_timezone( - (settings, defaults): (&TableSettings, &TableSettings), -) -> Result, String> { - match layered(&settings.timezone, &defaults.timezone) { - Some((name, origin)) => time_zone(&name) - .map(|zone| Some((zone, origin))) - .map_err(|problem| format!("timezone: {problem}")), - None => Ok(None), - } -} - /// The table's `constant_columns` (its own map, else its source's), each with its type for the target and its value as text; or why they cannot load: a name the source table already has among its loaded columns, ignoring case, a type with no Arrow type or one the target cannot load, or an array. A files source's are checked as before by its reader, which fills them and replaces a file column of the same name (`plan` notes it). fn table_constants( context: &SourceContext<'_>, @@ -720,42 +580,6 @@ fn warehouse_source( }) } -/// The table's layout, each field layered table over source; `table_settings` merged, the table's value winning per setting. -fn table_layout(table: &TableSettings, source: &TableSettings) -> TableLayout { - let mut table_settings = source.table_settings.clone().unwrap_or_default(); - table_settings.extend(table.table_settings.clone().unwrap_or_default()); - TableLayout { - engine: layered(&table.engine, &source.engine).map(|(value, _)| value), - order_by: layered(&table.order_by, &source.order_by).map(|(value, _)| value), - partition_by: layered(&table.partition_by, &source.partition_by).map(|(value, _)| value), - primary_key: layered(&table.primary_key, &source.primary_key).map(|(value, _)| value), - table_settings, - } -} - -/// A `postgres_cdc` source's stream settings, with the default slot and publication names. -fn cdc_spec(context: &SourceContext<'_>, deletes: Option) -> Option { - let source = context.source; - (source.kind == SourceKind::PostgresCdc).then(|| { - let default_name = format!("sqlload_{}", context.name.to_lowercase()); - CdcSpec { - apply: match (source.cdc_mode, deletes.unwrap_or(Deletes::Soft)) { - (CdcMode::Changelog, _) => ChangeApply::Changelog, - (CdcMode::Merge, Deletes::Soft) => ChangeApply::SoftDeletes, - (CdcMode::Merge, Deletes::Hard) => ChangeApply::HardDeletes, - }, - slot: source.slot.clone().unwrap_or_else(|| default_name.clone()), - publication: source.publication.clone().unwrap_or(default_name), - batch_interval: source.batch_interval.unwrap_or( - match sql_adapter(context.target.warehouse).runs_sql() { - true => BATCH_INTERVAL, - false => FILES_BATCH_INTERVAL, - }, - ), - } - }) -} - /// Why a table cannot be captured: it needs a primary key, which merge matches rows on, and without which publishing it would make Postgres refuse the application's own updates and deletes on it; and its `unique_key` must be within that key, the only columns Postgres sends with a delete by default. fn cdc_key_problems(table: &SourceTable, unique_key: &[String]) -> Vec { let qualified = table.qualified_name(); @@ -875,56 +699,6 @@ pub(crate) fn destination_name(template: &str, source: &str, table: &SourceTable .replace("{table}", &table.name) } -/// A table's value if set, otherwise its source's. -pub(crate) fn layered( - table: &Option, - source: &Option, -) -> Option<(T, SettingOrigin)> { - match (table, source) { - (Some(value), _) => Some((value.clone(), SettingOrigin::Table)), - (None, Some(value)) => Some((value.clone(), SettingOrigin::Source)), - (None, None) => None, - } -} - -/// The cursor a table's settings describe, if any. -pub(crate) fn cursor(table: &TableSettings, source: &TableSettings) -> Option { - let (columns, _) = layered(&table.cursor_column, &source.cursor_column)?; - let (column, coalesce) = columns.split_first()?; - Some(CursorSpec { - column: column.clone(), - coalesce: coalesce.to_vec(), - null_cursor: layered(&table.null_cursor, &source.null_cursor) - .map(|(value, _)| value) - .unwrap_or_default(), - out_of_range: layered( - &table.on_cursor_out_of_range, - &source.on_cursor_out_of_range, - ) - .map(|(value, _)| value) - .unwrap_or_default(), - start: layered(&table.cursor_start, &source.cursor_start).map(|(value, _)| value), - lookback: match layered(&table.lookback, &source.lookback) { - Some((Lookback::Duration(duration), _)) => Some(duration), - _ => None, - }, - lookback_units: match layered(&table.lookback, &source.lookback) { - Some((Lookback::Units(units), _)) => Some(units), - _ => None, - }, - lookahead: layered(&table.lookahead, &source.lookahead).map(|(value, _)| value), - from_now: layered(&table.lookback_from, &source.lookback_from) - .is_some_and(|(value, _)| value == LookbackFrom::Now), - inclusive: layered( - &table.append_cursor_inclusive, - &source.append_cursor_inclusive, - ) - .is_some_and(|(value, _)| value), - literals: layered(&table.cursor_bounds, &source.cursor_bounds) - .is_some_and(|(value, _)| value == CursorBounds::Literals), - }) -} - /// A table's `unique_key` (table over source) and whether a `merge` takes it from the primary key its source reports, set as `"{primary_key}"`. A `merge` table without one gets none, so it is refused; `"{primary_key}"` on it is refused for a source that reports no keys, and for a table whose source reports none. A table that doesn't merge (a `postgres_cdc` table included) keeps the primary key its source reports unless it names columns: it only orders and identifies rows (a ClickHouse table's sorting key, a CDC table's merge key), so a source's `"{primary_key}"` never fails it. fn table_key( context: &SourceContext<'_>, @@ -933,6 +707,12 @@ fn table_key( merges: bool, ) -> Result<(Vec, bool), String> { let set = layered(&settings.unique_key, &defaults.unique_key).map(|(key, _)| key); + let qualified = table.qualified_name(); + if let Some(problem) = + placeholder_problem(context.source.kind, &qualified, set.as_deref(), merges) + { + return Err(problem); + } let placeholder = set .as_ref() .is_some_and(|key| key.iter().any(|column| column == PRIMARY_KEY_PLACEHOLDER)); @@ -940,24 +720,7 @@ fn table_key( None if merges => Ok((Vec::new(), false)), None => Ok((table.primary_key.clone(), false)), Some(key) if !placeholder => Ok((key, false)), - Some(key) if key.len() > 1 => Err(format!( - "{}: unique_key {PRIMARY_KEY_PLACEHOLDER:?} stands for the whole primary key, so it can't be listed with other columns; set unique_key = {PRIMARY_KEY_PLACEHOLDER:?} or name every key column", - table.qualified_name() - )), Some(_) if !merges => Ok((table.primary_key.clone(), false)), - Some(_) - if matches!( - context.source.kind, - SourceKind::Python | SourceKind::Files | SourceKind::GoogleSheets - ) => - { - Err(format!( - "{} (kind = \"{}\"): unique_key = {PRIMARY_KEY_PLACEHOLDER:?} merges on the primary key the source reports, and a {} source reports none. Fix: name the key columns, such as unique_key = [\"id\"]", - table.qualified_name(), - context.source.kind.name(), - context.source.kind.name() - )) - } Some(_) if table.primary_key.is_empty() => Err(no_primary_key_problem(context, table)), Some(_) => match nullable_key_problem(context, table) { Some(problem) => Err(problem), @@ -1089,67 +852,12 @@ fn no_primary_key_problem(context: &SourceContext<'_>, table: &SourceTable) -> S ) } -/// The `newest_by` columns of a merge, and the problems with `on_duplicate_keys` and `newest_by` (a source's apply only to its merge tables, and either one set on a table drops the other from its source): both are for `merge`, `newest_by` names columns that are neither in the key, masked nor repeated, and has nothing to pick under `on_duplicate_keys = "fail"`. -fn dedupe_settings( - strategy: WriteStrategy, - unique_key: &[String], - (on_duplicate_keys, newest_by): (Option, Option<&[String]>), - overrides: &TableOverride, -) -> (Vec, Vec) { - let mut problems: Vec = Vec::new(); - if strategy != WriteStrategy::Merge { - problems.extend( - [ - on_duplicate_keys.map(|_| "on_duplicate_keys"), - newest_by.map(|_| "newest_by"), - ] - .into_iter() - .flatten() - .map(|name| format!("{name} is for write_strategy = \"merge\", which matches rows on unique_key; {strategy} keeps every row")), - ); - return (Vec::new(), problems); - } - let Some(columns) = newest_by else { - return (Vec::new(), problems); - }; - if columns.is_empty() { - problems.push("newest_by names a column, or a list compared in order, such as newest_by = \"updated_at\"".to_owned()); - } - for (index, column) in columns.iter().enumerate() { - if columns[..index].contains(column) { - problems.push(format!( - "newest_by names {column} twice; name each column once" - )); - } - if unique_key - .iter() - .any(|key| key.eq_ignore_ascii_case(column)) - { - problems.push(format!("newest_by column {column} is in the unique_key, so it is the same in every row it would compare; name another column")); - } - if overrides.mask.contains_key(column) { - problems.push(format!( - "newest_by column {column} is masked, so its values cannot say which row is newer" - )); - } - } - if on_duplicate_keys == Some(OnDuplicateKeys::Fail) { - problems.push("newest_by picks the newest of the rows repeating a key, but on_duplicate_keys = \"fail\" keeps none; set one of them".to_owned()); - } - (columns.to_vec(), problems) -} - -/// A table's `null_keys` (as set, else the default) and the columns of `unique_key` (the key it matches rows on: a merge's `unique_key`, a `delete_insert`'s `replace_key` when `keyed`) whose values are never NULL, so they compare with `=`: the source table's columns it declares NOT NULL and constant columns, or every key column under `null_keys = "fail"`, which refuses a commit holding a NULL in one (a `postgres_cdc` table's key, which its merge matches on, included); and the problem with `null_keys` set on a table that matches no key. +/// A table's `null_keys` (as set, else the default) and the columns of `unique_key` (the key it matches rows on: a merge's `unique_key`, a `delete_insert`'s `replace_key` when keyed) whose values are never NULL, so they compare with `=`: the source table's columns it declares NOT NULL and constant columns, or every key column under `null_keys = "fail"`, which refuses a commit holding a NULL in one (a `postgres_cdc` table's key, which its merge matches on, included). fn key_nulls( (table, constants): (&SourceTable, &[(String, ColumnType, String)]), - (strategy, unique_key, keyed): (WriteStrategy, &[String], bool), + unique_key: &[String], null_keys: Option, -) -> (NullKeys, Vec, Vec) { - let problems: Vec = null_keys - .filter(|_| strategy != WriteStrategy::Merge && !keyed) - .map(|_| format!("null_keys is for write_strategy = \"merge\", which matches rows on unique_key, and \"delete_insert\" with a replace_key; {strategy} keeps every row")) - .into_iter() - .collect(); +) -> (NullKeys, Vec) { let null_keys = null_keys.unwrap_or_default(); let never_null = |key: &String| { null_keys == NullKeys::Fail @@ -1163,180 +871,7 @@ fn key_nulls( .filter(|key| never_null(key)) .cloned() .collect(); - (null_keys, not_null, problems) -} - -/// Why a `delete_insert` by `replace_key` (`keyed`) cannot load where `context` puts it: a files target replaces whole partition folders; a files source picks its files from the run log, not by a cursor; and on any other source a cursor would read part of a key value's rows while the commit deletes all of them, losing those the read never returned. -fn replace_key_problems( - context: &SourceContext<'_>, - cursor: Option<&CursorSpec>, - keyed: bool, -) -> Vec { - let mut problems: Vec = Vec::new(); - if !keyed { - return problems; - } - if context.target.path.is_some() { - problems.push("replace_key deletes rows by key in a database table, and a files target replaces whole partition folders. Fix: load into a database target, or drop replace_key and use a partition cursor_column".to_owned()); - } - match (cursor, context.source.kind) { - (Some(cursor), SourceKind::Files) => problems.push(format!( - "cursor_column {} does not apply to a files source's delete_insert by replace_key, which reads each new or changed file once, oldest first, from the run log. Fix: remove cursor_column, or drop replace_key to replace partitions by the cursor", - cursor.column - )), - (Some(cursor), _) => problems.push(format!( - "cursor_column {} does not apply to delete_insert by replace_key: a load deletes every row of each key value it reads, so the rows of a key value outside the cursor range, which it never reads, would be lost. Fix: drop cursor_column, so every load reads the whole source and replaces each key value it holds; or use write_strategy = \"merge\" on a unique_key to read by the cursor", - cursor.column - )), - (None, _) => {} - } - problems -} - -/// Problems with a strategy and the keys and cursor it is given. -pub(crate) fn strategy_problems( - strategy: WriteStrategy, - (unique_key, replace_key): (&[String], &[String]), - cursor: Option<&CursorSpec>, -) -> Vec { - let mut problems: Vec = Vec::new(); - match (strategy, cursor) { - (WriteStrategy::Merge, _) if unique_key.is_empty() => problems.push(format!( - "write_strategy = \"merge\" needs a unique_key: the key columns, such as unique_key = [\"id\"], or unique_key = {PRIMARY_KEY_PLACEHOLDER:?} for the primary key the source reports" - )), - (WriteStrategy::Append, Some(cursor)) - if cursor.lookback.is_some() || cursor.lookback_units.is_some() => - { - problems.push( - "lookback re-inserts the window on every run with append; use delete_insert (no key needed) or merge" - .to_owned(), - ) - } - (WriteStrategy::Replace, Some(_)) => problems.push( - "write_strategy = \"replace\" reloads the whole table, so it takes no cursor_column".to_owned(), - ), - (WriteStrategy::DeleteInsert, None) if replace_key.is_empty() => problems.push( - "write_strategy = \"delete_insert\" replaces a cursor range or the rows of the key values it reads, so it needs a cursor_column or a replace_key. Fix: set cursor_column, or replace_key = [\"version\"] to replace every row of each version a load reads".to_owned(), - ), - _ => {} - } - if !replace_key.is_empty() && strategy != WriteStrategy::DeleteInsert { - let merge = match strategy { - WriteStrategy::Merge => " (merge matches rows one by one on unique_key)", - _ => "", - }; - problems.push(format!( - "replace_key is for write_strategy = \"delete_insert\", which replaces the rows holding the key values a load reads; {strategy} does not delete by it. Fix: set write_strategy = \"delete_insert\" to replace those rows whole, or drop replace_key{merge}" - )); - } - if let Some(cursor) = cursor.filter(|cursor| cursor.from_now && cursor.lookback_units.is_some()) - { - problems.push(format!( - "lookback_from = \"now\" counts lookback back from the time of the run, so {} needs a duration lookback, such as lookback = \"1d\", not a number of cursor units", - cursor.label() - )); - } - if let Some(cursor) = cursor.filter(|cursor| { - cursor.from_now && cursor.lookback.is_none() && cursor.lookback_units.is_none() - }) { - problems.push(format!( - "lookback_from = \"now\" counts lookback back from now, so {} needs a lookback", - cursor.label() - )); - } - problems -} - -/// Why the table's cursor columns and `null_cursor` cannot apply: an empty or repeating `cursor_column` list; a coalesced cursor where its value is one column's (a files source's partition or path column, a Python table's field, a files target's partitions, `delete_insert`'s replaced range); `null_cursor` on a table entry without a cursor; and `null_cursor = "include"`, which reads the NULL-cursor rows on every run, on anything but `merge`. -fn cursor_problems( - context: &SourceContext<'_>, - (settings, defaults): (&TableSettings, &TableSettings), - strategy: WriteStrategy, - cursor: Option<&CursorSpec>, -) -> Vec { - let mut problems: Vec = Vec::new(); - let listed = layered(&settings.cursor_column, &defaults.cursor_column).map(|(value, _)| value); - if listed.as_ref().is_some_and(Vec::is_empty) { - problems.push("cursor_column = [] names no column; name one, or list the columns to coalesce, such as [\"updated_at\", \"created_at\"]".to_owned()); - } - let listed = listed.unwrap_or_default(); - for (index, column) in listed.iter().enumerate() { - if listed[..index] - .iter() - .any(|earlier| earlier.eq_ignore_ascii_case(column)) - { - problems.push(format!( - "cursor_column lists {column} twice; list each column once" - )); - break; - } - } - if layered(&settings.null_cursor, &defaults.null_cursor) - .is_some_and(|(_, origin)| origin == SettingOrigin::Table) - && cursor.is_none() - { - problems.push("null_cursor says what a cursor read does with rows whose cursor is NULL, but the table has no cursor_column; remove it".to_owned()); - } - let out_of_range = layered( - &settings.on_cursor_out_of_range, - &defaults.on_cursor_out_of_range, - ); - match (out_of_range, context.source.kind) { - (None, _) => {} - (Some(_), SourceKind::Python) if cursor.is_none() => problems.push("on_cursor_out_of_range says what a load does with rows outside the cursor window, but the table has no cursor_column; remove it".to_owned()), - (Some(_), SourceKind::Python) => {} - (Some(_), kind) => problems.push(format!( - "on_cursor_out_of_range checks the rows a Python table's function returns against its cursor window; SQLLoad filters a {} source's reads itself, so remove it", - kind.name() - )), - } - let Some(cursor) = cursor else { - return problems; - }; - let label = cursor.label(); - let coalesced = !cursor.coalesce.is_empty(); - let one_column = match context.source.kind { - SourceKind::Files => Some( - "a files source's cursor is one partition or path column, the same in every row of a file", - ), - SourceKind::Python => Some( - "a Python table's cursor is one field of the rows it yields; yield the first set value as one field (such as row[\"updated_at\"] or row[\"created_at\"]) and name that field", - ), - _ if context.target.path.is_some() => { - Some("a files target partitions and reads its maximum by one cursor column") - } - _ if strategy == WriteStrategy::DeleteInsert => Some( - "delete_insert replaces the destination rows in a range of one cursor column; use merge, or name one column", - ), - _ => None, - }; - if let Some(reason) = one_column.filter(|_| coalesced) { - problems.push(format!( - "cursor_column lists several columns to coalesce ({label}), but {reason}" - )); - } - if cursor.null_cursor == NullCursor::Include { - let refusal = match strategy { - WriteStrategy::Append => Some(( - "append would append them again on every run, duplicating them", - format!( - "use write_strategy = \"merge\" with a unique_key, or coalesce a column that is always set (such as cursor_column = [\"{}\", \"created_at\"]), or set null_cursor = \"ignore\" to skip them", - cursor.column - ), - )), - WriteStrategy::DeleteInsert => Some(( - "they sit outside every cursor range delete_insert replaces, so it would insert them again on every run, duplicating them", - "use write_strategy = \"merge\" with a unique_key, or set null_cursor = \"ignore\" to skip them".to_owned(), - )), - WriteStrategy::Merge | WriteStrategy::Replace => None, - }; - if let Some((duplicates, fix)) = refusal { - problems.push(format!( - "null_cursor = \"include\" reads the rows whose {label} is NULL on every run, and {duplicates}; {fix}" - )); - } - } - problems + (null_keys, not_null) } /// How many of `table`'s source rows have a NULL cursor, which its read's bounds never select, when the table fails on them (`null_cursor` unset), counted by the database: `SELECT count(*) ... WHERE IS NULL`. `None` when nothing is counted: the read has no bounds (a first run reads those rows too), `null_cursor` includes or skips them, the source reports a cursor column NOT NULL, or the source is not a database: a Python table's rows are counted as they arrive, and a files source's cursor is each file's path value, never NULL. @@ -1411,236 +946,6 @@ pub(crate) fn null_cursor_problem(spec: &TableSpec, rows: u64) -> String { ) } -/// Why a files source's `after_load` cannot apply to its table: only `append`, `merge` and `delete_insert` by a `replace_key` (`keyed`) never read a loaded file again, and a files target commits its own way. -fn after_load_problems( - context: &SourceContext<'_>, - (strategy, keyed): (WriteStrategy, bool), -) -> Vec { - let mut problems: Vec = Vec::new(); - if context.source.after_load == AfterLoad::Keep { - return problems; - } - if !matches!(strategy, WriteStrategy::Append | WriteStrategy::Merge) && !keyed { - problems.push(format!( - "after_load deletes or moves each file once it loads, so it needs write_strategy = \"append\" or \"merge\", or \"delete_insert\" with a replace_key; {strategy} reads loaded files again" - )); - } - if context.target.path.is_some() { - problems.push("after_load is for database targets so far, not a files target".to_owned()); - } - problems -} - -/// What a table's nesting settings come to. -struct Nesting { - naming: Naming, - compat: Compat, - row_id: bool, - unnest: Unnest, - max_depth: u32, - flatten: Flatten, -} - -/// The table's naming and compat (each its own, its source's, then its target's), whether its rows get an id (always under `compat = "dlt"`), its `unnest` (under `compat = "dlt"`, `"all"` for JSON and NDJSON files on a warehouse), `max_depth` and `flatten` (see [`table_flatten`]), and the problems with them: `unnest` names list fields by dotted paths whose ancestors it also names, no deeper than `max_depth`, that no column setting names, on a table whose writes can carry child tables. -fn nesting( - context: &SourceContext<'_>, - overrides: &TableOverride, - strategy: WriteStrategy, -) -> (Nesting, Vec) { - let settings = &overrides.settings; - let defaults = &context.source.defaults; - let naming = table_naming((settings, defaults), context.target.naming); - let compat = table_compat((settings, defaults), context.target.compat); - let row_id = layered(&settings.row_id, &defaults.row_id).map(|(value, _)| value); - let max_depth = overrides.max_depth.unwrap_or(DEFAULT_MAX_DEPTH); - let mut problems: Vec = Vec::new(); - if compat == Compat::Dlt && row_id == Some(false) { - problems.push( - "row_id = false: compat = \"dlt\" gives every row its _dlt_id; drop row_id".to_owned(), - ); - } - let json_files = context.source.kind == SourceKind::Files - && matches!( - context.source.format, - SourceFormat::Json | SourceFormat::Ndjson - ); - let unnest = match &overrides.unnest { - None if compat == Compat::Dlt && json_files && context.target.path.is_none() => Unnest::All, - None => Unnest::None, - Some(PathsSetting::Paths(paths)) if paths.is_empty() => Unnest::None, - Some(PathsSetting::Word(word)) if word == UNNEST_ALL => Unnest::All, - Some(PathsSetting::Word(word)) => { - problems.push(format!( - "unnest = {word:?}: list the dotted paths of the list fields to unnest, or write \"{UNNEST_ALL}\"" - )); - Unnest::None - } - Some(PathsSetting::Paths(paths)) => { - problems.extend( - paths - .iter() - .filter_map(|path| path_problem(path, paths, max_depth)), - ); - problems.extend(column_setting_problems(context, overrides, paths)); - Unnest::Paths(paths.clone()) - } - }; - let transform = settings.transform.is_some() || defaults.transform.is_some(); - let (flatten, found) = table_flatten( - (context.source, Some(overrides)), - (compat, naming, transform), - ); - problems.extend(found); - match unnest { - Unnest::None if overrides.max_depth.is_some() && flatten.is_none() => { - problems.push( - "max_depth limits the child tables unnest makes and the objects flatten flattens, and this table sets neither" - .to_owned(), - ); - } - Unnest::None => {} - Unnest::All | Unnest::Paths(_) => { - problems.extend(refused_writes(context, overrides, strategy)); - if row_id == Some(false) { - problems.push("row_id = false: unnest gives every row an id, which its child rows name as their parent's; drop row_id".to_owned()); - } - } - } - ( - Nesting { - naming, - compat, - row_id: row_id.unwrap_or(compat == Compat::Dlt || unnest != Unnest::None), - unnest, - max_depth, - flatten, - }, - problems, - ) -} - -/// How a table names what it loads: its own `naming`, else its source's, else its target's (`target`), else snake_case. -pub(crate) fn table_naming( - (settings, defaults): (&TableSettings, &TableSettings), - target: Option, -) -> Naming { - layered(&settings.naming, &defaults.naming) - .map(|(value, _)| value) - .or(target) - .unwrap_or_default() -} - -/// Whose names the columns a table's load adds take: its own `compat`, else its source's, else its target's (`target`), else SQLLoad's. -pub(crate) fn table_compat( - (settings, defaults): (&TableSettings, &TableSettings), - target: Option, -) -> Compat { - layered(&settings.compat, &defaults.compat) - .map(|(value, _)| value) - .or(target) - .unwrap_or_default() -} - -/// What is wrong with the `unnest` path `path` among `paths`: an empty part, a parent path not also listed, or more parts than `max_depth`. -fn path_problem(path: &str, paths: &[String], max_depth: u32) -> Option { - let parts: Vec<&str> = path.split('.').collect(); - let parent = path.rsplit_once('.').map(|(parent, _)| parent); - let listed = parent.is_none_or(|parent| paths.iter().any(|listed| listed == parent)); - match (parts.iter().any(|part| part.trim().is_empty()), listed) { - (true, _) => Some(format!( - "unnest {path:?}: a path names a field at each level, joined by \".\"" - )), - (false, false) => Some(format!( - "unnest {path:?}: its parent list {:?} must be unnested too; add it", - parent.unwrap_or_default() - )), - (false, true) if parts.len() > max_depth as usize => Some(format!( - "unnest {path:?}: it is {} levels deep, past max_depth = {max_depth}; raise max_depth or drop it", - parts.len() - )), - (false, true) => None, - } -} - -/// The top-level `unnest` fields a `mask`, `columns` or `exclude_columns` entry also names: unnesting takes the field out of the table, so that setting would silently stop applying. -fn column_setting_problems( - context: &SourceContext<'_>, - overrides: &TableOverride, - paths: &[String], -) -> Vec { - let exclude: Vec<&String> = context - .source - .exclude_columns - .iter() - .chain(&overrides.exclude_columns) - .collect(); - paths - .iter() - .filter(|path| !path.contains('.')) - .filter_map(|field| { - let excluded = matching_pattern(field, &exclude); - let setting = match (excluded, overrides.mask.contains_key(field), overrides.columns.contains_key(field)) { - (Some(pattern), _, _) => format!("exclude_columns {pattern}"), - (None, true, _) => "mask".to_owned(), - (None, false, true) => "columns".to_owned(), - (None, false, false) => return None, - }; - Some(format!( - "unnest {field:?}: {setting} also names {field}, which unnesting moves to child tables; drop one of them" - )) - }) - .collect() -} - -/// The first of `patterns` matching `field`. -fn matching_pattern<'a>(field: &str, patterns: &[&'a String]) -> Option<&'a String> { - patterns - .iter() - .find(|pattern| Glob::new(pattern).is_ok_and(|glob| glob.compile_matcher().is_match(field))) - .copied() -} - -/// Why this table's writes cannot carry child tables yet: captured changes on a files target; on a files target, `"all"` (whose earlier child tables a load cannot find), a merge or `delete_insert` (which would rewrite a child table's files), and a path that would not give each child table a folder of its own (without `{table}`, or partitioned by the cursor, which child rows do not carry). -fn refused_writes( - context: &SourceContext<'_>, - overrides: &TableOverride, - strategy: WriteStrategy, -) -> Vec { - let template = context.target.path.as_ref().map(|target_path| { - overrides - .destination_path - .as_ref() - .or(context.source.destination_path.as_ref()) - .unwrap_or(target_path) - }); - let files = |refused: bool, what: String| (template.is_some() && refused).then_some(what); - let all = matches!(&overrides.unnest, Some(PathsSetting::Word(word)) if word == UNNEST_ALL); - let rewrites = matches!(strategy, WriteStrategy::Merge | WriteStrategy::DeleteInsert); - let files_target = template.is_some(); - let template = template.map(String::as_str).unwrap_or_default(); - [ - (context.source.kind == SourceKind::PostgresCdc && files_target) - .then(|| "kind = \"postgres_cdc\" on a files target".to_owned()), - files(all, "unnest = \"all\" on a files target (list the paths)".to_owned()), - files( - rewrites, - format!("write_strategy = \"{strategy}\" on a files target"), - ), - files( - !template.contains(TABLE_PLACEHOLDER), - format!("a files path without {TABLE_PLACEHOLDER} ({template:?}), as each child table needs its own folder"), - ), - files( - template.contains(CURSOR_PLACEHOLDER_START), - format!("a files path partitioned by the cursor ({template:?})"), - ), - ] - .into_iter() - .flatten() - .map(|what| format!("unnest does not yet write child tables with {what}; drop unnest, and its lists stay JSON columns")) - .collect() -} - /// A text column for each column `overrides` pins in `columns` or masks, one per name it loads as under `rule` (a pin and a mask may spell one column two ways), so a table whose files are gone still resolves with them. pub(crate) fn referenced_columns( overrides: Option<&TableOverride>, @@ -1988,3 +1293,13 @@ pub(crate) fn transform_input( sample: String::new(), }) } + +/// What the table's options read of `target`. +fn option_target(target: &ResolvedTarget) -> OptionTarget { + OptionTarget { + warehouse: target.warehouse, + path: target.path.clone(), + naming: target.naming, + compat: target.compat, + } +} diff --git a/crates/sqlload/src/loader/tests/test_table_parses.rs b/crates/sqlload/src/loader/tests/test_table_parses.rs index 9199c80db..98ff5d320 100644 --- a/crates/sqlload/src/loader/tests/test_table_parses.rs +++ b/crates/sqlload/src/loader/tests/test_table_parses.rs @@ -2,7 +2,7 @@ use crate::loader::tests::helpers::python_spec; use crate::loader::tests::test_types::TableParsesTestCase; #[test] -fn given_a_table_s_parse_and_timezone_when_resolving_then_columns_take_their_loaded_names_and_bad_settings_fail_plan() +fn given_a_table_s_parse_and_timezone_when_resolving_then_columns_take_their_loaded_names_and_bad_settings_fail_parse() { let test_cases = [ TableParsesTestCase { @@ -45,7 +45,7 @@ fn given_a_table_s_parse_and_timezone_when_resolving_then_columns_take_their_loa found.as_deref().map_err(|problem| test_case .expected_outcome .err() - .is_some_and(|expected| problem.contains(&expected.escape_debug().to_string()))), + .is_some_and(|expected| problem.contains(expected))), test_case.expected_outcome.map_err(|_| true), "{}: {found:?}", test_case.description diff --git a/crates/sqlload/src/project/_helpers/references.rs b/crates/sqlload/src/project/_helpers/references.rs index b2633a7e6..d69580bd4 100644 --- a/crates/sqlload/src/project/_helpers/references.rs +++ b/crates/sqlload/src/project/_helpers/references.rs @@ -24,8 +24,9 @@ use crate::project::models::{ use crate::sheets_source::main::a1_range::a1_range; use crate::store_paths::main::resolve_location::resolve_location; use crate::store_paths::models::{Location, StoreKind}; +use crate::table_options::main::option_problems::option_problems; -/// Problems with names one section uses to refer to another. +/// Problems with names one section uses to refer to another, and with how each table's options combine. pub(crate) fn reference_problems(project: &ProjectConfig) -> Vec { let mut problems: Vec = Vec::new(); if let Some(default_target) = &project.default_target @@ -89,6 +90,7 @@ pub(crate) fn reference_problems(project: &ProjectConfig) -> Vec { for (name, source) in &project.sources { problems.extend(source_problems(project, name, source)); } + problems.extend(option_problems(project)); problems } diff --git a/crates/sqlload/src/project/main/parse_python_project.rs b/crates/sqlload/src/project/main/parse_python_project.rs index ab303574f..6b75da004 100644 --- a/crates/sqlload/src/project/main/parse_python_project.rs +++ b/crates/sqlload/src/project/main/parse_python_project.rs @@ -14,7 +14,7 @@ use crate::project::models::ProjectConfig; use crate::python_sources::main::connection_settings::connection_settings; use crate::python_sources::models::PythonSource; -/// Parse and validate a project's TOML text (resolving `${ENV:NAME}` through `lookup`) with `python` sources added, checked by the same rules as `[sources]` entries, each `deletes_from`'s tombstone table, and `sessions` attached by name before its targets are checked: warehouse connections its caller owns ([`SessionConnection`]), which targets load into as into any other connection of their kind; Python settings are not interpolated. +/// Parse and validate a project's TOML text (resolving `${ENV:NAME}` through `lookup`) with `python` sources added, checked by the same rules as `[sources]` entries (how each table's options combine included, as `plan` checks them), each `deletes_from`'s tombstone table, and `sessions` attached by name before its targets are checked: warehouse connections its caller owns ([`SessionConnection`]), which targets load into as into any other connection of their kind; Python settings are not interpolated. pub fn parse_python_project( text: &str, lookup: &dyn Fn(&str) -> Option, diff --git a/crates/sqlload/src/project/tests/helpers.rs b/crates/sqlload/src/project/tests/helpers.rs index 385cd5154..1a52683cd 100644 --- a/crates/sqlload/src/project/tests/helpers.rs +++ b/crates/sqlload/src/project/tests/helpers.rs @@ -35,16 +35,17 @@ new_tables = "skip" exclude_columns = ["*email*"] write_strategy = "merge" unique_key = "id" -cursor_column = "updated_at" lookback = "1h" [sources.app.tables."public.accounts"] +write_strategy = "replace" columns = { balance = "decimal(18,2)" } type_change_rebuild = "allow" checks = { unique = ["id"], not_null = ["id"], max_row_drop = "20%", warn = ["max_row_drop"] } [sources.app.tables."public.events"] -write_strategy = "append" +write_strategy = "delete_insert" +cursor_column = "updated_at" unique_key = ["event_id", "line_no"] "#; diff --git a/crates/sqlload/src/table_options/_helpers/mod.rs b/crates/sqlload/src/table_options/_helpers/mod.rs new file mode 100644 index 000000000..06b4ad6a0 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/mod.rs @@ -0,0 +1,5 @@ +pub(crate) mod nesting; +pub(crate) mod option_target; +pub(crate) mod options; +pub(crate) mod rules; +pub(crate) mod settings; diff --git a/crates/sqlload/src/table_options/_helpers/nesting.rs b/crates/sqlload/src/table_options/_helpers/nesting.rs new file mode 100644 index 000000000..e3d527628 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/nesting.rs @@ -0,0 +1,192 @@ +use globset::Glob; + +use crate::adapters::files::constants::{CURSOR_PLACEHOLDER_START, TABLE_PLACEHOLDER}; +use crate::files_source::models::SourceFormat; +use crate::load_naming::models::Compat; +use crate::loader::constants::UNNEST_ALL; +use crate::project::constants::DEFAULT_MAX_DEPTH; +use crate::project::main::table_flatten::table_flatten; +use crate::project::models::{PathsSetting, SourceKind, TableOverride, WriteStrategy}; +use crate::row_batches::models::Unnest; +use crate::table_options::main::layered::layered; +use crate::table_options::main::table_compat::table_compat; +use crate::table_options::main::table_naming::table_naming; +use crate::table_options::models::{Nesting, OptionContext}; + +/// The table's naming and compat (each its own, its source's, then its target's), whether its rows get an id (always under `compat = "dlt"`), its `unnest` (under `compat = "dlt"`, `"all"` for JSON and NDJSON files on a warehouse), `max_depth` and `flatten` (see [`table_flatten`]), and the problems with them: `unnest` names list fields by dotted paths whose ancestors it also names, no deeper than `max_depth`, that no column setting names, on a table whose writes can carry child tables. +pub(crate) fn nesting( + context: &OptionContext<'_>, + overrides: &TableOverride, + strategy: WriteStrategy, +) -> (Nesting, Vec) { + let settings = &overrides.settings; + let defaults = &context.source.defaults; + let naming = table_naming((settings, defaults), context.target.naming); + let compat = table_compat((settings, defaults), context.target.compat); + let row_id = layered(&settings.row_id, &defaults.row_id).map(|(value, _)| value); + let max_depth = overrides.max_depth.unwrap_or(DEFAULT_MAX_DEPTH); + let mut problems: Vec = Vec::new(); + if compat == Compat::Dlt && row_id == Some(false) { + problems.push( + "row_id = false: compat = \"dlt\" gives every row its _dlt_id; drop row_id".to_owned(), + ); + } + let json_files = context.source.kind == SourceKind::Files + && matches!( + context.source.format, + SourceFormat::Json | SourceFormat::Ndjson + ); + let unnest = match &overrides.unnest { + None if compat == Compat::Dlt && json_files && context.target.path.is_none() => Unnest::All, + None => Unnest::None, + Some(PathsSetting::Paths(paths)) if paths.is_empty() => Unnest::None, + Some(PathsSetting::Word(word)) if word == UNNEST_ALL => Unnest::All, + Some(PathsSetting::Word(word)) => { + problems.push(format!( + "unnest = {word:?}: list the dotted paths of the list fields to unnest, or write \"{UNNEST_ALL}\"" + )); + Unnest::None + } + Some(PathsSetting::Paths(paths)) => { + problems.extend( + paths + .iter() + .filter_map(|path| path_problem(path, paths, max_depth)), + ); + problems.extend(column_setting_problems(context, overrides, paths)); + Unnest::Paths(paths.clone()) + } + }; + let transform = settings.transform.is_some() || defaults.transform.is_some(); + let (flatten, found) = table_flatten( + (context.source, Some(overrides)), + (compat, naming, transform), + ); + problems.extend(found); + match unnest { + Unnest::None if overrides.max_depth.is_some() && flatten.is_none() => { + problems.push( + "max_depth limits the child tables unnest makes and the objects flatten flattens, and this table sets neither" + .to_owned(), + ); + } + Unnest::None => {} + Unnest::All | Unnest::Paths(_) => { + problems.extend(refused_writes(context, overrides, strategy)); + if row_id == Some(false) { + problems.push("row_id = false: unnest gives every row an id, which its child rows name as their parent's; drop row_id".to_owned()); + } + } + } + ( + Nesting { + naming, + compat, + row_id: row_id.unwrap_or(compat == Compat::Dlt || unnest != Unnest::None), + unnest, + max_depth, + flatten, + }, + problems, + ) +} + +/// What is wrong with the `unnest` path `path` among `paths`: an empty part, a parent path not also listed, or more parts than `max_depth`. +fn path_problem(path: &str, paths: &[String], max_depth: u32) -> Option { + let parts: Vec<&str> = path.split('.').collect(); + let parent = path.rsplit_once('.').map(|(parent, _)| parent); + let listed = parent.is_none_or(|parent| paths.iter().any(|listed| listed == parent)); + match (parts.iter().any(|part| part.trim().is_empty()), listed) { + (true, _) => Some(format!( + "unnest {path:?}: a path names a field at each level, joined by \".\"" + )), + (false, false) => Some(format!( + "unnest {path:?}: its parent list {:?} must be unnested too; add it", + parent.unwrap_or_default() + )), + (false, true) if parts.len() > max_depth as usize => Some(format!( + "unnest {path:?}: it is {} levels deep, past max_depth = {max_depth}; raise max_depth or drop it", + parts.len() + )), + (false, true) => None, + } +} + +/// The top-level `unnest` fields a `mask`, `columns` or `exclude_columns` entry also names: unnesting takes the field out of the table, so that setting would silently stop applying. +fn column_setting_problems( + context: &OptionContext<'_>, + overrides: &TableOverride, + paths: &[String], +) -> Vec { + let exclude: Vec<&String> = context + .source + .exclude_columns + .iter() + .chain(&overrides.exclude_columns) + .collect(); + paths + .iter() + .filter(|path| !path.contains('.')) + .filter_map(|field| { + let excluded = matching_pattern(field, &exclude); + let setting = match (excluded, overrides.mask.contains_key(field), overrides.columns.contains_key(field)) { + (Some(pattern), _, _) => format!("exclude_columns {pattern}"), + (None, true, _) => "mask".to_owned(), + (None, false, true) => "columns".to_owned(), + (None, false, false) => return None, + }; + Some(format!( + "unnest {field:?}: {setting} also names {field}, which unnesting moves to child tables; drop one of them" + )) + }) + .collect() +} + +/// The first of `patterns` matching `field`. +fn matching_pattern<'a>(field: &str, patterns: &[&'a String]) -> Option<&'a String> { + patterns + .iter() + .find(|pattern| Glob::new(pattern).is_ok_and(|glob| glob.compile_matcher().is_match(field))) + .copied() +} + +/// Why this table's writes cannot carry child tables yet: captured changes on a files target; on a files target, `"all"` (whose earlier child tables a load cannot find), a merge or `delete_insert` (which would rewrite a child table's files), and a path that would not give each child table a folder of its own (without `{table}`, or partitioned by the cursor, which child rows do not carry). +fn refused_writes( + context: &OptionContext<'_>, + overrides: &TableOverride, + strategy: WriteStrategy, +) -> Vec { + let template = context.target.path.as_ref().map(|target_path| { + overrides + .destination_path + .as_ref() + .or(context.source.destination_path.as_ref()) + .unwrap_or(target_path) + }); + let files = |refused: bool, what: String| (template.is_some() && refused).then_some(what); + let all = matches!(&overrides.unnest, Some(PathsSetting::Word(word)) if word == UNNEST_ALL); + let rewrites = matches!(strategy, WriteStrategy::Merge | WriteStrategy::DeleteInsert); + let files_target = template.is_some(); + let template = template.map(String::as_str).unwrap_or_default(); + [ + (context.source.kind == SourceKind::PostgresCdc && files_target) + .then(|| "kind = \"postgres_cdc\" on a files target".to_owned()), + files(all, "unnest = \"all\" on a files target (list the paths)".to_owned()), + files( + rewrites, + format!("write_strategy = \"{strategy}\" on a files target"), + ), + files( + !template.contains(TABLE_PLACEHOLDER), + format!("a files path without {TABLE_PLACEHOLDER} ({template:?}), as each child table needs its own folder"), + ), + files( + template.contains(CURSOR_PLACEHOLDER_START), + format!("a files path partitioned by the cursor ({template:?})"), + ), + ] + .into_iter() + .flatten() + .map(|what| format!("unnest does not yet write child tables with {what}; drop unnest, and its lists stay JSON columns")) + .collect() +} diff --git a/crates/sqlload/src/table_options/_helpers/option_target.rs b/crates/sqlload/src/table_options/_helpers/option_target.rs new file mode 100644 index 000000000..4dddb6b29 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/option_target.rs @@ -0,0 +1,27 @@ +use crate::adapters::dispatch::main::dialect::connection_warehouse::connection_warehouse; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::project::models::{ProjectConfig, SourceConfig}; +use crate::table_options::models::OptionTarget; + +/// What `source`'s options read of the target it loads into (its own, the project default, or the only target); `None` when that target or its connection is missing or no destination, which parse reports itself. +pub(crate) fn option_target( + project: &ProjectConfig, + source: &SourceConfig, +) -> Option { + let only = (project.targets.len() == 1) + .then(|| project.targets.keys().next().cloned()) + .flatten(); + let name = source + .destination + .clone() + .or_else(|| project.default_target.clone()) + .or(only)?; + let target = project.targets.get(&name)?; + let (warehouse, _) = connection_warehouse(project.connections.get(&target.connection)?)?; + Some(OptionTarget { + warehouse, + path: (!sql_adapter(warehouse).runs_sql()).then(|| target.path_template().to_owned()), + naming: target.naming, + compat: target.compat, + }) +} diff --git a/crates/sqlload/src/table_options/_helpers/options.rs b/crates/sqlload/src/table_options/_helpers/options.rs new file mode 100644 index 000000000..903cb5b01 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/options.rs @@ -0,0 +1,175 @@ +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::cdc::constants::{CDC_FILES_PROBLEM, CDC_TARGETS_PROBLEM}; +use crate::files_source::models::FilesOrder; +use crate::loader::models::SettingOrigin; +use crate::project::models::{ + Deletes, MaskMethod, NullKeys, OnDuplicateKeys, OnOverlappingFiles, SourceKind, TableChecks, + TableOverride, WriteStrategy, +}; +use crate::publish_checks::main::check_problems::check_problems; +use crate::row_batches::models::Unnest; +use crate::row_deletes::main::deletes_problems::deletes_problems; +use crate::table_options::_helpers::nesting::nesting; +use crate::table_options::_helpers::rules::{ + after_load_problems, cursor_problems, dedupe_settings, overlapping_files_problem, + replace_key_problems, strategy_problems, +}; +use crate::table_options::main::layered::layered; +use crate::table_options::models::{Nesting, OptionContext, TableStrategy}; + +/// The strategy the table loads with (a captured table's is `append`) and the problems with it, its keys and its cursor: a `postgres_cdc` table on a target that cannot take its changes, or the strategy's own rules with `unique_key`, `replace_key` and the cursor. +pub(crate) fn strategy_checks( + context: &OptionContext<'_>, + overrides: &TableOverride, + (chosen, unique_key): (&TableStrategy, &[String]), +) -> (WriteStrategy, Vec) { + let cursor = chosen.cursor.as_ref(); + let adapter = sql_adapter(context.target.warehouse); + let (strategy, mut problems) = match &chosen.cdc { + Some(cdc) if !adapter.captures_changes(cdc.apply) => { + let problem = match adapter.runs_sql() { + true => CDC_TARGETS_PROBLEM, + false => CDC_FILES_PROBLEM, + }; + (WriteStrategy::Append, vec![problem.to_owned()]) + } + Some(_) => (WriteStrategy::Append, Vec::new()), + None => ( + chosen.strategy, + strategy_problems(chosen.strategy, (unique_key, &chosen.replace_key), cursor), + ), + }; + problems.extend(replace_key_problems(context, cursor, chosen.keyed)); + let settings = (&overrides.settings, &context.source.defaults); + problems.extend(cursor_problems(context, settings, strategy, cursor)); + (strategy, problems) +} + +/// The table's `on_duplicate_keys` and `newest_by` (its own, else its source's on a merge, the one it sets winning over the other the source sets), and the problems with them. +pub(crate) fn dedupe_options( + context: &OptionContext<'_>, + overrides: &TableOverride, + (strategy, merges, unique_key): (WriteStrategy, bool, &[String]), +) -> ( + Option<(OnDuplicateKeys, SettingOrigin)>, + Vec, + Vec, +) { + let (settings, defaults) = (&overrides.settings, &context.source.defaults); + let table_sorts = settings.newest_by.is_some(); + let on_duplicate_keys = layered(&settings.on_duplicate_keys, &defaults.on_duplicate_keys) + .filter(|(_, origin)| *origin == SettingOrigin::Table || (merges && !table_sorts)); + let table_fails = on_duplicate_keys == Some((OnDuplicateKeys::Fail, SettingOrigin::Table)); + let newest_by = layered(&settings.newest_by, &defaults.newest_by) + .filter(|(_, origin)| *origin == SettingOrigin::Table || (merges && !table_fails)) + .map(|(value, _)| value); + let (newest_by, problems) = dedupe_settings( + strategy, + unique_key, + ( + on_duplicate_keys.map(|(value, _)| value), + newest_by.as_deref(), + ), + overrides, + ); + (on_duplicate_keys, newest_by, problems) +} + +/// The table's `on_overlapping_files` (its source's only when the table takes the source's strategy, or replaces by key), and the problems with the settings of a files source: `order`, `on_overlapping_files` and `after_load`. +pub(crate) fn files_options( + context: &OptionContext<'_>, + overrides: &TableOverride, + (chosen, strategy): (&TableStrategy, WriteStrategy), +) -> (Option, Vec) { + let (settings, defaults) = (&overrides.settings, &context.source.defaults); + let keyed = chosen.keyed; + let mut problems: Vec = Vec::new(); + let ordered = strategy == WriteStrategy::Merge + || (strategy == WriteStrategy::DeleteInsert && !chosen.replace_key.is_empty()); + if context.source.order == FilesOrder::Path && !ordered { + problems.push(format!("order = \"path\" orders the files a merge or a delete_insert by replace_key applies in turn; {strategy} loads them without an order, so remove it")); + } + let own_strategy = chosen.strategy_origin == SettingOrigin::Table && !keyed; + let overlapping = layered( + &settings.on_overlapping_files, + &defaults.on_overlapping_files, + ) + .filter(|(_, origin)| !own_strategy || *origin == SettingOrigin::Table) + .map(|(value, _)| value); + let files = context.source.kind == SourceKind::Files; + problems.extend(overlapping.and_then(|_| overlapping_files_problem(files, strategy, keyed))); + problems.extend(after_load_problems(context, (strategy, keyed))); + (overlapping, problems) +} + +/// The table's `null_keys` (its own, else its source's on a merge or a `delete_insert` by key), and the problems with it and with `mask`: `null_keys` on a table matching no key, a masked cursor or key column, and an `hmac` mask without the source's `mask_key`. +pub(crate) fn key_options( + context: &OptionContext<'_>, + overrides: &TableOverride, + (chosen, strategy, unique_key): (&TableStrategy, WriteStrategy, &[String]), +) -> (Option, Vec) { + let (settings, defaults) = (&overrides.settings, &context.source.defaults); + let (keyed, merges) = (chosen.keyed, chosen.merges); + let mut problems: Vec = Vec::new(); + let null_keys = layered(&settings.null_keys, &defaults.null_keys) + .filter(|(_, origin)| *origin == SettingOrigin::Table || merges || keyed) + .map(|(value, _)| value); + if null_keys.is_some() && strategy != WriteStrategy::Merge && !keyed { + problems.push(format!("null_keys is for write_strategy = \"merge\", which matches rows on unique_key, and \"delete_insert\" with a replace_key; {strategy} keeps every row")); + } + let uses_key = strategy == WriteStrategy::Merge; + problems.extend(overrides.mask.keys().filter_map(|masked| { + let is_cursor = (chosen.cursor.as_ref()).is_some_and(|cursor| cursor.names(masked)); + let is_key = + (uses_key && unique_key.contains(masked)) || chosen.replace_key.contains(masked); + (is_cursor || is_key).then(|| { + format!("mask {masked}: a masked column cannot be the cursor_column or part of the unique_key or replace_key") + }) + })); + let hmac = (overrides.mask.values()).any(|method| *method == MaskMethod::Hmac); + if context.source.mask_key.is_none() && hmac { + problems.push("mask uses \"hmac\" but the source sets no mask_key (for example mask_key = \"${ENV:MASK_KEY}\")".to_owned()); + } + (null_keys, problems) +} + +/// The table's `deletes` (its own, else its source's on a merge or a captured table) and `checks`, and the checks its strategy and target cannot run. +pub(crate) fn deletes_and_checks( + context: &OptionContext<'_>, + overrides: &TableOverride, + (chosen, strategy): (&TableStrategy, WriteStrategy), +) -> (Option, Option, Vec) { + let (settings, defaults) = (&overrides.settings, &context.source.defaults); + let captured = chosen.cdc.is_some(); + let deletes = layered(&settings.deletes, &defaults.deletes) + .filter(|(_, origin)| *origin == SettingOrigin::Table || chosen.merges || captured) + .map(|(value, _)| value); + let checks = layered(&settings.checks, &defaults.checks).map(|(value, _)| value); + let files_target = context.target.path.is_some(); + let problems: Vec = checks + .iter() + .flat_map(|checks| check_problems(checks, (strategy, files_target, deletes.is_some()))) + .collect(); + (deletes, checks, problems) +} + +/// The table's nesting, and the problems with it and with what it carries: nesting settings, `deletes` the table cannot apply, and child tables a `delete_insert` by key cannot carry. +pub(crate) fn nesting_options( + context: &OptionContext<'_>, + overrides: &TableOverride, + (chosen, strategy, deletes): (&TableStrategy, WriteStrategy, Option), +) -> (Nesting, Vec) { + let (nesting, mut problems) = nesting(context, overrides, strategy); + let unnests = !matches!(nesting.unnest, Unnest::None); + let kind = (strategy, context.source.kind); + problems.extend(deletes_problems( + deletes, + kind, + context.target.warehouse, + unnests, + )); + if chosen.keyed && unnests { + problems.push("replace_key does not carry child tables yet, whose rows hang off the replaced rows by their ids. Fix: drop unnest, or use write_strategy = \"merge\" on a unique_key".to_owned()); + } + (nesting, problems) +} diff --git a/crates/sqlload/src/table_options/_helpers/rules.rs b/crates/sqlload/src/table_options/_helpers/rules.rs new file mode 100644 index 000000000..7186b1792 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/rules.rs @@ -0,0 +1,273 @@ +use crate::files_source::models::AfterLoad; +use crate::loader::constants::PRIMARY_KEY_PLACEHOLDER; +use crate::loader::models::{CursorSpec, SettingOrigin}; +use crate::project::models::{ + NullCursor, OnDuplicateKeys, SourceKind, TableOverride, TableSettings, WriteStrategy, +}; +use crate::table_options::main::layered::layered; +use crate::table_options::models::OptionContext; + +/// Problems with a strategy and the keys and cursor it is given. +pub(crate) fn strategy_problems( + strategy: WriteStrategy, + (unique_key, replace_key): (&[String], &[String]), + cursor: Option<&CursorSpec>, +) -> Vec { + let mut problems: Vec = Vec::new(); + match (strategy, cursor) { + (WriteStrategy::Merge, _) if unique_key.is_empty() => problems.push(format!( + "write_strategy = \"merge\" needs a unique_key: the key columns, such as unique_key = [\"id\"], or unique_key = {PRIMARY_KEY_PLACEHOLDER:?} for the primary key the source reports" + )), + (WriteStrategy::Append, Some(cursor)) + if cursor.lookback.is_some() || cursor.lookback_units.is_some() => + { + problems.push( + "lookback re-inserts the window on every run with append; use delete_insert (no key needed) or merge" + .to_owned(), + ) + } + (WriteStrategy::Replace, Some(_)) => problems.push( + "write_strategy = \"replace\" reloads the whole table, so it takes no cursor_column".to_owned(), + ), + (WriteStrategy::DeleteInsert, None) if replace_key.is_empty() => problems.push( + "write_strategy = \"delete_insert\" replaces a cursor range or the rows of the key values it reads, so it needs a cursor_column or a replace_key. Fix: set cursor_column, or replace_key = [\"version\"] to replace every row of each version a load reads".to_owned(), + ), + _ => {} + } + if !replace_key.is_empty() && strategy != WriteStrategy::DeleteInsert { + let merge = match strategy { + WriteStrategy::Merge => " (merge matches rows one by one on unique_key)", + _ => "", + }; + problems.push(format!( + "replace_key is for write_strategy = \"delete_insert\", which replaces the rows holding the key values a load reads; {strategy} does not delete by it. Fix: set write_strategy = \"delete_insert\" to replace those rows whole, or drop replace_key{merge}" + )); + } + if let Some(cursor) = cursor.filter(|cursor| cursor.from_now && cursor.lookback_units.is_some()) + { + problems.push(format!( + "lookback_from = \"now\" counts lookback back from the time of the run, so {} needs a duration lookback, such as lookback = \"1d\", not a number of cursor units", + cursor.label() + )); + } + if let Some(cursor) = cursor.filter(|cursor| { + cursor.from_now && cursor.lookback.is_none() && cursor.lookback_units.is_none() + }) { + problems.push(format!( + "lookback_from = \"now\" counts lookback back from now, so {} needs a lookback", + cursor.label() + )); + } + problems +} + +/// Why a `delete_insert` by `replace_key` (`keyed`) cannot load where `context` puts it: a files target replaces whole partition folders; a files source picks its files from the run log, not by a cursor; and on any other source a cursor would read part of a key value's rows while the commit deletes all of them, losing those the read never returned. +pub(crate) fn replace_key_problems( + context: &OptionContext<'_>, + cursor: Option<&CursorSpec>, + keyed: bool, +) -> Vec { + let mut problems: Vec = Vec::new(); + if !keyed { + return problems; + } + if context.target.path.is_some() { + problems.push("replace_key deletes rows by key in a database table, and a files target replaces whole partition folders. Fix: load into a database target, or drop replace_key and use a partition cursor_column".to_owned()); + } + match (cursor, context.source.kind) { + (Some(cursor), SourceKind::Files) => problems.push(format!( + "cursor_column {} does not apply to a files source's delete_insert by replace_key, which reads each new or changed file once, oldest first, from the run log. Fix: remove cursor_column, or drop replace_key to replace partitions by the cursor", + cursor.column + )), + (Some(cursor), _) => problems.push(format!( + "cursor_column {} does not apply to delete_insert by replace_key: a load deletes every row of each key value it reads, so the rows of a key value outside the cursor range, which it never reads, would be lost. Fix: drop cursor_column, so every load reads the whole source and replaces each key value it holds; or use write_strategy = \"merge\" on a unique_key to read by the cursor", + cursor.column + )), + (None, _) => {} + } + problems +} + +/// Why the table's cursor columns and `null_cursor` cannot apply: an empty or repeating `cursor_column` list; a coalesced cursor where its value is one column's (a files source's partition or path column, a Python table's field, a files target's partitions, `delete_insert`'s replaced range); `null_cursor` on a table entry without a cursor; and `null_cursor = "include"`, which reads the NULL-cursor rows on every run, on anything but `merge`. +pub(crate) fn cursor_problems( + context: &OptionContext<'_>, + (settings, defaults): (&TableSettings, &TableSettings), + strategy: WriteStrategy, + cursor: Option<&CursorSpec>, +) -> Vec { + let mut problems: Vec = Vec::new(); + let listed = layered(&settings.cursor_column, &defaults.cursor_column).map(|(value, _)| value); + if listed.as_ref().is_some_and(Vec::is_empty) { + problems.push("cursor_column = [] names no column; name one, or list the columns to coalesce, such as [\"updated_at\", \"created_at\"]".to_owned()); + } + let listed = listed.unwrap_or_default(); + for (index, column) in listed.iter().enumerate() { + if listed[..index] + .iter() + .any(|earlier| earlier.eq_ignore_ascii_case(column)) + { + problems.push(format!( + "cursor_column lists {column} twice; list each column once" + )); + break; + } + } + if layered(&settings.null_cursor, &defaults.null_cursor) + .is_some_and(|(_, origin)| origin == SettingOrigin::Table) + && cursor.is_none() + { + problems.push("null_cursor says what a cursor read does with rows whose cursor is NULL, but the table has no cursor_column; remove it".to_owned()); + } + let out_of_range = layered( + &settings.on_cursor_out_of_range, + &defaults.on_cursor_out_of_range, + ); + match (out_of_range, context.source.kind) { + (None, _) => {} + (Some(_), SourceKind::Python) if cursor.is_none() => problems.push("on_cursor_out_of_range says what a load does with rows outside the cursor window, but the table has no cursor_column; remove it".to_owned()), + (Some(_), SourceKind::Python) => {} + (Some(_), kind) => problems.push(format!( + "on_cursor_out_of_range checks the rows a Python table's function returns against its cursor window; SQLLoad filters a {} source's reads itself, so remove it", + kind.name() + )), + } + let Some(cursor) = cursor else { + return problems; + }; + let label = cursor.label(); + let coalesced = !cursor.coalesce.is_empty(); + let one_column = match context.source.kind { + SourceKind::Files => Some( + "a files source's cursor is one partition or path column, the same in every row of a file", + ), + SourceKind::Python => Some( + "a Python table's cursor is one field of the rows it yields; yield the first set value as one field (such as row[\"updated_at\"] or row[\"created_at\"]) and name that field", + ), + _ if context.target.path.is_some() => { + Some("a files target partitions and reads its maximum by one cursor column") + } + _ if strategy == WriteStrategy::DeleteInsert => Some( + "delete_insert replaces the destination rows in a range of one cursor column; use merge, or name one column", + ), + _ => None, + }; + if let Some(reason) = one_column.filter(|_| coalesced) { + problems.push(format!( + "cursor_column lists several columns to coalesce ({label}), but {reason}" + )); + } + if cursor.null_cursor == NullCursor::Include { + let refusal = match strategy { + WriteStrategy::Append => Some(( + "append would append them again on every run, duplicating them", + format!( + "use write_strategy = \"merge\" with a unique_key, or coalesce a column that is always set (such as cursor_column = [\"{}\", \"created_at\"]), or set null_cursor = \"ignore\" to skip them", + cursor.column + ), + )), + WriteStrategy::DeleteInsert => Some(( + "they sit outside every cursor range delete_insert replaces, so it would insert them again on every run, duplicating them", + "use write_strategy = \"merge\" with a unique_key, or set null_cursor = \"ignore\" to skip them".to_owned(), + )), + WriteStrategy::Merge | WriteStrategy::Replace => None, + }; + if let Some((duplicates, fix)) = refusal { + problems.push(format!( + "null_cursor = \"include\" reads the rows whose {label} is NULL on every run, and {duplicates}; {fix}" + )); + } + } + problems +} + +/// The `newest_by` columns of a merge, and the problems with `on_duplicate_keys` and `newest_by` (a source's apply only to its merge tables, and either one set on a table drops the other from its source): both are for `merge`, `newest_by` names columns that are neither in the key, masked nor repeated, and has nothing to pick under `on_duplicate_keys = "fail"`. +pub(crate) fn dedupe_settings( + strategy: WriteStrategy, + unique_key: &[String], + (on_duplicate_keys, newest_by): (Option, Option<&[String]>), + overrides: &TableOverride, +) -> (Vec, Vec) { + let mut problems: Vec = Vec::new(); + if strategy != WriteStrategy::Merge { + problems.extend( + [ + on_duplicate_keys.map(|_| "on_duplicate_keys"), + newest_by.map(|_| "newest_by"), + ] + .into_iter() + .flatten() + .map(|name| format!("{name} is for write_strategy = \"merge\", which matches rows on unique_key; {strategy} keeps every row")), + ); + return (Vec::new(), problems); + } + let Some(columns) = newest_by else { + return (Vec::new(), problems); + }; + if columns.is_empty() { + problems.push("newest_by names a column, or a list compared in order, such as newest_by = \"updated_at\"".to_owned()); + } + for (index, column) in columns.iter().enumerate() { + if columns[..index].contains(column) { + problems.push(format!( + "newest_by names {column} twice; name each column once" + )); + } + if unique_key + .iter() + .any(|key| key.eq_ignore_ascii_case(column)) + { + problems.push(format!("newest_by column {column} is in the unique_key, so it is the same in every row it would compare; name another column")); + } + if overrides.mask.contains_key(column) { + problems.push(format!( + "newest_by column {column} is masked, so its values cannot say which row is newer" + )); + } + } + if on_duplicate_keys == Some(OnDuplicateKeys::Fail) { + problems.push("newest_by picks the newest of the rows repeating a key, but on_duplicate_keys = \"fail\" keeps none; set one of them".to_owned()); + } + (columns.to_vec(), problems) +} + +/// Why a files source's `after_load` cannot apply to its table: only `append`, `merge` and `delete_insert` by a `replace_key` (`keyed`) never read a loaded file again, and a files target commits its own way. +pub(crate) fn after_load_problems( + context: &OptionContext<'_>, + (strategy, keyed): (WriteStrategy, bool), +) -> Vec { + let mut problems: Vec = Vec::new(); + if context.source.after_load == AfterLoad::Keep { + return problems; + } + if !matches!(strategy, WriteStrategy::Append | WriteStrategy::Merge) && !keyed { + problems.push(format!( + "after_load deletes or moves each file once it loads, so it needs write_strategy = \"append\" or \"merge\", or \"delete_insert\" with a replace_key; {strategy} reads loaded files again" + )); + } + if context.target.path.is_some() { + problems.push("after_load is for database targets so far, not a files target".to_owned()); + } + problems +} + +/// Why `on_overlapping_files` does not apply to a table loaded by `strategy`: it is for a `delete_insert` by `replace_key` (`keyed`) of a source of `files`, where two files of the folder can hold one key value. +pub(crate) fn overlapping_files_problem( + files: bool, + strategy: WriteStrategy, + keyed: bool, +) -> Option { + const FOR: &str = "on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value"; + match (files, strategy, keyed) { + (true, _, true) => None, + (false, _, _) => Some(format!("{FOR}; this source reads no files, so remove it")), + (true, WriteStrategy::Merge, _) => Some(format!( + "{FOR}; a merge already lets the last file win each unique_key; remove it" + )), + (true, WriteStrategy::DeleteInsert, false) => Some(format!( + "{FOR}; this delete_insert replaces a cursor range, not key values, so remove it, or set replace_key" + )), + (true, strategy, false) => Some(format!( + "{FOR}; {strategy} replaces no key values, so remove it" + )), + } +} diff --git a/crates/sqlload/src/table_options/_helpers/settings.rs b/crates/sqlload/src/table_options/_helpers/settings.rs new file mode 100644 index 000000000..e9231de52 --- /dev/null +++ b/crates/sqlload/src/table_options/_helpers/settings.rs @@ -0,0 +1,124 @@ +use std::collections::BTreeMap; + +use crate::adapters::contract::models::ChangeApply; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::cdc::constants::{BATCH_INTERVAL, FILES_BATCH_INTERVAL}; +use crate::column_parse::main::column_parse::column_parse; +use crate::column_parse::main::time_zone::time_zone; +use crate::column_parse::models::ColumnParse; +use crate::loader::models::{CdcSpec, CursorSpec, SettingOrigin, TableLayout}; +use crate::project::models::{ + CdcMode, CursorBounds, Deletes, Lookback, LookbackFrom, SourceKind, TableOverride, + TableSettings, +}; +use crate::table_options::main::layered::layered; +use crate::table_options::models::OptionContext; + +/// The cursor a table's settings describe, if any. +pub(crate) fn cursor(table: &TableSettings, source: &TableSettings) -> Option { + let (columns, _) = layered(&table.cursor_column, &source.cursor_column)?; + let (column, coalesce) = columns.split_first()?; + Some(CursorSpec { + column: column.clone(), + coalesce: coalesce.to_vec(), + null_cursor: layered(&table.null_cursor, &source.null_cursor) + .map(|(value, _)| value) + .unwrap_or_default(), + out_of_range: layered( + &table.on_cursor_out_of_range, + &source.on_cursor_out_of_range, + ) + .map(|(value, _)| value) + .unwrap_or_default(), + start: layered(&table.cursor_start, &source.cursor_start).map(|(value, _)| value), + lookback: match layered(&table.lookback, &source.lookback) { + Some((Lookback::Duration(duration), _)) => Some(duration), + _ => None, + }, + lookback_units: match layered(&table.lookback, &source.lookback) { + Some((Lookback::Units(units), _)) => Some(units), + _ => None, + }, + lookahead: layered(&table.lookahead, &source.lookahead).map(|(value, _)| value), + from_now: layered(&table.lookback_from, &source.lookback_from) + .is_some_and(|(value, _)| value == LookbackFrom::Now), + inclusive: layered( + &table.append_cursor_inclusive, + &source.append_cursor_inclusive, + ) + .is_some_and(|(value, _)| value), + literals: layered(&table.cursor_bounds, &source.cursor_bounds) + .is_some_and(|(value, _)| value == CursorBounds::Literals), + }) +} + +/// A `postgres_cdc` source's stream settings, with the default slot and publication names. +pub(crate) fn cdc_spec(context: &OptionContext<'_>, deletes: Option) -> Option { + let source = context.source; + (source.kind == SourceKind::PostgresCdc).then(|| { + let default_name = format!("sqlload_{}", context.name.to_lowercase()); + CdcSpec { + apply: match (source.cdc_mode, deletes.unwrap_or(Deletes::Soft)) { + (CdcMode::Changelog, _) => ChangeApply::Changelog, + (CdcMode::Merge, Deletes::Soft) => ChangeApply::SoftDeletes, + (CdcMode::Merge, Deletes::Hard) => ChangeApply::HardDeletes, + }, + slot: source.slot.clone().unwrap_or_else(|| default_name.clone()), + publication: source.publication.clone().unwrap_or(default_name), + batch_interval: source.batch_interval.unwrap_or( + match sql_adapter(context.target.warehouse).runs_sql() { + true => BATCH_INTERVAL, + false => FILES_BATCH_INTERVAL, + }, + ), + } + }) +} + +/// The table's `parse` entries read, or their problems; a column cannot be both pinned in `columns` and parsed, as `parse` gives its type. +pub(crate) fn table_parses( + overrides: &TableOverride, +) -> Result, Vec> { + let mut problems: Vec = Vec::new(); + let mut parses: BTreeMap = BTreeMap::new(); + for (column, setting) in &overrides.parse { + match column_parse(setting) { + Ok(_) if overrides.columns.contains_key(column) => problems.push(format!( + "parse {column}: the column is also pinned in columns, and parse gives its type; drop the pin" + )), + Ok(parse) => { + parses.insert(column.clone(), parse); + } + Err(problem) => problems.push(format!("parse {column}: {problem}")), + } + } + match problems.is_empty() { + true => Ok(parses), + false => Err(problems), + } +} + +/// The table's `timezone` (its own, else its source's) and where it is set, or why it is not an IANA zone. +pub(crate) fn table_timezone( + (settings, defaults): (&TableSettings, &TableSettings), +) -> Result, String> { + match layered(&settings.timezone, &defaults.timezone) { + Some((name, origin)) => time_zone(&name) + .map(|zone| Some((zone, origin))) + .map_err(|problem| format!("timezone: {problem}")), + None => Ok(None), + } +} + +/// The table's layout, each field layered table over source; `table_settings` merged, the table's value winning per setting. +pub(crate) fn table_layout(table: &TableSettings, source: &TableSettings) -> TableLayout { + let mut table_settings = source.table_settings.clone().unwrap_or_default(); + table_settings.extend(table.table_settings.clone().unwrap_or_default()); + TableLayout { + engine: layered(&table.engine, &source.engine).map(|(value, _)| value), + order_by: layered(&table.order_by, &source.order_by).map(|(value, _)| value), + partition_by: layered(&table.partition_by, &source.partition_by).map(|(value, _)| value), + primary_key: layered(&table.primary_key, &source.primary_key).map(|(value, _)| value), + table_settings, + } +} diff --git a/crates/sqlload/src/table_options/main/layered.rs b/crates/sqlload/src/table_options/main/layered.rs new file mode 100644 index 000000000..e02f3d24c --- /dev/null +++ b/crates/sqlload/src/table_options/main/layered.rs @@ -0,0 +1,12 @@ +//! A setting of a table over its source's. + +use crate::loader::models::SettingOrigin; + +/// A table's value if set, otherwise its source's. +pub fn layered(table: &Option, source: &Option) -> Option<(T, SettingOrigin)> { + match (table, source) { + (Some(value), _) => Some((value.clone(), SettingOrigin::Table)), + (None, Some(value)) => Some((value.clone(), SettingOrigin::Source)), + (None, None) => None, + } +} diff --git a/crates/sqlload/src/table_options/main/mod.rs b/crates/sqlload/src/table_options/main/mod.rs new file mode 100644 index 000000000..dcc149b00 --- /dev/null +++ b/crates/sqlload/src/table_options/main/mod.rs @@ -0,0 +1,7 @@ +pub mod layered; +pub mod option_problems; +pub mod placeholder_problem; +pub mod table_compat; +pub mod table_naming; +pub mod table_options; +pub mod table_strategy; diff --git a/crates/sqlload/src/table_options/main/option_problems.rs b/crates/sqlload/src/table_options/main/option_problems.rs new file mode 100644 index 000000000..1e1257297 --- /dev/null +++ b/crates/sqlload/src/table_options/main/option_problems.rs @@ -0,0 +1,82 @@ +//! Every table's options checked together at parse, before anything connects. + +use crate::project::models::{ProjectConfig, TableOverride}; +use crate::table_options::_helpers::option_target::option_target; +use crate::table_options::main::layered::layered; +use crate::table_options::main::placeholder_problem::placeholder_problem; +use crate::table_options::main::table_options::table_options; +use crate::table_options::main::table_strategy::table_strategy; +use crate::table_options::models::OptionContext; + +/// Every problem with how a table's options combine, each led by where the table is set (its `[sources.*.tables.*]` entry, or its Python table); with the wording `plan` gives them. A source listing no tables is checked with its own settings, which every table it finds takes; one listing some is checked table by table, as a table it finds besides them might set nothing. +pub fn option_problems(project: &ProjectConfig) -> Vec { + let mut problems: Vec = Vec::new(); + for (name, source) in &project.sources { + let Some(target) = option_target(project, source) else { + continue; + }; + let context = OptionContext { + name, + source, + target: &target, + }; + let entries: Vec<(Option<&String>, TableOverride)> = match source.tables.is_empty() { + true => vec![(None, TableOverride::default())], + false => source + .tables + .iter() + .map(|(key, table)| (Some(key), table.clone())) + .collect(), + }; + for (key, overrides) in entries { + let place = place(project, name, key.map(String::as_str)); + let found = table_problems( + &context, + key.map_or(name.as_str(), String::as_str), + &overrides, + ); + problems.extend( + found + .into_iter() + .map(|problem| format!("{place}: {problem}")), + ); + } + } + problems +} + +/// The problems of table `qualified`'s options, as the loader finds them: a `unique_key` its settings refuse first, alone, and none when no write strategy is set, which `plan` reports with the source table's key. +fn table_problems( + context: &OptionContext<'_>, + qualified: &str, + overrides: &TableOverride, +) -> Vec { + let Ok(chosen) = table_strategy(context, overrides) else { + return Vec::new(); + }; + let set = layered( + &overrides.settings.unique_key, + &context.source.defaults.unique_key, + ) + .map(|(key, _)| key); + if let Some(problem) = placeholder_problem( + context.source.kind, + qualified, + set.as_deref(), + chosen.merges, + ) { + return vec![problem]; + } + table_options(context, overrides, &chosen, &set.unwrap_or_default()).1 +} + +/// Where problems name a table: its TOML entry or Python table, or its source when it lists none. +fn place(project: &ProjectConfig, name: &str, key: Option<&str>) -> String { + let module = project.python_modules.get(name); + match (key, module) { + (Some(key), Some(module)) => format!("Python table {key} ({module})"), + (Some(key), None) => format!("[sources.{name}.tables.\"{key}\"]"), + (None, Some(module)) => format!("Python source {name} ({module})"), + (None, None) => format!("[sources.{name}]"), + } +} diff --git a/crates/sqlload/src/table_options/main/placeholder_problem.rs b/crates/sqlload/src/table_options/main/placeholder_problem.rs new file mode 100644 index 000000000..c968b0f90 --- /dev/null +++ b/crates/sqlload/src/table_options/main/placeholder_problem.rs @@ -0,0 +1,33 @@ +//! A `unique_key = "{primary_key}"` its settings alone refuse. + +use crate::loader::constants::PRIMARY_KEY_PLACEHOLDER; +use crate::project::models::SourceKind; + +/// Why table `qualified` of a `kind` source cannot take its `unique_key` (`set`) as written: `"{primary_key}"` listed with other columns, or a merge on it from a source that reports no keys; `merges` when it merges on a `unique_key`. +pub fn placeholder_problem( + kind: SourceKind, + qualified: &str, + set: Option<&[String]>, + merges: bool, +) -> Option { + let key = set?; + if !key.iter().any(|column| column == PRIMARY_KEY_PLACEHOLDER) { + return None; + } + if key.len() > 1 { + return Some(format!( + "{qualified}: unique_key {PRIMARY_KEY_PLACEHOLDER:?} stands for the whole primary key, so it can't be listed with other columns; set unique_key = {PRIMARY_KEY_PLACEHOLDER:?} or name every key column" + )); + } + let reports_none = matches!( + kind, + SourceKind::Python | SourceKind::Files | SourceKind::GoogleSheets + ); + (merges && reports_none).then(|| { + format!( + "{qualified} (kind = \"{}\"): unique_key = {PRIMARY_KEY_PLACEHOLDER:?} merges on the primary key the source reports, and a {} source reports none. Fix: name the key columns, such as unique_key = [\"id\"]", + kind.name(), + kind.name() + ) + }) +} diff --git a/crates/sqlload/src/table_options/main/table_compat.rs b/crates/sqlload/src/table_options/main/table_compat.rs new file mode 100644 index 000000000..ee49b3a16 --- /dev/null +++ b/crates/sqlload/src/table_options/main/table_compat.rs @@ -0,0 +1,16 @@ +//! Whose names the columns a load adds take. + +use crate::load_naming::models::Compat; +use crate::project::models::TableSettings; +use crate::table_options::main::layered::layered; + +/// Whose names the columns a table's load adds take: its own `compat`, else its source's, else its target's (`target`), else SQLLoad's. +pub fn table_compat( + (settings, defaults): (&TableSettings, &TableSettings), + target: Option, +) -> Compat { + layered(&settings.compat, &defaults.compat) + .map(|(value, _)| value) + .or(target) + .unwrap_or_default() +} diff --git a/crates/sqlload/src/table_options/main/table_naming.rs b/crates/sqlload/src/table_options/main/table_naming.rs new file mode 100644 index 000000000..805d91bed --- /dev/null +++ b/crates/sqlload/src/table_options/main/table_naming.rs @@ -0,0 +1,16 @@ +//! How a table names what it loads. + +use crate::load_naming::models::Naming; +use crate::project::models::TableSettings; +use crate::table_options::main::layered::layered; + +/// How a table names what it loads: its own `naming`, else its source's, else its target's (`target`), else snake_case. +pub fn table_naming( + (settings, defaults): (&TableSettings, &TableSettings), + target: Option, +) -> Naming { + layered(&settings.naming, &defaults.naming) + .map(|(value, _)| value) + .or(target) + .unwrap_or_default() +} diff --git a/crates/sqlload/src/table_options/main/table_options.rs b/crates/sqlload/src/table_options/main/table_options.rs new file mode 100644 index 000000000..cf6a3bee8 --- /dev/null +++ b/crates/sqlload/src/table_options/main/table_options.rs @@ -0,0 +1,56 @@ +//! Check a table's options together and read what they come to. + +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::project::models::TableOverride; +use crate::table_options::_helpers::options::{ + dedupe_options, deletes_and_checks, files_options, key_options, nesting_options, + strategy_checks, +}; +use crate::table_options::_helpers::settings::{table_layout, table_parses, table_timezone}; +use crate::table_options::models::{OptionContext, TableOptions, TableStrategy}; + +/// What `overrides` (the table's settings, over its source's in `context`) come to with `chosen`'s strategy and `unique_key` (the key a merge matches on), and every problem with how they combine: the strategy with its keys and cursor, the cursor settings, dedupe, a files source's settings, `null_keys` and masks, `checks`, nesting, `deletes`, the target's layout, `parse` and `timezone`. None of them needs the source table, so they are checked at parse as well as when the table is planned. +pub fn table_options( + context: &OptionContext<'_>, + overrides: &TableOverride, + chosen: &TableStrategy, + unique_key: &[String], +) -> (TableOptions, Vec) { + let (strategy, mut problems) = strategy_checks(context, overrides, (chosen, unique_key)); + let dedupe = (strategy, chosen.merges, unique_key); + let (on_duplicate_keys, newest_by, found) = dedupe_options(context, overrides, dedupe); + problems.extend(found); + let (overlapping, found) = files_options(context, overrides, (chosen, strategy)); + problems.extend(found); + let (null_keys, found) = key_options(context, overrides, (chosen, strategy, unique_key)); + problems.extend(found); + let (deletes, checks, found) = deletes_and_checks(context, overrides, (chosen, strategy)); + problems.extend(found); + let (nesting, found) = nesting_options(context, overrides, (chosen, strategy, deletes)); + problems.extend(found); + let layout = table_layout(&overrides.settings, &context.source.defaults); + problems.extend(sql_adapter(context.target.warehouse).layout_problems(&layout)); + let parses = table_parses(overrides).unwrap_or_else(|found| { + problems.extend(found); + Default::default() + }); + let timezone = + table_timezone((&overrides.settings, &context.source.defaults)).unwrap_or_else(|problem| { + problems.push(problem); + None + }); + let options = TableOptions { + strategy, + on_duplicate_keys, + newest_by, + overlapping, + null_keys, + deletes, + checks, + nesting, + layout, + parses, + timezone, + }; + (options, problems) +} diff --git a/crates/sqlload/src/table_options/main/table_strategy.rs b/crates/sqlload/src/table_options/main/table_strategy.rs new file mode 100644 index 000000000..869255bfa --- /dev/null +++ b/crates/sqlload/src/table_options/main/table_strategy.rs @@ -0,0 +1,46 @@ +//! A table's write strategy and the cursor and keys it reads and replaces by. + +use crate::loader::models::{CursorSpec, SettingOrigin}; +use crate::project::models::{TableOverride, WriteStrategy}; +use crate::table_options::_helpers::settings::{cdc_spec, cursor}; +use crate::table_options::main::layered::layered; +use crate::table_options::models::{OptionContext, TableStrategy}; + +/// The write strategy `overrides` (the table's settings, over its source's in `context`) loads with, with its cursor and `replace_key`; or the table's cursor when neither it nor its source sets one, which the caller reports. +pub fn table_strategy( + context: &OptionContext<'_>, + overrides: &TableOverride, +) -> Result>> { + let settings = &overrides.settings; + let defaults = &context.source.defaults; + let cursor = cursor(settings, defaults); + let deletes = layered(&settings.deletes, &defaults.deletes); + let cdc = cdc_spec(context, deletes.map(|(value, _)| value)); + let (strategy, strategy_origin) = match ( + layered(&settings.write_strategy, &defaults.write_strategy), + &cdc, + ) { + (Some(set), _) => set, + (None, Some(_)) => (WriteStrategy::Append, SettingOrigin::Source), + (None, None) => return Err(cursor.map(Box::new)), + }; + let merges = strategy == WriteStrategy::Merge && cdc.is_none(); + let replace_key: Vec = layered(&settings.replace_key, &defaults.replace_key) + .filter(|(_, origin)| { + *origin == SettingOrigin::Table + || strategy == WriteStrategy::DeleteInsert + || strategy_origin != SettingOrigin::Table + }) + .map(|(key, _)| key) + .unwrap_or_default(); + let keyed = strategy == WriteStrategy::DeleteInsert && !replace_key.is_empty(); + Ok(TableStrategy { + cursor, + cdc, + strategy, + strategy_origin, + merges, + replace_key, + keyed, + }) +} diff --git a/crates/sqlload/src/table_options/mod.rs b/crates/sqlload/src/table_options/mod.rs new file mode 100644 index 000000000..5c1d8907f --- /dev/null +++ b/crates/sqlload/src/table_options/mod.rs @@ -0,0 +1,8 @@ +//! How a table's options combine, checked from its settings alone: by the loader as it plans a table, and at parse. + +pub(crate) mod _helpers; +pub mod main; +pub mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlload/src/table_options/models.rs b/crates/sqlload/src/table_options/models.rs new file mode 100644 index 000000000..150df371d --- /dev/null +++ b/crates/sqlload/src/table_options/models.rs @@ -0,0 +1,69 @@ +use crate::column_parse::models::ColumnParse; +use crate::column_types::models::Warehouse; +use crate::load_naming::models::{Compat, Naming}; +use crate::loader::models::{CdcSpec, CursorSpec, SettingOrigin, TableLayout}; +use crate::project::models::{ + Deletes, NullKeys, OnDuplicateKeys, OnOverlappingFiles, SourceConfig, TableChecks, + WriteStrategy, +}; +use crate::row_batches::models::{Flatten, Unnest}; + +/// What a table's options read of the target it loads into. +#[derive(Debug, Clone)] +pub struct OptionTarget { + pub warehouse: Warehouse, + /// The table folder template, for a files target. + pub path: Option, + pub naming: Option, + pub compat: Option, +} + +/// The source a table belongs to, by name, and the target it loads into. +#[derive(Debug, Clone, Copy)] +pub struct OptionContext<'a> { + pub name: &'a str, + pub source: &'a SourceConfig, + pub target: &'a OptionTarget, +} + +/// A table's write strategy (its own, its source's, or a `postgres_cdc` source's `append`), cursor and keys it is replaced by. +#[derive(Debug, Clone)] +pub struct TableStrategy { + pub cursor: Option, + pub cdc: Option, + pub strategy: WriteStrategy, + pub strategy_origin: SettingOrigin, + /// It merges on a `unique_key` (not a captured table's merge). + pub merges: bool, + pub replace_key: Vec, + /// A `delete_insert` by `replace_key`. + pub keyed: bool, +} + +/// What a table's options come to once they are checked together. +#[derive(Debug, Clone)] +pub struct TableOptions { + /// The strategy it loads with: a captured table's is `append`. + pub strategy: WriteStrategy, + pub on_duplicate_keys: Option<(OnDuplicateKeys, SettingOrigin)>, + pub newest_by: Vec, + pub overlapping: Option, + pub null_keys: Option, + pub deletes: Option, + pub checks: Option, + pub nesting: Nesting, + pub layout: TableLayout, + pub parses: std::collections::BTreeMap, + pub timezone: Option<(chrono_tz::Tz, SettingOrigin)>, +} + +/// What a table's nesting settings come to. +#[derive(Debug, Clone)] +pub struct Nesting { + pub naming: Naming, + pub compat: Compat, + pub row_id: bool, + pub unnest: Unnest, + pub max_depth: u32, + pub flatten: Flatten, +} diff --git a/crates/sqlload/src/table_options/tests.rs b/crates/sqlload/src/table_options/tests.rs new file mode 100644 index 000000000..ca80f722d --- /dev/null +++ b/crates/sqlload/src/table_options/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_option_problems.rs"] +mod option_problems; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlload/src/table_options/tests/helpers.rs b/crates/sqlload/src/table_options/tests/helpers.rs new file mode 100644 index 000000000..cc57a986a --- /dev/null +++ b/crates/sqlload/src/table_options/tests/helpers.rs @@ -0,0 +1,50 @@ +use std::collections::BTreeMap; + +use crate::project::main::parse_project::parse_project; +use crate::project::main::parse_python_project::parse_python_project; +use crate::python_sources::models::PythonSource; + +/// The connections every test project reads and writes through. +const CONNECTIONS: &str = "[connections.wh]\nkind = \"duckdb\"\ndatabase = \":memory:\"\n[connections.pg]\nkind = \"postgres\"\nhost = \"localhost\"\nuser = \"reader\"\ndatabase = \"app\"\n[connections.files]\nkind = \"filesystem\"\nroot = \"in\"\n[connections.lake]\nkind = \"filesystem\"\nroot = \"lake\"\n"; + +/// A DuckDB target. +pub(crate) const DUCKDB: &str = "[targets.dev]\nconnection = \"wh\"\nloader_schema = \"raw\"\n"; + +/// A files target. +pub(crate) const FILES_TARGET: &str = "[targets.dev]\nconnection = \"lake\"\n"; + +/// A Postgres source's table `public.t`, whose settings follow. +pub(crate) const POSTGRES_TABLE: &str = "kind = \"postgres\"\nconnection = \"pg\"\ninclude = [\"public.t\"]\n[sources.s.tables.\"public.t\"]\n"; + +/// A Postgres source with its own settings, which follow, and no table entries. +pub(crate) const POSTGRES_SOURCE: &str = + "kind = \"postgres\"\nconnection = \"pg\"\ninclude = [\"public.*\"]\n"; + +/// A files source reading CSV files, whose settings follow. +pub(crate) const FILES_SOURCE: &str = "kind = \"files\"\nconnection = \"files\"\npath = \"orders/\"\nformat = \"csv\"\ndescription = \"Orders.\"\n"; + +/// Parse's error for a project of `target` and source `s` (`source` then `settings`), or nothing when it parses. +pub(crate) fn toml_problems(target: &str, source: &str, settings: &str) -> String { + let text = format!("{CONNECTIONS}{target}[sources.s]\n{source}{settings}"); + parse_project(&text, &|_| None) + .err() + .map(|error| error.to_string()) + .unwrap_or_default() +} + +/// Parse's error for a project whose Python source `s` (in `s.py`) declares table `t` with `settings` (TOML), or nothing when it parses. +pub(crate) fn python_problems(settings: &str) -> Result { + let mut table: toml::Table = toml::from_str(settings).map_err(|error| error.to_string())?; + table.insert("description".to_owned(), toml::Value::from("Table t.")); + let settings = serde_json::json!({"tables": {"t": table}}); + let source = serde_json::json!({"name": "s", "module": "s.py", "settings": settings}); + let python: Vec = + serde_json::from_value(serde_json::json!([source])).map_err(|error| error.to_string())?; + let text = format!("{CONNECTIONS}{DUCKDB}"); + Ok( + parse_python_project(&text, &|_| None, (&python, BTreeMap::new())) + .err() + .map(|error| error.to_string()) + .unwrap_or_default(), + ) +} diff --git a/crates/sqlload/src/table_options/tests/test_option_problems.rs b/crates/sqlload/src/table_options/tests/test_option_problems.rs new file mode 100644 index 000000000..8a7a95a22 --- /dev/null +++ b/crates/sqlload/src/table_options/tests/test_option_problems.rs @@ -0,0 +1,393 @@ +use crate::table_options::tests::helpers::{ + DUCKDB, FILES_SOURCE, FILES_TARGET, POSTGRES_SOURCE, POSTGRES_TABLE, python_problems, + toml_problems, +}; +use crate::table_options::tests::test_types::{PythonOptionsTestCase, TomlOptionsTestCase}; + +#[test] +fn given_table_options_that_do_not_combine_when_parsing_a_toml_project_then_parse_reports_each_with_plan_s_wording() + { + let test_cases = [ + TomlOptionsTestCase { + description: "merge without a unique_key", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: write_strategy = \"merge\" needs a unique_key", + }, + TomlOptionsTestCase { + description: "replace with a cursor", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\ncursor_column = \"updated_at\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: write_strategy = \"replace\" reloads the whole table, so it takes no cursor_column", + }, + TomlOptionsTestCase { + description: "append with a lookback", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\nlookback = \"1h\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: lookback re-inserts the window on every run with append", + }, + TomlOptionsTestCase { + description: "delete_insert with neither a cursor nor a replace_key", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: write_strategy = \"delete_insert\" replaces a cursor range or the rows of the key values it reads, so it needs a cursor_column or a replace_key", + }, + TomlOptionsTestCase { + description: "replace_key on a merge", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nreplace_key = [\"version\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: replace_key is for write_strategy = \"delete_insert\"", + }, + TomlOptionsTestCase { + description: "lookback_from now with a lookback in cursor units", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"seq\"\nlookback = 1\nlookback_from = \"now\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: lookback_from = \"now\" counts lookback back from the time of the run, so seq needs a duration lookback", + }, + TomlOptionsTestCase { + description: "lookback_from now without a lookback", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"updated_at\"\nlookback_from = \"now\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: lookback_from = \"now\" counts lookback back from now, so updated_at needs a lookback", + }, + TomlOptionsTestCase { + description: "a database source's replace_key with a cursor", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\ncursor_column = \"updated_at\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column updated_at does not apply to delete_insert by replace_key", + }, + TomlOptionsTestCase { + description: "an empty cursor_column list", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = []\n", + expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column = [] names no column", + }, + TomlOptionsTestCase { + description: "a cursor column listed twice", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = [\"updated_at\", \"updated_at\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column lists updated_at twice", + }, + TomlOptionsTestCase { + description: "null_cursor without a cursor", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\nnull_cursor = \"ignore\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: null_cursor says what a cursor read does with rows whose cursor is NULL, but the table has no cursor_column", + }, + TomlOptionsTestCase { + description: "on_cursor_out_of_range on a database source", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\non_cursor_out_of_range = \"skip\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: on_cursor_out_of_range checks the rows a Python table's function returns against its cursor window", + }, + TomlOptionsTestCase { + description: "a coalesced cursor on a delete_insert", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = [\"updated_at\", \"created_at\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column lists several columns to coalesce (coalesce(updated_at, created_at)), but delete_insert replaces the destination rows in a range of one cursor column", + }, + TomlOptionsTestCase { + description: "null_cursor include on an append", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\nnull_cursor = \"include\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and append would append them again", + }, + TomlOptionsTestCase { + description: "on_duplicate_keys on an append", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"append\"\non_duplicate_keys = \"fail\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: on_duplicate_keys is for write_strategy = \"merge\", which matches rows on unique_key; append keeps every row", + }, + TomlOptionsTestCase { + description: "newest_by naming a unique_key column", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = \"id\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: newest_by column id is in the unique_key", + }, + TomlOptionsTestCase { + description: "newest_by naming a column twice", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = [\"updated_at\", \"updated_at\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: newest_by names updated_at twice", + }, + TomlOptionsTestCase { + description: "newest_by naming a masked column", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = \"updated_at\"\nmask = { updated_at = \"hash\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: newest_by column updated_at is masked", + }, + TomlOptionsTestCase { + description: "newest_by with on_duplicate_keys fail", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = \"updated_at\"\non_duplicate_keys = \"fail\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: newest_by picks the newest of the rows repeating a key, but on_duplicate_keys = \"fail\" keeps none", + }, + TomlOptionsTestCase { + description: "null_keys on an append", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"append\"\nnull_keys = \"fail\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: null_keys is for write_strategy = \"merge\"", + }, + TomlOptionsTestCase { + description: "checks.max_row_drop on a merge", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nchecks = { max_row_drop = \"20%\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: only write_strategy = \"replace\" publishes the whole table in one commit", + }, + TomlOptionsTestCase { + description: "a masked cursor column", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = \"updated_at\"\nmask = { updated_at = \"hash\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: mask updated_at: a masked column cannot be the cursor_column or part of the unique_key or replace_key", + }, + TomlOptionsTestCase { + description: "a masked unique_key column", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nmask = { id = \"hash\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: mask id: a masked column cannot be the cursor_column or part of the unique_key or replace_key", + }, + TomlOptionsTestCase { + description: "an hmac mask without a mask_key", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\nmask = { email = \"hmac\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: mask uses \"hmac\" but the source sets no mask_key", + }, + TomlOptionsTestCase { + description: "unnest with a replace_key", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\nunnest = [\"items\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: replace_key does not carry child tables yet", + }, + TomlOptionsTestCase { + description: "deletes on a delete_insert", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"updated_at\"\ndeletes = \"soft\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: deletes marks the rows whose unique_key the source no longer holds, which needs write_strategy = \"merge\"; delete_insert keeps no key to match", + }, + TomlOptionsTestCase { + description: "an unnest path whose parent list is not unnested", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\nunnest = [\"items.lines\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: unnest \"items.lines\": its parent list \"items\" must be unnested too", + }, + TomlOptionsTestCase { + description: "row_id = false under compat dlt", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\ncompat = \"dlt\"\nrow_id = false\n", + expected_problem: "[sources.s.tables.\"public.t\"]: row_id = false: compat = \"dlt\" gives every row its _dlt_id", + }, + TomlOptionsTestCase { + description: "max_depth with neither unnest nor flatten", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\nmax_depth = 2\n", + expected_problem: "[sources.s.tables.\"public.t\"]: max_depth limits the child tables unnest makes and the objects flatten flattens, and this table sets neither", + }, + TomlOptionsTestCase { + description: "a column both pinned and parsed", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\ncolumns = { updated = \"text\" }\nparse = { updated = \"epoch_ms\" }\n", + expected_problem: "[sources.s.tables.\"public.t\"]: parse updated: the column is also pinned in columns", + }, + TomlOptionsTestCase { + description: "a timezone that is not an IANA zone", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\ntimezone = \"Europe/Pari\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: timezone: \"Europe/Pari\" is not an IANA time zone", + }, + TomlOptionsTestCase { + description: "a ClickHouse layout on a DuckDB target", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\norder_by = [\"id\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: engine, order_by, partition_by, primary_key and table_settings lay out ClickHouse tables", + }, + TomlOptionsTestCase { + description: "{primary_key} listed with other columns", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"{primary_key}\", \"id\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: public.t: unique_key \"{primary_key}\" stands for the whole primary key, so it can't be listed with other columns", + }, + TomlOptionsTestCase { + description: "on_overlapping_files on a database source", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"replace\"\non_overlapping_files = \"last_wins\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value; this source reads no files", + }, + TomlOptionsTestCase { + description: "a source's own settings, with no table entries, are checked as every table's", + target: DUCKDB, + source: POSTGRES_SOURCE, + settings: "write_strategy = \"merge\"\n", + expected_problem: "[sources.s]: write_strategy = \"merge\" needs a unique_key", + }, + TomlOptionsTestCase { + description: "a source's merge without a key, when its listed table sets one, parses", + target: DUCKDB, + source: POSTGRES_SOURCE, + settings: "write_strategy = \"merge\"\n[sources.s.tables.\"public.t\"]\nunique_key = [\"id\"]\n", + expected_problem: "", + }, + TomlOptionsTestCase { + description: "a merge on its key with a cursor parses", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = \"updated_at\"\n", + expected_problem: "", + }, + TomlOptionsTestCase { + description: "order = path on an append", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"append\"\norder = \"path\"\n", + expected_problem: "[sources.s]: order = \"path\" orders the files a merge or a delete_insert by replace_key applies in turn; append loads them without an order", + }, + TomlOptionsTestCase { + description: "on_overlapping_files on a files merge", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\non_overlapping_files = \"last_wins\"\n", + expected_problem: "[sources.s]: on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value; a merge already lets the last file win each unique_key", + }, + TomlOptionsTestCase { + description: "after_load on a replace", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"replace\"\nafter_load = \"delete\"\n", + expected_problem: "[sources.s]: after_load deletes or moves each file once it loads, so it needs write_strategy = \"append\" or \"merge\"", + }, + TomlOptionsTestCase { + description: "a files source's replace_key with a cursor", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\npath_columns = \"v_{file_version}.csv\"\ncursor_column = \"file_version\"\n", + expected_problem: "[sources.s]: cursor_column file_version does not apply to a files source's delete_insert by replace_key", + }, + TomlOptionsTestCase { + description: "a files source's coalesced cursor", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = [\"a\", \"b\"]\n", + expected_problem: "[sources.s]: cursor_column lists several columns to coalesce (coalesce(a, b)), but a files source's cursor is one partition or path column", + }, + TomlOptionsTestCase { + description: "replace_key on a files target", + target: FILES_TARGET, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: replace_key deletes rows by key in a database table, and a files target replaces whole partition folders", + }, + TomlOptionsTestCase { + description: "unnest on a files target merge", + target: FILES_TARGET, + source: POSTGRES_TABLE, + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nunnest = [\"items\"]\n", + expected_problem: "[sources.s.tables.\"public.t\"]: unnest does not yet write child tables with write_strategy = \"merge\" on a files target", + }, + TomlOptionsTestCase { + description: "a postgres_cdc source merging into a files target", + target: FILES_TARGET, + source: "kind = \"postgres_cdc\"\nconnection = \"pg\"\ninclude = [\"public.t\"]\n", + settings: "", + expected_problem: "[sources.s]: a files target takes kind = \"postgres_cdc\" only with cdc_mode = \"changelog\"", + }, + ]; + for test_case in test_cases { + let problems = toml_problems(test_case.target, test_case.source, test_case.settings); + assert!( + problems.contains(test_case.expected_problem) + && problems.is_empty() == test_case.expected_problem.is_empty(), + "{}: {problems}", + test_case.description + ); + } +} + +#[test] +fn given_python_table_options_that_do_not_combine_when_parsing_then_parse_reports_each_at_the_python_table() +-> Result<(), String> { + let test_cases = [ + PythonOptionsTestCase { + description: "merge without a unique_key", + settings: "write_strategy = \"merge\"", + expected_problem: "Python table t (s.py): write_strategy = \"merge\" needs a unique_key", + }, + PythonOptionsTestCase { + description: "replace with a cursor", + settings: "write_strategy = \"replace\"\ncursor_column = \"updated_at\"", + expected_problem: "Python table t (s.py): write_strategy = \"replace\" reloads the whole table, so it takes no cursor_column", + }, + PythonOptionsTestCase { + description: "on_cursor_out_of_range without a cursor", + settings: "write_strategy = \"append\"\non_cursor_out_of_range = \"skip\"", + expected_problem: "Python table t (s.py): on_cursor_out_of_range says what a load does with rows outside the cursor window, but the table has no cursor_column", + }, + PythonOptionsTestCase { + description: "a merge on {primary_key}, which a Python source never reports", + settings: "write_strategy = \"merge\"\nunique_key = \"{primary_key}\"", + expected_problem: "Python table t (s.py): t (kind = \"python\"): unique_key = \"{primary_key}\" merges on the primary key the source reports, and a python source reports none", + }, + PythonOptionsTestCase { + description: "a coalesced cursor", + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = [\"updated_at\", \"created_at\"]", + expected_problem: "Python table t (s.py): cursor_column lists several columns to coalesce (coalesce(updated_at, created_at)), but a Python table's cursor is one field of the rows it yields", + }, + PythonOptionsTestCase { + description: "newest_by naming a unique_key column", + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = \"id\"", + expected_problem: "Python table t (s.py): newest_by column id is in the unique_key", + }, + PythonOptionsTestCase { + description: "deletes on an append", + settings: "write_strategy = \"append\"\ndeletes = \"soft\"", + expected_problem: "Python table t (s.py): deletes marks the rows whose unique_key the source no longer holds", + }, + PythonOptionsTestCase { + description: "a merge on its key with a cursor and on_cursor_out_of_range parses", + settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\ncursor_column = \"updated_at\"\non_cursor_out_of_range = \"skip\"", + expected_problem: "", + }, + ]; + for test_case in test_cases { + let problems = python_problems(test_case.settings)?; + assert!( + problems.contains(test_case.expected_problem) + && problems.is_empty() == test_case.expected_problem.is_empty(), + "{}: {problems}", + test_case.description + ); + } + Ok(()) +} diff --git a/crates/sqlload/src/table_options/tests/test_types.rs b/crates/sqlload/src/table_options/tests/test_types.rs new file mode 100644 index 000000000..8550bb44b --- /dev/null +++ b/crates/sqlload/src/table_options/tests/test_types.rs @@ -0,0 +1,17 @@ +pub(crate) struct TomlOptionsTestCase { + pub(crate) description: &'static str, + /// The `[targets.dev]` section: a DuckDB target, or a files target. + pub(crate) target: &'static str, + /// The `[sources.s]` section's lines before `settings`: its kind and connection, and a table entry's header. + pub(crate) source: &'static str, + pub(crate) settings: &'static str, + /// Text parse's error must hold (where the table is set, then the problem); empty when the project parses. + pub(crate) expected_problem: &'static str, +} + +pub(crate) struct PythonOptionsTestCase { + pub(crate) description: &'static str, + /// Python table `t`'s settings, as TOML. + pub(crate) settings: &'static str, + pub(crate) expected_problem: &'static str, +} diff --git a/crates/sqlload/tests/loader/test_files_to_duckdb.rs b/crates/sqlload/tests/loader/test_files_to_duckdb.rs index c812ea6c0..90b8d7091 100644 --- a/crates/sqlload/tests/loader/test_files_to_duckdb.rs +++ b/crates/sqlload/tests/loader/test_files_to_duckdb.rs @@ -677,25 +677,6 @@ fn given_csv_files_when_merging_into_duckdb_then_the_newest_modified_file_wins_a check_query: MERGE_CHECK, expected_result: "1:wed,2:mon,3:wed|1", }, - FilesMergeTestCase { - description: "order = \"path\" on an append table, which loads files without an order, is refused at plan", - settings: "write_strategy = \"append\"\norder = \"path\"\n", - steps: &[MergeStep { - before: &[], - files: &[MergeFile { - key: "a.csv", - contents: "id,v\n1,a\n", - modified_secs: 1_000, - }], - removed: &[], - loads: true, - reload: false, - expected_error: "order = \"path\" orders the files a merge or a delete_insert by replace_key applies in turn; append loads them without an order, so remove it", - expected_plan: "", - }], - check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_name = 'scores'", - expected_result: "0", - }, FilesMergeTestCase { description: "by default a file repeating a key merges its last row of that key", settings: MERGE_SETTINGS, @@ -1645,51 +1626,6 @@ fn given_replace_key_when_planning_a_table_it_does_not_suit_then_plan_refuses_it -> Result<(), String> { run_async(|| async move { let test_cases = [ - FilesMergeTestCase { - description: "replace_key with merge", - settings: "write_strategy = \"merge\"\nunique_key = [\"line\"]\nreplace_key = [\"le_version\"]\n", - steps: &[MergeStep { - before: &[], - files: &[LE_P01], - removed: &[], - loads: true, - reload: false, - expected_error: "replace_key is for write_strategy = \"delete_insert\", which replaces the rows holding the key values a load reads; merge does not delete by it └── fix set write_strategy = \"delete_insert\" to replace those rows whole, or drop replace_key (merge matches rows one by one on unique_key)", - expected_plan: "", - }], - check_query: NO_TABLE, - expected_result: "0", - }, - FilesMergeTestCase { - description: "replace_key with append", - settings: "write_strategy = \"append\"\nreplace_key = [\"le_version\"]\n", - steps: &[MergeStep { - before: &[], - files: &[LE_P01], - removed: &[], - loads: true, - reload: false, - expected_error: "replace_key is for write_strategy = \"delete_insert\", which replaces the rows holding the key values a load reads; append does not delete by it └── fix set write_strategy = \"delete_insert\" to replace those rows whole, or drop replace_key", - expected_plan: "", - }], - check_query: NO_TABLE, - expected_result: "0", - }, - FilesMergeTestCase { - description: "replace_key with replace", - settings: "write_strategy = \"replace\"\nreplace_key = [\"le_version\"]\n", - steps: &[MergeStep { - before: &[], - files: &[LE_P01], - removed: &[], - loads: true, - reload: false, - expected_error: "replace_key is for write_strategy = \"delete_insert\", which replaces the rows holding the key values a load reads; replace does not delete by it └── fix set write_strategy = \"delete_insert\" to replace those rows whole, or drop replace_key", - expected_plan: "", - }], - check_query: NO_TABLE, - expected_result: "0", - }, FilesMergeTestCase { description: "a replace_key column the table doesn't have", settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\n", @@ -1705,21 +1641,6 @@ fn given_replace_key_when_planning_a_table_it_does_not_suit_then_plan_refuses_it check_query: NO_TABLE, expected_result: "0", }, - FilesMergeTestCase { - description: "delete_insert with neither a cursor nor a replace_key", - settings: "write_strategy = \"delete_insert\"\n", - steps: &[MergeStep { - before: &[], - files: &[LE_P01], - removed: &[], - loads: true, - reload: false, - expected_error: "write_strategy = \"delete_insert\" replaces a cursor range or the rows of the key values it reads, so it needs a cursor_column or a replace_key └── fix set cursor_column, or replace_key = [\"version\"]", - expected_plan: "", - }], - check_query: NO_TABLE, - expected_result: "0", - }, FilesMergeTestCase { description: "a files source's replace_key excluding _sqlload_source_file, which it finds a value's other files by", settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"le_version\"]\nexclude_columns = [\"_sqlload_source_file\"]\n", @@ -1735,21 +1656,6 @@ fn given_replace_key_when_planning_a_table_it_does_not_suit_then_plan_refuses_it check_query: NO_TABLE, expected_result: "0", }, - FilesMergeTestCase { - description: "a files source's replace_key with a cursor_column", - settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"le_version\"]\npath_columns = \"le_{file_version}.csv\"\ncursor_column = \"file_version\"\n", - steps: &[MergeStep { - before: &[], - files: &[LE_P01], - removed: &[], - loads: true, - reload: false, - expected_error: "cursor_column file_version does not apply to a files source's delete_insert by replace_key, which reads each new or changed file once, oldest first, from the run log └── fix remove cursor_column", - expected_plan: "", - }], - check_query: NO_TABLE, - expected_result: "0", - }, FilesMergeTestCase { description: "a cursor_column the files hold, which the plan points to replace_key", settings: "write_strategy = \"delete_insert\"\ncursor_column = \"le_version\"\n", diff --git a/crates/sqlload/tests/loader/test_loader_edge_cases.rs b/crates/sqlload/tests/loader/test_loader_edge_cases.rs index 6a41cdc03..b68b821c8 100644 --- a/crates/sqlload/tests/loader/test_loader_edge_cases.rs +++ b/crates/sqlload/tests/loader/test_loader_edge_cases.rs @@ -111,19 +111,6 @@ fn given_edge_cases_when_loading_postgres_into_duckdb_then_tables_stay_correct() check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", expected_result: "0", }, - ScenarioTestCase { - description: "append with lookback is rejected before anything runs", - setup: "CREATE TABLE public.ticks (seq int8, at timestamptz);", - settings: "write_strategy = \"append\"\ncursor_column = \"at\"\nlookback = \"1h\"\n[sources.app.tables.\"public.ticks\"]\n", - runs: &[ScenarioRun { - source_change: "", - destination_change: "", - expected_error: "lookback re-inserts the window on every run with append", - ..OK - }], - check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", - expected_result: "0", - }, ScenarioTestCase { description: "a column dropped by hand is added back, and one added by hand is left alone", setup: "CREATE TABLE public.stores (code text PRIMARY KEY, city text); @@ -401,17 +388,6 @@ fn given_edge_cases_when_loading_postgres_into_duckdb_then_tables_stay_correct() check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", expected_result: "0", }, - ScenarioTestCase { - description: "a masked cursor column is rejected", - setup: "CREATE TABLE public.users (id int8 PRIMARY KEY, code text);", - settings: "write_strategy = \"replace\"\n[sources.app.tables.\"public.users\"]\nwrite_strategy = \"merge\"\nunique_key = \"{primary_key}\"\ncursor_column = \"code\"\nmask = { code = \"hash\" }\n", - runs: &[ScenarioRun { - expected_error: "a masked column cannot be the cursor_column", - ..OK - }], - check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", - expected_result: "0", - }, ScenarioTestCase { description: "a write that fails inside the transaction keeps the old rows and drops the staging table", setup: "CREATE TABLE public.people (id int8 PRIMARY KEY, name text); @@ -460,17 +436,6 @@ fn given_edge_cases_when_loading_postgres_into_duckdb_then_tables_stay_correct() check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", expected_result: "0", }, - ScenarioTestCase { - description: "merge without a unique_key is refused, though the table has a primary key: SQLLoad no longer takes it unasked", - setup: "CREATE TABLE public.keyed (id int8 PRIMARY KEY, note text);", - settings: "write_strategy = \"merge\"\n", - runs: &[ScenarioRun { - expected_error: "write_strategy = \"merge\" needs a unique_key: the key columns, such as unique_key = [\"id\"], or unique_key = \"{primary_key}\"", - ..OK - }], - check_query: "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_schema = 'raw'", - expected_result: "0", - }, ScenarioTestCase { description: "merge on {primary_key} of a table with unique indexes but no primary key names its plain-column indexes and suggests the first never NULL", setup: "CREATE TABLE public.coded (code text, ref int8 NOT NULL, note text); diff --git a/crates/sqlload/tests/loader/test_sync_deletes.rs b/crates/sqlload/tests/loader/test_sync_deletes.rs index 838266920..83fadb30e 100644 --- a/crates/sqlload/tests/loader/test_sync_deletes.rs +++ b/crates/sqlload/tests/loader/test_sync_deletes.rs @@ -75,20 +75,12 @@ fn given_deletes_where_nothing_can_scan_when_planning_then_plan_fails_naming_the run_async(|| async move { let source = start_postgres().await?; let client = connect(&source).await?; - let test_cases = [ - SyncDeletesRefusalTestCase { - description: "--sync-deletes when no selected table sets deletes", - settings: "", - sync_deletes: true, - expected_error: "reason --sync-deletes reads every key of each selected table with deletes and marks its rows of the keys the source no longer holds, but none of the selected tables sets deletes └── fix set deletes = \"soft\" or \"hard\" on a merge table, or drop --sync-deletes", - }, - SyncDeletesRefusalTestCase { - description: "deletes on a delete_insert, which has no key to match", - settings: "deletes = \"soft\"", - sync_deletes: false, - expected_error: "deletes marks the rows whose unique_key the source no longer holds, which needs write_strategy = \"merge\"; delete_insert keeps no key to match", - }, - ]; + let test_cases = [SyncDeletesRefusalTestCase { + description: "--sync-deletes when no selected table sets deletes", + settings: "", + sync_deletes: true, + expected_error: "reason --sync-deletes reads every key of each selected table with deletes and marks its rows of the keys the source no longer holds, but none of the selected tables sets deletes └── fix set deletes = \"soft\" or \"hard\" on a merge table, or drop --sync-deletes", + }]; for test_case in &test_cases { let plan = sync_deletes_plan( (&client, source.port), diff --git a/crates/sqlload/tests/loader/test_typed_cursors.rs b/crates/sqlload/tests/loader/test_typed_cursors.rs index b427b75b5..c60a90060 100644 --- a/crates/sqlload/tests/loader/test_typed_cursors.rs +++ b/crates/sqlload/tests/loader/test_typed_cursors.rs @@ -302,32 +302,6 @@ fn given_a_lookback_that_does_not_fit_the_cursor_when_planning_then_plan_refuses check_query: "", expected_outcomes: &["refused => "], }, - TypedCursorTestCase { - description: "an integer lookback with append", - setup: FAMILIES, - settings: "include = [\"public.ledger\"]\n[sources.app.tables.\"public.ledger\"]\nwrite_strategy = \"append\"\ncursor_column = \"fiscal_year\"\nlookback = 1", - runs: &[TypedCursorRun { - expected_plan: &[ - "lookback re-inserts the window on every run with append; use delete_insert (no key needed) or merge", - ], - ..PLAN_ONLY - }], - check_query: "", - expected_outcomes: &["refused => "], - }, - TypedCursorTestCase { - description: "an integer lookback counted from now", - setup: FAMILIES, - settings: "include = [\"public.ledger\"]\n[sources.app.tables.\"public.ledger\"]\nwrite_strategy = \"delete_insert\"\ncursor_column = \"fiscal_year\"\nlookback = 1\nlookback_from = \"now\"", - runs: &[TypedCursorRun { - expected_plan: &[ - "lookback_from = \"now\" counts lookback back from the time of the run, so fiscal_year needs a duration lookback, such as lookback = \"1d\", not a number of cursor units", - ], - ..PLAN_ONLY - }], - check_query: "", - expected_outcomes: &["refused => "], - }, ]; for test_case in &test_cases { let outcomes = run_typed_cursors(&client, postgres.port, test_case).await?; diff --git a/website/src/content/docs/docs/cli/plan.mdx b/website/src/content/docs/docs/cli/plan.mdx index 391f935bd..6b3fff340 100644 --- a/website/src/content/docs/docs/cli/plan.mdx +++ b/website/src/content/docs/docs/cli/plan.mdx @@ -170,6 +170,27 @@ The sections, as `-v` shows them; without it, `Objects` counts a new table's col A table under `Errors` is left out; the others still run, and the command exits 1. +### Settings that don't combine + +Settings that don't combine are found as SQLLoad reads `sqlload.toml` and the Python sources, +before anything connects: a `merge` without a `unique_key`, a `cursor_column` on `replace`, +`lookback` with `append`, or a setting for another strategy. Then nothing runs. Every such table is +listed under `Errors` by its entry, and the command exits 1: + +```console +$ sqlload plan +Errors (2) +├── [sources.app.tables."public.customers"] +│ └── reason write_strategy = "replace" reloads the whole table, so it takes no cursor_column +└── [sources.app.tables."public.orders"] + └── reason write_strategy = "merge" needs a unique_key: the key columns, such as unique_key = ["id"], or unique_key = "{primary_key}" for the primary key the source reports + +✗ Plan failed 2 errors +``` + +A source that sets them for all its tables and lists none is named by `[sources.NAME]`, and a +Python table by its file, as `Python table orders (sources/shop.py)`. + ## Connecting and discovering `plan`, and the plan `apply` and `load` start with, times each target's and source's diff --git a/website/src/content/docs/docs/configuration.mdx b/website/src/content/docs/docs/configuration.mdx index 935a0c966..183ce7539 100644 --- a/website/src/content/docs/docs/configuration.mdx +++ b/website/src/content/docs/docs/configuration.mdx @@ -341,6 +341,8 @@ matches rows on the primary key, and a `unique_key` must lie within it. Set on a source for all its tables, or in a `[sources.NAME.tables."schema.table"]` entry for one. The `schema` in an entry's name is the source schema; where tables land is the source's `destination_schema`. +How a table's settings combine is checked when the project is read, before anything connects, so `plan`, `apply` and `load` stop on a mistake such as a `merge` without a `unique_key`. See [Settings that don't combine](/docs/cli/plan/#settings-that-dont-combine). + | Key | Default | Meaning | |-----|---------|---------| | `write_strategy` | required | `append`, `merge`, `delete_insert` or `replace`. Every table needs one, from its own entry or its source; `plan` refuses a table without it. See [Write strategies](/docs/concepts/write-strategies/). | From d5ea4126502ee76ab5febdc5cd47c4355f5e4a19 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:24:45 +0000 Subject: [PATCH 4/5] test: move settings-only refusals from the container tests to the parse test These combinations are refused when the project is parsed, which stops the whole command, so the container tests that expected plan to refuse one table no longer reach plan. Each case is a parse test case now (a masked newest_by column, a cursor on a delete_insert by replace_key, null_cursor = "include" on append and delete_insert, and on_overlapping_files on a merge, an append and a delete_insert by cursor), with the full message the container tests checked. The postgres_cdc files case that checks a source which cannot list its tables is refused while another source loads no longer declares a postgres_cdc source merging into a files target, which the project parse refuses; the parse test covers that. --- .../tests/test_option_problems.rs | 27 +++++++- crates/sqlload/tests/loader/merge/helpers.rs | 38 ------------ .../sqlload/tests/loader/test_merge_dedupe.rs | 62 +------------------ .../sqlload/tests/loader/test_null_cursors.rs | 13 +--- .../tests/loader/test_overlapping_files.rs | 29 --------- .../tests/loader/test_postgres_cdc_files.rs | 30 ++------- crates/sqlload/tests/loader/test_types.rs | 12 ---- 7 files changed, 34 insertions(+), 177 deletions(-) diff --git a/crates/sqlload/src/table_options/tests/test_option_problems.rs b/crates/sqlload/src/table_options/tests/test_option_problems.rs index 8a7a95a22..3156e2166 100644 --- a/crates/sqlload/src/table_options/tests/test_option_problems.rs +++ b/crates/sqlload/src/table_options/tests/test_option_problems.rs @@ -62,7 +62,7 @@ fn given_table_options_that_do_not_combine_when_parsing_a_toml_project_then_pars target: DUCKDB, source: POSTGRES_TABLE, settings: "write_strategy = \"delete_insert\"\nreplace_key = [\"version\"]\ncursor_column = \"updated_at\"\n", - expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column updated_at does not apply to delete_insert by replace_key", + expected_problem: "[sources.s.tables.\"public.t\"]: cursor_column updated_at does not apply to delete_insert by replace_key: a load deletes every row of each key value it reads, so the rows of a key value outside the cursor range, which it never reads, would be lost. Fix: drop cursor_column, so every load reads the whole source and replaces each key value it holds; or use write_strategy = \"merge\" on a unique_key to read by the cursor", }, TomlOptionsTestCase { description: "an empty cursor_column list", @@ -104,7 +104,14 @@ fn given_table_options_that_do_not_combine_when_parsing_a_toml_project_then_pars target: DUCKDB, source: POSTGRES_TABLE, settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\nnull_cursor = \"include\"\n", - expected_problem: "[sources.s.tables.\"public.t\"]: null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and append would append them again", + expected_problem: "[sources.s.tables.\"public.t\"]: null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and append would append them again on every run, duplicating them; use write_strategy = \"merge\" with a unique_key", + }, + TomlOptionsTestCase { + description: "null_cursor include on a delete_insert", + target: DUCKDB, + source: POSTGRES_TABLE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"updated_at\"\nnull_cursor = \"include\"\n", + expected_problem: "[sources.s.tables.\"public.t\"]: null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and they sit outside every cursor range delete_insert replaces, so it would insert them again on every run, duplicating them; use write_strategy = \"merge\" with a unique_key, or set null_cursor = \"ignore\" to skip them", }, TomlOptionsTestCase { description: "on_duplicate_keys on an append", @@ -132,7 +139,7 @@ fn given_table_options_that_do_not_combine_when_parsing_a_toml_project_then_pars target: DUCKDB, source: POSTGRES_TABLE, settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\nnewest_by = \"updated_at\"\nmask = { updated_at = \"hash\" }\n", - expected_problem: "[sources.s.tables.\"public.t\"]: newest_by column updated_at is masked", + expected_problem: "[sources.s.tables.\"public.t\"]: newest_by column updated_at is masked, so its values cannot say which row is newer", }, TomlOptionsTestCase { description: "newest_by with on_duplicate_keys fail", @@ -281,6 +288,20 @@ fn given_table_options_that_do_not_combine_when_parsing_a_toml_project_then_pars settings: "write_strategy = \"merge\"\nunique_key = [\"id\"]\non_overlapping_files = \"last_wins\"\n", expected_problem: "[sources.s]: on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value; a merge already lets the last file win each unique_key", }, + TomlOptionsTestCase { + description: "on_overlapping_files on a files append", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"append\"\non_overlapping_files = \"fail\"\n", + expected_problem: "[sources.s]: on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value; append replaces no key values, so remove it", + }, + TomlOptionsTestCase { + description: "on_overlapping_files on a files delete_insert by cursor", + target: DUCKDB, + source: FILES_SOURCE, + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"day\"\non_overlapping_files = \"last_wins\"\n", + expected_problem: "[sources.s]: on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value; this delete_insert replaces a cursor range, not key values, so remove it, or set replace_key", + }, TomlOptionsTestCase { description: "after_load on a replace", target: DUCKDB, diff --git a/crates/sqlload/tests/loader/merge/helpers.rs b/crates/sqlload/tests/loader/merge/helpers.rs index 87dbe6cce..df5d95a65 100644 --- a/crates/sqlload/tests/loader/merge/helpers.rs +++ b/crates/sqlload/tests/loader/merge/helpers.rs @@ -258,44 +258,6 @@ pub(crate) async fn run_replace_key_loads( Ok(rows) } -/// Plan and load `public.estimates` from Postgres on `postgres_port` (reached by `source`) into an in-memory DuckDB with `settings` added to its `delete_insert` by `replace_key`: the load's error, empty when it loads, and how many tables named `app__estimates` the target holds afterwards. -pub(crate) async fn replace_key_outcome( - (source, postgres_port): (&tokio_postgres::Client, u16), - settings: &str, -) -> Result<(String, Option), String> { - let text = estimates_project( - ("kind = \"duckdb\"\ndatabase = \":memory:\"", "raw"), - postgres_port, - settings, - ); - source - .batch_execute(ESTIMATES_SETUP) - .await - .map_err(|error| error.to_string())?; - let project = described_project(&text).await?; - let destinations = connect_targets(&project) - .await - .map_err(|error| error.to_string())?; - let destination = destinations - .get("dev") - .ok_or_else(|| "no dev destination".to_owned())?; - let error = load_selected(&project, &destinations, &[]) - .await - .err() - .unwrap_or_default(); - let tables = single_text( - destination, - "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_name = 'app__estimates'".to_owned(), - ) - .await - .map_err(|error| error.to_string())?; - source - .batch_execute("DROP TABLE public.estimates") - .await - .map_err(|error| error.to_string())?; - Ok((error, tables)) -} - /// The rows `target.check_query` returns after each rule of `RULES`, loaded from Postgres on `postgres_port` into `target`, each from a fresh table; `""` where it returns none. pub(crate) async fn run_dedupe_rules( target: &DedupeTargetTestCase, diff --git a/crates/sqlload/tests/loader/test_merge_dedupe.rs b/crates/sqlload/tests/loader/test_merge_dedupe.rs index 8f637e059..fa9e2ee7b 100644 --- a/crates/sqlload/tests/loader/test_merge_dedupe.rs +++ b/crates/sqlload/tests/loader/test_merge_dedupe.rs @@ -8,14 +8,13 @@ use sqlload_testkit::postgres::main::connect::connect; use sqlload_testkit::postgres::main::start_postgres::start_postgres; use sqlload_testkit::postgres::main::start_postgres_version::start_postgres_version; -use crate::helpers::{run_async, words}; +use crate::helpers::run_async; use crate::merge_helpers::{ - READINGS_SETUP, replace_key_outcome, run_dedupe_case, run_dedupe_rules, run_null_key_loads, - run_replace_key_loads, + READINGS_SETUP, run_dedupe_case, run_dedupe_rules, run_null_key_loads, run_replace_key_loads, }; use crate::test_types::{ DedupeRefusalTestCase, DedupeRule, DedupeTargetTestCase, NullKeyTargetTestCase, - ReplaceKeyRefusalTestCase, ReplaceKeyTargetTestCase, + ReplaceKeyTargetTestCase, }; /// What a merge on `(company, item, site)` holds after each of three loads, the source's `qty` growing by 10 between them: one row per key, NULL parts included, each with the latest load's value, and the empty key (`/`) apart from the NULL one. @@ -197,16 +196,6 @@ fn given_a_newest_by_column_it_cannot_compare_when_planning_then_plan_refuses_th .await .map_err(|error| error.to_string())?; let test_cases = [ - DedupeRefusalTestCase { - description: "a masked column", - rule: DedupeRule { - description: "a masked column", - settings: "newest_by = \"seen_at\"\nmask = { seen_at = \"hash\" }", - expected_error: "newest_by column seen_at is masked, so its values cannot say which row is newer", - expected_plan: "", - }, - expected_tables: "0", - }, DedupeRefusalTestCase { description: "a JSON column, which has no order", rule: DedupeRule { @@ -310,48 +299,3 @@ fn given_a_database_source_with_a_replace_key_and_no_cursor_when_loading_into_ea Ok(()) }) } - -#[test] -fn given_a_cursor_column_with_a_replace_key_on_a_database_source_when_planning_then_plan_refuses_it_naming_the_full_read() --> Result<(), String> { - run_async(|| async move { - let source = start_postgres().await?; - let client = connect(&source).await?; - let test_cases = [ - ReplaceKeyRefusalTestCase { - description: "a cursor would read part of a version's rows while the commit deletes all of them, so plan refuses it and creates no table", - settings: "cursor_column = \"updated_at\"", - expected_error: "cursor_column updated_at does not apply to delete_insert by replace_key: a load deletes every row of each key value it reads, so the rows of a key value outside the cursor range, which it never reads, would be lost", - expected_fix: "drop cursor_column, so every load reads the whole source and replaces each key value it holds; or use write_strategy = \"merge\" on a unique_key to read by the cursor", - expected_tables: "0", - }, - ReplaceKeyRefusalTestCase { - description: "without a cursor the table is read whole and loads", - settings: "", - expected_error: "", - expected_fix: "", - expected_tables: "1", - }, - ]; - for test_case in &test_cases { - let (error, tables) = - replace_key_outcome((&client, source.port), test_case.settings).await?; - assert_eq!( - ( - words(&error).contains(&words(test_case.expected_error)) - && words(&error).contains(&words(test_case.expected_fix)), - error.is_empty(), - tables.as_deref(), - ), - ( - true, - test_case.expected_error.is_empty(), - Some(test_case.expected_tables) - ), - "{}: {error}", - test_case.description - ); - } - Ok(()) - }) -} diff --git a/crates/sqlload/tests/loader/test_null_cursors.rs b/crates/sqlload/tests/loader/test_null_cursors.rs index cef39a071..cbd7ac693 100644 --- a/crates/sqlload/tests/loader/test_null_cursors.rs +++ b/crates/sqlload/tests/loader/test_null_cursors.rs @@ -212,8 +212,7 @@ null_cursor = "ignore" } #[test] -fn given_a_null_cursor_rule_when_planning_then_the_reads_line_names_it_and_include_is_refused_where_it_would_duplicate_rows() --> Result<(), String> { +fn given_a_null_cursor_rule_when_planning_then_the_reads_line_names_it() -> Result<(), String> { let test_cases = [ NullCursorPlanTestCase { description: "by default the reads line says a NULL cursor fails the load, as the source reports updated_at nullable", @@ -235,16 +234,6 @@ fn given_a_null_cursor_rule_when_planning_then_the_reads_line_names_it_and_inclu settings: "write_strategy = \"merge\"\nunique_key = \"{primary_key}\"\ncursor_column = [\"updated_at\", \"created_at\"]", expected_plan: "reads coalesce(updated_at, created_at): first run, everything (NULL cursors: fail the load)", }, - NullCursorPlanTestCase { - description: "null_cursor = \"include\" on append is refused, as every run would append the NULL rows again", - settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\nnull_cursor = \"include\"", - expected_plan: "null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and append would append them again on every run, duplicating them; use write_strategy = \"merge\" with a unique_key", - }, - NullCursorPlanTestCase { - description: "null_cursor = \"include\" on delete_insert is refused, as no range it replaces holds the NULL rows", - settings: "write_strategy = \"delete_insert\"\ncursor_column = \"updated_at\"\nnull_cursor = \"include\"", - expected_plan: "null_cursor = \"include\" reads the rows whose updated_at is NULL on every run, and they sit outside every cursor range delete_insert replaces, so it would insert them again on every run, duplicating them; use write_strategy = \"merge\" with a unique_key, or set null_cursor = \"ignore\" to skip them", - }, NullCursorPlanTestCase { description: "coalescing a timestamp with text is refused", settings: "write_strategy = \"merge\"\nunique_key = \"{primary_key}\"\ncursor_column = [\"updated_at\", \"v\"]", diff --git a/crates/sqlload/tests/loader/test_overlapping_files.rs b/crates/sqlload/tests/loader/test_overlapping_files.rs index 51028bcd0..d2704dc4d 100644 --- a/crates/sqlload/tests/loader/test_overlapping_files.rs +++ b/crates/sqlload/tests/loader/test_overlapping_files.rs @@ -9,10 +9,6 @@ use crate::test_types::{FilesMergeTestCase, MergeFile, MergeStep}; /// Every row as `version:line:amount`, then how many file commits the run log records. const CHECK: &str = "SELECT (SELECT COALESCE(string_agg(COALESCE(le_version, 'NULL') || ':' || line || ':' || CAST(amount AS VARCHAR), ',' ORDER BY le_version NULLS LAST, line), '') FROM raw.scores) || '|' || (SELECT CAST(count(*) AS VARCHAR) FROM raw._sqlload_runs WHERE table_name = 'scores' AND event = 'run')"; -/// No table is created when plan refuses the settings. -const NO_TABLE: &str = - "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_name = 'scores'"; - const LAST_WINS: &str = "write_strategy = \"delete_insert\"\nreplace_key = [\"le_version\"]\non_overlapping_files = \"last_wins\"\n"; const LAST_WINS_BY_PATH: &str = "write_strategy = \"delete_insert\"\nreplace_key = [\"le_version\"]\non_overlapping_files = \"last_wins\"\norder = \"path\"\n"; @@ -35,8 +31,6 @@ const SECOND: MergeFile = MergeFile { const LAST_WINS_PLAN: &str = "2 files, 1 commit, oldest modified first (ties by path), each recorded in the run log; the last file holding a replace_key value replaces it (on_overlapping_files = \"last_wins\")"; -const OUTSIDE: &str = "on_overlapping_files says which file wins when two files of a files source's folder hold one replace_key value"; - const ONE_RUN: &[MergeStep] = &[load_step(&[FIRST, SECOND], "", LAST_WINS_PLAN)]; const TWO_RUNS: &[MergeStep] = &[load_step(&[FIRST], "", ""), load_step(&[SECOND], "", "")]; @@ -65,8 +59,6 @@ const SPLIT: &[MergeStep] = &[load_step( "", )]; -const REFUSED: &[MergeStep] = &[load_step(&[FIRST], OUTSIDE, "")]; - /// The newer file loads first, and the older one, by path, arrives in a later run. const SENT_LATE: &[MergeStep] = &[ load_step( @@ -167,27 +159,6 @@ fn given_files_holding_one_replace_key_value_when_loading_into_duckdb_then_on_ov check_query: CHECK, expected_result: "P01:A:1,P01:B:2,P02:A:10|1", }, - FilesMergeTestCase { - description: "plan refuses it on a merge, where the last file already wins each key", - settings: "write_strategy = \"merge\"\nunique_key = [\"le_version\", \"line\"]\non_overlapping_files = \"last_wins\"\n", - steps: REFUSED, - check_query: NO_TABLE, - expected_result: "0", - }, - FilesMergeTestCase { - description: "plan refuses it on an append", - settings: "write_strategy = \"append\"\non_overlapping_files = \"fail\"\n", - steps: REFUSED, - check_query: NO_TABLE, - expected_result: "0", - }, - FilesMergeTestCase { - description: "plan refuses it on a delete_insert by cursor", - settings: "write_strategy = \"delete_insert\"\ncursor_column = \"le_version\"\non_overlapping_files = \"last_wins\"\n", - steps: REFUSED, - check_query: NO_TABLE, - expected_result: "0", - }, ]; for test_case in &test_cases { let result = run_merge_case( diff --git a/crates/sqlload/tests/loader/test_postgres_cdc_files.rs b/crates/sqlload/tests/loader/test_postgres_cdc_files.rs index 894c4c626..3e58f8c13 100644 --- a/crates/sqlload/tests/loader/test_postgres_cdc_files.rs +++ b/crates/sqlload/tests/loader/test_postgres_cdc_files.rs @@ -47,32 +47,14 @@ destination_path = "parts/{table}/{cursor:date}/" description = "Items, captured." "#; -const FILES_MERGED: &str = r#" -[sources.merged] -kind = "postgres_cdc" -connection = "pg" -include = ["public.items"] - -[sources.merged.tables."public.items"] -description = "Items, merged." - +const FILES_UNLISTED: &str = r#" [sources.down] kind = "postgres" connection = "pg" include = ["public.["] "#; -const MERGE_REFUSED: (bool, &str) = ( - false, - "a files target takes kind = \"postgres_cdc\" only with cdc_mode = \"changelog\"", -); - -const FILES_MERGE_REFUSED: [CdcStep; 8] = [ - step("", &["plan", "merged"], "", MERGE_REFUSED), - step("", &["plan", "merged__items"], "", MERGE_REFUSED), - step("", &["plan", "public.items"], "", MERGE_REFUSED), - step("", &["plan"], "", MERGE_REFUSED), - step("", &["load", "merged", "--follow"], "", MERGE_REFUSED), +const FILES_UNLISTED_REFUSED: [CdcStep; 3] = [ step( "", &["plan", "down"], @@ -81,7 +63,7 @@ const FILES_MERGE_REFUSED: [CdcStep; 8] = [ ), step( "", - &["plan", "--exclude", "merged__items", "--exclude", "down"], + &["plan", "--exclude", "down"], "", (true, "Plan complete"), ), @@ -244,12 +226,12 @@ fn given_a_postgres_cdc_changelog_into_files_when_loads_stop_at_each_restart_poi expected_result: CHANGELOG_RESULT, }, CdcFilesTestCase { - description: "a source merging its changes, or one that cannot list its tables, is refused when selected, and a load of another source goes ahead", + description: "a source that cannot list its tables is refused when selected, and a load of another source goes ahead", tag: "17-alpine", - steps: &FILES_MERGE_REFUSED, + steps: &FILES_UNLISTED_REFUSED, store: local_store, spill_bytes: "", - extra_config: FILES_MERGED, + extra_config: FILES_UNLISTED, plant: nothing_planted, check_query: "SELECT CAST((SELECT count(*) FROM glob('{root}/out/merged/**')) AS VARCHAR) || ':' || CAST((SELECT count(*) > 0 FROM glob('{root}/out/log/orders/*.parquet')) AS VARCHAR)", expected_result: "0:true", diff --git a/crates/sqlload/tests/loader/test_types.rs b/crates/sqlload/tests/loader/test_types.rs index b6c7aa32b..dee4b9616 100644 --- a/crates/sqlload/tests/loader/test_types.rs +++ b/crates/sqlload/tests/loader/test_types.rs @@ -1191,18 +1191,6 @@ pub(crate) struct DedupeTargetTestCase { pub(crate) expected_rows: [&'static str; 4], } -/// A `delete_insert` by `replace_key` on a database source with `settings` added, and what plan says of it. -pub(crate) struct ReplaceKeyRefusalTestCase { - pub(crate) description: &'static str, - pub(crate) settings: &'static str, - /// Text the load's error must contain; empty when it must load. - pub(crate) expected_error: &'static str, - /// Text the error's fix must contain. - pub(crate) expected_fix: &'static str, - /// How many tables named `app__estimates` the target holds afterwards. - pub(crate) expected_tables: &'static str, -} - /// A target that `delete_insert` with a cursor and a `replace_key` loads Postgres rows into twice. pub(crate) struct ReplaceKeyTargetTestCase { pub(crate) description: &'static str, From bdbbd9efbe4687165db1b05f1f6f0bd690a1092e Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:10:32 +0000 Subject: [PATCH 5/5] ci: install this build's sqlload-api beside the sqlload wheel in the smoke tests The wheel smoke tests installed the sqlload wheel with --find-links dist. Before Release Please bumps the version, the branch's sqlload-api has the version of the release already on PyPI, so pip took PyPI's copy, which lacks this branch's modules. Each install now names dist's sqlload_api wheel too: the smoke test on every OS, its Linux ODBC container, and the MySQL Connector/ODBC smoke script. The Makefile already installs the local package, and published-smoke.yml keeps installing from PyPI. --- .github/scripts/smoke_mysql_odbc_wheel.sh | 3 ++- .github/workflows/publish.yml | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/scripts/smoke_mysql_odbc_wheel.sh b/.github/scripts/smoke_mysql_odbc_wheel.sh index 919167fef..c17ab47b0 100755 --- a/.github/scripts/smoke_mysql_odbc_wheel.sh +++ b/.github/scripts/smoke_mysql_odbc_wheel.sh @@ -55,7 +55,8 @@ 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 --find-links /dist /dist/sqlload-*.whl +# This build's sqlload-api wheel by name, so pip never takes a release of the same version from PyPI. +python -m venv /v && /v/bin/pip install --quiet /dist/sqlload_api-*.whl /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. diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c78e939c6..015ae30ad 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -339,7 +339,8 @@ 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. + # The sqlload wheel pins sqlload-api at its own version. Both wheels are named on each install, so + # pip takes this build's sqlload-api, never a release of the same version from PyPI. - uses: actions/download-artifact@v5 with: name: sqlload-api @@ -350,7 +351,7 @@ jobs: python -m venv smoke bin=smoke/bin if [[ "${RUNNER_OS}" == "Windows" ]]; then bin=smoke/Scripts; fi - "${bin}/python" -m pip install --quiet --find-links dist dist/sqlload-*.whl + "${bin}/python" -m pip install --quiet dist/sqlload_api-*.whl dist/sqlload-*.whl "${bin}/sqlload" --help "${bin}/sqll" --help > /dev/null "${bin}/python" -c "import sqlload, sqlload._native" @@ -366,7 +367,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 --find-links dist dist/sqlload-*.whl && + python -m venv /v && /v/bin/pip install --quiet dist/sqlload_api-*.whl 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"' ;;