diff --git a/.github/scripts/assert_sdist_sources.sh b/.github/scripts/assert_sdist_sources.sh index d501c0d03..b92ec2706 100755 --- a/.github/scripts/assert_sdist_sources.sh +++ b/.github/scripts/assert_sdist_sources.sh @@ -11,7 +11,12 @@ sha256="$(sed -n 's/^UNIXODBC_SHA256=//p' "$pins")" name="unixODBC-${version}.tar.gz" shopt -s nullglob -sdists=("$1"/*.tar.gz) +sdists=() +for sdist in "$1"/*.tar.gz; do + # sqlload-api is pure Python, with no wheel bundling unixODBC, so its sdist carries none of its source. + case "$(basename "$sdist")" in sqlload_api-*) continue ;; esac + sdists+=("$sdist") +done if [ "${#sdists[@]}" -eq 0 ]; then echo "no sdists in $1" >&2 exit 1 diff --git a/.github/scripts/assert_wheel_notices.sh b/.github/scripts/assert_wheel_notices.sh index 575664e13..7fbd5b02b 100755 --- a/.github/scripts/assert_wheel_notices.sh +++ b/.github/scripts/assert_wheel_notices.sh @@ -7,7 +7,12 @@ set -euo pipefail python="$(command -v python3 || command -v python)" shopt -s nullglob -wheels=("$1"/*.whl) +wheels=() +for wheel in "$1"/*.whl; do + # sqlload-api is pure Python: it bundles nothing, so it carries no notice of unixODBC. + case "$(basename "$wheel")" in sqlload_api-*) continue ;; esac + wheels+=("$wheel") +done if [ "${#wheels[@]}" -eq 0 ]; then echo "no wheels in $1" >&2 exit 1 diff --git a/.github/scripts/smoke_mysql_odbc_wheel.sh b/.github/scripts/smoke_mysql_odbc_wheel.sh index 8ed9ba422..919167fef 100755 --- a/.github/scripts/smoke_mysql_odbc_wheel.sh +++ b/.github/scripts/smoke_mysql_odbc_wheel.sh @@ -55,7 +55,7 @@ curl -fsSL --retry 3 --retry-all-errors -o "/tmp/$package" "https://cdn.mysql.co curl -fsSL --retry 3 --retry-all-errors -o "/tmp/$package" "https://downloads.mysql.com/archives/get/p/10/file/$package" echo "$MYSQL_ODBC_SHA256 /tmp/$package" | sha256sum -c --quiet - apt-get -o Acquire::Retries=3 install -y -qq "/tmp/$package" > /dev/null -python -m venv /v && /v/bin/pip install --quiet /dist/sqlload-*.whl +python -m venv /v && /v/bin/pip install --quiet --find-links /dist /dist/sqlload-*.whl python -m venv /c && /c/bin/pip install --quiet /dist/sqlload_cli-*.whl # Load into a fresh project with SQLLOAD (and the environment before it); print what it said. diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0ae5ee730..6db63b03e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -88,8 +88,12 @@ jobs: manifests = [ ("Python package", project_version("packages/sqlload/pyproject.toml")), ("CLI package", project_version("packages/sqlload-cli/pyproject.toml")), + ("API package", project_version("packages/sqlload-api/pyproject.toml")), ("Cargo workspace", workspace_version), ] + with Path("packages/sqlload/pyproject.toml").open("rb") as file: + pins = [d for d in tomllib.load(file)["project"]["dependencies"] if d.startswith("sqlload-api")] + manifests.append(("Python package's sqlload-api pin", pins[0].partition("==")[2] if pins else "missing")) mismatches = [f"{label}={version}" for label, version in manifests if version != expected] if mismatches: raise SystemExit( @@ -271,10 +275,35 @@ jobs: name: wheel-${{ matrix.platform.name }}-${{ matrix.package.id }} path: dist + # sqlload-api is pure Python: one wheel for every platform, and its sdist; every sqlload wheel pins it. + api: + name: Build sqlload-api + needs: [release-tag, release-metadata] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ needs.release-tag.outputs.tag }} + - uses: astral-sh/setup-uv@v6 + with: + version: "0.12.9" + - name: Build the wheel and sdist + run: uv build packages/sqlload-api --out-dir dist + - name: Assert the wheel is pure Python and imports without the engine + run: | + ls dist/sqlload_api-*-py3-none-any.whl + python3 -m venv api + api/bin/pip install --quiet dist/sqlload_api-*.whl + api/bin/python -c "import sys, sqlload_api; assert not any(m.split('.')[0] == 'sqlload' for m in sys.modules)" + - uses: actions/upload-artifact@v5 + with: + name: sqlload-api + path: dist + # Each platform's two wheels, installed and run natively: the Intel Mac's on an Intel runner. wheel-smoke: name: Smoke-test wheels (${{ matrix.platform.name }}) - needs: [release-tag, wheels] + needs: [release-tag, wheels, api] runs-on: ${{ matrix.platform.runner }} strategy: fail-fast: false @@ -304,13 +333,18 @@ jobs: pattern: wheel-${{ matrix.platform.name }}-* path: dist merge-multiple: true + # The sqlload wheel pins sqlload-api at its own version, which installs from here. + - uses: actions/download-artifact@v5 + with: + name: sqlload-api + path: dist - name: Smoke-test the wheels shell: bash run: | python -m venv smoke bin=smoke/bin if [[ "${RUNNER_OS}" == "Windows" ]]; then bin=smoke/Scripts; fi - "${bin}/python" -m pip install --quiet dist/sqlload-*.whl + "${bin}/python" -m pip install --quiet --find-links dist dist/sqlload-*.whl "${bin}/sqlload" --help "${bin}/sqll" --help > /dev/null "${bin}/python" -c "import sqlload, sqlload._native" @@ -326,7 +360,7 @@ jobs: case "${RUNNER_OS}" in Linux) docker run --rm -v "$PWD:/w" -w /w python:3.12-slim bash -c ' - python -m venv /v && /v/bin/pip install --quiet dist/sqlload-*.whl && + python -m venv /v && /v/bin/pip install --quiet --find-links dist dist/sqlload-*.whl && python -m venv /c && /c/bin/pip install --quiet dist/sqlload_cli-*.whl && /v/bin/python .github/scripts/smoke_odbc_wheel.py /v/bin/sqlload /c/bin/sqlload --default-ini /etc/odbcinst.ini --driver-folder "/usr/lib/$(uname -m)-linux-gnu/odbc"' ;; @@ -386,6 +420,7 @@ jobs: - wheels - wheel-smoke - sdist + - api runs-on: ubuntu-latest environment: pypi permissions: @@ -416,6 +451,17 @@ jobs: shell: bash run: bash .github/scripts/assert_sdist_sources.sh dist + # sqlload pins sqlload-api at its own version, so sqlload-api goes up first: `pip install sqlload==` + # resolves as soon as sqlload is listed. + - name: Set sqlload-api's files apart + run: mkdir dist-api && mv dist/sqlload_api-* dist-api/ + + - name: Publish sqlload-api to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist-api + skip-existing: true + - name: Publish to PyPI uses: pypa/gh-action-pypi-publish@release/v1 with: diff --git a/.github/workflows/published-smoke.yml b/.github/workflows/published-smoke.yml index 87d1352ba..b78eb038c 100644 --- a/.github/workflows/published-smoke.yml +++ b/.github/workflows/published-smoke.yml @@ -63,6 +63,18 @@ jobs: echo "PyPI's index still lacks files of ${package} ${VERSION} after 180 attempts" exit 1 done + # sqlload-api is pure Python: one wheel for every platform, and its sdist. + for attempt in $(seq 1 180); do + listed=$(curl -fsS -H "Accept: application/vnd.pypi.simple.v1+json" "https://pypi.org/simple/sqlload-api/" | jq -r '.files[].filename' || true) + if grep -qx "sqlload_api-${VERSION}-py3-none-any.whl" <<< "$listed" && grep -qx "sqlload_api-${VERSION}.tar.gz" <<< "$listed"; then + echo "PyPI's index lists sqlload-api ${VERSION} (attempt ${attempt})" + exit 0 + fi + echo "attempt ${attempt}: sqlload-api ${VERSION} is not listed yet" + sleep 60 + done + echo "PyPI's index still lacks sqlload-api ${VERSION} after 180 attempts" + exit 1 smoke: name: Smoke (${{ matrix.platform.name }}) diff --git a/Makefile b/Makefile index 3d3115dc2..f9ec1bd3a 100644 --- a/Makefile +++ b/Makefile @@ -50,12 +50,14 @@ test-clickhouse-latest: test-clickhouse-older: SQLLOAD_TEST_CLICKHOUSE_TAG=$(CLICKHOUSE_OLDER) AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test cargo test -p sqlload --features container-tests,odbc --test loader --quiet -- to_clickhouse --test-threads=2 -# Builds the sqlload extension (debug) into .venv and runs the package's tests. +# Installs sqlload-api (pure Python, which sqlload pins) and builds the sqlload extension (debug) into .venv, and runs +# both packages' tests. test-python: uv venv --quiet --allow-existing --python 3.12 .venv uv pip install --quiet --python .venv/bin/python 'maturin>=1.9,<2' pytest pytest-xdist pyarrow polars pandas orjson duckdb + uv pip install --quiet --python .venv/bin/python -e packages/sqlload-api cd packages/sqlload && VIRTUAL_ENV=$(CURDIR)/.venv $(CURDIR)/.venv/bin/maturin develop --uv --quiet --features odbc - .venv/bin/python -m pytest packages/sqlload/tests -n auto --dist loadfile + .venv/bin/python -m pytest packages/sqlload-api/tests packages/sqlload/tests -n auto --dist loadfile test: test-unit test-containers @@ -66,12 +68,13 @@ verify: check-ci test bench-perf: cargo bench -p sqlload-benches --bench hot_paths --quiet -- $(BENCH_ARGS) -# The sqlload wheel, built from this tree with release settings, in the harness's environment. +# The sqlload wheel, built from this tree with release settings, in the harness's environment, with the sqlload-api it +# pins installed from this tree too (it reaches PyPI only with the release). bench-wheel: cd benchmarks && uv sync --quiet --locked $(BENCH_GROUPS) rm -rf benchmarks/.wheels cd packages/sqlload && VIRTUAL_ENV=$(CURDIR)/benchmarks/.venv $(CURDIR)/benchmarks/.venv/bin/maturin build --release --quiet --out $(CURDIR)/benchmarks/.wheels - uv pip install --quiet --python benchmarks/.venv/bin/python --reinstall --no-deps benchmarks/.wheels/*.whl + uv pip install --quiet --python benchmarks/.venv/bin/python --reinstall --no-deps ./packages/sqlload-api benchmarks/.wheels/*.whl # Compares sqlload with dlt and ingestr (needs Docker); on demand, not in CI. Results go to # BENCH_OUT; BENCH_ARGS takes the harness's options (see benchmarks/README.md). diff --git a/crates/sqlload-python/src/bindings/main/native_module.rs b/crates/sqlload-python/src/bindings/main/native_module.rs index 7f653dfee..3a39caf8e 100644 --- a/crates/sqlload-python/src/bindings/main/native_module.rs +++ b/crates/sqlload-python/src/bindings/main/native_module.rs @@ -5,7 +5,7 @@ use pyo3::{Bound, PyResult, pymodule, wrap_pyfunction}; use crate::bindings::_helpers::cross::cross; use crate::bindings::_helpers::run_cli::{run_cli, run_cli_captured, run_stopped}; -use crate::bindings::models::{BatchStream, JsonData}; +use crate::bindings::models::BatchStream; /// Register `sqlload._native`'s functions and classes. #[pymodule] @@ -15,7 +15,6 @@ pub fn native_module(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_function(wrap_pyfunction!(run_cli_captured, module)?)?; module.add_function(wrap_pyfunction!(run_stopped, module)?)?; module.add_function(wrap_pyfunction!(cross, module)?)?; - module.add_class::()?; module.add_class::()?; Ok(()) } diff --git a/crates/sqlload-python/src/bindings/models.rs b/crates/sqlload-python/src/bindings/models.rs index 29746df2f..7746348d2 100644 --- a/crates/sqlload-python/src/bindings/models.rs +++ b/crates/sqlload-python/src/bindings/models.rs @@ -5,80 +5,14 @@ use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::SchemaRef; use pyo3::exceptions::{PyConnectionError, PyRuntimeError, PyValueError}; -use pyo3::pybacked::PyBackedBytes; use pyo3::types::{PyAnyMethods, PyDict, PyDictMethods, PyList, PyListMethods}; use pyo3::{Bound, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; use sqlload::row_batches::main::conform_batch::conform_batch; -use sqlload::row_batches::main::projection::projection; use sqlload::row_batches::main::settled_schema::settled_schema; -use sqlload::row_batches::models::{FieldSpec, JsonLayout, Projection}; use crate::crossing::errors::CrossError; use crate::crossing::models::{Polled, TableBatches}; -/// JSON or NDJSON bytes yielded by a table function (`sl.json(...)`, `sl.ndjson(...)`), parsed in Rust without the GIL. -#[derive(Debug)] -#[pyclass(frozen, module = "sqlload._native", name = "JsonData")] -pub struct JsonData { - pub(crate) bytes: PyBackedBytes, - pub(crate) layout: JsonLayout, - pub(crate) path: Option, - /// The columns each row loads as, when only some of its values load. - pub(crate) projection: Option, -} - -#[pymethods] -impl JsonData { - /// `data` as one JSON document (rows at dotted `path`, or the whole document), or as NDJSON when `lines`; `fields` (a JSON list of `sl.field` specs: name, path, required, parse, on_error) and `keep_record` project each row. - #[new] - #[pyo3(signature = (data, *, lines = false, path = None, fields = None, keep_record = None))] - fn new( - data: PyBackedBytes, - lines: bool, - path: Option, - fields: Option, - keep_record: Option, - ) -> PyResult { - let fields = fields - .map(|text| serde_json::from_str::>(&text)) - .transpose() - .map_err(|error| PyValueError::new_err(format!("fields: {error}")))?; - let projection = - projection(fields.as_deref(), keep_record.as_deref()).map_err(PyValueError::new_err)?; - let layout = match (lines, &path) { - (true, Some(_)) => { - return Err(PyValueError::new_err( - "path picks rows out of a JSON document; NDJSON has none", - )); - } - (true, None) => JsonLayout::Lines, - (false, _) => JsonLayout::Document, - }; - Ok(Self { - bytes: data, - layout, - path, - projection, - }) - } - - /// Whether the bytes are NDJSON. - #[getter] - fn lines(&self) -> bool { - self.layout == JsonLayout::Lines - } - - /// The dotted path to the rows inside the document, if any. - #[getter] - fn path(&self) -> Option { - self.path.clone() - } - - fn __len__(&self) -> usize { - self.bytes.len() - } -} - /// The Arrow batches of one table generator, as `pyarrow.RecordBatch`es (the crossing's test hook). #[derive(Debug)] #[pyclass(module = "sqlload._native", name = "BatchStream")] diff --git a/crates/sqlload-python/src/crossing/_helpers/producer.rs b/crates/sqlload-python/src/crossing/_helpers/producer.rs index 22867ae78..99e99473e 100644 --- a/crates/sqlload-python/src/crossing/_helpers/producer.rs +++ b/crates/sqlload-python/src/crossing/_helpers/producer.rs @@ -5,18 +5,19 @@ use std::time::Instant; use arrow_array::RecordBatch; use arrow_array::ffi_stream::RecordBatchStreamReader; use arrow_pyarrow::FromPyArrow; -use pyo3::exceptions::{PyImportError, PyTypeError}; +use pyo3::exceptions::{PyImportError, PyTypeError, PyValueError}; use pyo3::pybacked::PyBackedBytes; use pyo3::types::{ PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, PyTypeMethods, }; use pyo3::{Bound, Py, PyAny, PyResult, Python}; +use sqlload::python_sources::constants::{CHECKPOINT_METHOD, HTTP_JOB_METHOD, JSON_DATA_METHOD}; +use sqlload::row_batches::main::json_read_spec::json_read_spec; use sqlload::row_batches::models::{JsonLayout, JsonRead}; -use crate::bindings::models::JsonData; use crate::crossing::_helpers::parser::{panic_if, panicked}; use crate::crossing::_helpers::walk::{holds_nonfinite, walk_rows}; -use crate::crossing::constants::{CHECKPOINT_METHOD, CROSSING_DEFAULT, HTTP_JOB_METHOD}; +use crate::crossing::constants::CROSSING_DEFAULT; use crate::crossing::errors::CrossError; use crate::crossing::models::{ Crossed, CrossingOptions, CrossingStats, DictCrossing, Dispatch, PanicSite, @@ -120,15 +121,11 @@ impl<'py> Producer<'py> { if let Ok(rows) = item.cast::() { return self.take_list(rows); } - if let Ok(json) = item.cast::() { - let json = json.get(); - let read = JsonRead { - layout: json.layout, - path: json.path.clone(), - batch_rows: self.options.batch_rows, - projection: json.projection.clone(), - }; - let bytes = json.bytes.clone_ref(self.py); + if item.hasattr(JSON_DATA_METHOD)? { + let (bytes, spec): (PyBackedBytes, String) = + item.call_method0(JSON_DATA_METHOD)?.extract()?; + let read = + json_read_spec(&spec, self.options.batch_rows).map_err(PyValueError::new_err)?; return Ok(self.flush()? && self.send(Crossed::Json { bytes, read })?); } if item.hasattr(HTTP_JOB_METHOD)? { diff --git a/crates/sqlload-python/src/crossing/constants.rs b/crates/sqlload-python/src/crossing/constants.rs index 2753479a6..cca0a93c5 100644 --- a/crates/sqlload-python/src/crossing/constants.rs +++ b/crates/sqlload-python/src/crossing/constants.rs @@ -16,11 +16,5 @@ pub(crate) const MICROS_PER_SECOND: i64 = 1_000_000; /// The `sqlload._runtime` function orjson calls for values it cannot write itself. pub(crate) const CROSSING_DEFAULT: &str = "crossing_default"; -/// The method of an `sl.http` job that returns its definition as JSON. -pub(crate) const HTTP_JOB_METHOD: &str = "__sqlload_http_job__"; - -/// The method of an `sl.checkpoint` that returns its state as JSON. -pub(crate) const CHECKPOINT_METHOD: &str = "__sqlload_checkpoint__"; - /// How long a page `transform`'s crossing is waited on at a time; it polls again until the function's output ends. pub(crate) const PAGE_POLL: std::time::Duration = std::time::Duration::from_secs(3600); diff --git a/crates/sqlload-testkit/src/doc_pages/_helpers/output.rs b/crates/sqlload-testkit/src/doc_pages/_helpers/output.rs index 4611ff193..36790ba6e 100644 --- a/crates/sqlload-testkit/src/doc_pages/_helpers/output.rs +++ b/crates/sqlload-testkit/src/doc_pages/_helpers/output.rs @@ -2,7 +2,7 @@ use regex::Regex; -use crate::doc_pages::constants::{ELISION, VOLATILE}; +use crate::doc_pages::constants::{ELISION, TALLY_VERBS, VOLATILE}; /// What the page should show of `actual`: all of it, or around a `…` line the page's line counts. pub(crate) fn shown_output(expected: &[String], actual: &[String]) -> Vec { @@ -19,7 +19,7 @@ pub(crate) fn shown_output(expected: &[String], actual: &[String]) -> Vec Result, String> { let mut patterns: Vec<(Regex, &str)> = Vec::new(); for (pattern, replacement) in VOLATILE { @@ -34,7 +34,26 @@ pub(crate) fn normalized(lines: &[String]) -> Result, String> { } normalized.push(text.trim().to_owned()); } - Ok(normalized) + Ok(tally_runs_sorted(normalized)) +} + +/// `lines` with each run of adjacent tally lines (`loaded`, `failed`, `skipped`) sorted: `load` prints a table's line as the table finishes, so tables loading at once print in no fixed order; which tables, and what each line says, still have to match. +pub(crate) fn tally_runs_sorted(lines: Vec) -> Vec { + let tally = |line: &String| TALLY_VERBS.iter().any(|verb| line.starts_with(verb)); + let mut sorted: Vec = Vec::with_capacity(lines.len()); + let mut run: Vec = Vec::new(); + for line in lines { + if tally(&line) { + run.push(line); + continue; + } + run.sort(); + sorted.append(&mut run); + sorted.push(line); + } + run.sort(); + sorted.append(&mut run); + sorted } /// A difference between the page's lines and a run's, for a failure message. diff --git a/crates/sqlload-testkit/src/doc_pages/constants.rs b/crates/sqlload-testkit/src/doc_pages/constants.rs index 9e5f56054..d1ff3db8b 100644 --- a/crates/sqlload-testkit/src/doc_pages/constants.rs +++ b/crates/sqlload-testkit/src/doc_pages/constants.rs @@ -14,6 +14,9 @@ pub const VOLATILE: &[(&str, &str)] = &[ (r"\s+", " "), ]; +/// How a load's tally line for one table starts, once normalized: the lines `load` prints as each table finishes. +pub const TALLY_VERBS: &[&str] = &["loaded ", "failed ", "skipped "]; + /// The Postgres image a page's `docker run` starts. pub const PAGE_POSTGRES_IMAGE: (&str, &str) = ("postgres", "17"); diff --git a/crates/sqlload/src/adapters/bigquery/_helpers/dialect/sql_adapter.rs b/crates/sqlload/src/adapters/bigquery/_helpers/dialect/sql_adapter.rs index 640b4048a..6a4c4e83a 100644 --- a/crates/sqlload/src/adapters/bigquery/_helpers/dialect/sql_adapter.rs +++ b/crates/sqlload/src/adapters/bigquery/_helpers/dialect/sql_adapter.rs @@ -11,6 +11,7 @@ use crate::adapters::contract::models::{ }; use crate::adapters::contract::types::SqlAdapter; use crate::column_types::models::{ColumnType, LiveColumnType, Warehouse, WarehouseType}; +use crate::schema_plan::models::LiveColumn; impl SqlAdapter for BigQuerySql { fn warehouse(&self) -> Warehouse { @@ -246,4 +247,85 @@ impl SqlAdapter for BigQuerySql { self.render_staging_filter(&format!("{STAGING_SUFFIX}_")) ) } + + /// From the dataset's `INFORMATION_SCHEMA.COLUMNS`, in the table's own project, else `database`: a caller's session has no `tables.get`. + fn render_describe_table(&self, table: &TableName, database: Option<&str>) -> Option { + let project = table.database.as_deref().or(database)?; + Some(format!( + "SELECT column_name, data_type FROM {}.{}.INFORMATION_SCHEMA.COLUMNS WHERE table_name = {} ORDER BY ordinal_position", + self.render_identifier(project), + self.render_identifier(&table.schema), + self.render_loader_value_literal(&table.table) + )) + } + + /// `INFORMATION_SCHEMA` writes sizes into the type (`NUMERIC(10, 2)`, `STRING(20)`) and spells records out (`STRUCT`): read as `tables.get` gives them, a record as `STRUCT`. + fn describe_text_rows(&self, rows: &[Vec>]) -> Result, String> { + rows.iter() + .map(|row| { + let name = row.first().cloned().flatten().unwrap_or_default(); + let written = row.get(1).cloned().flatten().unwrap_or_default(); + let live = + described_type(&written).map_err(|error| format!("column {name}: {error}"))?; + Ok(LiveColumn { + name, + column_type: self.live_type(&live), + fraction_digits: None, + }) + }) + .collect() + } +} + +/// A type as `INFORMATION_SCHEMA.COLUMNS` writes it, as `tables.get` would give it: its base type with its sizes apart. +fn described_type(written: &str) -> Result { + let upper = written.trim().to_ascii_uppercase(); + if upper.starts_with("STRUCT<") { + return Ok(LiveColumnType { + data_type: "STRUCT".to_owned(), + ..LiveColumnType::default() + }); + } + if let Some(element) = upper + .strip_prefix("ARRAY<") + .and_then(|rest| rest.strip_suffix('>')) + { + let element = match element.starts_with("STRUCT<") { + true => "STRUCT", + false => element.split('(').next().unwrap_or_default().trim(), + }; + return Ok(LiveColumnType { + data_type: format!("ARRAY<{element}>"), + ..LiveColumnType::default() + }); + } + let Some((base, sizes)) = upper.split_once('(') else { + return Ok(LiveColumnType { + data_type: upper, + ..LiveColumnType::default() + }); + }; + let sizes: Vec = sizes + .trim_end_matches(')') + .split(',') + .map(|size| { + size.trim().parse::().map_err(|error| { + format!("its type {written:?} has a size that is not a number: {error}") + }) + }) + .collect::>()?; + let base = base.trim().to_owned(); + Ok(match base.as_str() { + "STRING" | "BYTES" => LiveColumnType { + data_type: base, + char_length: sizes.first().copied(), + ..LiveColumnType::default() + }, + _ => LiveColumnType { + data_type: base, + precision: sizes.first().copied(), + scale: sizes.get(1).copied(), + ..LiveColumnType::default() + }, + }) } diff --git a/crates/sqlload/src/adapters/clickhouse/_helpers/dialect/sql_adapter.rs b/crates/sqlload/src/adapters/clickhouse/_helpers/dialect/sql_adapter.rs index be9ab7a54..86fc9cbf8 100644 --- a/crates/sqlload/src/adapters/clickhouse/_helpers/dialect/sql_adapter.rs +++ b/crates/sqlload/src/adapters/clickhouse/_helpers/dialect/sql_adapter.rs @@ -334,4 +334,13 @@ impl SqlAdapter for ClickHouseSql { CursorValue::Date | CursorValue::Plain => format!("toString(MAX({column}))"), } } + + /// From `system.columns`; the database is the table's schema. + fn render_describe_table(&self, table: &TableName, _database: Option<&str>) -> Option { + Some(format!( + "SELECT name, type FROM system.columns WHERE database = {} AND table = {} ORDER BY position", + self.render_loader_value_literal(&table.schema), + self.render_loader_value_literal(&table.table) + )) + } } diff --git a/crates/sqlload/src/adapters/clickhouse/main/session/_describe_table.rs b/crates/sqlload/src/adapters/clickhouse/main/session/_describe_table.rs index bc0220cda..c1c60decb 100644 --- a/crates/sqlload/src/adapters/clickhouse/main/session/_describe_table.rs +++ b/crates/sqlload/src/adapters/clickhouse/main/session/_describe_table.rs @@ -4,37 +4,20 @@ use crate::adapters::clickhouse::main::session::_query_rows::query_rows; use crate::adapters::clickhouse::models::{ClickHouseDestination, ClickHouseSql}; use crate::adapters::contract::models::TableName; use crate::adapters::contract::types::SqlAdapter; -use crate::column_types::models::LiveColumnType; use crate::http::errors::ApiError; use crate::schema_plan::models::LiveColumn; -/// The table's columns in order, or `None` if it does not exist, from `system.columns`; the database is the table's schema. +/// The table's columns in order, or `None` if it does not exist, from `system.columns`: the dialect's describe query, as a caller's session runs it too. pub(in crate::adapters) async fn describe_table( destination: &ClickHouseDestination, table: &TableName, ) -> Result>, ApiError> { - let adapter = ClickHouseSql; - let query = format!( - "SELECT name, type FROM system.columns WHERE database = {} AND table = {} ORDER BY position", - adapter.render_loader_value_literal(&table.schema), - adapter.render_loader_value_literal(&table.table) - ); - let columns: Vec = query_rows(destination, &query) - .await? - .into_iter() - .map(|row| { - let mut values = row.into_iter().map(Option::unwrap_or_default); - let name = values.next().unwrap_or_default(); - let data_type = values.next().unwrap_or_default(); - LiveColumn { - name, - column_type: adapter.live_type(&LiveColumnType { - data_type, - ..LiveColumnType::default() - }), - fraction_digits: None, - } - }) - .collect(); + let Some(query) = ClickHouseSql.render_describe_table(table, None) else { + return Ok(None); + }; + let rows = query_rows(destination, &query).await?; + let columns = ClickHouseSql + .describe_text_rows(&rows) + .map_err(ApiError::Protocol)?; Ok((!columns.is_empty()).then_some(columns)) } diff --git a/crates/sqlload/src/adapters/contract/main/_described_columns.rs b/crates/sqlload/src/adapters/contract/main/_described_columns.rs new file mode 100644 index 000000000..f0a2884e6 --- /dev/null +++ b/crates/sqlload/src/adapters/contract/main/_described_columns.rs @@ -0,0 +1,35 @@ +//! Read the columns a caller's session described. + +use crate::adapters::contract::types::SqlAdapter; +use crate::column_types::models::LiveColumnType; +use crate::schema_plan::models::LiveColumn; + +/// The columns of described `rows`, each its name, type, numeric precision and scale, character length and fractional-second digits, as text, as many of them as the row has; a size that is not a number fails, naming the column. +pub(in crate::adapters) fn described_columns( + adapter: &A, + rows: &[Vec>], +) -> Result, String> { + rows.iter() + .map(|row| { + let name = row.first().cloned().flatten().unwrap_or_default(); + let number = |index: usize| -> Result, String> { + match row.get(index).cloned().flatten() { + None => Ok(None), + Some(text) => text.trim().parse::().map(Some).map_err(|error| { + format!("column {name}: its size {text:?} is not a number: {error}") + }), + } + }; + Ok(LiveColumn { + column_type: adapter.live_type(&LiveColumnType { + data_type: row.get(1).cloned().flatten().unwrap_or_default(), + precision: number(2)?, + scale: number(3)?, + char_length: number(4)?, + }), + fraction_digits: number(5)?, + name, + }) + }) + .collect() +} diff --git a/crates/sqlload/src/adapters/contract/main/_session_parquet.rs b/crates/sqlload/src/adapters/contract/main/_session_parquet.rs new file mode 100644 index 000000000..7d47469ca --- /dev/null +++ b/crates/sqlload/src/adapters/contract/main/_session_parquet.rs @@ -0,0 +1,25 @@ +//! A batch as the Parquet file a caller's session loads. + +use arrow_array::RecordBatch; +use parquet::arrow::ArrowWriter; +use parquet::basic::{Compression, ZstdLevel}; +use parquet::file::properties::WriterProperties; + +use crate::schema_plan::models::DesiredColumn; + +/// `batch` as one zstd Parquet file, its columns as they are: what a warehouse without its own needs loads (`columns` are those it is loaded into). +pub(in crate::adapters) fn default_session_parquet( + batch: &RecordBatch, + columns: &[DesiredColumn], +) -> Result, String> { + let _ = columns; + let properties = WriterProperties::builder() + .set_compression(Compression::ZSTD(ZstdLevel::default())) + .build(); + let mut body: Vec = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut body, batch.schema(), Some(properties)) + .map_err(|error| error.to_string())?; + writer.write(batch).map_err(|error| error.to_string())?; + writer.close().map_err(|error| error.to_string())?; + Ok(body) +} diff --git a/crates/sqlload/src/adapters/contract/main/mod.rs b/crates/sqlload/src/adapters/contract/main/mod.rs index b5fc0a7f7..71c48a0ea 100644 --- a/crates/sqlload/src/adapters/contract/main/mod.rs +++ b/crates/sqlload/src/adapters/contract/main/mod.rs @@ -1,5 +1,6 @@ pub(in crate::adapters) mod _batch_direct_problem; pub(in crate::adapters) mod _custom_endpoint; +pub(in crate::adapters) mod _described_columns; pub(in crate::adapters) mod _dropped_ordinals; pub(in crate::adapters) mod _files_direct_problem; pub(in crate::adapters) mod _footer_rows; @@ -9,6 +10,7 @@ pub(in crate::adapters) mod _older_rows; pub(in crate::adapters) mod _ranked_source; pub(in crate::adapters) mod _rebuilt_in_place; pub(in crate::adapters) mod _rekeyed_row_ids; +pub(in crate::adapters) mod _session_parquet; pub mod bound_parameter; pub mod cursor_bound; pub mod cursor_from_now; diff --git a/crates/sqlload/src/adapters/contract/models.rs b/crates/sqlload/src/adapters/contract/models.rs index a3bb039f2..2bf613e8d 100644 --- a/crates/sqlload/src/adapters/contract/models.rs +++ b/crates/sqlload/src/adapters/contract/models.rs @@ -333,3 +333,37 @@ pub enum CheckQuery<'a> { held_by: Option<&'a TableName>, }, } + +/// How a batch's rows reach the staging table through a caller's session. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionRows { + /// The warehouse reads the Parquet file SQLLoad wrote on this machine itself, with the statement [`SqlAdapter::render_insert_local_parquet`](crate::adapters::contract::types::SqlAdapter::render_insert_local_parquet) renders. + LocalParquet, + /// The batch's Parquet files go up to the user's stage with `PUT` as they fill, and load together when the batch loads. + StagedParquet, + /// A binary `COPY ... FROM STDIN` the session runs with the encoded rows. + CopyIn, + /// The session loads each Parquet file through its own client. + CallerLoadsParquet, +} + +/// One step of a batch's files through the user's stage, for [`SessionRows::StagedParquet`]: each batch's files wait in a folder of their own, named by the load and the batch. +#[derive(Debug, Clone, Copy)] +pub enum SessionStage<'a> { + /// Upload the Parquet file at `file`, a path on this machine, into the batch's folder unchanged. + Put { + load_id: &'a str, + batch: u64, + file: &'a str, + }, + /// Load the named files of the batch's folder into `table`: by column name, or filling `selected` by a `SELECT` where given (a table holding JSON the files carry as text). + Copy { + load_id: &'a str, + batch: u64, + table: &'a TableName, + names: &'a [String], + selected: Option<&'a [crate::schema_plan::models::DesiredColumn]>, + }, + /// Remove every file of the batch's folder. + Remove { load_id: &'a str, batch: u64 }, +} diff --git a/crates/sqlload/src/adapters/contract/types.rs b/crates/sqlload/src/adapters/contract/types.rs index 9ee1bec93..c9c4cde47 100644 --- a/crates/sqlload/src/adapters/contract/types.rs +++ b/crates/sqlload/src/adapters/contract/types.rs @@ -25,13 +25,16 @@ use crate::adapters::contract::_helpers::type_fit::type_fit; use crate::adapters::contract::_helpers::write::{ mark_statement, marked_counts, replaced_rows, tombstone_statements, write_statements, }; +use crate::adapters::contract::main::_described_columns::described_columns; use crate::adapters::contract::main::_dropped_ordinals::dropped_ordinals; use crate::adapters::contract::main::_kept_row_ids::kept_row_ids; use crate::adapters::contract::main::_older_rows::older_rows; use crate::adapters::contract::main::_rekeyed_row_ids::rekeyed_row_ids; +use crate::adapters::contract::main::_session_parquet::default_session_parquet; use crate::adapters::contract::models::{ ChangeApply, ChangeWrite, CheckQuery, CursorQuery, CursorRead, CursorValue, MarkWrite, - TableName, TombstoneWrite, WriteMode, WriteStatementsRequest, WriteTarget, + SessionRows, SessionStage, TableName, TombstoneWrite, WriteMode, WriteStatementsRequest, + WriteTarget, }; use crate::column_types::models::{ColumnType, LiveColumnType, TypeFit, Warehouse, WarehouseType}; use crate::loader::errors::LoaderError; @@ -678,6 +681,69 @@ pub trait SqlAdapter: Sync + std::fmt::Debug { ) -> (String, Option) { (self.render_create_table(runs, columns), None) } + + /// The statements a caller's session runs when it opens, so it reads and writes as SQLLoad's own sessions do. + fn render_session_setup(&self) -> Vec { + Vec::new() + } + + /// The query a caller's session answers with its autocommit setting, as its first row's second value (`true` or `false`); `None` where the server does not hold it. + fn render_autocommit_check(&self) -> Option { + None + } + + /// How a batch's rows reach the staging table through a caller's session. + fn session_rows(&self) -> SessionRows { + SessionRows::CallerLoadsParquet + } + + /// The query a caller's session lists `table`'s columns with (in `database`, else the table's own), in order: each row its name, type, numeric precision and scale, character length and fractional-second digits, as many of these as the warehouse gives; `None` where no query lists them. + fn render_describe_table(&self, table: &TableName, database: Option<&str>) -> Option { + let _ = (table, database); + None + } + + /// The live columns of the rows [`Self::render_describe_table`]'s query gave, as text. + fn describe_text_rows(&self, rows: &[Vec>]) -> Result, String> { + described_columns(self, rows) + } + + /// The statement adding the rows of the Parquet file at `file` (a path on this machine) to `table`, filling the columns `names`, read by name; `None` where the warehouse cannot read the machine's files. + fn render_insert_local_parquet( + &self, + table: &TableName, + names: &[String], + file: &str, + ) -> Option { + let _ = (table, names, file); + None + } + + /// One batch as the Parquet file a caller's session loads, given the columns it is loaded into. + fn session_parquet( + &self, + batch: &RecordBatch, + columns: &[DesiredColumn], + ) -> Result, String> { + default_session_parquet(batch, columns) + } + + /// The statements of one step of a batch's files through the user's stage, for [`SessionRows::StagedParquet`]; none elsewhere. + fn render_session_stage(&self, stage: SessionStage<'_>) -> Vec { + let _ = stage; + Vec::new() + } + + /// The batch as a caller's session's `COPY ... FROM STDIN` into `table` loads it, given the columns it fills: the statement and its input, for [`SessionRows::CopyIn`]; `None` elsewhere. + fn session_copy_in( + &self, + table: &TableName, + batch: &RecordBatch, + columns: &[DesiredColumn], + ) -> Option), String>> { + let _ = (table, batch, columns); + None + } } /// One table's write session on its destination: how its batches get in. The loader keeps the commit cycle (staging and build tables, commit points, run records); the writer owns the transport. diff --git a/crates/sqlload/src/adapters/databricks/_helpers/dialect/sql_adapter.rs b/crates/sqlload/src/adapters/databricks/_helpers/dialect/sql_adapter.rs index 24fd97e5e..fc503973d 100644 --- a/crates/sqlload/src/adapters/databricks/_helpers/dialect/sql_adapter.rs +++ b/crates/sqlload/src/adapters/databricks/_helpers/dialect/sql_adapter.rs @@ -194,4 +194,15 @@ impl SqlAdapter for DatabricksSql { self.render_staging_filter(&format!("{STAGING_SUFFIX}_")) ) } + + /// From the catalog's `information_schema` (the table's own catalog first); types come from `full_data_type` (`decimal(18,2)`, `varchar(10)`). + fn render_describe_table(&self, table: &TableName, database: Option<&str>) -> Option { + let catalog = table.database.as_deref().or(database)?; + Some(format!( + "SELECT column_name, full_data_type, numeric_precision, numeric_scale FROM {}.information_schema.columns WHERE table_schema = {} AND table_name = {} ORDER BY ordinal_position", + self.render_identifier(catalog), + self.render_loader_value_literal(&table.schema.to_ascii_lowercase()), + self.render_loader_value_literal(&table.table.to_ascii_lowercase()), + )) + } } diff --git a/crates/sqlload/src/adapters/databricks/main/session/_describe_table.rs b/crates/sqlload/src/adapters/databricks/main/session/_describe_table.rs index 3183b562e..52418021e 100644 --- a/crates/sqlload/src/adapters/databricks/main/session/_describe_table.rs +++ b/crates/sqlload/src/adapters/databricks/main/session/_describe_table.rs @@ -3,42 +3,21 @@ use crate::adapters::contract::models::TableName; use crate::adapters::contract::types::SqlAdapter; use crate::adapters::databricks::models::{DatabricksDestination, DatabricksSql}; -use crate::column_types::models::LiveColumnType; use crate::databricks_api::main::execute_statement::execute_statement; use crate::http::errors::ApiError; use crate::schema_plan::models::LiveColumn; -/// The table's columns in order, or `None` if it does not exist; types come from `full_data_type` (`decimal(18,2)`, `varchar(10)`). +/// The table's columns in order, or `None` if it does not exist: the dialect's describe query, as a caller's session runs it too. pub(in crate::adapters) async fn describe_table( destination: &DatabricksDestination, table: &TableName, ) -> Result>, ApiError> { - let adapter = DatabricksSql; - let catalog = table.database.as_deref().unwrap_or(&destination.catalog); - let query = format!( - "SELECT column_name, full_data_type, numeric_precision, numeric_scale FROM {}.information_schema.columns WHERE table_schema = {} AND table_name = {} ORDER BY ordinal_position", - adapter.render_identifier(catalog), - adapter.render_loader_value_literal(&table.schema.to_ascii_lowercase()), - adapter.render_loader_value_literal(&table.table.to_ascii_lowercase()), - ); - let rows = execute_statement(&destination.api, &query).await?; - let number = |value: &Option| match value.as_deref().map(str::parse::) { - Some(Ok(number)) => Some(number), - _ => None, + let Some(query) = DatabricksSql.render_describe_table(table, Some(&destination.catalog)) else { + return Ok(None); }; - let columns: Vec = rows - .rows - .iter() - .map(|row| LiveColumn { - name: row.first().cloned().flatten().unwrap_or_default(), - column_type: adapter.live_type(&LiveColumnType { - data_type: row.get(1).cloned().flatten().unwrap_or_default(), - precision: row.get(2).and_then(number), - scale: row.get(3).and_then(number), - char_length: None, - }), - fraction_digits: None, - }) - .collect(); + let rows = execute_statement(&destination.api, &query).await?; + let columns = DatabricksSql + .describe_text_rows(&rows.rows) + .map_err(ApiError::Protocol)?; Ok((!columns.is_empty()).then_some(columns)) } diff --git a/crates/sqlload/src/adapters/dispatch/_helpers/writer.rs b/crates/sqlload/src/adapters/dispatch/_helpers/writer.rs index 0f0f630a9..6ad02116f 100644 --- a/crates/sqlload/src/adapters/dispatch/_helpers/writer.rs +++ b/crates/sqlload/src/adapters/dispatch/_helpers/writer.rs @@ -18,6 +18,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.writes_directly(), Writer::ClickHouse(writer) => writer.writes_directly(), Writer::Files(writer) => writer.writes_directly(), + Writer::Session(writer) => writer.writes_directly(), } } @@ -35,6 +36,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.write_batch(target, batch).await, Writer::ClickHouse(writer) => writer.write_batch(target, batch).await, Writer::Files(writer) => writer.write_batch(target, batch).await, + Writer::Session(writer) => writer.write_batch(target, batch).await, } } @@ -48,6 +50,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.staged_bytes(), Writer::ClickHouse(writer) => writer.staged_bytes(), Writer::Files(writer) => writer.staged_bytes(), + Writer::Session(writer) => writer.staged_bytes(), } } @@ -61,6 +64,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.finish_files(target).await, Writer::ClickHouse(writer) => writer.finish_files(target).await, Writer::Files(writer) => writer.finish_files(target).await, + Writer::Session(writer) => writer.finish_files(target).await, } } @@ -74,6 +78,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.load_batch(target).await, Writer::ClickHouse(writer) => writer.load_batch(target).await, Writer::Files(writer) => writer.load_batch(target).await, + Writer::Session(writer) => writer.load_batch(target).await, } } @@ -87,6 +92,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.next_batch(), Writer::ClickHouse(writer) => writer.next_batch(), Writer::Files(writer) => writer.next_batch(), + Writer::Session(writer) => writer.next_batch(), } } @@ -100,6 +106,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.settle_rows().await, Writer::ClickHouse(writer) => writer.settle_rows().await, Writer::Files(writer) => writer.settle_rows().await, + Writer::Session(writer) => writer.settle_rows().await, } } @@ -113,6 +120,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.reopen_rows(), Writer::ClickHouse(writer) => writer.reopen_rows(), Writer::Files(writer) => writer.reopen_rows(), + Writer::Session(writer) => writer.reopen_rows(), } } @@ -126,6 +134,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.rollback_batch().await, Writer::ClickHouse(writer) => writer.rollback_batch().await, Writer::Files(writer) => writer.rollback_batch().await, + Writer::Session(writer) => writer.rollback_batch().await, } } @@ -139,6 +148,7 @@ impl TableWriter for Writer { Writer::Postgres(writer) => writer.remove_batch_files(target).await, Writer::ClickHouse(writer) => writer.remove_batch_files(target).await, Writer::Files(writer) => writer.remove_batch_files(target).await, + Writer::Session(writer) => writer.remove_batch_files(target).await, } } diff --git a/crates/sqlload/src/adapters/dispatch/main/dialect/connection_warehouse.rs b/crates/sqlload/src/adapters/dispatch/main/dialect/connection_warehouse.rs index 3423d8679..463bc5573 100644 --- a/crates/sqlload/src/adapters/dispatch/main/dialect/connection_warehouse.rs +++ b/crates/sqlload/src/adapters/dispatch/main/dialect/connection_warehouse.rs @@ -23,6 +23,7 @@ pub fn connection_warehouse(connection: &ConnectionConfig) -> Option<(Warehouse, ConnectionConfig::Postgres { database, .. } => { Some((Warehouse::Postgres, Some(database.clone()))) } + ConnectionConfig::Session(session) => Some((session.warehouse, session.database.clone())), ConnectionConfig::Odbc { .. } | ConnectionConfig::GoogleSheets { .. } | ConnectionConfig::Http { .. } diff --git a/crates/sqlload/src/adapters/dispatch/main/route/writer_accepts.rs b/crates/sqlload/src/adapters/dispatch/main/route/writer_accepts.rs index 35d5820f0..9531721a5 100644 --- a/crates/sqlload/src/adapters/dispatch/main/route/writer_accepts.rs +++ b/crates/sqlload/src/adapters/dispatch/main/route/writer_accepts.rs @@ -11,7 +11,7 @@ use crate::number_text::main::thousands::thousands; use crate::routing::models::WriterAccepts; use crate::routing::models::{FileFormat, Store}; -/// What `destination` takes over the chosen `stage`: Arrow batches (DuckDB also reads Parquet in S3, GCS or on this machine itself; MotherDuck takes zstd Parquet chunks it `COPY`s, and reads Parquet in S3 or GCS on its servers; and ClickHouse Parquet in S3, BigQuery Parquet in GCS), or what its stage route takes. +/// What `destination` takes over the chosen `stage`: Arrow batches (DuckDB also reads Parquet in S3, GCS or on this machine itself; MotherDuck takes zstd Parquet chunks it `COPY`s, and reads Parquet in S3 or GCS on its servers; and ClickHouse Parquet in S3, BigQuery Parquet in GCS), or what its stage route takes. A caller's session takes Arrow batches only: no warehouse reads files itself through it, so SQLLoad reads a files source's files for it. pub fn writer_accepts(destination: &Destination, stage: Option<&StageRoute>) -> WriterAccepts { match destination { #[cfg(feature = "duckdb")] @@ -57,10 +57,12 @@ pub fn writer_accepts(destination: &Destination, stage: Option<&StageRoute>) -> pull_formats: vec![FileFormat::Parquet], ..WriterAccepts::default() }, - Destination::Files(_) | Destination::Postgres(_) => WriterAccepts { - arrow: true, - ..WriterAccepts::default() - }, + Destination::Files(_) | Destination::Postgres(_) | Destination::Session(_) => { + WriterAccepts { + arrow: true, + ..WriterAccepts::default() + } + } Destination::Snowflake(_) => snowflake_accepts(stage), Destination::Databricks(databricks) => databricks_accepts(databricks), } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/_own_destination.rs b/crates/sqlload/src/adapters/dispatch/main/session/_own_destination.rs new file mode 100644 index 000000000..d13a4817c --- /dev/null +++ b/crates/sqlload/src/adapters/dispatch/main/session/_own_destination.rs @@ -0,0 +1,133 @@ +//! Open the destination a target loads into through a connection SQLLoad opens itself. + +use crate::adapters::bigquery::main::session::_connect_bigquery::connect_bigquery; +use crate::adapters::clickhouse::main::session::_connect_clickhouse::connect_clickhouse; +use crate::adapters::contract::models::TableName; +use crate::adapters::databricks::main::session::_connect_databricks::connect_databricks; +use crate::adapters::dispatch::models::Destination; +#[cfg(feature = "duckdb")] +use crate::adapters::duckdb::main::_open_target::open_target; +use crate::adapters::files::models::FilesDestination; +use crate::adapters::postgres::main::session::_open_postgres::open_postgres; +use crate::adapters::snowflake::main::session::_connect_snowflake::connect_snowflake; +use crate::adapters::snowflake::main::stage::_forced_stage::forced_stage; +use crate::adapters::snowflake::models::SnowflakeAccount; +use crate::loader::errors::LoaderError; +use crate::project::models::{ConnectionConfig, ProjectConfig, TargetConfig}; +use crate::store_paths::main::connection_store::connection_store; + +/// The destination target `name` loads into through `connection`, which SQLLoad opens itself. +pub(in crate::adapters) fn own_destination( + project: &ProjectConfig, + (name, target): (&str, &TargetConfig), + connection: Option<&ConnectionConfig>, +) -> Result { + let destination = match connection { + #[cfg(feature = "duckdb")] + Some(ConnectionConfig::DuckDb { .. } | ConnectionConfig::MotherDuck { .. }) => { + Destination::DuckDb(open_target(project, target)?) + } + #[cfg(not(feature = "duckdb"))] + Some(ConnectionConfig::DuckDb { .. } | ConnectionConfig::MotherDuck { .. }) => { + return Err(LoaderError::Invalid(format!( + "target {name:?}: this sqlload was built without DuckDB (cargo feature \"duckdb\")" + ))); + } + Some(connection @ ConnectionConfig::Snowflake { .. }) => { + Destination::Snowflake(Box::new(snowflake(connection, target, name)?)) + } + Some(connection @ ConnectionConfig::Databricks { .. }) => Destination::Databricks( + Box::new(connect_databricks(connection, target.database.as_deref())?), + ), + Some(connection @ ConnectionConfig::BigQuery { .. }) => Destination::BigQuery(Box::new( + connect_bigquery(connection, target.database.as_deref())?, + )), + Some(ConnectionConfig::Postgres { .. }) => Destination::Postgres(Box::new(open_postgres( + project, + &target.connection, + target.database.as_deref(), + )?)), + Some(connection @ ConnectionConfig::ClickHouse { .. }) => { + Destination::ClickHouse(Box::new(connect_clickhouse(connection)?)) + } + Some( + connection @ (ConnectionConfig::S3 { .. } + | ConnectionConfig::Gcs { .. } + | ConnectionConfig::Filesystem { .. }), + ) => files(connection, target).ok_or_else(|| { + LoaderError::Invalid(format!("target {name:?}: its connection holds no files")) + })?, + Some(other) => { + return Err(LoaderError::Invalid(format!( + "target {name:?}: {} destinations are not supported yet", + other.kind() + ))); + } + None => { + return Err(LoaderError::Invalid(format!( + "target {name:?}: connection {:?} does not exist", + target.connection + ))); + } + }; + Ok(destination) +} + +/// The files destination of `target`, from its `s3`, `gcs` or `filesystem` connection (the only kinds it is called for). +fn files( + connection: &ConnectionConfig, + target: &crate::project::models::TargetConfig, +) -> Option { + let store = connection_store(connection)?; + Some(Destination::Files(Box::new(FilesDestination { + connection: target.connection.clone(), + store, + max_footer_reads: target.footer_read_limit(), + encoding: target.output_encoding(), + }))) +} + +/// The Snowflake destination of target `name`, from its `snowflake` connection. +fn snowflake( + connection: &ConnectionConfig, + target: &crate::project::models::TargetConfig, + name: &str, +) -> Result { + let ConnectionConfig::Snowflake { + account, + user, + auth, + role, + warehouse, + database, + base_url, + load_method, + } = connection + else { + return Err(LoaderError::Invalid(format!( + "target {name:?}: its connection is not a Snowflake one" + ))); + }; + Ok(connect_snowflake(SnowflakeAccount { + account: account.clone(), + user: user.clone(), + auth: auth.clone(), + role: role.clone(), + warehouse: warehouse.clone(), + database: target.database.clone().unwrap_or_else(|| database.clone()), + base_url: base_url.clone(), + stage: forced_stage( + load_method.as_deref().ok_or_else(|| { + LoaderError::Invalid(format!( + "target {name:?}: its connection has no load_method" + )) + })?, + TableName { + database: Some(target.database.clone().unwrap_or_else(|| database.clone())), + schema: target.loader_schema.clone().unwrap_or_default(), + table: String::new(), + }, + ) + .map_err(LoaderError::Invalid)?, + })?) +} diff --git a/crates/sqlload/src/adapters/dispatch/main/session/check_destination.rs b/crates/sqlload/src/adapters/dispatch/main/session/check_destination.rs index 8f8073a94..f4b64b97c 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/check_destination.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/check_destination.rs @@ -4,6 +4,7 @@ use crate::adapters::databricks::main::stage::_check_volume::check_volume; use crate::adapters::dispatch::main::session::single_text::single_text; use crate::adapters::dispatch::models::Destination; use crate::adapters::postgres::main::session::_check_session::check_session; +use crate::adapters::session::main::_check_session::check_session as check_caller_session; use crate::adapters::snowflake::main::stage::_check_stage::check_stage; use crate::adapters::snowflake::models::ForcedStage; use crate::file_store::main::open_folder::open_folder; @@ -63,6 +64,7 @@ pub async fn check_destination(destination: Destination) -> Result check_session(&postgres).await, + Destination::Session(session) => check_caller_session(&session).await, #[cfg(feature = "duckdb")] destination @ Destination::DuckDb(_) => { let answer = single_text(&destination, version_query(&destination).to_owned()).await?; diff --git a/crates/sqlload/src/adapters/dispatch/main/session/connect_destination.rs b/crates/sqlload/src/adapters/dispatch/main/session/connect_destination.rs index 8635ff0a7..ebfe4c468 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/connect_destination.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/connect_destination.rs @@ -1,22 +1,12 @@ //! Open the destination one target uses. -use crate::adapters::bigquery::main::session::_connect_bigquery::connect_bigquery; -use crate::adapters::clickhouse::main::session::_connect_clickhouse::connect_clickhouse; -use crate::adapters::contract::models::TableName; -use crate::adapters::databricks::main::session::_connect_databricks::connect_databricks; +use crate::adapters::dispatch::main::session::_own_destination::own_destination; use crate::adapters::dispatch::models::Destination; -#[cfg(feature = "duckdb")] -use crate::adapters::duckdb::main::_open_target::open_target; -use crate::adapters::files::models::FilesDestination; -use crate::adapters::postgres::main::session::_open_postgres::open_postgres; -use crate::adapters::snowflake::main::session::_connect_snowflake::connect_snowflake; -use crate::adapters::snowflake::main::stage::_forced_stage::forced_stage; -use crate::adapters::snowflake::models::SnowflakeAccount; +use crate::adapters::session::main::_connect_session::connect_session; use crate::loader::errors::LoaderError; use crate::project::models::{ConnectionConfig, ProjectConfig}; -use crate::store_paths::main::connection_store::connection_store; -/// The open destination of target `name`. +/// The open destination of target `name`: its caller's session, or a connection of SQLLoad's own. pub async fn connect_destination( project: &ProjectConfig, name: &str, @@ -25,112 +15,10 @@ pub async fn connect_destination( .targets .get(name) .ok_or_else(|| LoaderError::Invalid(format!("target {name:?} does not exist")))?; - let destination = match project.connections.get(&target.connection) { - #[cfg(feature = "duckdb")] - Some(ConnectionConfig::DuckDb { .. } | ConnectionConfig::MotherDuck { .. }) => { - Destination::DuckDb(open_target(project, target)?) - } - #[cfg(not(feature = "duckdb"))] - Some(ConnectionConfig::DuckDb { .. } | ConnectionConfig::MotherDuck { .. }) => { - return Err(LoaderError::Invalid(format!( - "target {name:?}: this sqlload was built without DuckDB (cargo feature \"duckdb\")" - ))); - } - Some(connection @ ConnectionConfig::Snowflake { .. }) => { - Destination::Snowflake(Box::new(snowflake(connection, target, name)?)) - } - Some(connection @ ConnectionConfig::Databricks { .. }) => Destination::Databricks( - Box::new(connect_databricks(connection, target.database.as_deref())?), - ), - Some(connection @ ConnectionConfig::BigQuery { .. }) => Destination::BigQuery(Box::new( - connect_bigquery(connection, target.database.as_deref())?, - )), - Some(ConnectionConfig::Postgres { .. }) => Destination::Postgres(Box::new(open_postgres( - project, - &target.connection, - target.database.as_deref(), - )?)), - Some(connection @ ConnectionConfig::ClickHouse { .. }) => { - Destination::ClickHouse(Box::new(connect_clickhouse(connection)?)) - } - Some( - connection @ (ConnectionConfig::S3 { .. } - | ConnectionConfig::Gcs { .. } - | ConnectionConfig::Filesystem { .. }), - ) => files(connection, target).ok_or_else(|| { - LoaderError::Invalid(format!("target {name:?}: its connection holds no files")) - })?, - Some(other) => { - return Err(LoaderError::Invalid(format!( - "target {name:?}: {} destinations are not supported yet", - other.kind() - ))); - } - None => { - return Err(LoaderError::Invalid(format!( - "target {name:?}: connection {:?} does not exist", - target.connection - ))); - } - }; - Ok(destination) -} - -/// The files destination of `target`, from its `s3`, `gcs` or `filesystem` connection (the only kinds it is called for). -fn files( - connection: &ConnectionConfig, - target: &crate::project::models::TargetConfig, -) -> Option { - let store = connection_store(connection)?; - Some(Destination::Files(Box::new(FilesDestination { - connection: target.connection.clone(), - store, - max_footer_reads: target.footer_read_limit(), - encoding: target.output_encoding(), - }))) -} - -/// The Snowflake destination of target `name`, from its `snowflake` connection. -fn snowflake( - connection: &ConnectionConfig, - target: &crate::project::models::TargetConfig, - name: &str, -) -> Result { - let ConnectionConfig::Snowflake { - account, - user, - auth, - role, - warehouse, - database, - base_url, - load_method, - } = connection - else { - return Err(LoaderError::Invalid(format!( - "target {name:?}: its connection is not a Snowflake one" - ))); - }; - Ok(connect_snowflake(SnowflakeAccount { - account: account.clone(), - user: user.clone(), - auth: auth.clone(), - role: role.clone(), - warehouse: warehouse.clone(), - database: target.database.clone().unwrap_or_else(|| database.clone()), - base_url: base_url.clone(), - stage: forced_stage( - load_method.as_deref().ok_or_else(|| { - LoaderError::Invalid(format!( - "target {name:?}: its connection has no load_method" - )) - })?, - TableName { - database: Some(target.database.clone().unwrap_or_else(|| database.clone())), - schema: target.loader_schema.clone().unwrap_or_default(), - table: String::new(), - }, - ) - .map_err(LoaderError::Invalid)?, - })?) + match project.connections.get(&target.connection) { + Some(ConnectionConfig::Session(session)) => Ok(Destination::Session(Box::new( + connect_session(session, target.database.as_deref()).await?, + ))), + connection => own_destination(project, (name, target), connection), + } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/ddl_guard.rs b/crates/sqlload/src/adapters/dispatch/main/session/ddl_guard.rs index 73522db11..78bd92186 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/ddl_guard.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/ddl_guard.rs @@ -14,6 +14,7 @@ pub async fn ddl_guard(destination: &Destination) -> Option> Destination::BigQuery(bigquery) => Some(bigquery.ddl.clone()), Destination::Postgres(postgres) => Some(postgres.ddl.clone()), Destination::ClickHouse(clickhouse) => Some(clickhouse.ddl.clone()), + Destination::Session(session) => Some(session.ddl.clone()), Destination::Files(_) => None, }; match lock { diff --git a/crates/sqlload/src/adapters/dispatch/main/session/drop_stale_staging.rs b/crates/sqlload/src/adapters/dispatch/main/session/drop_stale_staging.rs index 6d8d66d96..90e7b1298 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/drop_stale_staging.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/drop_stale_staging.rs @@ -15,13 +15,16 @@ pub async fn drop_stale_staging( name: &TableName, warehouse: Warehouse, ) -> Result { - if let Destination::Postgres(_) = destination { + if warehouse == Warehouse::Postgres { return Ok(0); } let database = match destination { Destination::Snowflake(snowflake) => Some(snowflake.database.as_str()), Destination::Databricks(databricks) => Some(databricks.catalog.as_str()), Destination::BigQuery(bigquery) => Some(bigquery.project.as_str()), + Destination::Session(session) if warehouse != Warehouse::DuckDb => { + session.database.as_deref() + } _ => None, }; let adapter = sql_adapter(warehouse); @@ -45,6 +48,12 @@ fn listed_name(destination: &Destination, name: &TableName) -> TableName { database: None, ..name.clone() }, + Destination::Session(session) if session.connection.warehouse == Warehouse::DuckDb => { + TableName { + database: None, + ..name.clone() + } + } _ => name.clone(), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/execute.rs b/crates/sqlload/src/adapters/dispatch/main/session/execute.rs index 922c2b09f..860655df6 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/execute.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/execute.rs @@ -8,6 +8,7 @@ use crate::adapters::dispatch::models::Destination; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_execute_statements::execute_statements; use crate::adapters::postgres::main::session::_run_statements::run_statements as run_postgres; +use crate::adapters::session::main::_run_statements::run_statements as run_session; use crate::adapters::snowflake::main::session::_run_statements::run_statements; use crate::loader::errors::LoaderError; @@ -24,6 +25,7 @@ pub async fn execute( Destination::BigQuery(bigquery) => Ok(run_bigquery(bigquery, &statements).await?), Destination::Postgres(postgres) => run_postgres(postgres, &statements).await, Destination::ClickHouse(clickhouse) => Ok(run_clickhouse(clickhouse, &statements).await?), + Destination::Session(session) => run_session(session, statements).await, Destination::Files(_) => Err(no_sql()), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/live_columns.rs b/crates/sqlload/src/adapters/dispatch/main/session/live_columns.rs index aeb6aee56..cd0ecf1a0 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/live_columns.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/live_columns.rs @@ -9,6 +9,7 @@ use crate::adapters::dispatch::models::Destination; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_describe_table::describe_table as describe_duckdb; use crate::adapters::postgres::main::session::_describe_table::describe_table as describe_postgres; +use crate::adapters::session::main::_describe_table::describe_table as describe_session; use crate::adapters::snowflake::main::session::_describe_table::describe_table as describe_snowflake; use crate::loader::errors::LoaderError; use crate::schema_plan::models::LiveColumn; @@ -27,6 +28,7 @@ pub async fn live_columns( Destination::BigQuery(bigquery) => Ok(describe_bigquery(bigquery, table).await?), Destination::Postgres(postgres) => describe_postgres(postgres, table).await, Destination::ClickHouse(clickhouse) => Ok(describe_clickhouse(clickhouse, table).await?), + Destination::Session(session) => describe_session(session, table).await, Destination::Files(_) => Err(no_sql()), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/mod.rs b/crates/sqlload/src/adapters/dispatch/main/session/mod.rs index ebd17fce5..19a9b82ae 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/mod.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/mod.rs @@ -1,3 +1,4 @@ +pub(in crate::adapters) mod _own_destination; pub mod check_destination; pub mod clean_stage; pub mod connect_destination; diff --git a/crates/sqlload/src/adapters/dispatch/main/session/single_text.rs b/crates/sqlload/src/adapters/dispatch/main/session/single_text.rs index 70f157b5d..76e81d106 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/single_text.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/single_text.rs @@ -8,6 +8,7 @@ use crate::adapters::dispatch::models::Destination; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_query_text::query_text as query_duckdb; use crate::adapters::postgres::main::session::_query_rows::query_rows as query_postgres; +use crate::adapters::session::main::_query_rows::query_rows as query_session; use crate::adapters::snowflake::main::session::_query_text::query_text as query_snowflake; use crate::loader::errors::LoaderError; @@ -41,6 +42,12 @@ pub async fn single_text( .next() .and_then(|row| row.into_iter().next()) .flatten()), + Destination::Session(session) => Ok(query_session(session, query) + .await? + .into_iter() + .next() + .and_then(|row| row.into_iter().next()) + .flatten()), Destination::Files(_) => Err(no_sql()), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/table_destination.rs b/crates/sqlload/src/adapters/dispatch/main/session/table_destination.rs index 7a1b311e7..a362c8372 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/table_destination.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/table_destination.rs @@ -3,9 +3,10 @@ use crate::adapters::dispatch::models::Destination; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_own_connection::own_connection; +use crate::adapters::session::main::_table_session::table_session; use crate::loader::errors::LoaderError; -/// The destination for one table's load: DuckDB gets a connection of its own, so the table's transactions never mix with another table loading at the same time; BigQuery a Storage Write API connection of its own, so a table's open streams never wait on another table's for the connection's stream limit; Postgres a session of its own, which holds the table's temporary staging table and its transactions. +/// The destination for one table's load: a caller's session gets a session of its own, for the same reasons as the warehouse's own destination; DuckDB gets a connection of its own, so the table's transactions never mix with another table loading at the same time; BigQuery a Storage Write API connection of its own, so a table's open streams never wait on another table's for the connection's stream limit; Postgres a session of its own, which holds the table's temporary staging table and its transactions. pub fn table_destination(destination: &Destination) -> Result { match destination { #[cfg(feature = "duckdb")] @@ -21,6 +22,7 @@ pub fn table_destination(destination: &Destination) -> Result Ok(Destination::Session(Box::new(table_session(session)))), other => Ok(other.clone()), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/table_names.rs b/crates/sqlload/src/adapters/dispatch/main/session/table_names.rs index bfea4604a..f24f91bb5 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/table_names.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/table_names.rs @@ -2,10 +2,11 @@ use crate::adapters::dispatch::main::session::text_values::text_values; use crate::adapters::dispatch::models::Destination; +use crate::adapters::session::errors::SessionErrorKind; use crate::bigquery_api::constants::NOT_FOUND; use crate::loader::errors::LoaderError; -/// The names `query` lists from a schema's tables, none before the schema exists: BigQuery lists a dataset's tables in the dataset's own `INFORMATION_SCHEMA`, which is not found until the first load creates the dataset. +/// The names `query` lists from a schema's tables, none before the schema exists: BigQuery lists a dataset's tables in the dataset's own `INFORMATION_SCHEMA`, which is not found until the first load creates the dataset (a caller's session says so as not found). pub async fn table_names( destination: &Destination, query: String, @@ -17,6 +18,9 @@ pub async fn table_names( { Ok(Vec::new()) } + Err(LoaderError::Session(error)) if error.kind == SessionErrorKind::NotFound => { + Ok(Vec::new()) + } found => found, } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/text_values.rs b/crates/sqlload/src/adapters/dispatch/main/session/text_values.rs index 55a97798d..790b3db2e 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/text_values.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/text_values.rs @@ -8,6 +8,7 @@ use crate::adapters::dispatch::models::Destination; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_query_texts::query_texts as query_duckdb_texts; use crate::adapters::postgres::main::session::_query_rows::query_rows as query_postgres; +use crate::adapters::session::main::_query_rows::query_rows as query_session; use crate::adapters::snowflake::main::session::query_texts::query_texts as query_snowflake_texts; use crate::loader::errors::LoaderError; @@ -40,6 +41,11 @@ pub async fn text_values( .into_iter() .filter_map(|row| row.into_iter().next().flatten()) .collect()), + Destination::Session(session) => Ok(query_session(session, query) + .await? + .into_iter() + .filter_map(|row| row.into_iter().next().flatten()) + .collect()), Destination::Files(_) => Err(no_sql()), } } diff --git a/crates/sqlload/src/adapters/dispatch/main/session/write_problems.rs b/crates/sqlload/src/adapters/dispatch/main/session/write_problems.rs index dff24f07b..9edd5e3fc 100644 --- a/crates/sqlload/src/adapters/dispatch/main/session/write_problems.rs +++ b/crates/sqlload/src/adapters/dispatch/main/session/write_problems.rs @@ -6,7 +6,9 @@ use crate::adapters::dispatch::models::Destination; use crate::adapters::duckdb::main::_stage_problems::stage_problems; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::main::_variant_problems::variant_problems; +use crate::adapters::postgres::main::session::_session_write_problems::session_write_problems as session_postgres_write_problems; use crate::adapters::postgres::main::session::_write_problems::write_problems as postgres_write_problems; +use crate::column_types::models::Warehouse; use crate::loader::errors::LoaderError; /// Why `mode` cannot run against `table` (`exists` when it does) (problems), and what it may fail on (warnings); `variants` when the table has `VARIANT` columns, which MotherDuck needs a recent enough DuckDB for; and a MotherDuck `external_stage` SQLLoad cannot write or MotherDuck cannot read. None where the warehouse's writes need nothing of the table or its server. @@ -21,6 +23,9 @@ pub async fn write_problems( Destination::Postgres(postgres) => { postgres_write_problems(postgres, table, (mode, exists)).await } + Destination::Session(session) if session.connection.warehouse == Warehouse::Postgres => { + session_postgres_write_problems(session, table, (mode, exists)).await + } #[cfg(feature = "duckdb")] Destination::DuckDb(duckdb) => { let (mut problems, warnings) = match variants { diff --git a/crates/sqlload/src/adapters/dispatch/main/write/open_table_writer.rs b/crates/sqlload/src/adapters/dispatch/main/write/open_table_writer.rs index f03405f97..7e69bc5ea 100644 --- a/crates/sqlload/src/adapters/dispatch/main/write/open_table_writer.rs +++ b/crates/sqlload/src/adapters/dispatch/main/write/open_table_writer.rs @@ -8,6 +8,7 @@ use crate::adapters::dispatch::models::{Destination, Writer}; use crate::adapters::duckdb::models::DuckDbWriter; use crate::adapters::files::models::ParquetFiles; use crate::adapters::postgres::models::PostgresWriter; +use crate::adapters::session::main::_open_writer::open_writer; use crate::adapters::snowflake::models::{SnowflakeWriter, StageRoute}; use crate::file_store::main::open_folder::open_folder; use crate::loader::errors::LoaderError; @@ -63,5 +64,6 @@ pub fn open_table_writer( staged_build: None, }))), Destination::Files(_) => Ok(Writer::Files(ParquetFiles)), + Destination::Session(session) => Ok(Writer::Session(Box::new(open_writer(session)?))), } } diff --git a/crates/sqlload/src/adapters/dispatch/models.rs b/crates/sqlload/src/adapters/dispatch/models.rs index 56c308dd1..0da498f4d 100644 --- a/crates/sqlload/src/adapters/dispatch/models.rs +++ b/crates/sqlload/src/adapters/dispatch/models.rs @@ -5,6 +5,7 @@ use crate::adapters::databricks::models::{DatabricksDestination, DatabricksWrite use crate::adapters::duckdb::models::{DuckDbDestination, DuckDbWriter}; use crate::adapters::files::models::{FilesDestination, ParquetFiles}; use crate::adapters::postgres::models::{PostgresDestination, PostgresWriter}; +use crate::adapters::session::models::{SessionDestination, SessionWriter}; use crate::adapters::snowflake::models::{SnowflakeDestination, SnowflakeWriter}; /// An open destination. @@ -19,6 +20,8 @@ pub enum Destination { ClickHouse(Box), /// Parquet files in an s3, gcs or filesystem connection. Files(Box), + /// A warehouse reached through a connection the caller owns. + Session(Box), } /// One table's write session, on the destination it loads into. @@ -32,4 +35,5 @@ pub enum Writer { Postgres(Box), ClickHouse(Box), Files(ParquetFiles), + Session(Box), } diff --git a/crates/sqlload/src/adapters/duckdb/_helpers/sql_adapter.rs b/crates/sqlload/src/adapters/duckdb/_helpers/sql_adapter.rs index 4722cab44..07b50f2da 100644 --- a/crates/sqlload/src/adapters/duckdb/_helpers/sql_adapter.rs +++ b/crates/sqlload/src/adapters/duckdb/_helpers/sql_adapter.rs @@ -1,9 +1,10 @@ //! DuckDB's SQL: the contract's shared rendering, with DuckDB's types. use crate::adapters::contract::main::_rebuilt_in_place::rebuilt_in_place; -use crate::adapters::contract::models::TableName; +use crate::adapters::contract::models::{SessionRows, TableName}; use crate::adapters::contract::types::SqlAdapter; use crate::adapters::duckdb::_helpers::type_names::{logical_type, portable_type}; +use crate::adapters::duckdb::constants::DESCRIBE_TABLE_SQL; use crate::adapters::duckdb::models::DuckDbSql; use crate::column_types::constants::VARIANT_TYPE; use crate::column_types::main::is_variant::is_variant; @@ -89,4 +90,38 @@ impl SqlAdapter for DuckDbSql { self.render_loader_value_literal(&format!("%{suffix}%")) ) } + + /// A caller's session reads the Parquet files SQLLoad writes on this machine itself. + fn session_rows(&self) -> SessionRows { + SessionRows::LocalParquet + } + + /// [`DESCRIBE_TABLE_SQL`] with the schema and table as literals: in the session's current database, which is the one tables load into. + fn render_describe_table(&self, table: &TableName, _database: Option<&str>) -> Option { + let mut parts = DESCRIBE_TABLE_SQL.split('?'); + let (head, middle, tail) = (parts.next()?, parts.next()?, parts.next()?); + Some(format!( + "{head}{}{middle}{}{tail}", + self.render_loader_value_literal(&table.schema), + self.render_loader_value_literal(&table.table) + )) + } + + fn render_insert_local_parquet( + &self, + table: &TableName, + names: &[String], + file: &str, + ) -> Option { + let list: Vec = names + .iter() + .map(|name| self.render_identifier(name)) + .collect(); + Some(format!( + "INSERT INTO {} ({list}) SELECT {list} FROM read_parquet({})", + self.render_qualified_name(table), + self.render_loader_value_literal(file), + list = list.join(", ") + )) + } } diff --git a/crates/sqlload/src/adapters/mod.rs b/crates/sqlload/src/adapters/mod.rs index 5cbf3261a..88effe315 100644 --- a/crates/sqlload/src/adapters/mod.rs +++ b/crates/sqlload/src/adapters/mod.rs @@ -10,4 +10,5 @@ pub mod files; #[cfg(feature = "duckdb")] pub mod motherduck_bridge; pub mod postgres; +pub mod session; pub mod snowflake; diff --git a/crates/sqlload/src/adapters/postgres/_helpers/mod.rs b/crates/sqlload/src/adapters/postgres/_helpers/mod.rs index 3081bd659..8b2fa4468 100644 --- a/crates/sqlload/src/adapters/postgres/_helpers/mod.rs +++ b/crates/sqlload/src/adapters/postgres/_helpers/mod.rs @@ -4,3 +4,4 @@ pub(crate) mod session; pub(crate) mod sql_adapter; pub(crate) mod table_writer; pub(crate) mod type_names; +pub(crate) mod write_checks; diff --git a/crates/sqlload/src/adapters/postgres/_helpers/sql_adapter.rs b/crates/sqlload/src/adapters/postgres/_helpers/sql_adapter.rs index ea9869756..c3857d06a 100644 --- a/crates/sqlload/src/adapters/postgres/_helpers/sql_adapter.rs +++ b/crates/sqlload/src/adapters/postgres/_helpers/sql_adapter.rs @@ -3,11 +3,14 @@ use crate::adapters::contract::constants::{BEGIN_STATEMENT, COMMIT_STATEMENT, STAGING_SUFFIX}; use crate::adapters::contract::main::_ranked_source::ranked_source; use crate::adapters::contract::models::{ - ChangeApply, CursorValue, TableName, WriteMode, WriteStatementsRequest, + ChangeApply, CursorValue, SessionRows, TableName, WriteMode, WriteStatementsRequest, }; use crate::adapters::contract::types::SqlAdapter; +use crate::adapters::postgres::_helpers::copy_rows::copy_chunks; use crate::adapters::postgres::_helpers::type_names::{logical_type, portable_type, staging_type}; -use crate::adapters::postgres::constants::{BLOCK_QUOTE, TEMPORARY_SCHEMA, UNBOUNDED_NUMERIC}; +use crate::adapters::postgres::constants::{ + BLOCK_QUOTE, DESCRIBE_TABLE_SQL, TEMPORARY_SCHEMA, UNBOUNDED_NUMERIC, +}; use crate::adapters::postgres::models::PostgresSql; use crate::column_types::models::{ColumnType, LiveColumnType, TypeFit, Warehouse, WarehouseType}; use crate::schema_plan::models::DesiredColumn; @@ -288,4 +291,38 @@ impl SqlAdapter for PostgresSql { fn render_binary_text(&self, expression: &str) -> String { format!("{expression} COLLATE \"C\"") } + + /// A caller's session copies the rows in with a binary `COPY ... FROM STDIN`, as Postgres's own writer does. + fn session_rows(&self) -> SessionRows { + SessionRows::CopyIn + } + + /// [`DESCRIBE_TABLE_SQL`] with the schema and table as literals. + fn render_describe_table(&self, table: &TableName, _database: Option<&str>) -> Option { + let (head, rest) = DESCRIBE_TABLE_SQL.split_once("$1")?; + let (middle, tail) = rest.split_once("$2")?; + Some(format!( + "{head}{}{middle}{}{tail}", + self.render_loader_value_literal(&self.stored_name(&table.schema)), + self.render_loader_value_literal(&self.stored_name(&table.table)) + )) + } + + fn session_copy_in( + &self, + table: &TableName, + batch: &arrow_array::RecordBatch, + columns: &[DesiredColumn], + ) -> Option), String>> { + let names: Vec = columns + .iter() + .map(|column| self.render_identifier(&column.name)) + .collect(); + let statement = format!( + "COPY {} ({}) FROM STDIN (FORMAT binary)", + self.render_qualified_name(table), + names.join(", ") + ); + Some(copy_chunks(batch, columns, usize::MAX).map(|chunks| (statement, chunks.concat()))) + } } diff --git a/crates/sqlload/src/adapters/postgres/_helpers/write_checks.rs b/crates/sqlload/src/adapters/postgres/_helpers/write_checks.rs new file mode 100644 index 000000000..70f8f3b12 --- /dev/null +++ b/crates/sqlload/src/adapters/postgres/_helpers/write_checks.rs @@ -0,0 +1,201 @@ +//! The checks before a Postgres write, apart from how their queries run: on SQLLoad's own session, or a caller's. + +use crate::adapters::contract::models::{TableName, WriteMode}; +use crate::adapters::contract::types::SqlAdapter; +use crate::adapters::postgres::constants::{KEY_INDEX_SQL, REFERENCES_SQL}; +use crate::adapters::postgres::models::{KeyIndexes, PostgresSql, ReferenceRow}; + +/// The merge key's columns as stored, sorted as `KEY_INDEX_SQL` compares them. +pub(crate) fn sorted_key(unique_key: &[String]) -> Vec { + let mut key: Vec = unique_key + .iter() + .map(|column| PostgresSql.stored_name(column)) + .collect(); + key.sort(); + key +} + +/// The key columns of `mode` that may hold NULL: those the source says may, unless the existing table's `indexes` say it declares them NOT NULL. +pub(crate) fn nullable_keys<'a>(mode: &'a WriteMode, indexes: Option<&KeyIndexes>) -> Vec<&'a str> { + mode.matched_keys() + .into_iter() + .filter_map(|(key, nullable)| nullable.then_some(key)) + .filter(|key| { + indexes.is_none_or(|indexes| !indexes.not_null.contains(&PostgresSql.stored_name(key))) + }) + .collect() +} + +/// The foreign keys in `rows` referencing `schema.name` that a write deleting its rows (`mode`) would carry into their tables (problems), or that would refuse it while their rows reference the rows it deletes (warnings); `replace` skips the table's own. +pub(crate) fn reference_outcome( + rows: &[ReferenceRow], + (schema, name): (&str, &str), + mode: &WriteMode, +) -> (Vec, Vec) { + let strategy = match mode { + WriteMode::Replace => "replace", + _ => "delete_insert", + }; + let (mut problems, mut warnings) = (Vec::new(), Vec::new()); + for row in rows { + let carried = match row.action.as_str() { + "c" => Some("ON DELETE CASCADE deletes"), + "n" => Some("ON DELETE SET NULL changes"), + "d" => Some("ON DELETE SET DEFAULT changes"), + _ => None, + }; + let (referencing, constraint) = (&row.referencing, &row.constraint); + match ( + carried, + row.deferred, + row.action.as_str(), + row.own && matches!(mode, WriteMode::Replace), + ) { + (_, _, _, true) => {} + (Some(effect), _, _, _) => problems.push(format!( + "{referencing} references {schema}.{name} ({constraint}), and its {effect} its rows when {strategy} deletes the rows it replaces; SQLLoad refuses to change another table, so change the constraint's ON DELETE action, or load with merge" + )), + (None, true, "a", _) => {} + (None, _, _, _) => warnings.push(format!( + "{referencing} references {schema}.{name} ({constraint}), so {strategy} fails while any of its rows reference a row it deletes" + )), + } + } + (problems, warnings) +} + +/// `sql` with each `$N` placeholder replaced by `values[N - 1]`, SQL already: for a session that runs SQL text alone. +pub(crate) fn bound(sql: &str, values: &[String]) -> Result { + let mut out = String::with_capacity(sql.len()); + let mut characters = sql.chars().peekable(); + while let Some(character) = characters.next() { + if character != '$' || !characters.peek().is_some_and(char::is_ascii_digit) { + out.push(character); + continue; + } + let mut digits = String::new(); + while let Some(digit) = characters.next_if(char::is_ascii_digit) { + digits.push(digit); + } + let number: usize = digits + .parse() + .map_err(|error| format!("${digits} is not a placeholder: {error}"))?; + let value = number + .checked_sub(1) + .and_then(|index| values.get(index)) + .ok_or_else(|| format!("${digits} has no value"))?; + out.push_str(value); + } + Ok(out) +} + +/// `sql`, which gives `columns` columns, with each value cast to text, so what a caller's driver gives back is Postgres's own text whatever the column's type. +pub(crate) fn as_text(sql: &str, columns: usize) -> String { + let names: Vec = (1..=columns).map(|index| format!("c{index}")).collect(); + let casts: Vec = names.iter().map(|name| format!("{name}::text")).collect(); + format!( + "SELECT {} FROM ({sql}) AS q({})", + casts.join(", "), + names.join(", ") + ) +} + +/// The elements of a one-dimensional Postgres array in its text form (`{a,"b c"}`). +pub(crate) fn text_array(text: &str) -> Result, String> { + let inner = text + .strip_prefix('{') + .and_then(|rest| rest.strip_suffix('}')) + .ok_or_else(|| format!("{text:?} is not an array"))?; + let mut elements: Vec = Vec::new(); + let (mut current, mut quoted, mut escaped) = (String::new(), false, false); + for character in inner.chars() { + match (escaped, quoted, character) { + (true, _, _) => { + current.push(character); + escaped = false; + } + (false, true, '\\') => escaped = true, + (false, _, '"') => quoted = !quoted, + (false, false, ',') => elements.push(std::mem::take(&mut current)), + _ => current.push(character), + } + } + if !inner.is_empty() { + elements.push(current); + } + Ok(elements) +} + +/// `KEY_INDEX_SQL` for `table` (as stored) and `unique_key`, its values as text, for a caller's session. +pub(crate) fn key_index_text_query( + table: &TableName, + unique_key: &[String], +) -> Result { + let key: Vec = sorted_key(unique_key) + .iter() + .map(|column| PostgresSql.render_loader_value_literal(column)) + .collect(); + let query = bound( + KEY_INDEX_SQL, + &[ + PostgresSql.render_loader_value_literal(&table.schema), + PostgresSql.render_loader_value_literal(&table.table), + format!("ARRAY[{}]", key.join(", ")), + ], + )?; + Ok(as_text(&query, 5)) +} + +/// `REFERENCES_SQL` for `schema.name` (as stored), its values as text, for a caller's session. +pub(crate) fn references_text_query((schema, name): (&str, &str)) -> Result { + let query = bound( + REFERENCES_SQL, + &[ + PostgresSql.render_loader_value_literal(schema), + PostgresSql.render_loader_value_literal(name), + ], + )?; + Ok(as_text(&query, 5)) +} + +/// The unique indexes [`key_index_text_query`]'s row describes. +pub(crate) fn text_key_indexes(row: &[Option]) -> Result { + Ok(KeyIndexes { + count: parsed(row, 0)?, + nulls_equal: parsed(row, 1)?, + others: row_text(row, 2), + drops: row_text(row, 3), + not_null: text_array(&row_text(row, 4))?, + }) +} + +/// The foreign keys [`references_text_query`]'s rows describe. +pub(crate) fn text_references(rows: &[Vec>]) -> Result, String> { + rows.iter() + .map(|row| { + Ok(ReferenceRow { + referencing: row_text(row, 0), + constraint: row_text(row, 1), + action: row_text(row, 2), + deferred: parsed(row, 3)?, + own: parsed(row, 4)?, + }) + }) + .collect() +} + +/// The text of `row`'s value at `index`, empty for NULL. +pub(crate) fn row_text(row: &[Option], index: usize) -> String { + row.get(index).cloned().flatten().unwrap_or_default() +} + +/// `row`'s value at `index`, as Postgres writes a number or a boolean as text, parsed. +pub(crate) fn parsed( + row: &[Option], + index: usize, +) -> Result { + let text = row_text(row, index); + text.parse::().map_err(|_| { + format!("a check before the write gave {text:?}, which does not read as its type") + }) +} diff --git a/crates/sqlload/src/adapters/postgres/main/session/_session_write_problems.rs b/crates/sqlload/src/adapters/postgres/main/session/_session_write_problems.rs new file mode 100644 index 000000000..61afb4f96 --- /dev/null +++ b/crates/sqlload/src/adapters/postgres/main/session/_session_write_problems.rs @@ -0,0 +1,85 @@ +//! What stops or endangers a write into a table loaded through a caller's session. + +use crate::adapters::contract::models::{TableName, WriteMode}; +use crate::adapters::contract::types::SqlAdapter; +use crate::adapters::postgres::_helpers::null_keys::{index_problem, version_problem}; +use crate::adapters::postgres::_helpers::write_checks::{ + as_text, key_index_text_query, nullable_keys, parsed, reference_outcome, references_text_query, + row_text, text_key_indexes, text_references, +}; +use crate::adapters::postgres::constants::SERVER_VERSION_SQL; +use crate::adapters::postgres::models::PostgresSql; +use crate::adapters::session::main::_query_rows::query_rows; +use crate::adapters::session::models::SessionDestination; +use crate::loader::errors::LoaderError; + +/// The same checks as SQLLoad's own Postgres session runs before a write (see `write_problems`), with the same queries run as text on the caller's session. +pub(in crate::adapters) async fn session_write_problems( + destination: &SessionDestination, + table: &TableName, + (mode, exists): (&WriteMode, bool), +) -> Result<(Vec, Vec), LoaderError> { + let stored = TableName { + database: None, + schema: PostgresSql.stored_name(&table.schema), + table: PostgresSql.stored_name(&table.table), + }; + match mode { + WriteMode::Merge { unique_key, .. } => { + merge_problems(destination, &stored, (mode, unique_key, exists)).await + } + WriteMode::Replace | WriteMode::DeleteInsert { .. } if exists => { + let place = (stored.schema.as_str(), stored.table.as_str()); + let query = references_text_query(place).map_err(LoaderError::Invalid)?; + let rows = text_references(&query_rows(destination, query).await?) + .map_err(LoaderError::Invalid)?; + Ok(reference_outcome(&rows, place, mode)) + } + _ => Ok((Vec::new(), Vec::new())), + } +} + +/// What stops a merge on `unique_key` into `stored` (which exists when `exists`): no unique index `ON CONFLICT` can use, or a key that may be NULL on a server before Postgres 15. +async fn merge_problems( + destination: &SessionDestination, + stored: &TableName, + (mode, unique_key, exists): (&WriteMode, &[String], bool), +) -> Result<(Vec, Vec), LoaderError> { + let indexes = match exists { + true => { + let query = key_index_text_query(stored, unique_key).map_err(LoaderError::Invalid)?; + Some( + text_key_indexes(&first_row(destination, query).await?) + .map_err(LoaderError::Invalid)?, + ) + } + false => None, + }; + let nullable = nullable_keys(mode, indexes.as_ref()); + if !nullable.is_empty() { + let row = first_row(destination, as_text(SERVER_VERSION_SQL, 2)).await?; + let number: i32 = parsed(&row, 0).map_err(LoaderError::Invalid)?; + if let Some(problem) = version_problem(stored, &nullable, (number, &row_text(&row, 1))) { + return Ok((vec![problem], Vec::new())); + } + } + Ok(( + indexes + .and_then(|indexes| index_problem(stored, (unique_key, &nullable), &indexes)) + .into_iter() + .collect(), + Vec::new(), + )) +} + +/// The first row of `query` on the session. +async fn first_row( + destination: &SessionDestination, + query: String, +) -> Result>, LoaderError> { + query_rows(destination, query) + .await? + .into_iter() + .next() + .ok_or_else(|| LoaderError::Invalid("a check before the write returned no row".to_owned())) +} diff --git a/crates/sqlload/src/adapters/postgres/main/session/_write_problems.rs b/crates/sqlload/src/adapters/postgres/main/session/_write_problems.rs index 7882c39b5..c1ac6cac6 100644 --- a/crates/sqlload/src/adapters/postgres/main/session/_write_problems.rs +++ b/crates/sqlload/src/adapters/postgres/main/session/_write_problems.rs @@ -6,8 +6,13 @@ use crate::adapters::contract::models::{TableName, WriteMode}; use crate::adapters::contract::types::SqlAdapter; use crate::adapters::postgres::_helpers::null_keys::{index_problem, version_problem}; use crate::adapters::postgres::_helpers::session::{query_error, session}; +use crate::adapters::postgres::_helpers::write_checks::{ + nullable_keys, reference_outcome, sorted_key, +}; use crate::adapters::postgres::constants::{KEY_INDEX_SQL, REFERENCES_SQL, SERVER_VERSION_SQL}; -use crate::adapters::postgres::models::{KeyIndexes, PostgresDestination, PostgresSql}; +use crate::adapters::postgres::models::{ + KeyIndexes, PostgresDestination, PostgresSql, ReferenceRow, +}; use crate::loader::errors::LoaderError; /// Why `mode` cannot run against `table` (`exists` when it does), and what it may fail on: `merge` needs a unique index `ON CONFLICT` can use on exactly its key, which treats NULLs as equal (Postgres 15 and later) when a key column may hold NULL (the source says it may, and an existing table does not declare it NOT NULL), so a row with a NULL key matches the one the table holds; `replace` and `delete_insert` delete rows, which a foreign key with `ON DELETE CASCADE`, `SET NULL` or `SET DEFAULT` would carry into its own table (refused), and one checked at once (any `RESTRICT`) would refuse while its rows reference them (warned); a table's reference to itself only matters to `delete_insert`, since `replace` deletes every row. @@ -33,16 +38,7 @@ pub(in crate::adapters) async fn write_problems( true => Some(key_indexes(client, &stored, unique_key).await?), false => None, }; - let nullable: Vec<&str> = mode - .matched_keys() - .into_iter() - .filter_map(|(key, nullable)| nullable.then_some(key)) - .filter(|key| { - indexes.as_ref().is_none_or(|indexes| { - !indexes.not_null.contains(&PostgresSql.stored_name(key)) - }) - }) - .collect(); + let nullable = nullable_keys(mode, indexes.as_ref()); if !nullable.is_empty() { let row = client .query_one(SERVER_VERSION_SQL, &[]) @@ -63,7 +59,8 @@ pub(in crate::adapters) async fn write_problems( )) } WriteMode::Replace | WriteMode::DeleteInsert { .. } if exists => { - reference_problems(client, (&schema, &name), mode).await + let rows = reference_rows(client, (&schema, &name)).await?; + Ok(reference_outcome(&rows, (&schema, &name), mode)) } _ => Ok((Vec::new(), Vec::new())), } @@ -75,11 +72,7 @@ async fn key_indexes( table: &TableName, unique_key: &[String], ) -> Result { - let mut key: Vec = unique_key - .iter() - .map(|column| PostgresSql.stored_name(column)) - .collect(); - key.sort(); + let key = sorted_key(unique_key); let row = client .query_one(KEY_INDEX_SQL, &[&table.schema, &table.table, &key]) .await @@ -93,43 +86,25 @@ async fn key_indexes( }) } -/// The foreign keys referencing `schema.name` that a write deleting its rows would carry into their tables (problems), or that would refuse it while their rows reference the rows it deletes (warnings); `replace` skips the table's own. -async fn reference_problems( +/// The foreign keys referencing `schema.name`. +async fn reference_rows( client: &Client, (schema, name): (&str, &str), - mode: &WriteMode, -) -> Result<(Vec, Vec), LoaderError> { - let strategy = match mode { - WriteMode::Replace => "replace", - _ => "delete_insert", - }; - let rows = client +) -> Result, LoaderError> { + client .query(REFERENCES_SQL, &[&schema, &name]) .await - .map_err(query_error)?; - let (mut problems, mut warnings) = (Vec::new(), Vec::new()); - for row in rows { - let referencing: String = row.try_get(0).map_err(query_error)?; - let constraint: String = row.try_get(1).map_err(query_error)?; - let action: String = row.try_get(2).map_err(query_error)?; - let deferred: bool = row.try_get(3).map_err(query_error)?; - let own: bool = row.try_get(4).map_err(query_error)?; - let carried = match action.as_str() { - "c" => Some("ON DELETE CASCADE deletes"), - "n" => Some("ON DELETE SET NULL changes"), - "d" => Some("ON DELETE SET DEFAULT changes"), - _ => None, - }; - match (carried, deferred, action.as_str(), own && matches!(mode, WriteMode::Replace)) { - (_, _, _, true) => {} - (Some(effect), _, _, _) => problems.push(format!( - "{referencing} references {schema}.{name} ({constraint}), and its {effect} its rows when {strategy} deletes the rows it replaces; SQLLoad refuses to change another table, so change the constraint's ON DELETE action, or load with merge" - )), - (None, true, "a", _) => {} - (None, _, _, _) => warnings.push(format!( - "{referencing} references {schema}.{name} ({constraint}), so {strategy} fails while any of its rows reference a row it deletes" - )), - } - } - Ok((problems, warnings)) + .map_err(query_error)? + .iter() + .map(|row| { + Ok(ReferenceRow { + referencing: row.try_get(0)?, + constraint: row.try_get(1)?, + action: row.try_get(2)?, + deferred: row.try_get(3)?, + own: row.try_get(4)?, + }) + }) + .collect::, tokio_postgres::Error>>() + .map_err(query_error) } diff --git a/crates/sqlload/src/adapters/postgres/main/session/mod.rs b/crates/sqlload/src/adapters/postgres/main/session/mod.rs index eb34f8c5f..d1b41d3c7 100644 --- a/crates/sqlload/src/adapters/postgres/main/session/mod.rs +++ b/crates/sqlload/src/adapters/postgres/main/session/mod.rs @@ -3,4 +3,5 @@ pub(in crate::adapters) mod _describe_table; pub(in crate::adapters) mod _open_postgres; pub(in crate::adapters) mod _query_rows; pub(in crate::adapters) mod _run_statements; +pub(in crate::adapters) mod _session_write_problems; pub(in crate::adapters) mod _write_problems; diff --git a/crates/sqlload/src/adapters/postgres/models.rs b/crates/sqlload/src/adapters/postgres/models.rs index 0d1c09bb6..5a45313ca 100644 --- a/crates/sqlload/src/adapters/postgres/models.rs +++ b/crates/sqlload/src/adapters/postgres/models.rs @@ -44,6 +44,19 @@ pub(crate) struct KeyIndexes { pub(crate) not_null: Vec, } +/// A foreign key referencing a table, as `REFERENCES_SQL` lists it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ReferenceRow { + /// The referencing table, `schema.table`. + pub(crate) referencing: String, + pub(crate) constraint: String, + /// Its `ON DELETE` action as `confdeltype` spells it (`c`, `n`, `d`, `r` or `a`). + pub(crate) action: String, + pub(crate) deferred: bool, + /// The table references itself. + pub(crate) own: bool, +} + /// One table's write session on Postgres: each batch is sent by binary `COPY` into the temporary staging table on the table's own session. #[derive(Debug)] pub struct PostgresWriter { diff --git a/crates/sqlload/src/adapters/postgres/tests.rs b/crates/sqlload/src/adapters/postgres/tests.rs index 1cdb77b9a..832450835 100644 --- a/crates/sqlload/src/adapters/postgres/tests.rs +++ b/crates/sqlload/src/adapters/postgres/tests.rs @@ -8,3 +8,5 @@ mod helpers; mod null_keys; #[path = "tests/test_types.rs"] mod test_types; +#[path = "tests/test_write_checks.rs"] +mod write_checks; diff --git a/crates/sqlload/src/adapters/postgres/tests/test_types.rs b/crates/sqlload/src/adapters/postgres/tests/test_types.rs index 8856228e5..ea9247c81 100644 --- a/crates/sqlload/src/adapters/postgres/tests/test_types.rs +++ b/crates/sqlload/src/adapters/postgres/tests/test_types.rs @@ -53,3 +53,17 @@ pub(crate) struct NullKeysProblemTestCase { /// Text the problem holds; `None` when the merge can run. pub(crate) expected_problem: Option<&'static str>, } + +pub(crate) struct BoundTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + pub(crate) values: &'static [&'static str], + /// The SQL with its placeholders filled, or why it cannot be. + pub(crate) expected_sql: Result<&'static str, &'static str>, +} + +pub(crate) struct TextArrayTestCase { + pub(crate) description: &'static str, + pub(crate) text: &'static str, + pub(crate) expected_elements: &'static [&'static str], +} diff --git a/crates/sqlload/src/adapters/postgres/tests/test_write_checks.rs b/crates/sqlload/src/adapters/postgres/tests/test_write_checks.rs new file mode 100644 index 000000000..b363d5e04 --- /dev/null +++ b/crates/sqlload/src/adapters/postgres/tests/test_write_checks.rs @@ -0,0 +1,82 @@ +use crate::adapters::postgres::_helpers::write_checks::{bound, text_array}; +use crate::adapters::postgres::tests::test_types::{BoundTestCase, TextArrayTestCase}; + +#[test] +fn given_a_query_with_placeholders_when_bound_for_a_callers_session_then_each_takes_its_value_once() +{ + let test_cases = [ + BoundTestCase { + description: "each placeholder takes its value, wherever it repeats", + sql: "WHERE n = $1 AND c = $2 OR n2 = $1", + values: &["'raw'", "'orders'"], + expected_sql: Ok("WHERE n = 'raw' AND c = 'orders' OR n2 = 'raw'"), + }, + BoundTestCase { + description: "a value holding a placeholder's text is not filled again", + sql: "WHERE n = $1 AND c = $2", + values: &["'$2'", "'orders'"], + expected_sql: Ok("WHERE n = '$2' AND c = 'orders'"), + }, + BoundTestCase { + description: "a dollar sign not before a digit stays", + sql: "SELECT $sqlload$x$sqlload$, $1", + values: &["1"], + expected_sql: Ok("SELECT $sqlload$x$sqlload$, 1"), + }, + BoundTestCase { + description: "a placeholder without a value fails", + sql: "WHERE n = $3", + values: &["'raw'"], + expected_sql: Err("$3 has no value"), + }, + ]; + for test_case in test_cases { + let values: Vec = test_case + .values + .iter() + .map(|value| (*value).to_owned()) + .collect(); + assert_eq!( + bound(test_case.sql, &values), + test_case + .expected_sql + .map(str::to_owned) + .map_err(str::to_owned), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_postgres_array_as_text_when_read_then_its_elements_come_apart() { + let test_cases = [ + TextArrayTestCase { + description: "an empty array has no elements", + text: "{}", + expected_elements: &[], + }, + TextArrayTestCase { + description: "plain names split at commas", + text: "{customer_id,order_id}", + expected_elements: &["customer_id", "order_id"], + }, + TextArrayTestCase { + description: "quoted names keep their commas, spaces and escaped quotes", + text: "{\"a,b\",\"c d\",\"e\\\"f\"}", + expected_elements: &["a,b", "c d", "e\"f"], + }, + ]; + for test_case in test_cases { + assert_eq!( + text_array(test_case.text), + Ok(test_case + .expected_elements + .iter() + .map(|element| (*element).to_owned()) + .collect()), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlload/src/adapters/session/_helpers/blocking.rs b/crates/sqlload/src/adapters/session/_helpers/blocking.rs new file mode 100644 index 000000000..8b77d8a03 --- /dev/null +++ b/crates/sqlload/src/adapters/session/_helpers/blocking.rs @@ -0,0 +1,64 @@ +//! Calls into the caller's session, which block, made from a blocking thread. + +use std::sync::Arc; + +use crate::adapters::contract::types::SqlAdapter; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::adapters::session::errors::SessionError; +use crate::adapters::session::models::SessionDestination; +use crate::adapters::session::types::CallerSession; +use crate::loader::errors::LoaderError; + +/// The destination's session, opened on first use. +pub(crate) async fn opened( + destination: &SessionDestination, +) -> Result, LoaderError> { + let caller = destination.connection.caller.clone(); + let dialect = sql_adapter(destination.connection.warehouse); + destination + .session + .get_or_try_init(|| async move { + tokio::task::spawn_blocking(move || prepared(caller.open()?, dialect)) + .await + .map_err(joined)? + }) + .await + .cloned() +} + +/// `session` set up as SQLLoad's own sessions are, once its autocommit is checked: with it off, statements outside SQLLoad's transactions would never commit. +fn prepared( + session: Arc, + dialect: &'static dyn SqlAdapter, +) -> Result, LoaderError> { + if let Some(query) = dialect.render_autocommit_check() { + let rows = session.query_text(&query)?; + let value = rows.first().and_then(|row| row.get(1)).cloned().flatten(); + if value.is_some_and(|value| value.eq_ignore_ascii_case("false")) { + return Err(LoaderError::Invalid(format!( + "the caller's {} session has autocommit off; SQLLoad needs it on, and sends BEGIN and COMMIT itself", + dialect.warehouse() + ))); + } + } + for statement in dialect.render_session_setup() { + session.execute(&statement)?; + } + Ok(session) +} + +/// Run `work` on the destination's session from a blocking thread. +pub(crate) async fn on_session( + destination: &SessionDestination, + work: impl FnOnce(&dyn CallerSession) -> Result + Send + 'static, +) -> Result { + let session = opened(destination).await?; + tokio::task::spawn_blocking(move || work(session.as_ref())) + .await + .map_err(joined)? + .map_err(LoaderError::from) +} + +fn joined(error: tokio::task::JoinError) -> LoaderError { + LoaderError::Invalid(format!("the caller's session thread failed: {error}")) +} diff --git a/crates/sqlload/src/adapters/session/_helpers/mod.rs b/crates/sqlload/src/adapters/session/_helpers/mod.rs new file mode 100644 index 000000000..e1bf1f432 --- /dev/null +++ b/crates/sqlload/src/adapters/session/_helpers/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod blocking; +pub(crate) mod table_writer; diff --git a/crates/sqlload/src/adapters/session/_helpers/table_writer.rs b/crates/sqlload/src/adapters/session/_helpers/table_writer.rs new file mode 100644 index 000000000..edf508e62 --- /dev/null +++ b/crates/sqlload/src/adapters/session/_helpers/table_writer.rs @@ -0,0 +1,205 @@ +//! A table's write session through the caller's session: each batch goes into the staging table, by the way the warehouse takes rows from a caller's session. + +use std::path::PathBuf; + +use arrow_array::RecordBatch; + +use crate::adapters::contract::models::{SessionRows, SessionStage, TableName, WriteTarget}; +use crate::adapters::contract::types::TableWriter; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::adapters::session::_helpers::blocking::on_session; +use crate::adapters::session::main::_run_statements::run_statements; +use crate::adapters::session::models::SessionWriter; +use crate::column_types::models::ColumnType; +use crate::loader::errors::LoaderError; +use crate::schema_plan::models::DesiredColumn; + +impl TableWriter for SessionWriter { + /// Never: every batch waits in the staging table, so each commit is one transaction on the table, in statements SQLLoad renders. + fn writes_directly(&self) -> bool { + false + } + + async fn write_batch( + &mut self, + target: &WriteTarget<'_>, + batch: RecordBatch, + ) -> Result<(), LoaderError> { + let Some(staging) = target.staging.cloned() else { + return Err(LoaderError::Invalid(format!( + "{}: a caller's session loads every batch through a staging table", + target.table.table + ))); + }; + let dialect = sql_adapter(self.destination.connection.warehouse); + let columns = batch_columns(target, &batch); + match dialect.session_rows() { + SessionRows::CopyIn => { + let (statement, data) = encode(move || { + dialect + .session_copy_in(&staging, &batch, &columns) + .unwrap_or_else(|| Err("the warehouse takes no COPY FROM STDIN".to_owned())) + }) + .await?; + on_session(&self.destination, move |session| { + session.copy_in(&statement, &data) + }) + .await + } + SessionRows::LocalParquet => { + let file = self.write_file(&batch, &columns).await?; + let names: Vec = columns.iter().map(|column| column.name.clone()).collect(); + let statement = dialect + .render_insert_local_parquet(&staging, &names, &file.to_string_lossy()) + .ok_or_else(|| { + LoaderError::Invalid( + "the warehouse cannot read this machine's files".to_owned(), + ) + })?; + let loaded = run_statements(&self.destination, vec![statement]).await; + remove_file(&file); + loaded + } + SessionRows::CallerLoadsParquet => { + let file = self.write_file(&batch, &columns).await?; + let into = file.clone(); + let loaded = on_session(&self.destination, move |session| { + session.load_parquet(&staging, &into) + }) + .await; + remove_file(&file); + loaded + } + SessionRows::StagedParquet => { + let file = self.write_file(&batch, &columns).await?; + let put = dialect.render_session_stage(SessionStage::Put { + load_id: target.load_id, + batch: target.batch, + file: &file.to_string_lossy(), + }); + let name = file + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + self.staged.push(name); + let loaded = run_statements(&self.destination, put).await; + remove_file(&file); + loaded + } + } + } + + fn staged_bytes(&self) -> Option { + None + } + + async fn finish_files(&mut self, _target: &WriteTarget<'_>) -> Result<(), LoaderError> { + Ok(()) + } + + /// `COPY` the batch's staged files into the staging table, then remove them, where the warehouse loads them together. + async fn load_batch(&mut self, target: &WriteTarget<'_>) -> Result<(), LoaderError> { + if self.staged.is_empty() { + return Ok(()); + } + let dialect = sql_adapter(self.destination.connection.warehouse); + let into: &TableName = target.staging.unwrap_or(target.table); + let holds_json = target.builds + && target.columns.iter().any(|column| { + matches!(column.column_type, ColumnType::Json | ColumnType::Array(_)) + }); + let copies = dialect.render_session_stage(SessionStage::Copy { + load_id: target.load_id, + batch: target.batch, + table: into, + names: &self.staged, + selected: holds_json.then_some(target.columns), + }); + run_statements(&self.destination, copies).await?; + self.remove_batch_files(target).await; + Ok(()) + } + + fn next_batch(&mut self) { + self.staged.clear(); + } + + async fn settle_rows(&mut self) -> Result<(), LoaderError> { + Ok(()) + } + + fn reopen_rows(&mut self) {} + + async fn rollback_batch(&mut self) {} + + /// Remove the batch's files from the stage; a failure only warns. + async fn remove_batch_files(&mut self, target: &WriteTarget<'_>) { + if self.staged.is_empty() { + return; + } + let dialect = sql_adapter(self.destination.connection.warehouse); + let remove = dialect.render_session_stage(SessionStage::Remove { + load_id: target.load_id, + batch: target.batch, + }); + if let Err(error) = run_statements(&self.destination, remove).await { + tracing::warn!(%error, load_id = %target.load_id, "cannot remove a batch's staged files"); + } + self.staged.clear(); + } +} + +impl SessionWriter { + /// Write `batch` as the warehouse's Parquet file in the writer's folder, on a blocking thread. + async fn write_file( + &mut self, + batch: &RecordBatch, + columns: &[DesiredColumn], + ) -> Result { + self.written += 1; + let file = self + .folder + .path() + .join(format!("part-{:05}.parquet", self.written)); + let dialect = sql_adapter(self.destination.connection.warehouse); + let (batch, columns, path) = (batch.clone(), columns.to_vec(), file.clone()); + encode(move || { + let body = dialect.session_parquet(&batch, &columns)?; + std::fs::write(&path, body) + .map_err(|error| format!("cannot write {}: {error}", path.display())) + }) + .await?; + Ok(file) + } +} + +/// The staged columns `batch` carries, in its order. +fn batch_columns(target: &WriteTarget<'_>, batch: &RecordBatch) -> Vec { + let schema = batch.schema(); + let mut columns: Vec = Vec::with_capacity(schema.fields().len()); + for field in schema.fields() { + columns.extend( + target + .columns + .iter() + .find(|column| column.name == *field.name()) + .cloned(), + ); + } + columns +} + +/// Run encoding on a blocking thread, so tables loading at once encode in parallel. +async fn encode( + work: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(work) + .await + .map_err(|error| LoaderError::Invalid(format!("the encoding thread failed: {error}")))? + .map_err(LoaderError::Invalid) +} + +/// Delete a file the session has loaded; one left behind goes with the writer's folder. +fn remove_file(file: &PathBuf) { + let _ = std::fs::remove_file(file); +} diff --git a/crates/sqlload/src/adapters/session/errors.rs b/crates/sqlload/src/adapters/session/errors.rs new file mode 100644 index 000000000..bc8f9c261 --- /dev/null +++ b/crates/sqlload/src/adapters/session/errors.rs @@ -0,0 +1,44 @@ +/// What kind of failure a caller's session reported. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionErrorKind { + /// A failure a rerun will meet again: bad SQL, data, permissions. + Failed, + /// A failure a rerun may pass: a dropped connection or throttling, as the caller judges it. + Transient, + /// What a statement or query names does not exist, such as a BigQuery dataset before its first load: SQLLoad reads that as no table yet where it asks. + NotFound, +} + +/// Why the caller's session could not run a statement or take a file: the caller's own message, such as its driver's error. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{message}")] +pub struct SessionError { + pub message: String, + pub kind: SessionErrorKind, +} + +impl SessionError { + /// A failure a rerun will meet again. + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + kind: SessionErrorKind::Failed, + } + } + + /// A failure a rerun may pass. + pub fn transient(message: impl Into) -> Self { + Self { + message: message.into(), + kind: SessionErrorKind::Transient, + } + } + + /// A failure because what the statement names does not exist. + pub fn not_found(message: impl Into) -> Self { + Self { + message: message.into(), + kind: SessionErrorKind::NotFound, + } + } +} diff --git a/crates/sqlload/src/adapters/session/main/_check_session.rs b/crates/sqlload/src/adapters/session/main/_check_session.rs new file mode 100644 index 000000000..a17664fe5 --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_check_session.rs @@ -0,0 +1,17 @@ +//! What a session destination connects as. + +use crate::adapters::session::_helpers::blocking::opened; +use crate::adapters::session::models::SessionDestination; +use crate::loader::errors::LoaderError; + +/// The line a destination check prints for the caller's connection, once its session opens. +pub(in crate::adapters) async fn check_session( + destination: &SessionDestination, +) -> Result { + opened(destination).await?; + Ok(format!( + "{} through the caller's connection: {}", + destination.connection.warehouse, + destination.connection.caller.describe() + )) +} diff --git a/crates/sqlload/src/adapters/session/main/_connect_session.rs b/crates/sqlload/src/adapters/session/main/_connect_session.rs new file mode 100644 index 000000000..5193274cc --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_connect_session.rs @@ -0,0 +1,30 @@ +//! Open a destination on the caller's connection. + +use std::sync::Arc; + +use crate::adapters::session::_helpers::blocking::opened; +use crate::adapters::session::models::{SessionConnection, SessionDestination}; +use crate::column_types::models::Warehouse; +use crate::loader::errors::LoaderError; + +/// The destination a target on `connection` loads into, its names qualified with `database` (the target's), else the connection's; its session opens now, so a connection that cannot be reached fails before planning. +pub(in crate::adapters) async fn connect_session( + connection: &SessionConnection, + database: Option<&str>, +) -> Result { + if connection.warehouse == Warehouse::Parquet { + return Err(LoaderError::Invalid( + "a caller's session loads into a warehouse; files targets write through SQLLoad's own connections".to_owned(), + )); + } + let destination = SessionDestination { + connection: connection.clone(), + database: database + .map(str::to_owned) + .or_else(|| connection.database.clone()), + session: Arc::default(), + ddl: Arc::default(), + }; + opened(&destination).await?; + Ok(destination) +} diff --git a/crates/sqlload/src/adapters/session/main/_describe_table.rs b/crates/sqlload/src/adapters/session/main/_describe_table.rs new file mode 100644 index 000000000..04b14b178 --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_describe_table.rs @@ -0,0 +1,34 @@ +//! Read a table's live columns through the caller's session. + +use crate::adapters::contract::models::TableName; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::adapters::session::errors::SessionErrorKind; +use crate::adapters::session::main::_query_rows::query_rows; +use crate::adapters::session::models::SessionDestination; +use crate::loader::errors::LoaderError; +use crate::schema_plan::models::LiveColumn; + +/// The table's columns in order, or `None` if it does not exist: the dialect's describe query, which the warehouse's own destination runs too. A query the session reports as naming something that does not exist (a BigQuery dataset before its first load) means no table yet. +pub(in crate::adapters) async fn describe_table( + destination: &SessionDestination, + table: &TableName, +) -> Result>, LoaderError> { + let warehouse = destination.connection.warehouse; + let dialect = sql_adapter(warehouse); + let Some(query) = dialect.render_describe_table(table, destination.database.as_deref()) else { + return Err(LoaderError::Invalid(format!( + "{} needs a database to list {}'s columns: set the target's database", + warehouse, table.table + ))); + }; + let rows = match query_rows(destination, query).await { + Err(LoaderError::Session(error)) if error.kind == SessionErrorKind::NotFound => { + return Ok(None); + } + rows => rows?, + }; + let columns = dialect + .describe_text_rows(&rows) + .map_err(LoaderError::Invalid)?; + Ok((!columns.is_empty()).then_some(columns)) +} diff --git a/crates/sqlload/src/adapters/session/main/_open_writer.rs b/crates/sqlload/src/adapters/session/main/_open_writer.rs new file mode 100644 index 000000000..b154696bf --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_open_writer.rs @@ -0,0 +1,24 @@ +//! One table's write session through the caller's session. + +use crate::adapters::session::models::{SessionDestination, SessionWriter}; +use crate::loader::errors::LoaderError; + +/// The writer of one table's batches on `destination` (the table's own session), with a new folder for the files it writes. +pub(in crate::adapters) fn open_writer( + destination: &SessionDestination, +) -> Result { + let folder = tempfile::Builder::new() + .prefix("sqlload-session-") + .tempdir() + .map_err(|error| { + LoaderError::Invalid(format!( + "cannot create a folder for the files a caller's session loads: {error}" + )) + })?; + Ok(SessionWriter { + destination: destination.clone(), + staged: Vec::new(), + written: 0, + folder, + }) +} diff --git a/crates/sqlload/src/adapters/session/main/_query_rows.rs b/crates/sqlload/src/adapters/session/main/_query_rows.rs new file mode 100644 index 000000000..79fbf0781 --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_query_rows.rs @@ -0,0 +1,14 @@ +//! Run a query on the caller's session. + +use crate::adapters::session::_helpers::blocking::on_session; +use crate::adapters::session::models::SessionDestination; +use crate::loader::errors::LoaderError; + +/// The rows `query` gives on the destination's session, each value as text. +pub(in crate::adapters) async fn query_rows( + destination: &SessionDestination, + query: String, +) -> Result>>, LoaderError> { + tracing::debug!(%query, "querying the caller's session"); + on_session(destination, move |session| session.query_text(&query)).await +} diff --git a/crates/sqlload/src/adapters/session/main/_run_statements.rs b/crates/sqlload/src/adapters/session/main/_run_statements.rs new file mode 100644 index 000000000..d1d8c6672 --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_run_statements.rs @@ -0,0 +1,38 @@ +//! Run SQL statements on the caller's session. + +use crate::adapters::contract::constants::{BEGIN_STATEMENT, COMMIT_STATEMENT, ROLLBACK_STATEMENT}; +use crate::adapters::session::_helpers::blocking::on_session; +use crate::adapters::session::models::SessionDestination; +use crate::loader::errors::LoaderError; + +/// Run each statement in order on the destination's session, stopping at the first failure; a transaction open then (a failed `COMMIT` included) is rolled back, so a failed write leaves the table as it was. The caller's session never ends with the statements, as SQLLoad's own Snowflake requests do, so SQLLoad rolls back itself. +pub(in crate::adapters) async fn run_statements( + destination: &SessionDestination, + statements: Vec, +) -> Result<(), LoaderError> { + if statements.is_empty() { + return Ok(()); + } + on_session(destination, move |session| { + let mut in_transaction = false; + for statement in &statements { + tracing::debug!(%statement, "running on the caller's session"); + let opens = statement.trim() == BEGIN_STATEMENT; + if let Err(error) = session.execute(statement) { + if (in_transaction || opens) + && let Err(rollback) = session.execute(ROLLBACK_STATEMENT) + { + tracing::warn!(error = %rollback, "cannot roll back after a failed statement"); + } + return Err(error); + } + in_transaction = match statement.trim() { + BEGIN_STATEMENT => true, + COMMIT_STATEMENT | ROLLBACK_STATEMENT => false, + _ => in_transaction, + }; + } + Ok(()) + }) + .await +} diff --git a/crates/sqlload/src/adapters/session/main/_table_session.rs b/crates/sqlload/src/adapters/session/main/_table_session.rs new file mode 100644 index 000000000..ef73394c4 --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/_table_session.rs @@ -0,0 +1,13 @@ +//! A destination for one table's load. + +use std::sync::Arc; + +use crate::adapters::session::models::SessionDestination; + +/// `destination` with a session of its own, opened on first use, so the table's temporary tables and transactions never mix with another table loading at the same time; schema changes still wait for each other. +pub(in crate::adapters) fn table_session(destination: &SessionDestination) -> SessionDestination { + SessionDestination { + session: Arc::default(), + ..destination.clone() + } +} diff --git a/crates/sqlload/src/adapters/session/main/mod.rs b/crates/sqlload/src/adapters/session/main/mod.rs new file mode 100644 index 000000000..f44e0212f --- /dev/null +++ b/crates/sqlload/src/adapters/session/main/mod.rs @@ -0,0 +1,7 @@ +pub(in crate::adapters) mod _check_session; +pub(in crate::adapters) mod _connect_session; +pub(in crate::adapters) mod _describe_table; +pub(in crate::adapters) mod _open_writer; +pub(in crate::adapters) mod _query_rows; +pub(in crate::adapters) mod _run_statements; +pub(in crate::adapters) mod _table_session; diff --git a/crates/sqlload/src/adapters/session/mod.rs b/crates/sqlload/src/adapters/session/mod.rs new file mode 100644 index 000000000..22c46fb79 --- /dev/null +++ b/crates/sqlload/src/adapters/session/mod.rs @@ -0,0 +1,10 @@ +//! A destination SQLLoad writes through a connection its caller owns. SQLLoad still plans the load, renders every statement in the warehouse's dialect and decides every write; the caller runs the statements on its own connection, with its own credentials, and takes rows in the files SQLLoad writes. + +pub(crate) mod _helpers; +pub mod errors; +pub mod main; +pub mod models; +pub mod types; + +#[cfg(all(test, feature = "duckdb"))] +mod tests; diff --git a/crates/sqlload/src/adapters/session/models.rs b/crates/sqlload/src/adapters/session/models.rs new file mode 100644 index 000000000..68bbe0067 --- /dev/null +++ b/crates/sqlload/src/adapters/session/models.rs @@ -0,0 +1,54 @@ +use std::sync::Arc; + +use crate::adapters::session::types::{CallerConnection, CallerSession}; +use crate::column_types::models::Warehouse; + +/// A connection the caller attaches to a project by name (as `ConnectionConfig::Session`, which no project file can write): the warehouse its SQL is rendered for, and the caller's connection that runs it. +#[derive(Debug, Clone)] +pub struct SessionConnection { + /// Any warehouse but Parquet files. + pub warehouse: Warehouse, + /// A DuckDB connection that is MotherDuck's. + pub motherduck: bool, + /// The database tables load into, which every name SQLLoad renders is qualified with; a target's `database` overrides it. `None` where the warehouse has no level above schemas (ClickHouse) or the session's current one is meant. + pub database: Option, + pub caller: Arc, +} + +impl SessionConnection { + /// The connection kind this one stands in for, as `kind` spells it. + pub fn kind(&self) -> &'static str { + match (self.warehouse, self.motherduck) { + (Warehouse::DuckDb, true) => "motherduck", + (Warehouse::DuckDb, false) => "duckdb", + (Warehouse::Snowflake, _) => "snowflake", + (Warehouse::Databricks, _) => "databricks", + (Warehouse::BigQuery, _) => "bigquery", + (Warehouse::Postgres, _) => "postgres", + (Warehouse::ClickHouse, _) => "clickhouse", + (Warehouse::Parquet, _) => "filesystem", + } + } +} + +/// An open session destination: the connection, the database names are qualified with, and its session, opened on first use; each table loading gets a destination with a session of its own. +#[derive(Debug, Clone)] +pub struct SessionDestination { + pub connection: SessionConnection, + pub database: Option, + pub session: Arc>>, + /// Held while schema changes run, so tables loading at once never change the catalog together. + pub ddl: Arc>, +} + +/// One table's write session through the caller's session: every batch goes into the staging table, as files SQLLoad writes in a folder of its own. +#[derive(Debug)] +pub struct SessionWriter { + pub destination: SessionDestination, + /// The batch's files uploaded to the stage, by name ([`SessionRows::StagedParquet`](crate::adapters::contract::models::SessionRows::StagedParquet)). + pub staged: Vec, + /// Files written so far, for their names. + pub written: u64, + /// Where the files SQLLoad writes for the session wait until they load; removed with the writer. + pub folder: tempfile::TempDir, +} diff --git a/crates/sqlload/src/adapters/session/tests.rs b/crates/sqlload/src/adapters/session/tests.rs new file mode 100644 index 000000000..42c63014a --- /dev/null +++ b/crates/sqlload/src/adapters/session/tests.rs @@ -0,0 +1,8 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_session_loads.rs"] +mod session_loads; +#[path = "tests/test_session_routes.rs"] +mod session_routes; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlload/src/adapters/session/tests/helpers.rs b/crates/sqlload/src/adapters/session/tests/helpers.rs new file mode 100644 index 000000000..7eb2c32f9 --- /dev/null +++ b/crates/sqlload/src/adapters/session/tests/helpers.rs @@ -0,0 +1,540 @@ +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray}; + +use crate::adapters::contract::models::{TableName, WriteMode, WriteTarget}; +use crate::adapters::contract::types::TableWriter; +use crate::adapters::session::errors::SessionError; +use crate::adapters::session::main::_connect_session::connect_session; +use crate::adapters::session::main::_open_writer::open_writer; +use crate::adapters::session::models::SessionConnection; +use crate::adapters::session::tests::test_types::{ + Calls, DuckDbCaller, DuckDbSession, RecordingCaller, RecordingSession, +}; +use crate::adapters::session::types::{CallerConnection, CallerSession}; +use crate::column_types::models::{ColumnType, Warehouse}; +use crate::loader::main::apply_project::apply_project; +use crate::loader::main::connect_targets::connect_targets; +use crate::loader::main::load_tables::load_tables; +use crate::loader::main::plan_project::plan_project; +use crate::loader::models::{LoadRun, PlanOptions}; +use crate::project::main::parse_python_project::parse_python_project; +use crate::project::models::ProjectConfig; +use crate::schema_plan::models::{ColumnOrigin, DesiredColumn}; + +/// Each table's loaded rows, or why it failed, by table. +pub(crate) type Outcomes = BTreeMap>; + +/// The source's `orders` table at the start: two rows. +const ORDERS: &str = "CREATE TABLE orders (id INTEGER PRIMARY KEY, name VARCHAR, updated_at TIMESTAMP); +INSERT INTO orders VALUES (1, 'first', '2026-01-01 00:00:00'), (2, 'second', '2026-01-02 00:00:00');"; + +/// The loaded table's rows, as `id:name` by id. +const LOADED_ROWS: &str = "SELECT id, name FROM raw.shop__orders ORDER BY id"; + +/// The loaded table's data columns, in order. +const LOADED_COLUMNS: &str = "SELECT column_name FROM information_schema.columns WHERE table_schema = 'raw' AND table_name = 'shop__orders' AND NOT starts_with(column_name, '_sqlload_') ORDER BY ordinal_position"; + +/// The table every load test loads. +const LOADED_TABLE: &str = "raw.shop__orders"; + +/// The stack a load needs in a debug build, as the command line gives it. +const LOAD_STACK_BYTES: usize = 8 * 1024 * 1024; + +impl CallerConnection for DuckDbCaller { + fn open(&self) -> Result, SessionError> { + let connection = self + .connection + .lock() + .map_err(|_| SessionError::new("the connection's lock is poisoned"))? + .try_clone() + .map_err(|error| SessionError::new(error.to_string()))?; + Ok(Arc::new(DuckDbSession { + connection: Mutex::new(connection), + calls: self.calls.clone(), + fail_on: self.fail_on.clone(), + })) + } + + fn describe(&self) -> String { + "a test's DuckDB".to_owned() + } +} + +impl CallerSession for DuckDbSession { + fn execute(&self, statement: &str) -> Result<(), SessionError> { + record(&self.calls, statement.to_owned())?; + let refused = self + .fail_on + .as_deref() + .is_some_and(|fail_on| statement.contains(fail_on)); + refused + .then(|| SessionError::new(format!("refused for the test: {statement}"))) + .map_or(Ok(()), Err)?; + self.connection + .lock() + .map_err(|_| SessionError::new("the session's lock is poisoned"))? + .execute_batch(statement) + .map_err(|error| SessionError::new(error.to_string())) + } + + fn query_text(&self, query: &str) -> Result>>, SessionError> { + record(&self.calls, query.to_owned())?; + let connection = self + .connection + .lock() + .map_err(|_| SessionError::new("the session's lock is poisoned"))?; + texts(&connection, query).map_err(|error| SessionError::new(error.to_string())) + } +} + +impl CallerConnection for RecordingCaller { + fn open(&self) -> Result, SessionError> { + Ok(Arc::new(RecordingSession { + calls: self.calls.clone(), + autocommit: self.autocommit, + references: self.references.clone(), + })) + } + + fn describe(&self) -> String { + "a recording".to_owned() + } +} + +impl CallerSession for RecordingSession { + fn execute(&self, statement: &str) -> Result<(), SessionError> { + record(&self.calls, statement.to_owned()) + } + + fn query_text(&self, query: &str) -> Result>>, SessionError> { + record(&self.calls, query.to_owned())?; + let answer = self + .autocommit + .filter(|_| query.contains("AUTOCOMMIT")) + .map(|value| vec![Some("AUTOCOMMIT".to_owned()), Some(value.to_owned())]); + let asks_references = query.contains("pg_constraint con"); + let references = self.references.iter().filter(|_| asks_references).cloned(); + Ok(answer.into_iter().chain(references).collect()) + } + + fn copy_in(&self, statement: &str, data: &[u8]) -> Result<(), SessionError> { + let signature = String::from_utf8_lossy(data.get(..6).unwrap_or_default()).into_owned(); + record(&self.calls, format!("{statement} <- {signature}")) + } + + fn load_parquet(&self, table: &TableName, file: &Path) -> Result<(), SessionError> { + let exists = file.exists(); + record( + &self.calls, + format!( + "load_parquet {}.{} exists={exists}", + table.schema, table.table + ), + ) + } +} + +/// Add `call` to `calls`. +fn record(calls: &Calls, call: String) -> Result<(), SessionError> { + calls + .lock() + .map_err(|_| SessionError::new("the calls' lock is poisoned"))? + .push(call); + Ok(()) +} + +/// `query`'s rows on `connection`, each value as text. +fn texts( + connection: &duckdb::Connection, + query: &str, +) -> Result>>, duckdb::Error> { + let wrapped = format!("SELECT CAST(COLUMNS(*) AS VARCHAR) FROM ({query}) AS q"); + let mut statement = connection.prepare(&wrapped)?; + let rows = statement.query_map([], |row| { + (0..row.as_ref().column_count()) + .map(|index| row.get::<_, Option>(index)) + .collect::>, duckdb::Error>>() + })?; + rows.collect() +} + +/// Run `setup` on the DuckDB database file at `path`, creating it. +pub(crate) fn run_sql(path: &Path, setup: &str) -> Result<(), String> { + duckdb::Connection::open(path) + .and_then(|connection| connection.execute_batch(setup)) + .map_err(|error| error.to_string()) +} + +/// A project loading `source`'s `main.orders` (with `settings`) into the target on the caller's connection, in schema `raw`. +fn orders_project(source: &Path, settings: &str) -> String { + format!( + "default_target = \"dev\" + +[connections.shop_file] +kind = \"duckdb\" +database = {source:?} + +[targets.dev] +connection = \"caller\" +loader_schema = \"raw\" + +[sources.shop] +kind = \"duckdb\" +connection = \"shop_file\" +include = [\"main.orders\"] + +[sources.shop.tables.\"main.orders\"] +{settings} +", + source = source.display().to_string() + ) +} + +/// `project`'s TOML parsed with a caller's connection attached as `caller`, on `warehouse`. +fn session_project( + project: &str, + (warehouse, caller): (Warehouse, Arc), +) -> Result { + let sessions = BTreeMap::from([( + "caller".to_owned(), + SessionConnection { + warehouse, + motherduck: false, + database: None, + caller, + }, + )]); + parse_python_project(project, &|_| None, (&[], sessions)).map_err(|error| error.to_string()) +} + +/// Plan, apply and load `project`: each table's outcome, or the plan's problems. +async fn load(project: &ProjectConfig) -> Result { + let destinations = connect_targets(project) + .await + .map_err(|error| error.to_string())?; + let options = PlanOptions::default(); + let plan = plan_project(project, &destinations, &options) + .await + .map_err(|error| error.to_string())?; + let problems = plan.problems.join("\n"); + plan.problems.is_empty().then_some(()).ok_or(problems)?; + apply_project(&plan, &destinations) + .await + .map_err(|error| error.to_string())?; + let run = LoadRun { + project, + destinations: &destinations, + host: None, + options: &options, + }; + Ok(load_tables(&run, &plan, None) + .await + .into_iter() + .map(|outcome| (outcome.table, outcome.loaded.map(|loaded| loaded.rows))) + .collect()) +} + +/// Load `project`'s text through a fake caller on the target database at `target`, which fails the first statement containing `fail_on`: each table's outcome, and every call the caller's sessions got. +fn load_through( + project: &str, + target: &Path, + fail_on: Option<&str>, +) -> Result<(Outcomes, Vec), String> { + let calls: Calls = Arc::default(); + let connection = duckdb::Connection::open(target).map_err(|error| error.to_string())?; + let caller = Arc::new(DuckDbCaller { + connection: Mutex::new(connection), + calls: calls.clone(), + fail_on: fail_on.map(str::to_owned), + }); + let parsed = session_project(project, (Warehouse::DuckDb, caller))?; + let outcomes = on_load_stack(move || runtime()?.block_on(load(&parsed)))?; + let calls = calls.lock().map_err(|_| "poisoned".to_owned())?.clone(); + Ok((outcomes, calls)) +} + +/// Whether every table loaded; fails naming the first that did not. +fn loaded(outcomes: Outcomes) -> Result<(), String> { + outcomes + .into_iter() + .map(|(table, outcome)| outcome.map_err(|error| format!("{table}: {error}"))) + .collect::, String>>() + .map(|_| ()) +} + +/// `query`'s rows on the database at `path`, each row's values joined by `:`. +fn rows_at(path: &Path, query: &str) -> Result, String> { + let connection = duckdb::Connection::open(path).map_err(|error| error.to_string())?; + let rows = texts(&connection, query).map_err(|error| error.to_string())?; + Ok(rows + .into_iter() + .map(|row| { + row.into_iter() + .map(Option::unwrap_or_default) + .collect::>() + .join(":") + }) + .collect()) +} + +/// The source and target files of a test in `folder`, the source holding [`ORDERS`]. +fn orders_files(folder: &Path) -> Result<(std::path::PathBuf, std::path::PathBuf), String> { + let (source, target) = (folder.join("shop.duckdb"), folder.join("warehouse.duckdb")); + run_sql(&source, ORDERS)?; + run_sql(&target, "SELECT 1")?; + Ok((source, target)) +} + +/// The loaded table's rows after a load of `settings`, `change` to the source and a second load, both through a caller's session. +pub(crate) fn twice_loaded(settings: &str, change: &str) -> Result, String> { + let folder = tempfile::tempdir().map_err(|error| error.to_string())?; + let (source, target) = orders_files(folder.path())?; + let project = orders_project(&source, settings); + loaded(load_through(&project, &target, None)?.0).map_err(|error| format!("load 1, {error}"))?; + run_sql(&source, change)?; + loaded(load_through(&project, &target, None)?.0).map_err(|error| format!("load 2, {error}"))?; + rows_at(&target, LOADED_ROWS) +} + +/// After a load of `settings` and the source gaining a `status` column: whether a second load loaded the table, and its data columns. +pub(crate) fn after_new_column(settings: &str) -> Result<(bool, Vec), String> { + let folder = tempfile::tempdir().map_err(|error| error.to_string())?; + let (source, target) = orders_files(folder.path())?; + let project = orders_project(&source, settings); + loaded(load_through(&project, &target, None)?.0).map_err(|error| format!("load 1, {error}"))?; + run_sql( + &source, + "ALTER TABLE orders ADD COLUMN status VARCHAR; INSERT INTO orders VALUES (3, 'third', '2026-01-03 00:00:00', 'open');", + )?; + let (outcomes, _) = load_through(&project, &target, None)?; + let second = matches!(outcomes.get(LOADED_TABLE), Some(Ok(_))); + Ok((second, rows_at(&target, LOADED_COLUMNS)?)) +} + +/// After a load of `settings`, `change` to the source, and a second load whose `COMMIT` the session refuses: the statement sent after the refused `COMMIT`, and the loaded table's rows. +pub(crate) fn refused_commit( + settings: &str, + change: &str, +) -> Result<(String, Vec), String> { + let folder = tempfile::tempdir().map_err(|error| error.to_string())?; + let (source, target) = orders_files(folder.path())?; + let project = orders_project(&source, settings); + loaded(load_through(&project, &target, None)?.0).map_err(|error| format!("load 1, {error}"))?; + run_sql(&source, change)?; + let (outcomes, calls) = load_through(&project, &target, Some("COMMIT"))?; + loaded(outcomes) + .is_err() + .then_some(()) + .ok_or("the refused load succeeded")?; + let next = calls + .iter() + .skip_while(|call| !call.contains("COMMIT")) + .nth(1) + .cloned() + .ok_or_else(|| format!("nothing followed a COMMIT: {calls:?}"))?; + Ok((next, rows_at(&target, LOADED_ROWS)?)) +} + +/// Write one batch of two rows (`id`, `name`) through a writer on `warehouse`'s session, then load the batch: every call the session got, the writer's folder written `` (and on Windows the separator after it `/`), as plain or as a SQL literal writes it. +pub(crate) fn written_batch(warehouse: Warehouse) -> Result, String> { + let caller = Arc::new(RecordingCaller::default()); + let calls = caller.calls.clone(); + let connection = SessionConnection { + warehouse, + motherduck: false, + database: Some("analytics".to_owned()), + caller, + }; + let column = |name: &str, column_type: ColumnType| DesiredColumn { + name: name.to_owned(), + column_type, + origin: ColumnOrigin::Source, + }; + let columns = [ + column("id", ColumnType::Int), + column("name", ColumnType::Text), + ]; + let table = TableName { + database: Some("analytics".to_owned()), + schema: "raw".to_owned(), + table: "orders".to_owned(), + }; + let staging = TableName { + table: "orders__sqlload_staging_1".to_owned(), + ..table.clone() + }; + let target = WriteTarget { + table: &table, + staging: Some(&staging), + columns: &columns, + write_columns: &columns, + compat: crate::load_naming::models::Compat::default(), + load_id: "load1", + batch: 1, + direct: false, + builds: false, + constants: &[], + }; + let batch = RecordBatch::try_from_iter([ + ("id", Arc::new(Int64Array::from(vec![1, 2])) as ArrayRef), + ( + "name", + Arc::new(StringArray::from(vec!["first", "second"])) as ArrayRef, + ), + ]) + .map_err(|error| error.to_string())?; + let folder = on_load_stack(move || { + runtime()?.block_on(async { + let destination = connect_session(&connection, None) + .await + .map_err(|error| error.to_string())?; + let mut writer = open_writer(&destination).map_err(|error| error.to_string())?; + let folder = writer.folder.path().display().to_string(); + writer + .write_batch(&target, batch) + .await + .map_err(|error| error.to_string())?; + writer + .load_batch(&target) + .await + .map_err(|error| error.to_string())?; + Ok::(folder) + }) + })?; + let calls = calls.lock().map_err(|_| "poisoned".to_owned())?.clone(); + // A SQL literal doubles a Windows path's backslashes, the separator before the file name among them. + let escaped = folder.replace('\\', "\\\\"); + Ok(calls + .into_iter() + .map(|call| { + call.replace(&escaped, "") + .replace(&folder, "") + .replace("\\\\", "/") + }) + .collect()) +} + +/// A runtime whose threads have the stack a load needs in a debug build. +fn runtime() -> Result { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_stack_size(LOAD_STACK_BYTES) + .build() + .map_err(|error| error.to_string()) +} + +/// `body` run on a thread with the stack a load needs in a debug build, as the command line runs a load. +fn on_load_stack(body: impl FnOnce() -> Result + Send) -> Result { + std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(LOAD_STACK_BYTES) + .spawn_scoped(scope, body) + .map_err(|error| error.to_string())? + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + }) +} + +/// `texts` as owned strings, as expected values compare with results. +pub(crate) fn owned(texts: &[&str]) -> Vec { + texts.iter().map(|text| (*text).to_owned()).collect() +} + +/// Why `project`'s TOML, with a recording caller's connection attached as `caller`, does not parse; `None` when it does. +pub(crate) fn caller_parse_problem(project: &str) -> Option { + session_project( + project, + (Warehouse::DuckDb, Arc::new(RecordingCaller::default())), + ) + .err() +} + +/// Why a session on `warehouse` that says its autocommit is `autocommit` is refused when it opens; `None` when it opens. +pub(crate) fn autocommit_refusal( + warehouse: Warehouse, + autocommit: Option<&'static str>, +) -> Result, String> { + let caller = Arc::new(RecordingCaller { + calls: Arc::default(), + autocommit, + references: Vec::new(), + }); + let connection = SessionConnection { + warehouse, + motherduck: false, + database: Some("analytics".to_owned()), + caller, + }; + on_load_stack(move || { + Ok(runtime()? + .block_on(connect_session(&connection, None)) + .err() + .map(|error| error.to_string())) + }) +} + +/// What the checks before a write in `mode` into an existing Postgres table through a caller's session refuse and warn of, when one foreign key references it with `reference`: its action, whether it is deferred, and whether it is the table's own. +pub(crate) fn reference_checks( + (action, deferred, own): (&str, bool, bool), + mode: WriteMode, +) -> Result<(Vec, Vec), String> { + use crate::adapters::dispatch::main::session::write_problems::write_problems; + use crate::adapters::dispatch::models::Destination; + + let text = |value: &str| Some(value.to_owned()); + let flag = |value: bool| Some(value.to_string()); + let caller = Arc::new(RecordingCaller { + calls: Arc::default(), + autocommit: None, + references: vec![vec![ + text("shop.order_lines"), + text("order_lines_order_fkey"), + text(action), + flag(deferred), + flag(own), + ]], + }); + let connection = SessionConnection { + warehouse: Warehouse::Postgres, + motherduck: false, + database: None, + caller, + }; + let table = TableName { + database: None, + schema: "shop".to_owned(), + table: "orders".to_owned(), + }; + on_load_stack(move || { + runtime()?.block_on(async { + let destination = Destination::Session(Box::new( + connect_session(&connection, None) + .await + .map_err(|error| error.to_string())?, + )); + write_problems(&destination, &table, (&mode, true, false)) + .await + .map_err(|error| error.to_string()) + }) + }) +} + +/// A `replace`. +pub(crate) fn replace_mode() -> WriteMode { + WriteMode::Replace +} + +/// A `delete_insert` on `updated_at`. +pub(crate) fn delete_insert_mode() -> WriteMode { + WriteMode::DeleteInsert { + cursor_column: Some("updated_at".to_owned()), + from: None, + to: None, + values: Vec::new(), + replace_key: Vec::new(), + not_null_keys: Vec::new(), + } +} diff --git a/crates/sqlload/src/adapters/session/tests/test_session_loads.rs b/crates/sqlload/src/adapters/session/tests/test_session_loads.rs new file mode 100644 index 000000000..697b9e6d4 --- /dev/null +++ b/crates/sqlload/src/adapters/session/tests/test_session_loads.rs @@ -0,0 +1,102 @@ +use crate::adapters::session::tests::helpers::{ + after_new_column, owned, refused_commit, twice_loaded, +}; +use crate::adapters::session::tests::test_types::{ + RefusedCommitTestCase, SchemaChangeTestCase, SessionLoadTestCase, +}; + +#[test] +fn given_each_write_strategy_when_two_loads_go_through_a_callers_session_then_the_table_holds_what_the_strategy_writes() + { + let test_cases = [ + SessionLoadTestCase { + description: "replace rewrites the table from the source", + settings: "write_strategy = \"replace\"", + change: "DELETE FROM orders WHERE id = 2; INSERT INTO orders VALUES (3, 'third', '2026-01-03 00:00:00');", + expected_rows: &["1:first", "3:third"], + }, + SessionLoadTestCase { + description: "append adds the rows past the cursor", + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"", + change: "INSERT INTO orders VALUES (3, 'third', '2026-01-03 00:00:00');", + expected_rows: &["1:first", "2:second", "3:third"], + }, + SessionLoadTestCase { + description: "merge updates rows by key and adds new ones", + settings: "write_strategy = \"merge\"\ncursor_column = \"updated_at\"\nunique_key = \"id\"", + change: "UPDATE orders SET name = 'first again', updated_at = '2026-01-04 00:00:00' WHERE id = 1; INSERT INTO orders VALUES (3, 'third', '2026-01-03 00:00:00');", + expected_rows: &["1:first again", "2:second", "3:third"], + }, + SessionLoadTestCase { + description: "delete_insert replaces the rows of the cursor's range", + settings: "write_strategy = \"delete_insert\"\ncursor_column = \"updated_at\"", + change: "INSERT INTO orders VALUES (3, 'third', '2026-01-03 00:00:00');", + expected_rows: &["1:first", "2:second", "3:third"], + }, + ]; + for test_case in test_cases { + let rows = twice_loaded(test_case.settings, test_case.change) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + assert_eq!(rows, test_case.expected_rows, "{}", test_case.description); + } +} + +#[test] +fn given_a_source_gaining_a_column_when_it_loads_through_a_callers_session_then_on_schema_change_decides() + { + let test_cases = [ + SchemaChangeTestCase { + description: "append_new_columns, the default, adds the column", + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"", + expected_loaded: true, + expected_columns: &["id", "name", "updated_at", "status"], + }, + SchemaChangeTestCase { + description: "ignore loads the rows without it", + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\non_schema_change = \"ignore\"", + expected_loaded: true, + expected_columns: &["id", "name", "updated_at"], + }, + SchemaChangeTestCase { + description: "fail refuses to load the table", + settings: "write_strategy = \"append\"\ncursor_column = \"updated_at\"\non_schema_change = \"fail\"", + expected_loaded: false, + expected_columns: &["id", "name", "updated_at"], + }, + ]; + for test_case in test_cases { + let (loaded, columns) = after_new_column(test_case.settings) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + assert_eq!( + (loaded, columns), + (test_case.expected_loaded, owned(test_case.expected_columns)), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_commit_the_callers_session_refuses_when_a_load_writes_then_sqlload_rolls_back_and_the_table_is_unchanged() + { + let test_cases = [RefusedCommitTestCase { + description: "a merge whose commit fails leaves the rows of the load before", + settings: "write_strategy = \"merge\"\ncursor_column = \"updated_at\"\nunique_key = \"id\"", + change: "UPDATE orders SET name = 'changed', updated_at = '2026-01-04 00:00:00' WHERE id = 1;", + expected_next: "ROLLBACK", + expected_rows: &["1:first", "2:second"], + }]; + for test_case in test_cases { + let (next, rows) = refused_commit(test_case.settings, test_case.change) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + assert_eq!( + (next, rows), + ( + test_case.expected_next.to_owned(), + owned(test_case.expected_rows) + ), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlload/src/adapters/session/tests/test_session_routes.rs b/crates/sqlload/src/adapters/session/tests/test_session_routes.rs new file mode 100644 index 000000000..c14bc9498 --- /dev/null +++ b/crates/sqlload/src/adapters/session/tests/test_session_routes.rs @@ -0,0 +1,288 @@ +use crate::adapters::contract::models::TableName; +use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; +use crate::adapters::session::tests::helpers::{ + autocommit_refusal, caller_parse_problem, delete_insert_mode, reference_checks, replace_mode, + written_batch, +}; +use crate::adapters::session::tests::test_types::{ + AttachedNameTestCase, AutocommitTestCase, DescribeQueryTestCase, DescribedTypeTestCase, + ReferenceCheckTestCase, SessionRouteTestCase, +}; +use crate::column_types::models::Warehouse; + +#[test] +fn given_a_session_on_each_warehouse_when_a_batch_loads_then_its_rows_reach_the_staging_table_by_the_warehouses_route() + { + let test_cases = [ + SessionRouteTestCase { + description: "Snowflake checks autocommit, runs in UTC, puts the file on the user stage, copies it into staging and removes it", + warehouse: Warehouse::Snowflake, + expected_calls: &[ + "SHOW PARAMETERS LIKE 'AUTOCOMMIT' IN SESSION", + "ALTER SESSION SET TIMEZONE = 'UTC'", + "PUT 'file:///part-00001.parquet' @~/sqlload/load1/00001/ AUTO_COMPRESS = FALSE OVERWRITE = TRUE", + "COPY INTO \"ANALYTICS\".\"RAW\".\"ORDERS__SQLLOAD_STAGING_1\" FROM @~/sqlload/load1/00001/ FILES = ('part-00001.parquet')", + "REMOVE @~/sqlload/load1/00001/", + ], + }, + SessionRouteTestCase { + description: "Postgres copies the rows in as binary COPY data", + warehouse: Warehouse::Postgres, + expected_calls: &[ + "COPY \"raw\".\"orders__sqlload_staging_1\" (\"id\", \"name\") FROM STDIN (FORMAT binary) <- PGCOPY", + ], + }, + SessionRouteTestCase { + description: "BigQuery's session loads the Parquet file itself", + warehouse: Warehouse::BigQuery, + expected_calls: &["load_parquet raw.orders__sqlload_staging_1 exists=true"], + }, + SessionRouteTestCase { + description: "ClickHouse's session loads the Parquet file itself", + warehouse: Warehouse::ClickHouse, + expected_calls: &["load_parquet raw.orders__sqlload_staging_1 exists=true"], + }, + SessionRouteTestCase { + description: "Databricks' session loads the Parquet file itself", + warehouse: Warehouse::Databricks, + expected_calls: &["load_parquet raw.orders__sqlload_staging_1 exists=true"], + }, + ]; + for test_case in test_cases { + let calls = written_batch(test_case.warehouse) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + let starts: Vec = calls + .iter() + .zip(test_case.expected_calls) + .map(|(call, expected)| call.starts_with(expected)) + .collect(); + assert_eq!( + (calls.len(), starts.iter().all(|starts| *starts)), + (test_case.expected_calls.len(), true), + "{}: {calls:?}", + test_case.description + ); + } +} + +#[test] +fn given_a_table_when_a_callers_session_describes_it_then_the_query_names_it_with_literals() { + let test_cases = [ + DescribeQueryTestCase { + description: "DuckDB fills both placeholders of its describe query", + warehouse: Warehouse::DuckDb, + schema: "raw", + table: "it's", + expected_parts: &["table_schema = 'raw'", "table_name = 'it''s'"], + }, + DescribeQueryTestCase { + description: "Postgres fills $1 and $2 with the stored names", + warehouse: Warehouse::Postgres, + schema: "Raw", + table: "orders", + expected_parts: &["n.nspname = 'Raw'", "c.relname = 'orders'"], + }, + DescribeQueryTestCase { + description: "BigQuery reads the dataset's INFORMATION_SCHEMA in the session's project", + warehouse: Warehouse::BigQuery, + schema: "raw", + table: "orders", + expected_parts: &[ + "`analytics`.`raw`.INFORMATION_SCHEMA.COLUMNS", + "table_name = 'orders'", + ], + }, + ]; + for test_case in test_cases { + let table = TableName { + database: None, + schema: test_case.schema.to_owned(), + table: test_case.table.to_owned(), + }; + let query = sql_adapter(test_case.warehouse) + .render_describe_table(&table, Some("analytics")) + .unwrap_or_else(|| panic!("{}: no query", test_case.description)); + assert!( + test_case + .expected_parts + .iter() + .all(|part| query.contains(part)), + "{}: {query}", + test_case.description + ); + } +} + +#[test] +fn given_a_bigquery_column_type_as_information_schema_writes_it_when_read_then_its_sizes_come_apart() + { + let test_cases = [ + DescribedTypeTestCase { + description: "a sized NUMERIC keeps its precision and scale", + written: "NUMERIC(10, 2)", + expected_type: "Decimal { precision: 10, scale: 2 }", + }, + DescribedTypeTestCase { + description: "a sized STRING is a varchar", + written: "STRING(20)", + expected_type: "Varchar(20)", + }, + DescribedTypeTestCase { + description: "an unsized STRING is text", + written: "STRING", + expected_type: "Text", + }, + DescribedTypeTestCase { + description: "an array of integers is an array", + written: "ARRAY", + expected_type: "Array(Int)", + }, + DescribedTypeTestCase { + description: "a record reads as a struct, as tables.get gives it", + written: "STRUCT", + expected_type: "Native(\"STRUCT\")", + }, + ]; + for test_case in test_cases { + let rows = vec![vec![ + Some("c".to_owned()), + Some(test_case.written.to_owned()), + ]]; + let columns = sql_adapter(Warehouse::BigQuery) + .describe_text_rows(&rows) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + assert_eq!( + columns + .first() + .map(|column| format!("{:?}", column.column_type)), + Some(test_case.expected_type.to_owned()), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_callers_connection_attached_to_a_project_when_it_parses_then_targets_use_it_by_name() { + let test_cases = [ + AttachedNameTestCase { + description: "a target loads into the attached connection as into any DuckDB connection", + project: "[targets.dev]\nconnection = \"caller\"\nloader_schema = \"raw\"\n", + expected_problem: None, + }, + AttachedNameTestCase { + description: "a project connection of the same name is refused", + project: "[connections.caller]\nkind = \"duckdb\"\ndatabase = \":memory:\"\n", + expected_problem: Some( + "[connections.caller] is also a connection the caller attaches; give one of them another name", + ), + }, + AttachedNameTestCase { + description: "a target on it is checked as a warehouse target", + project: "[targets.dev]\nconnection = \"caller\"\n", + expected_problem: Some("[targets.dev] needs a loader_schema"), + }, + ]; + for test_case in test_cases { + let problem = caller_parse_problem(test_case.project); + assert_eq!( + problem.is_some(), + test_case.expected_problem.is_some(), + "{}: {problem:?}", + test_case.description + ); + assert!( + problem + .unwrap_or_default() + .contains(test_case.expected_problem.unwrap_or_default()), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_callers_session_with_autocommit_off_when_it_opens_then_sqlload_refuses_it() { + let test_cases = [ + AutocommitTestCase { + description: "a Snowflake session with autocommit off is refused", + warehouse: Warehouse::Snowflake, + autocommit: Some("false"), + expected_refusal: Some("the caller's Snowflake session has autocommit off"), + }, + AutocommitTestCase { + description: "a Snowflake session with autocommit on opens", + warehouse: Warehouse::Snowflake, + autocommit: Some("true"), + expected_refusal: None, + }, + AutocommitTestCase { + description: "a Postgres session is not asked, as the server does not hold it", + warehouse: Warehouse::Postgres, + autocommit: Some("false"), + expected_refusal: None, + }, + ]; + for test_case in test_cases { + let refusal = autocommit_refusal(test_case.warehouse, test_case.autocommit) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + assert_eq!( + refusal.is_some(), + test_case.expected_refusal.is_some(), + "{}: {refusal:?}", + test_case.description + ); + assert!( + refusal + .unwrap_or_default() + .contains(test_case.expected_refusal.unwrap_or_default()), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_foreign_key_referencing_a_postgres_table_when_a_write_through_a_callers_session_deletes_rows_then_it_is_checked_as_on_sqlloads_own_session() + { + let test_cases = [ + ReferenceCheckTestCase { + description: "ON DELETE CASCADE would change another table, so replace is refused", + reference: ("c", false, false), + mode: replace_mode, + expected_problem: Some("ON DELETE CASCADE deletes its rows when replace deletes"), + expected_warning: None, + }, + ReferenceCheckTestCase { + description: "a restricting key is warned of, as delete_insert fails while it holds rows", + reference: ("r", false, false), + mode: delete_insert_mode, + expected_problem: None, + expected_warning: Some( + "so delete_insert fails while any of its rows reference a row it deletes", + ), + }, + ReferenceCheckTestCase { + description: "replace ignores the table's reference to itself", + reference: ("c", false, true), + mode: replace_mode, + expected_problem: None, + expected_warning: None, + }, + ]; + for test_case in test_cases { + let (problems, warnings) = reference_checks(test_case.reference, (test_case.mode)()) + .unwrap_or_else(|error| panic!("{}: {error}", test_case.description)); + let found = |lines: &[String], part: Option<&str>| { + part.map_or(lines.is_empty(), |part| { + lines.len() == 1 && lines[0].contains(part) + }) + }; + assert!( + found(&problems, test_case.expected_problem) + && found(&warnings, test_case.expected_warning), + "{}: {problems:?} {warnings:?}", + test_case.description + ); + } +} diff --git a/crates/sqlload/src/adapters/session/tests/test_types.rs b/crates/sqlload/src/adapters/session/tests/test_types.rs new file mode 100644 index 000000000..d6165186a --- /dev/null +++ b/crates/sqlload/src/adapters/session/tests/test_types.rs @@ -0,0 +1,122 @@ +use std::sync::{Arc, Mutex}; + +use crate::column_types::models::Warehouse; + +/// What a fake caller's sessions were asked to do, in order: each statement, query, `COPY` and Parquet load. +pub(crate) type Calls = Arc>>; + +/// A caller's connection over a DuckDB database, as a caller's own DuckDB connection would be; it records every call and fails the first statement containing `fail_on`. +#[derive(Debug)] +pub(crate) struct DuckDbCaller { + pub(crate) connection: Mutex, + pub(crate) calls: Calls, + pub(crate) fail_on: Option, +} + +/// One session of a [`DuckDbCaller`]. +#[derive(Debug)] +pub(crate) struct DuckDbSession { + pub(crate) connection: Mutex, + pub(crate) calls: Calls, + pub(crate) fail_on: Option, +} + +/// A caller's connection that runs nothing and records every call: statements, queries, `COPY` input (its signature) and Parquet loads; it answers a question about autocommit with `autocommit`. +#[derive(Debug, Default)] +pub(crate) struct RecordingCaller { + pub(crate) calls: Calls, + pub(crate) autocommit: Option<&'static str>, + /// The rows it answers a query of the catalog's constraints with. + pub(crate) references: Vec>>, +} + +/// One session of a [`RecordingCaller`]. +#[derive(Debug)] +pub(crate) struct RecordingSession { + pub(crate) calls: Calls, + pub(crate) autocommit: Option<&'static str>, + pub(crate) references: Vec>>, +} + +pub(crate) struct SessionLoadTestCase { + pub(crate) description: &'static str, + /// The table's settings in `[sources.shop.tables."main.orders"]`. + pub(crate) settings: &'static str, + /// SQL changing the source's `main.orders` before the second load. + pub(crate) change: &'static str, + /// The loaded table's rows after the second load, as `id:name`, by id. + pub(crate) expected_rows: &'static [&'static str], +} + +pub(crate) struct SchemaChangeTestCase { + pub(crate) description: &'static str, + /// The table's settings, its `on_schema_change` among them. + pub(crate) settings: &'static str, + /// Whether the second load, after the source gains a column, loads the table. + pub(crate) expected_loaded: bool, + /// The loaded table's data columns after it, in order. + pub(crate) expected_columns: &'static [&'static str], +} + +pub(crate) struct RefusedCommitTestCase { + pub(crate) description: &'static str, + pub(crate) settings: &'static str, + /// SQL changing the source before the second load, whose `COMMIT` the session refuses. + pub(crate) change: &'static str, + /// The statement the session sends right after the refused `COMMIT`. + pub(crate) expected_next: &'static str, + /// The loaded table's rows after the refused load, as `id:name`, by id. + pub(crate) expected_rows: &'static [&'static str], +} + +pub(crate) struct SessionRouteTestCase { + pub(crate) description: &'static str, + pub(crate) warehouse: Warehouse, + /// How each call the session gets starts, in order (the writer's folder written ``). + pub(crate) expected_calls: &'static [&'static str], +} + +pub(crate) struct DescribedTypeTestCase { + pub(crate) description: &'static str, + /// The type as `INFORMATION_SCHEMA.COLUMNS` writes it. + pub(crate) written: &'static str, + /// The portable type read from it, as `Debug` prints it. + pub(crate) expected_type: &'static str, +} + +pub(crate) struct DescribeQueryTestCase { + pub(crate) description: &'static str, + pub(crate) warehouse: Warehouse, + pub(crate) schema: &'static str, + pub(crate) table: &'static str, + /// Text the query must hold: the schema and table as literals. + pub(crate) expected_parts: &'static [&'static str], +} + +pub(crate) struct AttachedNameTestCase { + pub(crate) description: &'static str, + /// The project's TOML; the caller attaches a connection named `caller`. + pub(crate) project: &'static str, + /// Why the project does not parse; `None` when it does. + pub(crate) expected_problem: Option<&'static str>, +} + +pub(crate) struct AutocommitTestCase { + pub(crate) description: &'static str, + pub(crate) warehouse: Warehouse, + /// What the session says its autocommit is, if asked. + pub(crate) autocommit: Option<&'static str>, + /// Why the session is refused; `None` when it opens. + pub(crate) expected_refusal: Option<&'static str>, +} + +pub(crate) struct ReferenceCheckTestCase { + pub(crate) description: &'static str, + /// The foreign key referencing the table: its `ON DELETE` action (`confdeltype`), whether it is deferred, and whether the table references itself. + pub(crate) reference: (&'static str, bool, bool), + /// The write: a `replace` or a `delete_insert`. + pub(crate) mode: fn() -> crate::adapters::contract::models::WriteMode, + /// What the check refuses, and what it warns of, each as a part of its line. + pub(crate) expected_problem: Option<&'static str>, + pub(crate) expected_warning: Option<&'static str>, +} diff --git a/crates/sqlload/src/adapters/session/types.rs b/crates/sqlload/src/adapters/session/types.rs new file mode 100644 index 000000000..1276a0b73 --- /dev/null +++ b/crates/sqlload/src/adapters/session/types.rs @@ -0,0 +1,35 @@ +use std::path::Path; +use std::sync::Arc; + +use crate::adapters::contract::models::TableName; +use crate::adapters::session::errors::SessionError; + +/// One session on the caller's connection, SQLLoad's alone until its last handle drops: SQLLoad may set session parameters on it (Snowflake's `TIMEZONE`) and runs one table's load on it, holding that table's temporary tables and transactions; every call blocks, and SQLLoad makes them from a blocking thread. +pub trait CallerSession: Send + Sync + std::fmt::Debug { + /// Run one statement in autocommit. SQLLoad sends its own `BEGIN`, `COMMIT` and `ROLLBACK`, which the session runs as written, so a transaction spans the statements between them. + fn execute(&self, statement: &str) -> Result<(), SessionError>; + + /// Run a query and return its rows, each value as text and `None` for NULL. + fn query_text(&self, query: &str) -> Result>>, SessionError>; + + /// Run `statement`, a Postgres `COPY ... FROM STDIN (FORMAT binary)`, with `data` as its input; Postgres sessions only. + fn copy_in(&self, statement: &str, data: &[u8]) -> Result<(), SessionError> { + let _ = (statement, data); + Err(SessionError::new("this session cannot run COPY FROM STDIN")) + } + + /// Load the zstd Parquet file at `file` into `table`, whose columns it names (BigQuery, ClickHouse and Databricks sessions, which load files through their own client); the table exists, and the load appends. + fn load_parquet(&self, table: &TableName, file: &Path) -> Result<(), SessionError> { + let _ = (table, file); + Err(SessionError::new("this session cannot load Parquet files")) + } +} + +/// The caller's connection to the warehouse a target loads into, which opens SQLLoad's sessions on it. +pub trait CallerConnection: Send + Sync + std::fmt::Debug { + /// A new session, in autocommit, whose current database is the one tables load into, never one the caller uses for other work at the same time; its last handle may drop on one of SQLLoad's async workers, so dropping it must not block for long. + fn open(&self) -> Result, SessionError>; + + /// What the connection connects as, for the line a destination check prints, such as `alice as LOADER, warehouse LOAD_WH`. + fn describe(&self) -> String; +} diff --git a/crates/sqlload/src/adapters/snowflake/_helpers/dialect/sql_adapter.rs b/crates/sqlload/src/adapters/snowflake/_helpers/dialect/sql_adapter.rs index 63ecc8c3e..3951210a5 100644 --- a/crates/sqlload/src/adapters/snowflake/_helpers/dialect/sql_adapter.rs +++ b/crates/sqlload/src/adapters/snowflake/_helpers/dialect/sql_adapter.rs @@ -1,17 +1,23 @@ //! Snowflake's SQL, where it differs from the contract's shared rendering. +use arrow_array::RecordBatch; use chrono::NaiveDateTime; use crate::adapters::contract::constants::{STAGING_SUFFIX, STALE_STAGING_HOURS}; -use crate::adapters::contract::models::{CursorValue, TableName, WriteStatementsRequest}; +use crate::adapters::contract::main::_session_parquet::default_session_parquet; +use crate::adapters::contract::models::{ + CursorValue, SessionRows, SessionStage, TableName, WriteStatementsRequest, +}; use crate::adapters::contract::types::SqlAdapter; use crate::adapters::snowflake::_helpers::dialect::type_names::{ logical_type, portable_type, widens_in_place, }; +use crate::adapters::snowflake::_helpers::write::table_writer::lists_as_json; use crate::adapters::snowflake::constants::{ - MERGE_KEYWORD, RUN_LOG_FALLBACK_RETENTION_DAYS, RUN_LOG_RETENTION_DAYS, + MERGE_KEYWORD, RUN_LOG_FALLBACK_RETENTION_DAYS, RUN_LOG_RETENTION_DAYS, STAGE_FOLDER, }; -use crate::adapters::snowflake::models::SnowflakeSql; +use crate::adapters::snowflake::main::copy::_copy_staged::copy_staged; +use crate::adapters::snowflake::models::{CopyStaged, SnowflakeSql}; use crate::column_types::models::{ColumnType, LiveColumnType, Warehouse, WarehouseType}; use crate::schema_plan::models::{DesiredColumn, LiveColumn}; @@ -255,4 +261,72 @@ impl SqlAdapter for SnowflakeSql { )), ) } + + /// In UTC, as SQLLoad's own Snowflake sessions are, so `TIMESTAMP_TZ` values are stored at `+00:00`. + fn render_session_setup(&self) -> Vec { + vec!["ALTER SESSION SET TIMEZONE = 'UTC'".to_owned()] + } + + fn render_autocommit_check(&self) -> Option { + Some("SHOW PARAMETERS LIKE 'AUTOCOMMIT' IN SESSION".to_owned()) + } + + /// A caller's session uploads each batch's Parquet files to the user's stage with `PUT`, then `COPY`s them in together. + fn session_rows(&self) -> SessionRows { + SessionRows::StagedParquet + } + + /// From `database`'s `INFORMATION_SCHEMA` (the table's own database first), which need not be the session's. + fn render_describe_table(&self, table: &TableName, database: Option<&str>) -> Option { + let database = table.database.as_deref().or(database)?; + let literal = |text: &str| self.render_loader_value_literal(text); + Some(format!( + "SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE, CHARACTER_MAXIMUM_LENGTH, DATETIME_PRECISION FROM \"{}\".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} ORDER BY ORDINAL_POSITION", + self.stored_name(database).replace('"', "\"\""), + literal(&self.stored_name(&table.schema)), + literal(&self.stored_name(&table.table)), + )) + } + + /// Lists and arrays as JSON text, which the `COPY` parses, as Snowflake's own writer stages them. + fn session_parquet( + &self, + batch: &RecordBatch, + columns: &[DesiredColumn], + ) -> Result, String> { + let batch = lists_as_json(batch.clone())?; + default_session_parquet(&batch, columns) + } + + /// `PUT` into, `COPY` from and `REMOVE` of `@~/sqlload///`, the folder Snowflake's own writer stages a batch in. + fn render_session_stage(&self, stage: SessionStage<'_>) -> Vec { + let folder = |load_id: &str, batch: u64| format!("{STAGE_FOLDER}/{load_id}/{batch:05}/"); + match stage { + SessionStage::Put { + load_id, + batch, + file, + } => vec![format!( + "PUT {} @~/{} AUTO_COMPRESS = FALSE OVERWRITE = TRUE", + self.render_loader_value_literal(&format!("file://{file}")), + folder(load_id, batch) + )], + SessionStage::Copy { + load_id, + batch, + table, + names, + selected, + } => copy_staged(&CopyStaged { + table, + stage: "@~", + folder: &folder(load_id, batch), + names, + selected, + }), + SessionStage::Remove { load_id, batch } => { + vec![format!("REMOVE @~/{}", folder(load_id, batch))] + } + } + } } diff --git a/crates/sqlload/src/adapters/snowflake/main/session/_describe_table.rs b/crates/sqlload/src/adapters/snowflake/main/session/_describe_table.rs index 06c2f0550..f9665cf61 100644 --- a/crates/sqlload/src/adapters/snowflake/main/session/_describe_table.rs +++ b/crates/sqlload/src/adapters/snowflake/main/session/_describe_table.rs @@ -4,42 +4,21 @@ use crate::adapters::contract::models::TableName; use crate::adapters::contract::types::SqlAdapter; use crate::adapters::snowflake::models::SnowflakeDestination; use crate::adapters::snowflake::models::SnowflakeSql; -use crate::column_types::models::LiveColumnType; use crate::http::errors::ApiError; use crate::schema_plan::models::LiveColumn; use crate::sql_api::main::execute_sql::execute_sql; -/// The table's columns in order, or `None` if it does not exist. +/// The table's columns in order, or `None` if it does not exist: the dialect's describe query, as a caller's session runs it too. pub(in crate::adapters) async fn describe_table( destination: &SnowflakeDestination, table: &TableName, ) -> Result>, ApiError> { - let literal = |text: &str| SnowflakeSql.render_loader_value_literal(text); - let database = table.database.as_deref().unwrap_or(&destination.database); - let query = format!( - "SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE, CHARACTER_MAXIMUM_LENGTH, DATETIME_PRECISION FROM \"{}\".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} ORDER BY ORDINAL_POSITION", - SnowflakeSql.stored_name(database).replace('"', "\"\""), - literal(&SnowflakeSql.stored_name(&table.schema)), - literal(&SnowflakeSql.stored_name(&table.table)), - ); - let rows = execute_sql(&destination.sql, &query).await?; - let number = |value: &Option| match value.as_deref().map(str::parse::) { - Some(Ok(number)) => Some(number), - _ => None, + let Some(query) = SnowflakeSql.render_describe_table(table, Some(&destination.database)) else { + return Ok(None); }; - let columns: Vec = rows - .rows - .iter() - .map(|row| LiveColumn { - name: row.first().cloned().flatten().unwrap_or_default(), - column_type: SnowflakeSql.live_type(&LiveColumnType { - data_type: row.get(1).cloned().flatten().unwrap_or_default(), - precision: row.get(2).and_then(number), - scale: row.get(3).and_then(number), - char_length: row.get(4).and_then(number), - }), - fraction_digits: row.get(5).and_then(number), - }) - .collect(); + let rows = execute_sql(&destination.sql, &query).await?; + let columns = SnowflakeSql + .describe_text_rows(&rows.rows) + .map_err(ApiError::Protocol)?; Ok((!columns.is_empty()).then_some(columns)) } diff --git a/crates/sqlload/src/command/_helpers/loader_commands.rs b/crates/sqlload/src/command/_helpers/loader_commands.rs index 5a9fc7a04..3f388f9bb 100644 --- a/crates/sqlload/src/command/_helpers/loader_commands.rs +++ b/crates/sqlload/src/command/_helpers/loader_commands.rs @@ -212,8 +212,8 @@ async fn parsed_project(request: &LoaderRequest<'_>) -> Result Result { let python: Vec = serde_json::from_str(python).map_err(|error| error.to_string())?; - let project = - parse_python_project(text, &|_| None, &python).map_err(|error| error.to_string())?; + let project = parse_python_project( + text, + &|_| None, + (&python, std::collections::BTreeMap::new()), + ) + .map_err(|error| error.to_string())?; let resolved = resolve_tables( &project, source_name, @@ -155,7 +159,7 @@ fn write(text: &str, description: &str) -> Result, String> { /// The sources of a project with DuckDB targets `dev` and `test` and Snowflake target `prod` (source `orders` into `dev`, `events` into `prod`) whose own warehouse differs from `from`'s. pub(crate) fn other_warehouse_sources(from: Option<&str>) -> Vec { let text = "[connections.wh]\nkind = \"duckdb\"\ndatabase = \":memory:\"\n[connections.sf]\nkind = \"snowflake\"\naccount = \"acct\"\nuser = \"loader\"\nauth = { method = \"pat\", token = \"t\" }\ndatabase = \"DB\"\nload_method = { type = \"internal_user_stage\" }\n[connections.lake]\nkind = \"filesystem\"\nroot = \"/tmp\"\n[targets.dev]\nconnection = \"wh\"\nloader_schema = \"RAW\"\n[targets.test]\nconnection = \"wh\"\nloader_schema = \"TEST\"\n[targets.prod]\nconnection = \"sf\"\nloader_schema = \"RAW\"\n[sources.orders]\nkind = \"files\"\nconnection = \"lake\"\npath = \"o/\"\ndescription = \"O.\"\ndestination = \"dev\"\n[sources.events]\nkind = \"files\"\nconnection = \"lake\"\npath = \"e/\"\ndescription = \"E.\"\ndestination = \"prod\"\n"; - parse_python_project(text, &|_| None, &[]) + parse_python_project(text, &|_| None, (&[], std::collections::BTreeMap::new())) .map(|project| other_warehouse(&project, from)) .unwrap_or_else(|error| vec![format!("error: {error}")]) } diff --git a/crates/sqlload/src/http_source/tests.rs b/crates/sqlload/src/http_source/tests.rs index ab7c531b5..5ef29b6fc 100644 --- a/crates/sqlload/src/http_source/tests.rs +++ b/crates/sqlload/src/http_source/tests.rs @@ -1,3 +1,5 @@ +#[path = "tests/test_api_wire.rs"] +mod api_wire; #[path = "tests/test_credential_source.rs"] mod credential_source; #[path = "tests/helpers.rs"] diff --git a/crates/sqlload/src/http_source/tests/helpers.rs b/crates/sqlload/src/http_source/tests/helpers.rs index db13782e2..46983c5e3 100644 --- a/crates/sqlload/src/http_source/tests/helpers.rs +++ b/crates/sqlload/src/http_source/tests/helpers.rs @@ -44,3 +44,67 @@ pub(crate) fn read_ahead_turns(aborted: &[usize]) -> Vec { went }) } + +/// The folder `sqlload_api` commits the wire it crosses as in, one `.json` per item. +fn wire_folder() -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../packages/sqlload-api/python/sqlload_api/_wire") +} + +/// The names of the wire files `sqlload_api` commits, in name order. +pub(crate) fn wire_files() -> Result, String> { + let folder = wire_folder(); + let entries = + std::fs::read_dir(&folder).map_err(|error| format!("{}: {error}", folder.display()))?; + let mut names: Vec = entries + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "json") + }) + .filter_map(|path| { + path.file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + }) + .collect(); + names.sort(); + Ok(names) +} + +/// What wire file `name` holds as a `kind` (`job`, `json` or `checkpoint`), or why it holds none. +fn wire_item(name: &str, kind: &str) -> Result { + let path = wire_folder().join(format!("{name}.json")); + let text = + std::fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display()))?; + let item: serde_json::Value = serde_json::from_str(&text).map_err(|error| error.to_string())?; + item.get(kind) + .cloned() + .ok_or_else(|| format!("{name} holds no {kind}")) +} + +/// The problems the engine finds in wire file `name`'s job before any request. +pub(crate) fn wire_job_problems(name: &str) -> Result, String> { + let job: crate::http_source::models::HttpJob = + serde_json::from_value(wire_item(name, "job")?).map_err(|error| error.to_string())?; + Ok(crate::http_source::_helpers::job::job_problems( + &job, + crate::row_batches::models::ProjectionRules::default(), + )) +} + +/// Why the engine can't read wire file `name`'s JSON data as its read spec asks, if it can't. +pub(crate) fn wire_json_problems(name: &str) -> Result, String> { + let read = wire_item(name, "json")?["read"].to_string(); + Ok( + crate::row_batches::main::json_read_spec::json_read_spec(&read, 1_000) + .err() + .into_iter() + .collect(), + ) +} + +/// Nothing, once wire file `name` holds a checkpoint's state. +pub(crate) fn wire_checkpoint_problems(name: &str) -> Result, String> { + wire_item(name, "checkpoint").map(|_| Vec::new()) +} diff --git a/crates/sqlload/src/http_source/tests/test_api_wire.rs b/crates/sqlload/src/http_source/tests/test_api_wire.rs new file mode 100644 index 000000000..5d215aa4f --- /dev/null +++ b/crates/sqlload/src/http_source/tests/test_api_wire.rs @@ -0,0 +1,142 @@ +use crate::http_source::tests::helpers::{ + wire_checkpoint_problems, wire_files, wire_job_problems, wire_json_problems, +}; +use crate::http_source::tests::test_types::{ApiWireTestCase, WireFilesTestCase}; + +#[test] +fn given_each_item_sqlload_api_commits_as_its_wire_when_the_engine_reads_it_then_it_finds_no_problem() + { + let test_cases = [ + ApiWireTestCase { + description: "the fan out batch job reads without a problem", + file: "fan_out_batch", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the fan out nested job reads without a problem", + file: "fan_out_nested", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the fan out values job reads without a problem", + file: "fan_out_values", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate cells job reads without a problem", + file: "paginate_cells", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate cursor job reads without a problem", + file: "paginate_cursor", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate header row job reads without a problem", + file: "paginate_header_row", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate link header job reads without a problem", + file: "paginate_link_header", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate next link job reads without a problem", + file: "paginate_next_link", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate offset job reads without a problem", + file: "paginate_offset", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate page number post job reads without a problem", + file: "paginate_page_number_post", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the paginate projected job reads without a problem", + file: "paginate_projected", + read: wire_job_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the JSON document reads as its spec asks", + file: "json_document", + read: wire_json_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the NDJSON lines read as their spec asks", + file: "ndjson_lines", + read: wire_json_problems, + expected_problems: &[], + }, + ApiWireTestCase { + description: "the checkpoint holds its state", + file: "checkpoint", + read: wire_checkpoint_problems, + expected_problems: &[], + }, + ]; + for test_case in test_cases { + assert_eq!( + (test_case.read)(test_case.file), + Ok(test_case + .expected_problems + .iter() + .map(|problem| (*problem).to_owned()) + .collect()), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_the_wire_folder_when_listing_it_then_every_file_has_a_case_above() { + let test_cases = [WireFilesTestCase { + description: "every committed wire file is read by the test above", + expected_files: &[ + "checkpoint", + "fan_out_batch", + "fan_out_nested", + "fan_out_values", + "json_document", + "ndjson_lines", + "paginate_cells", + "paginate_cursor", + "paginate_header_row", + "paginate_link_header", + "paginate_next_link", + "paginate_offset", + "paginate_page_number_post", + "paginate_projected", + ], + }]; + for test_case in test_cases { + assert_eq!( + wire_files(), + Ok(test_case + .expected_files + .iter() + .map(|file| (*file).to_owned()) + .collect()), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlload/src/http_source/tests/test_types.rs b/crates/sqlload/src/http_source/tests/test_types.rs index 97bdd3d9e..0b5fb548d 100644 --- a/crates/sqlload/src/http_source/tests/test_types.rs +++ b/crates/sqlload/src/http_source/tests/test_types.rs @@ -32,3 +32,17 @@ pub(crate) struct CredentialSourceTestCase { pub(crate) set: &'static [&'static str], pub(crate) expected_source: Result<&'static str, &'static str>, } + +pub(crate) struct ApiWireTestCase { + pub(crate) description: &'static str, + /// The wire file's name, without `.json`. + pub(crate) file: &'static str, + /// How the engine reads the file's item: as a job, JSON data or a checkpoint. + pub(crate) read: fn(&str) -> Result, String>, + pub(crate) expected_problems: &'static [&'static str], +} + +pub(crate) struct WireFilesTestCase { + pub(crate) description: &'static str, + pub(crate) expected_files: &'static [&'static str], +} diff --git a/crates/sqlload/src/loader/errors.rs b/crates/sqlload/src/loader/errors.rs index 4c7ba5225..5728aebda 100644 --- a/crates/sqlload/src/loader/errors.rs +++ b/crates/sqlload/src/loader/errors.rs @@ -6,6 +6,7 @@ use object_store::client::HttpErrorKind; #[cfg(feature = "duckdb")] use crate::adapters::duckdb::errors::DuckDbError; use crate::adapters::files::errors::FilesDestinationError; +use crate::adapters::session::errors::{SessionError, SessionErrorKind}; use crate::file_store::errors::StoreError; use crate::files_source::errors::FilesError; use crate::http::constants::FIRST_SERVER_ERROR; @@ -46,6 +47,9 @@ pub enum LoaderError { FilesDestination(#[from] FilesDestinationError), #[error(transparent)] Lease(#[from] LeaseError), + /// The caller's session, on a destination it provides, could not run a statement or take a file. + #[error(transparent)] + Session(#[from] SessionError), #[error("{0}")] Invalid(String), /// A Python table's read failed. @@ -84,6 +88,7 @@ impl LoaderError { } }, Self::Read(error) => error.retryable, + Self::Session(error) => error.kind == SessionErrorKind::Transient, Self::Transient(_) | Self::Replan(_) => true, other => Self::transient_cause(other), } diff --git a/crates/sqlload/src/loader/tests/helpers.rs b/crates/sqlload/src/loader/tests/helpers.rs index 5960697b9..09c64d607 100644 --- a/crates/sqlload/src/loader/tests/helpers.rs +++ b/crates/sqlload/src/loader/tests/helpers.rs @@ -157,7 +157,7 @@ pub(crate) fn python_spec(settings: &str) -> Result { let project = parse_python_project( "[connections.wh]\nkind = \"duckdb\"\ndatabase = \":memory:\"\n[targets.dev]\nconnection = \"wh\"\nloader_schema = \"RAW\"\n", &|_| None, - &python, + (&python, std::collections::BTreeMap::new()), ) .map_err(|error| error.to_string())?; let source = &project.sources["s"]; diff --git a/crates/sqlload/src/project/_helpers/mod.rs b/crates/sqlload/src/project/_helpers/mod.rs index 3a5f170be..89123669f 100644 --- a/crates/sqlload/src/project/_helpers/mod.rs +++ b/crates/sqlload/src/project/_helpers/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod flatten_rules; pub(crate) mod python_checks; pub(crate) mod references; pub(crate) mod serde_values; +pub(crate) mod sessions; pub(crate) mod targets; pub(crate) mod tombstones; pub(crate) mod unknown_keys; diff --git a/crates/sqlload/src/project/_helpers/sessions.rs b/crates/sqlload/src/project/_helpers/sessions.rs new file mode 100644 index 000000000..df0b25c9c --- /dev/null +++ b/crates/sqlload/src/project/_helpers/sessions.rs @@ -0,0 +1,31 @@ +//! The connections a caller attaches to a project. + +use std::collections::BTreeMap; + +use crate::adapters::session::models::SessionConnection; +use crate::project::models::{ConnectionConfig, ProjectConfig}; + +/// `project` with `sessions` added to its connections by name; a name the project's `[connections]` also gives is a problem. +pub(crate) fn attach_sessions( + mut project: ProjectConfig, + sessions: BTreeMap, +) -> Result> { + let taken: Vec = sessions + .keys() + .filter(|name| project.connections.contains_key(*name)) + .map(|name| { + format!( + "[connections.{name}] is also a connection the caller attaches; give one of them another name" + ) + }) + .collect(); + if !taken.is_empty() { + return Err(taken); + } + project.connections.extend( + sessions + .into_iter() + .map(|(name, session)| (name, ConnectionConfig::Session(session))), + ); + Ok(project) +} diff --git a/crates/sqlload/src/project/main/parse_project.rs b/crates/sqlload/src/project/main/parse_project.rs index 145e478c6..81453a6f5 100644 --- a/crates/sqlload/src/project/main/parse_project.rs +++ b/crates/sqlload/src/project/main/parse_project.rs @@ -1,5 +1,7 @@ //! Parse project text. +use std::collections::BTreeMap; + use crate::project::errors::ProjectError; use crate::project::main::parse_python_project::parse_python_project; use crate::project::models::ProjectConfig; @@ -9,5 +11,5 @@ pub fn parse_project( text: &str, lookup: &dyn Fn(&str) -> Option, ) -> Result { - parse_python_project(text, lookup, &[]) + parse_python_project(text, lookup, (&[], BTreeMap::new())) } diff --git a/crates/sqlload/src/project/main/parse_python_project.rs b/crates/sqlload/src/project/main/parse_python_project.rs index 4e23c3280..9d2252d8e 100644 --- a/crates/sqlload/src/project/main/parse_python_project.rs +++ b/crates/sqlload/src/project/main/parse_python_project.rs @@ -1,22 +1,24 @@ -//! Parse project text together with the sources declared in Python. +//! Parse project text together with the sources declared in Python and the connections its caller attaches. use std::collections::BTreeMap; +use crate::adapters::session::models::SessionConnection; use crate::config::main::interpolate_toml::interpolate_toml; use crate::project::_helpers::python_checks::{checked_python_sources, with_python_sources}; use crate::project::_helpers::references::reference_problems; use crate::project::_helpers::serde_values::typed_constants; +use crate::project::_helpers::sessions::attach_sessions; use crate::project::_helpers::tombstones::with_tombstone_tables; use crate::project::errors::ProjectError; 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, and each `deletes_from`'s tombstone table; 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, 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, - python: &[PythonSource], + (python, sessions): (&[PythonSource], BTreeMap), ) -> Result { let value: toml::Value = toml::from_str(text).map_err(|error| ProjectError::Syntax(error.to_string()))?; @@ -40,6 +42,7 @@ pub fn parse_python_project( .map(|source| (source.name.clone(), source.http_paths.clone())) .collect(); project.connection_variables = variables; + let project = attach_sessions(project, sessions).map_err(ProjectError::Invalid)?; let problems = reference_problems(&project); match problems.is_empty() { true => Ok(with_tombstone_tables(project)), diff --git a/crates/sqlload/src/project/models.rs b/crates/sqlload/src/project/models.rs index a9f0233ba..8af3dc88f 100644 --- a/crates/sqlload/src/project/models.rs +++ b/crates/sqlload/src/project/models.rs @@ -366,12 +366,16 @@ pub enum ConnectionConfig { #[serde(default)] retries: Option, }, + /// A warehouse connection the caller owns, which a library caller attaches to the project by name (see [`SessionConnection`](crate::adapters::session::models::SessionConnection)); no project file can write one. + #[serde(skip_deserializing)] + Session(crate::adapters::session::models::SessionConnection), } impl ConnectionConfig { - /// The `kind` value as written. + /// The `kind` value as written; a caller's connection gives the kind it stands in for. pub fn kind(&self) -> &'static str { match self { + Self::Session(session) => session.kind(), Self::Snowflake { .. } => "snowflake", Self::Databricks { .. } => "databricks", Self::BigQuery { .. } => "bigquery", diff --git a/crates/sqlload/src/project/tests/helpers.rs b/crates/sqlload/src/project/tests/helpers.rs index bb1d8415a..385cd5154 100644 --- a/crates/sqlload/src/project/tests/helpers.rs +++ b/crates/sqlload/src/project/tests/helpers.rs @@ -124,7 +124,7 @@ pub(crate) fn parse_with_python( crate::project::main::parse_python_project::parse_python_project( &format!("{CONNECTIONS}{toml}"), &environment, - &python, + (&python, std::collections::BTreeMap::new()), ) .map(|project| read(&project)) .map_err(|error| error.to_string()) diff --git a/crates/sqlload/src/python_sources/constants.rs b/crates/sqlload/src/python_sources/constants.rs new file mode 100644 index 000000000..fac675724 --- /dev/null +++ b/crates/sqlload/src/python_sources/constants.rs @@ -0,0 +1,10 @@ +//! The methods by which what a table function yields crosses into the engine as plain data, so the Python that builds it (the `sqlload_api` package) needs no compiled code. + +/// The method of an `sl.http` job that returns its definition as JSON, which [`run_http_job`](crate::http_source::main::run_http_job::run_http_job) runs. +pub const HTTP_JOB_METHOD: &str = "__sqlload_http_job__"; + +/// The method of an `sl.checkpoint` that returns its state as JSON. +pub const CHECKPOINT_METHOD: &str = "__sqlload_checkpoint__"; + +/// The method of an `sl.json(...)` or `sl.ndjson(...)` that returns its bytes and their read spec as JSON, which [`json_read_spec`](crate::row_batches::main::json_read_spec::json_read_spec) reads. +pub const JSON_DATA_METHOD: &str = "__sqlload_json__"; diff --git a/crates/sqlload/src/python_sources/mod.rs b/crates/sqlload/src/python_sources/mod.rs index 921db3393..35682f7a7 100644 --- a/crates/sqlload/src/python_sources/mod.rs +++ b/crates/sqlload/src/python_sources/mod.rs @@ -1,6 +1,7 @@ //! Python sources: declarations found by importing `python_paths`, and the host that runs their table functions. pub(crate) mod _helpers; +pub mod constants; pub mod errors; pub mod main; pub mod models; diff --git a/crates/sqlload/src/row_batches/main/json_read_spec.rs b/crates/sqlload/src/row_batches/main/json_read_spec.rs new file mode 100644 index 000000000..0944dac02 --- /dev/null +++ b/crates/sqlload/src/row_batches/main/json_read_spec.rs @@ -0,0 +1,20 @@ +//! Read the read spec a yielded `sl.json(...)` or `sl.ndjson(...)` crosses with. + +use crate::row_batches::main::projection::projection; +use crate::row_batches::models::{JsonLayout, JsonRead, JsonReadSpec}; + +/// The read `text` (a yielded JSON item's `__sqlload_json__()` spec) asks for, in batches of `batch_rows`, or why it can't be read: an NDJSON read with a `path`, or `fields` and `keep_record` that don't describe a projection. +pub fn json_read_spec(text: &str, batch_rows: usize) -> Result { + let spec: JsonReadSpec = + serde_json::from_str(text).map_err(|error| format!("fields: {error}"))?; + if spec.layout == JsonLayout::Lines && spec.path.is_some() { + return Err("path picks rows out of a JSON document; NDJSON has none".to_owned()); + } + let projection = projection(spec.fields.as_deref(), spec.keep_record.as_deref())?; + Ok(JsonRead { + layout: spec.layout, + path: spec.path, + batch_rows, + projection, + }) +} diff --git a/crates/sqlload/src/row_batches/main/mod.rs b/crates/sqlload/src/row_batches/main/mod.rs index 033d2277d..1d73b1025 100644 --- a/crates/sqlload/src/row_batches/main/mod.rs +++ b/crates/sqlload/src/row_batches/main/mod.rs @@ -7,6 +7,7 @@ pub mod flatten_lines; pub mod flattened_columns; pub mod item_position; pub mod json_lists; +pub mod json_read_spec; pub mod json_rows; pub mod loaded_batch; pub mod merge_schema; diff --git a/crates/sqlload/src/row_batches/models.rs b/crates/sqlload/src/row_batches/models.rs index c8c6de326..be3d56cbf 100644 --- a/crates/sqlload/src/row_batches/models.rs +++ b/crates/sqlload/src/row_batches/models.rs @@ -138,7 +138,8 @@ impl RowColumns { } /// How JSON bytes hold their rows. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum JsonLayout { /// One JSON document: an array of objects, or objects one after another. Document, @@ -157,6 +158,22 @@ pub struct JsonRead { pub projection: Option, } +/// How a yielded `sl.json(...)` or `sl.ndjson(...)` asks its bytes to be read, as its `__sqlload_json__()` writes it. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JsonReadSpec { + pub layout: JsonLayout, + /// A dotted path to the array of rows inside a document. + #[serde(default)] + pub path: Option, + /// `fields=`: the columns each row loads as. + #[serde(default)] + pub fields: Option>, + /// `keep_record=`: the column the whole row object loads in, beside `fields`. + #[serde(default)] + pub keep_record: Option, +} + /// Which values of each row object load, under which column names. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Projection { diff --git a/crates/sqlload/tests/loader.rs b/crates/sqlload/tests/loader.rs index 706d0f704..116ea293d 100644 --- a/crates/sqlload/tests/loader.rs +++ b/crates/sqlload/tests/loader.rs @@ -32,6 +32,8 @@ mod merge_helpers; mod odbc_helpers; #[path = "loader/postgres/helpers.rs"] mod postgres_helpers; +#[path = "loader/session/helpers.rs"] +mod session_helpers; #[path = "loader/sftp/helpers.rs"] mod sftp_helpers; #[path = "loader/sheets/helpers.rs"] @@ -101,6 +103,8 @@ mod test_postgres_cdc; mod test_postgres_cdc_files; #[path = "loader/test_postgres_reader.rs"] mod test_postgres_reader; +#[path = "loader/test_postgres_session.rs"] +mod test_postgres_session; #[path = "loader/test_postgres_ssh.rs"] mod test_postgres_ssh; #[path = "loader/test_postgres_target.rs"] diff --git a/crates/sqlload/tests/loader/session/helpers.rs b/crates/sqlload/tests/loader/session/helpers.rs new file mode 100644 index 000000000..80751b4bd --- /dev/null +++ b/crates/sqlload/tests/loader/session/helpers.rs @@ -0,0 +1,220 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use sqlload::adapters::contract::models::TableName; +use sqlload::adapters::session::errors::SessionError; +use sqlload::adapters::session::models::SessionConnection; +use sqlload::adapters::session::types::{CallerConnection, CallerSession}; +use sqlload::column_types::models::Warehouse; +use sqlload::loader::main::apply_project::apply_project; +use sqlload::loader::main::connect_targets::connect_targets; +use sqlload::loader::main::load_tables::load_tables; +use sqlload::loader::main::plan_project::plan_project; +use sqlload::loader::models::{LoadRun, PlanOptions}; +use sqlload::project::main::parse_python_project::parse_python_project; +use sqlload::project::models::ProjectConfig; +use sqlload_testkit::postgres::constants::{DATABASE, PASSWORD, USER}; + +use crate::test_types::{PostgresCaller, PostgresCallerSession}; + +impl CallerConnection for PostgresCaller { + fn open(&self) -> Result, SessionError> { + let port = self.port; + on_own_thread(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| SessionError::new(error.to_string()))?; + let address = format!( + "host=127.0.0.1 port={port} user={USER} password={PASSWORD} dbname={DATABASE}" + ); + let (client, connection) = runtime + .block_on(tokio_postgres::connect(&address, tokio_postgres::NoTls)) + .map_err(|error| SessionError::new(message(&error)))?; + runtime.spawn(connection); + Ok(Arc::new(PostgresCallerSession { + runtime: Some(runtime), + client, + }) as Arc) + }) + } + + fn describe(&self) -> String { + format!("{USER} on a test server") + } +} + +impl Drop for PostgresCallerSession { + fn drop(&mut self) { + if let Some(runtime) = self.runtime.take() { + runtime.shutdown_background(); + } + } +} + +impl PostgresCallerSession { + /// `work` run to its end on the session's runtime. + fn block_on(&self, work: impl std::future::Future) -> Result { + self.runtime + .as_ref() + .map(|runtime| runtime.block_on(work)) + .ok_or_else(|| SessionError::new("the session is closed")) + } +} + +impl CallerSession for PostgresCallerSession { + fn execute(&self, statement: &str) -> Result<(), SessionError> { + on_own_thread(|| { + self.block_on(self.client.batch_execute(statement))? + .map_err(|error| SessionError::new(message(&error))) + }) + } + + fn query_text(&self, query: &str) -> Result>>, SessionError> { + on_own_thread(|| { + let messages = self + .block_on(self.client.simple_query(query))? + .map_err(|error| SessionError::new(message(&error)))?; + Ok(messages + .iter() + .filter_map(|message| match message { + tokio_postgres::SimpleQueryMessage::Row(row) => Some( + (0..row.len()) + .map(|index| row.get(index).map(str::to_owned)) + .collect(), + ), + _ => None, + }) + .collect()) + }) + } + + fn copy_in(&self, statement: &str, data: &[u8]) -> Result<(), SessionError> { + use futures_util::SinkExt; + on_own_thread(|| { + self.block_on(async { + let failed = |error: tokio_postgres::Error| SessionError::new(message(&error)); + let sink = self.client.copy_in(statement).await.map_err(failed)?; + futures_util::pin_mut!(sink); + sink.send(bytes::Bytes::copy_from_slice(data)) + .await + .map_err(failed)?; + sink.as_mut().finish().await.map(|_| ()).map_err(failed) + })? + }) + } + + fn load_parquet( + &self, + _table: &TableName, + _file: &std::path::Path, + ) -> Result<(), SessionError> { + Err(SessionError::new("Postgres copies rows in")) + } +} + +/// What the server said, where it said anything: `tokio_postgres` shows only "db error". +pub(crate) fn message(error: &tokio_postgres::Error) -> String { + error + .as_db_error() + .map_or_else(|| error.to_string(), |db| db.message().to_owned()) +} + +/// `body` run on a thread of its own, outside any async runtime, as a caller's blocking driver runs. +fn on_own_thread( + body: impl FnOnce() -> Result + Send, +) -> Result { + std::thread::scope(|scope| { + scope + .spawn(body) + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + }) +} + +/// The project loading `public.accounts` from the server on `port` into its schema `raw` through a caller's session, with `settings`. +pub(crate) fn session_project(port: u16, settings: &str) -> Result { + let text = format!( + r#"default_target = "raw" + +[connections.app_pg] +kind = "postgres" +host = "127.0.0.1" +port = {port} +user = "{USER}" +password = "{PASSWORD}" +database = "{DATABASE}" + +[targets.raw] +connection = "caller" +loader_schema = "raw" + +[sources.app] +kind = "postgres" +connection = "app_pg" +include = ["public.accounts"] +table_name = "{{table}}" + +[sources.app.tables."public.accounts"] +description = "Test accounts." +{settings} +"# + ); + let sessions = BTreeMap::from([( + "caller".to_owned(), + SessionConnection { + warehouse: Warehouse::Postgres, + motherduck: false, + database: None, + caller: Arc::new(PostgresCaller { port }), + }, + )]); + parse_python_project(&text, &|_| None, (&[], sessions)).map_err(|error| error.to_string()) +} + +/// Plan, apply and load `project`: `ok` or the table's error, or what blocks the plan as the error. +pub(crate) async fn load(project: &ProjectConfig) -> Result { + let destinations = connect_targets(project) + .await + .map_err(|error| error.to_string())?; + let options = PlanOptions::default(); + let plan = plan_project(project, &destinations, &options) + .await + .map_err(|error| error.to_string())?; + let blocked: Vec = plan + .tables + .iter() + .filter_map(|table| { + table + .schema + .blocked + .as_ref() + .map(|blocked| blocked.reasons.join("; ")) + }) + .chain(plan.problems.iter().cloned()) + .collect(); + blocked + .is_empty() + .then_some(()) + .ok_or_else(|| blocked.join("\n"))?; + apply_project(&plan, &destinations) + .await + .map_err(|error| error.to_string())?; + let run = LoadRun { + project, + destinations: &destinations, + host: None, + options: &options, + }; + let outcomes = load_tables(&run, &plan, None).await; + Ok(outcomes + .into_iter() + .map(|outcome| { + outcome + .loaded + .map(|_| "ok".to_owned()) + .unwrap_or_else(|error| error) + }) + .collect::>() + .join("\n")) +} diff --git a/crates/sqlload/tests/loader/test_postgres_session.rs b/crates/sqlload/tests/loader/test_postgres_session.rs new file mode 100644 index 000000000..b83e01385 --- /dev/null +++ b/crates/sqlload/tests/loader/test_postgres_session.rs @@ -0,0 +1,68 @@ +use sqlload_testkit::postgres::main::connect::connect; +use sqlload_testkit::postgres::main::start_postgres::start_postgres; + +use crate::helpers::run_async; +use crate::session_helpers::{load, message, session_project}; +use crate::test_types::PostgresSessionTestCase; + +const SETUP: &str = " +CREATE TABLE public.accounts (id int8 PRIMARY KEY, name text, updated_at timestamptz NOT NULL); +INSERT INTO public.accounts VALUES (1, 'Acme', '2026-11-01 10:00:00+00'), (2, 'Beta', '2026-11-02 10:00:00+00'); +CREATE SCHEMA raw; +"; + +#[test] +fn given_a_callers_postgres_session_when_loading_twice_then_rows_copy_in_and_the_checks_before_a_write_run_on_it() +-> Result<(), String> { + run_async(|| async move { + let test_cases = [ + PostgresSessionTestCase { + description: "merge copies the rows in, matching the key the table's unique index holds", + settings: "write_strategy = \"merge\"\nunique_key = \"{primary_key}\"\ncursor_column = \"updated_at\"", + change: "UPDATE public.accounts SET name = 'Acme Two', updated_at = '2026-11-03 10:00:00+00' WHERE id = 1", + expected_second: "ok", + expected_rows: &["1:Acme Two", "2:Beta"], + }, + PostgresSessionTestCase { + description: "replace is refused while a foreign key would cascade its deletes into another table", + settings: "write_strategy = \"replace\"", + change: "ALTER TABLE raw.accounts ADD PRIMARY KEY (id); CREATE TABLE public.notes (account_id int8 REFERENCES raw.accounts (id) ON DELETE CASCADE)", + expected_second: "ON DELETE CASCADE", + expected_rows: &["1:Acme", "2:Beta"], + }, + ]; + for test_case in test_cases { + let postgres = start_postgres().await?; + let client = connect(&postgres).await?; + client + .batch_execute(SETUP) + .await + .map_err(|error| message(&error))?; + let project = session_project(postgres.port, test_case.settings)?; + let first = load(&project).await?; + client + .batch_execute(test_case.change) + .await + .map_err(|error| message(&error))?; + let second = load(&project).await.unwrap_or_else(|blocked| blocked); + let rows: Vec = client + .query( + "SELECT id::text || ':' || name FROM raw.accounts ORDER BY id", + &[], + ) + .await + .map_err(|error| error.to_string())? + .iter() + .map(|row| row.get(0)) + .collect(); + assert_eq!(first, "ok", "{}", test_case.description); + assert!( + second.contains(test_case.expected_second), + "{}: {second}", + test_case.description + ); + assert_eq!(rows, test_case.expected_rows, "{}", test_case.description); + } + Ok(()) + }) +} diff --git a/crates/sqlload/tests/loader/test_types.rs b/crates/sqlload/tests/loader/test_types.rs index fdee434f8..b6c7aa32b 100644 --- a/crates/sqlload/tests/loader/test_types.rs +++ b/crates/sqlload/tests/loader/test_types.rs @@ -1733,3 +1733,29 @@ pub(crate) struct ManyFilesTestCase { /// Rows of the table not in the newest-file-wins oracle, then the reverse, then its rows, its commits and the rows its commits recorded. pub(crate) expected_result: &'static str, } + +/// A caller's connection to a Postgres server, as a program embedding SQLLoad would hold one: each session is its own connection, run on a runtime of its own. +#[derive(Debug)] +pub(crate) struct PostgresCaller { + pub(crate) port: u16, +} + +/// One session of a [`PostgresCaller`]: its connection, and the runtime that drives it. +#[derive(Debug)] +pub(crate) struct PostgresCallerSession { + /// Taken when the session drops, which may happen on an async worker, where a runtime only shuts down in the background. + pub(crate) runtime: Option, + pub(crate) client: tokio_postgres::Client, +} + +pub(crate) struct PostgresSessionTestCase { + pub(crate) description: &'static str, + /// The table's settings in `[sources.app.tables."public.accounts"]`. + pub(crate) settings: &'static str, + /// SQL run on the server before the second load. + pub(crate) change: &'static str, + /// The second load's outcome for the table: `ok`, or a part of its problem. + pub(crate) expected_second: &'static str, + /// The loaded `raw.accounts` rows after it, as `id:name`, by id. + pub(crate) expected_rows: &'static [&'static str], +} diff --git a/fensu.toml b/fensu.toml index 1bff2c0dc..f671640f5 100644 --- a/fensu.toml +++ b/fensu.toml @@ -309,12 +309,6 @@ path = "crates/sqlload-python/src/bindings/_helpers/cross.rs" symbols = ["cross"] reason = "PyO3 maps each of the Python function's keyword-only arguments to one Rust parameter." -[[targets.rust.rule_exceptions]] -rule = "FPRSS120" -path = "crates/sqlload-python/src/bindings/models.rs" -symbols = ["JsonData::new"] -reason = "PyO3 maps each of sl.json's and sl.ndjson's keyword-only arguments to one Rust parameter." - [[targets.rust.rule_exceptions]] rule = "FPRSH003" path = "crates/sqlload-python/src/crossing/_helpers/parser.rs" diff --git a/packages/sqlload-api/LICENSE b/packages/sqlload-api/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/packages/sqlload-api/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/sqlload-api/README.md b/packages/sqlload-api/README.md new file mode 100644 index 000000000..873b4d750 --- /dev/null +++ b/packages/sqlload-api/README.md @@ -0,0 +1,18 @@ +# sqlload-api + +SQLLoad's Python API for describing data and HTTP requests, in pure Python with no compiled code: `http(...)` jobs and +their paginators, `json(...)` / `ndjson(...)`, `field`, `parent`, `key`, `checkpoint` and `transform`. + +You rarely install it yourself: [`sqlload`](https://pypi.org/project/sqlload/) depends on it and re-exports it +(`import sqlload as sl; sl.http(...)`). Tools that run SQLLoad's engine in their own process use it to build the same jobs +without loading a second engine: + +```python +import sqlload_api as sl + +api = sl.http(connection="shop_api") +job = api.paginate("/orders", paginator=sl.next_link("$.next"), select="$.items") +``` + +A job built this way is identical to one built from a SQLLoad source with the same connection. Released together with +`sqlload`, at the same version; an engine reads the API of its own version. diff --git a/packages/sqlload-api/pyproject.toml b/packages/sqlload-api/pyproject.toml new file mode 100644 index 000000000..400562feb --- /dev/null +++ b/packages/sqlload-api/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["hatchling>=1.26"] +build-backend = "hatchling.build" + +[project] +name = "sqlload-api" +version = "0.84.0" # x-release-please-version +description = "SQLLoad's Python API for describing data and HTTP requests, without the engine." +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +license-files = ["LICENSE"] +classifiers = [ + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Topic :: Database", +] +dependencies = [] + +[project.urls] +Homepage = "https://github.com/sqlstack-io/sqlload" +Issues = "https://github.com/sqlstack-io/sqlload/issues" +Repository = "https://github.com/sqlstack-io/sqlload" + +[tool.hatch.build.targets.wheel] +packages = ["python/sqlload_api"] + +[tool.hatch.build.targets.sdist] +include = ["python/sqlload_api", "tests", "README.md", "LICENSE"] diff --git a/packages/sqlload-api/python/sqlload_api/__init__.py b/packages/sqlload-api/python/sqlload_api/__init__.py new file mode 100644 index 000000000..ad294319f --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/__init__.py @@ -0,0 +1,68 @@ +"""SQLLoad's Python API for describing data and requests, without the engine. + +A table function (or another tool's loader) yields what these build, and the engine that reads them runs it: + +- `http(...)` jobs (`paginate`, `fan_out`) that make every request and parse every page in Rust; +- `json(...)` and `ndjson(...)` bytes, parsed without the GIL; +- `checkpoint(...)` positions between a logged table's rows. + +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")`. +""" + +from importlib.metadata import version + +from sqlload_api._data import Checkpoint, Field, JsonData, checkpoint, field, json, key, ndjson, parent +from sqlload_api._http import ( + CellName, + Cells, + ConnectionOwner, + Http, + Job, + cells, + cursor, + header_row, + http, + link_header, + listed, + next_link, + offset, + page_number, + single, +) +from sqlload_api._http_paths import literal_paths +from sqlload_api._transform import TransformContext, transform + +__version__: str = version("sqlload-api") + +__all__ = [ + "CellName", + "Cells", + "Checkpoint", + "ConnectionOwner", + "Field", + "Http", + "Job", + "JsonData", + "TransformContext", + "__version__", + "cells", + "checkpoint", + "cursor", + "field", + "header_row", + "http", + "json", + "key", + "link_header", + "listed", + "literal_paths", + "ndjson", + "next_link", + "offset", + "page_number", + "parent", + "single", + "transform", +] diff --git a/packages/sqlload/python/sqlload/_data.py b/packages/sqlload-api/python/sqlload_api/_data.py similarity index 76% rename from packages/sqlload/python/sqlload/_data.py rename to packages/sqlload-api/python/sqlload_api/_data.py index 7ee2c9048..8c2626785 100644 --- a/packages/sqlload/python/sqlload/_data.py +++ b/packages/sqlload-api/python/sqlload_api/_data.py @@ -1,12 +1,14 @@ -"""What a table function can yield besides rows: JSON bytes, which Rust parses without the GIL, and checkpoints.""" +"""What a table function can yield besides rows: JSON bytes, which Rust parses without the GIL, and checkpoints. + +Each crosses into the engine through a method returning plain data (`__sqlload_json__`, `__sqlload_checkpoint__`), so +this module needs no compiled code; the engine checks what it reads. +""" import json as _json from collections.abc import Mapping from dataclasses import dataclass from typing import Any -from sqlload._native import JsonData - BytesLike = bytes | bytearray | memoryview | str @@ -63,17 +65,72 @@ def key(name: str, *, required: bool = False) -> Field: return Field("$", required, None, "fail", {"kind": "key", "name": name}) +class JsonData: + """JSON or NDJSON bytes yielded by a table function (`sl.json(...)`, `sl.ndjson(...)`), parsed by the engine. + + It crosses as `__sqlload_json__()`: the bytes, and how to read them as JSON. The engine checks the read when the + item crosses (a field's path syntax among it), failing the table with the problem.""" + + __slots__ = ("_bytes", "_fields", "_keep_record", "_lines", "_path") + + def __init__( + self, + data: bytes | bytearray, + *, + lines: bool = False, + path: str | None = None, + fields: list[dict[str, Any]] | None = None, + keep_record: str | None = None, + ) -> None: + if lines and path is not None: + raise ValueError("path picks rows out of a JSON document; NDJSON has none") + if keep_record is not None and fields is None: + raise ValueError("keep_record needs fields: name the columns to load beside the whole record") + self._bytes = data + self._lines = lines + self._path = path + self._fields = fields + self._keep_record = keep_record + + @property + def lines(self) -> bool: + """Whether the bytes are NDJSON.""" + return self._lines + + @property + def path(self) -> str | None: + """The dotted path to the rows inside the document, if any.""" + return self._path + + def __len__(self) -> int: + return len(self._bytes) + + def __sqlload_json__(self) -> tuple[bytes | bytearray, str]: + """The bytes, and the read as the engine takes it: layout, path, fields and keep_record.""" + read = { + "layout": "lines" if self._lines else "document", + "path": self._path, + "fields": self._fields, + "keep_record": self._keep_record, + } + return self._bytes, _json.dumps(read) + + def __repr__(self) -> str: + kind = "sl.ndjson" if self._lines else "sl.json" + return f"{kind}({len(self._bytes)} bytes)" + + def json(data: BytesLike, path: str | None = None, *, fields: Fields | None = None, keep_record: str | None = None) -> JsonData: """Rows in a JSON document: an array of objects (at dotted `path`, such as `"data.items"`), or objects. `fields` loads only those values, renamed (`{"account_code": "$.code"}`); `keep_record` adds each row's whole object as a JSON column.""" - return JsonData(_as_bytes(data), path=path, fields=_fields_text(fields), keep_record=keep_record) + return JsonData(_as_bytes(data), path=path, fields=_json_fields(fields), keep_record=keep_record) def ndjson(data: BytesLike, *, fields: Fields | None = None, keep_record: str | None = None) -> JsonData: """Rows as newline-delimited JSON, one object per line; `fields` and `keep_record` as for `sl.json`.""" - return JsonData(_as_bytes(data), lines=True, fields=_fields_text(fields), keep_record=keep_record) + return JsonData(_as_bytes(data), lines=True, fields=_json_fields(fields), keep_record=keep_record) def field_list(fields: Fields | None) -> list[dict[str, Any]] | None: @@ -114,13 +171,13 @@ def _conversion(name: str, projected: Field) -> dict[str, Any]: return {"parse": parse if isinstance(parse, str) else dict(parse), **({"on_error": "null"} if projected.on_error == "null" else {})} -def _fields_text(fields: Fields | None) -> str | None: - """`fields` as the JSON list of specs `JsonData` reads.""" +def _json_fields(fields: Fields | None) -> list[dict[str, Any]] | None: + """`fields` as the list of specs `JsonData` crosses with.""" listed = field_list(fields) for spec in listed or []: if "from" in spec: raise ValueError(f"fields[{spec['name']!r}]: sl.parent and sl.key read around the rows of an sl.http job; sl.json and sl.ndjson rows have no request") - return None if listed is None else _json.dumps(listed) + return listed def _as_bytes(data: BytesLike) -> bytes | bytearray: diff --git a/packages/sqlload/python/sqlload/_http.py b/packages/sqlload-api/python/sqlload_api/_http.py similarity index 93% rename from packages/sqlload/python/sqlload/_http.py rename to packages/sqlload-api/python/sqlload_api/_http.py index c921fca27..c330476b3 100644 --- a/packages/sqlload/python/sqlload/_http.py +++ b/packages/sqlload-api/python/sqlload_api/_http.py @@ -8,11 +8,10 @@ import json from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass -from typing import Any +from typing import Any, Protocol -from sqlload._data import Field, Fields, field_list -from sqlload._declare import Source -from sqlload._transform import TRANSFORMS +from sqlload_api._data import Field, Fields, field_list +from sqlload_api._transform import TRANSFORMS #: What moved from `sl.http` onto the `http` connection in sqlload.toml. CONNECTION_SETTINGS = ("auth", "rate_limit", "max_in_flight", "retries") @@ -23,6 +22,16 @@ ) +class ConnectionOwner(Protocol): + """What `sl.http` reads a connection from: a SQLLoad `sl.source(...)`, or anything with a name and settings.""" + + @property + def name(self) -> str: ... + + @property + def settings(self) -> Mapping[str, Any]: ... + + @dataclass(frozen=True) class Paginator: """How the next page is found; every paginate names one.""" @@ -199,17 +208,19 @@ def __repr__(self) -> str: class Http: - """Requests to one source's HTTP connection: `paginate` and `fan_out` build jobs.""" + """Requests to one HTTP connection, a source's or one named: `paginate` and `fan_out` build jobs.""" def __init__( self, - source: Source, + source: ConnectionOwner | None = None, *, headers: Mapping[str, str] | None = None, connection: str | None = None, **moved: Any, ) -> None: - name = connection or source.settings.get("connection") + name = connection or (None if source is None else source.settings.get("connection")) + if not name and source is None: + raise ValueError("sl.http needs a connection: pass connection=, or a source that sets one") if not name: raise ValueError(f"sl.http needs a connection: set connection= on source {source.name} or pass connection=") for key in moved: @@ -404,13 +415,14 @@ def _projection(fields: Fields | None, keep_record: str | None) -> dict[str, Any def http( - source: Source, + source: ConnectionOwner | None = None, *, headers: Mapping[str, str] | None = None, connection: str | None = None, **moved: Any, ) -> Http: - """Requests to `source`'s HTTP connection (or `connection`), adding `headers` to the connection's. The connection in - sqlload.toml sets how requests authenticate (`auth`), the limits every request to it shares in the run (`rate_limit`, - `max_in_flight`) and its `retries`.""" + """Requests to `source`'s HTTP connection (or `connection`, which is all it needs without a source), adding `headers` + to the connection's. The connection sets how requests authenticate (`auth`), the limits every request to it shares + in the run (`rate_limit`, `max_in_flight`) and its `retries`. The job is the same whichever way the connection is + given.""" return Http(source, headers=headers, connection=connection, **moved) diff --git a/packages/sqlload/python/sqlload/_http_paths.py b/packages/sqlload-api/python/sqlload_api/_http_paths.py similarity index 77% rename from packages/sqlload/python/sqlload/_http_paths.py rename to packages/sqlload-api/python/sqlload_api/_http_paths.py index 8fc024cdb..2e21d33c8 100644 --- a/packages/sqlload/python/sqlload/_http_paths.py +++ b/packages/sqlload-api/python/sqlload_api/_http_paths.py @@ -1,8 +1,9 @@ """The `sl.http` field paths a table function writes as literals, read from its source without calling it. `plan` checks them with load's own path checker, so a bad literal path fails `plan` instead of the load. Only calls whose -names resolve to sqlload count: `paginate` and `fan_out` on an `sl.http(...)` client, and `sl.field`, `sl.parent` and -`sl.key` in their `fields=`. A `transform=` given as a name must be one `@sl.transform` registered. A path `plan` can't +names resolve to sqlload or sqlload_api count: `paginate` and `fan_out` on an `sl.http(...)` client (or, with +`context_clients`, one the function's context makes, such as `ctx.http()`), and `sl.field`, `sl.parent` and `sl.key` in +their `fields=`. A `transform=` given as a name must be one `@sl.transform` registered. A path `plan` can't read as a literal (a variable, an f-string, a dict built elsewhere), or a function whose source can't be read, is left to load, which checks every job before its first request. """ @@ -13,17 +14,17 @@ import sys import textwrap import types -from collections.abc import Callable, Iterator, Mapping +from collections.abc import Callable, Collection, Iterator, Mapping from typing import Any -from sqlload import _data, _http -from sqlload._transform import TRANSFORMS +from sqlload_api import _data, _http +from sqlload_api._transform import TRANSFORMS #: The methods of an `sl.http` client that build a job. JOB_METHODS: frozenset[str] = frozenset({"paginate", "fan_out"}) -#: The module a name must resolve into for its call to count. -PACKAGE = "sqlload" +#: The packages a name must resolve into for its call to count: `sqlload` re-exports `sqlload_api`'s functions. +PACKAGES: tuple[str, ...] = ("sqlload", "sqlload_api") #: A name or attribute that doesn't resolve to anything `plan` may look at. _UNRESOLVED: Any = object() @@ -31,13 +32,22 @@ #: A local name assigned an `sl.http(...)` client inside the table function. _LOCAL_CLIENT: Any = object() +#: The table function's first parameter, its context, when `context_clients` names methods of it that make clients. +_CONTEXT: Any = object() -def literal_paths(function: Callable[..., Any]) -> dict[str, Any] | None: +#: A context method named in `context_clients`: calling it makes a client. +_CONTEXT_CLIENT: Any = object() + + +def literal_paths(function: Callable[..., Any], *, context_clients: Collection[str] = ()) -> dict[str, Any] | None: """The literal paths of the jobs `function` builds that load rows: each `fields=` entry's `[name, path]` and each `key_path`; why a `transform=` name can't be looked up; what `plan` can't read as a literal; and whether the source can't be read at all. A job passed as another job's `over=` is left out: load refuses its `fields` and `key_path` whatever their paths. `None` when the function builds - no job `plan` can see.""" + no job `plan` can see. + + `context_clients` names methods of the function's first parameter that return an `sl.http` client (`{"http"}` for + `api = ctx.http()` or `ctx.http().paginate(...)`); none by default.""" try: tree = ast.parse(textwrap.dedent(inspect.getsource(function))) except (OSError, TypeError, SyntaxError): @@ -45,7 +55,7 @@ def literal_paths(function: Callable[..., Any]) -> dict[str, Any] | None: definition = next((node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))), None) if definition is None: return {"fields": [], "key_paths": [], "computed": [], "no_source": True} - names = _Names(function, definition) + names = _Names(function, definition, frozenset(context_clients)) jobs = [call for call in ast.walk(definition) if isinstance(call, ast.Call) and _job_method(call, names)] if not jobs: return None @@ -61,7 +71,10 @@ class _Names: """What the names a table function uses resolve to: its own imports and `sl.http(...)` clients, else its closure and module globals; a name it assigns otherwise shadows them and resolves to nothing.""" - def __init__(self, function: Callable[..., Any], definition: ast.FunctionDef | ast.AsyncFunctionDef) -> None: + def __init__( + self, function: Callable[..., Any], definition: ast.FunctionDef | ast.AsyncFunctionDef, context_clients: frozenset[str] + ) -> None: + self.context_clients = context_clients self.outer: dict[str, Any] = dict(getattr(function, "__globals__", {})) code = getattr(function, "__code__", None) for name, cell in zip(code.co_freevars if code else (), getattr(function, "__closure__", None) or ()): @@ -74,6 +87,9 @@ def __init__(self, function: Callable[..., Any], definition: ast.FunctionDef | a for argument in [*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs, arguments.vararg, arguments.kwarg]: if argument is not None: self.local[argument.arg] = _UNRESOLVED + positional = [*arguments.posonlyargs, *arguments.args] + if context_clients and positional: + self.local[positional[0].arg] = _CONTEXT for node in ast.walk(definition): self._bind(node) @@ -87,7 +103,7 @@ def _bind(self, node: ast.AST) -> None: for alias in node.names: self.local[alias.asname or alias.name] = getattr(module, alias.name, _UNRESOLVED) if _ours(module) else _UNRESOLVED elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): - client = isinstance(node.value, ast.Call) and self.resolve(node.value.func) in (_http.http, _http.Http) + client = isinstance(node.value, ast.Call) and _makes_client(self.resolve(node.value.func)) self.local[node.targets[0].id] = _LOCAL_CLIENT if client and self.local.get(node.targets[0].id, _LOCAL_CLIENT) is _LOCAL_CLIENT else _UNRESOLVED elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id not in self.local: self.local[node.id] = _UNRESOLVED @@ -96,9 +112,13 @@ def resolve(self, node: ast.expr) -> Any: """What a name or a dotted attribute resolves to, looking only into sqlload's modules and clients.""" if isinstance(node, ast.Name): return self.local[node.id] if node.id in self.local else self.outer.get(node.id, _UNRESOLVED) + if isinstance(node, ast.Call) and self.resolve(node.func) is _CONTEXT_CLIENT: + return _LOCAL_CLIENT if not isinstance(node, ast.Attribute): return _UNRESOLVED owner = self.resolve(node.value) + if owner is _CONTEXT: + return _CONTEXT_CLIENT if node.attr in self.context_clients else _UNRESOLVED if isinstance(owner, types.ModuleType) and _ours(owner): return getattr(owner, node.attr, _UNRESOLVED) if (owner is _LOCAL_CLIENT or isinstance(owner, _http.Http)) and node.attr in JOB_METHODS: @@ -107,9 +127,15 @@ def resolve(self, node: ast.expr) -> Any: def _ours(module: Any) -> bool: - """Whether `module` is sqlload or one of its modules.""" + """Whether `module` is sqlload, sqlload_api or one of their modules.""" name = getattr(module, "__name__", "") if isinstance(module, types.ModuleType) else "" - return name == PACKAGE or name.startswith(f"{PACKAGE}.") + return any(name == package or name.startswith(f"{package}.") for package in PACKAGES) + + +def _makes_client(resolved: Any) -> bool: + """Whether calling what a name resolved to makes an `sl.http` client: `sl.http`, `sl.Http`, or a context method + `context_clients` names.""" + return resolved is _CONTEXT_CLIENT or resolved in (_http.http, _http.Http) def _job_method(call: ast.Call, names: _Names) -> str | None: diff --git a/packages/sqlload/python/sqlload/_registry.py b/packages/sqlload-api/python/sqlload_api/_registry.py similarity index 100% rename from packages/sqlload/python/sqlload/_registry.py rename to packages/sqlload-api/python/sqlload_api/_registry.py diff --git a/packages/sqlload/python/sqlload/_transform.py b/packages/sqlload-api/python/sqlload_api/_transform.py similarity index 98% rename from packages/sqlload/python/sqlload/_transform.py rename to packages/sqlload-api/python/sqlload_api/_transform.py index 5f726a681..850d8e020 100644 --- a/packages/sqlload/python/sqlload/_transform.py +++ b/packages/sqlload-api/python/sqlload_api/_transform.py @@ -10,7 +10,7 @@ from datetime import datetime from typing import Any, TypeVar, overload -from sqlload._registry import Registry +from sqlload_api._registry import Registry _Function = TypeVar("_Function", bound=Callable[..., Any]) diff --git a/packages/sqlload-api/python/sqlload_api/_wire/__init__.py b/packages/sqlload-api/python/sqlload_api/_wire/__init__.py new file mode 100644 index 000000000..58c7acaaf --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/__init__.py @@ -0,0 +1,149 @@ +"""The wire every engine reads, pinned: one item of each kind a loader yields, and what each crosses as. + +`CASES` builds each item through an `http` client its caller makes (`make_http(**options)`: SQLLoad's `sl.http(source, +...)`, or a context's `http(...)` in another tool), and `expected(name)` is what it must cross as, as committed here. +Building every case both ways and comparing with `expected` proves the two give the engine the same items; the engine's own +tests parse every expected item. + +Set `SQLLOAD_UPDATE_WIRE=1` when running `sqlload_api`'s tests to rewrite the expected files from the cases. +""" + +import json +from collections.abc import Callable, Mapping +from importlib import resources +from typing import Any + +from sqlload_api import _data +from sqlload_api import _http as sl +from sqlload_api._data import field, key, parent + +#: Builds an `http` client for the cases: `make_http(headers=...)` and `make_http()`. +MakeHttp = Callable[..., sl.Http] + + +def crossed(item: Any) -> Any: + """What `item` crosses into the engine as, parsed: a job's definition, a JSON item's text and read, a checkpoint's state.""" + if hasattr(item, "__sqlload_http_job__"): + return {"job": json.loads(item.__sqlload_http_job__())} + if hasattr(item, "__sqlload_json__"): + data, read = item.__sqlload_json__() + return {"json": {"data": bytes(data).decode(), "read": json.loads(read)}} + if hasattr(item, "__sqlload_checkpoint__"): + return {"checkpoint": json.loads(item.__sqlload_checkpoint__())} + raise TypeError(f"{type(item).__name__} does not cross as a job, JSON data or a checkpoint") + + +def expected(name: str) -> Any: + """What case `name` must cross as.""" + return json.loads(resources.files(__package__).joinpath(f"{name}.json").read_text()) + + +def _paginate_next_link(make_http: MakeHttp) -> Any: + return make_http().paginate("/orders", paginator=sl.next_link("$.next"), select="$.items") + + +def _paginate_link_header(make_http: MakeHttp) -> Any: + api = make_http(headers={"Accept": "application/json"}) + return api.paginate("/orders", paginator=sl.link_header(), select="$", on_status={404: "skip"}) + + +def _paginate_offset(make_http: MakeHttp) -> Any: + paginator = sl.offset("start", limit=100, limit_param="count", read_ahead=4) + return make_http().paginate("/orders", paginator=paginator, params={"status": "open"}, select="$.data") + + +def _paginate_page_number_post(make_http: MakeHttp) -> Any: + paginator = sl.page_number("$.page.number", page_size=50, page_size_param="$.page.size", location="body") + body = {"filter": {"status": "open"}, "page": {}} + return make_http().paginate("/search", paginator=paginator, method="POST", json_body=body, select="$.results") + + +def _paginate_cursor(make_http: MakeHttp) -> Any: + return make_http().paginate("/events", paginator=sl.cursor("$.next_token", "token"), select="$.events") + + +def _paginate_projected(make_http: MakeHttp) -> Any: + fields: Mapping[str, Any] = { + "id": "$.id", + "city": field("$.address.city", required=True), + "updated_at": field("$.updated", parse="epoch_ms", on_error="null"), + "page_total": parent("$.total", levels=2), + } + return make_http().paginate( + "/accounts", + paginator=sl.single(), + select="$.data.items", + fields=fields, + keep_record="raw", + select_missing="empty", + error_path="$.errors", + transform="account_page", + ) + + +def _paginate_cells(make_http: MakeHttp) -> Any: + cells = sl.cells("$.cells", value=["$.value", "$.displayValue"], name=sl.listed("$.columns")) + return make_http().paginate("/sheets/1", paginator=sl.single(), select="$.rows", cells=cells) + + +def _paginate_header_row(make_http: MakeHttp) -> Any: + cells = sl.cells("$.values", value="$", name=sl.header_row()) + return make_http().paginate("/values/A1:Z", paginator=sl.single(), select="$.rows", cells=cells) + + +def _fan_out_values(make_http: MakeHttp) -> Any: + return make_http().fan_out("/regions/{region}/stock", over=["north", "south"], concurrency=2, select="$.items") + + +def _fan_out_nested(make_http: MakeHttp) -> Any: + api = make_http() + orders = api.paginate("/orders", paginator=sl.next_link("$.next"), select="$.items[*].id", key="order_id") + items = api.fan_out("/orders/{order_id}/items", over=orders, select="$.items[*].id", key="item_id") + fields = {"order_id": key("order_id"), "item_id": key("item_id"), "sku": "$.sku"} + return api.fan_out("/orders/{order_id}/items/{item_id}/parts", over=items, select="$.parts", fields=fields) + + +def _fan_out_batch(make_http: MakeHttp) -> Any: + api = make_http() + issues = api.paginate("/issues", paginator=sl.offset(limit=50), select="$.issues[*].id") + return api.fan_out( + "/comments", + over=issues, + method="POST", + json_body={"ids": "{id}"}, + batch=100, + concurrency=4, + select="$.comments", + key_path=parent("$.issueId"), + ) + + +def _json_document(_: MakeHttp) -> Any: + return _data.json('{"data": {"items": [{"id": 1}]}}', path="data.items", fields={"id": "$.id"}, keep_record="raw") + + +def _ndjson_lines(_: MakeHttp) -> Any: + return _data.ndjson(b'{"id": 1}\n{"id": 2}\n', fields={"id": field("$.id", required=True)}) + + +def _checkpoint(_: MakeHttp) -> Any: + return _data.checkpoint({"page": 3, "token": "abc"}) + + +#: Each case's name and how it is built. +CASES: dict[str, Callable[[MakeHttp], Any]] = { + "paginate_next_link": _paginate_next_link, + "paginate_link_header": _paginate_link_header, + "paginate_offset": _paginate_offset, + "paginate_page_number_post": _paginate_page_number_post, + "paginate_cursor": _paginate_cursor, + "paginate_projected": _paginate_projected, + "paginate_cells": _paginate_cells, + "paginate_header_row": _paginate_header_row, + "fan_out_values": _fan_out_values, + "fan_out_nested": _fan_out_nested, + "fan_out_batch": _fan_out_batch, + "json_document": _json_document, + "ndjson_lines": _ndjson_lines, + "checkpoint": _checkpoint, +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/checkpoint.json b/packages/sqlload-api/python/sqlload_api/_wire/checkpoint.json new file mode 100644 index 000000000..2ebfccc34 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/checkpoint.json @@ -0,0 +1,6 @@ +{ + "checkpoint": { + "page": 3, + "token": "abc" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/fan_out_batch.json b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_batch.json new file mode 100644 index 000000000..322215b4c --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_batch.json @@ -0,0 +1,53 @@ +{ + "job": { + "batch": 100, + "client": { + "connection": "shop_api", + "headers": {} + }, + "concurrency": 4, + "fields": null, + "json_body": { + "ids": "{id}" + }, + "keep_record": null, + "key_path": { + "from": { + "kind": "parent", + "levels": 1 + }, + "path": "$.issueId" + }, + "kind": "fan_out", + "method": "POST", + "on_status": {}, + "over": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "offset", + "limit": 50, + "limit_param": "limit", + "location": "query", + "param": "offset" + }, + "params": {}, + "path": "/issues", + "select": "$.issues[*].id" + }, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/comments", + "select": "$.comments" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/fan_out_nested.json b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_nested.json new file mode 100644 index 000000000..9267cbfab --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_nested.json @@ -0,0 +1,85 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "concurrency": 8, + "fields": [ + { + "from": { + "kind": "key", + "name": "order_id" + }, + "name": "order_id", + "path": "$", + "required": false + }, + { + "from": { + "kind": "key", + "name": "item_id" + }, + "name": "item_id", + "path": "$", + "required": false + }, + { + "name": "sku", + "path": "$.sku", + "required": false + } + ], + "json_body": null, + "keep_record": null, + "kind": "fan_out", + "method": "GET", + "on_status": {}, + "over": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "concurrency": 8, + "fields": null, + "json_body": null, + "keep_record": null, + "key": "item_id", + "kind": "fan_out", + "method": "GET", + "on_status": {}, + "over": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "key": "order_id", + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "next_link", + "pointer": "$.next" + }, + "params": {}, + "path": "/orders", + "select": "$.items[*].id" + }, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/orders/{order_id}/items", + "select": "$.items[*].id" + }, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/orders/{order_id}/items/{item_id}/parts", + "select": "$.parts" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/fan_out_values.json b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_values.json new file mode 100644 index 000000000..5f63cc929 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/fan_out_values.json @@ -0,0 +1,28 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "concurrency": 2, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "fan_out", + "method": "GET", + "on_status": {}, + "over": { + "kind": "values", + "values": [ + "north", + "south" + ] + }, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/regions/{region}/stock", + "select": "$.items" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/json_document.json b/packages/sqlload-api/python/sqlload_api/_wire/json_document.json new file mode 100644 index 000000000..e1c84b306 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/json_document.json @@ -0,0 +1,17 @@ +{ + "json": { + "data": "{\"data\": {\"items\": [{\"id\": 1}]}}", + "read": { + "fields": [ + { + "name": "id", + "path": "$.id", + "required": false + } + ], + "keep_record": "raw", + "layout": "document", + "path": "data.items" + } + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/ndjson_lines.json b/packages/sqlload-api/python/sqlload_api/_wire/ndjson_lines.json new file mode 100644 index 000000000..376e819d8 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/ndjson_lines.json @@ -0,0 +1,17 @@ +{ + "json": { + "data": "{\"id\": 1}\n{\"id\": 2}\n", + "read": { + "fields": [ + { + "name": "id", + "path": "$.id", + "required": true + } + ], + "keep_record": null, + "layout": "lines", + "path": null + } + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_cells.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_cells.json new file mode 100644 index 000000000..4f28a15f1 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_cells.json @@ -0,0 +1,34 @@ +{ + "job": { + "cells": { + "name": { + "from": "$.columns", + "id_key": "id", + "key": "columnId", + "kind": "listed", + "name_key": "title" + }, + "pointer": "$.cells", + "value": [ + "$.value", + "$.displayValue" + ] + }, + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/sheets/1", + "select": "$.rows" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_cursor.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_cursor.json new file mode 100644 index 000000000..664e8b34f --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_cursor.json @@ -0,0 +1,23 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "cursor", + "location": "query", + "param": "token", + "pointer": "$.next_token" + }, + "params": {}, + "path": "/events", + "select": "$.events" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_header_row.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_header_row.json new file mode 100644 index 000000000..a60e9e4e9 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_header_row.json @@ -0,0 +1,29 @@ +{ + "job": { + "cells": { + "name": { + "kind": "header_row" + }, + "pointer": "$.values", + "value": [ + "$" + ] + }, + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/values/A1:Z", + "select": "$.rows" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_link_header.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_link_header.json new file mode 100644 index 000000000..94136f9b0 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_link_header.json @@ -0,0 +1,24 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": { + "Accept": "application/json" + } + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": { + "404": "skip" + }, + "paginator": { + "kind": "link_header" + }, + "params": {}, + "path": "/orders", + "select": "$" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_next_link.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_next_link.json new file mode 100644 index 000000000..204707c50 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_next_link.json @@ -0,0 +1,21 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "next_link", + "pointer": "$.next" + }, + "params": {}, + "path": "/orders", + "select": "$.items" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_offset.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_offset.json new file mode 100644 index 000000000..d33ffb9bb --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_offset.json @@ -0,0 +1,27 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": null, + "keep_record": null, + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "offset", + "limit": 100, + "limit_param": "count", + "location": "query", + "param": "start", + "read_ahead": 4 + }, + "params": { + "status": "open" + }, + "path": "/orders", + "select": "$.data" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_page_number_post.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_page_number_post.json new file mode 100644 index 000000000..0693ba691 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_page_number_post.json @@ -0,0 +1,30 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "fields": null, + "json_body": { + "filter": { + "status": "open" + }, + "page": {} + }, + "keep_record": null, + "kind": "paginate", + "method": "POST", + "on_status": {}, + "paginator": { + "kind": "page_number", + "location": "body", + "page_size": 50, + "page_size_param": "$.page.size", + "param": "$.page.number", + "start": 1 + }, + "params": {}, + "path": "/search", + "select": "$.results" + } +} diff --git a/packages/sqlload-api/python/sqlload_api/_wire/paginate_projected.json b/packages/sqlload-api/python/sqlload_api/_wire/paginate_projected.json new file mode 100644 index 000000000..8ae10f311 --- /dev/null +++ b/packages/sqlload-api/python/sqlload_api/_wire/paginate_projected.json @@ -0,0 +1,53 @@ +{ + "job": { + "client": { + "connection": "shop_api", + "headers": {} + }, + "error_path": "$.errors", + "fields": [ + { + "name": "id", + "path": "$.id", + "required": false + }, + { + "name": "city", + "path": "$.address.city", + "required": true + }, + { + "name": "updated_at", + "on_error": "null", + "parse": "epoch_ms", + "path": "$.updated", + "required": false + }, + { + "from": { + "kind": "parent", + "levels": 2 + }, + "name": "page_total", + "path": "$.total", + "required": false + } + ], + "json_body": null, + "keep_record": "raw", + "kind": "paginate", + "method": "GET", + "on_status": {}, + "paginator": { + "kind": "single" + }, + "params": {}, + "path": "/accounts", + "select": "$.data.items", + "select_missing": "empty", + "transform": { + "function": "account_page", + "name": "account_page" + } + } +} diff --git a/packages/sqlload-api/python/sqlload_api/py.typed b/packages/sqlload-api/python/sqlload_api/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/packages/sqlload-api/tests/test_context_clients.py b/packages/sqlload-api/tests/test_context_clients.py new file mode 100644 index 000000000..355142a30 --- /dev/null +++ b/packages/sqlload-api/tests/test_context_clients.py @@ -0,0 +1,51 @@ +"""`literal_paths(..., context_clients=...)` reads the paths of jobs built on a client the function's context makes.""" + +from typing import Any + +import pytest + +import sqlload_api as sl + + +def assigned(ctx: Any) -> Any: + api = ctx.http() + return api.paginate("/orders", paginator=sl.single(), fields={"id": "$.id", "city": sl.field("$.address.city")}) + + +def chained(ctx: Any) -> Any: + return ctx.http(connection="other").fan_out("/orders/{id}", over=[1, 2], key_path="$.orderId", fields={"total": "$.total"}) + + +def other_method(ctx: Any) -> Any: + return ctx.client().paginate("/orders", paginator=sl.single(), fields={"id": "$.id"}) + + +def module_client(ctx: Any) -> Any: + return API.paginate("/orders", paginator=sl.single(), fields={"id": "$.id"}) + + +API = sl.http(connection="shop_api") + + +@pytest.mark.parametrize( + ("function", "context_clients", "expected_paths"), + [ + (assigned, {"http"}, {"fields": [["id", "$.id"], ["city", "$.address.city"]], "key_paths": []}), + (chained, {"http"}, {"fields": [["total", "$.total"]], "key_paths": ["$.orderId"]}), + (assigned, set(), None), + (other_method, {"http"}, None), + (module_client, set(), {"fields": [["id", "$.id"]], "key_paths": []}), + (module_client, {"http"}, {"fields": [["id", "$.id"]], "key_paths": []}), + ], + ids=["assigned", "chained", "hook-off", "unnamed-method", "module-client", "module-client-hook-on"], +) +def test_given_a_context_client_when_reading_literal_paths_then_only_named_context_methods_make_clients( + function: Any, context_clients: set[str], expected_paths: dict[str, Any] | None +) -> None: + found = sl.literal_paths(function, context_clients=context_clients) + paths = None if found is None else {"fields": found["fields"], "key_paths": found["key_paths"]} + assert paths == expected_paths + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/packages/sqlload-api/tests/test_job_wire.py b/packages/sqlload-api/tests/test_job_wire.py new file mode 100644 index 000000000..5ae75a440 --- /dev/null +++ b/packages/sqlload-api/tests/test_job_wire.py @@ -0,0 +1,93 @@ +"""The items `sqlload_api` builds cross as the committed wire, whichever way the connection is given, without the engine.""" + +import json +import os +import subprocess +import sys +from collections.abc import Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import pytest + +import sqlload_api as sl +from sqlload_api import _wire + +WIRE = Path(_wire.__file__).parent + + +@dataclass +class Owner: + """A source as `sl.http` reads one: a name and settings, as SQLLoad's `sl.source(...)` has them.""" + + name: str + settings: Mapping[str, Any] = field(default_factory=dict) + + +def by_name(**options: Any) -> sl.Http: + return sl.http(connection="shop_api", **options) + + +def by_owner(**options: Any) -> sl.Http: + return sl.http(Owner("shop", {"connection": "shop_api"}), **options) + + +@pytest.mark.parametrize("name", sorted(_wire.CASES)) +def test_given_each_case_when_built_by_connection_name_then_it_crosses_as_the_committed_wire(name: str) -> None: + crossed = _wire.crossed(_wire.CASES[name](by_name)) + if os.environ.get("SQLLOAD_UPDATE_WIRE") == "1": + (WIRE / f"{name}.json").write_text(json.dumps(crossed, indent=2, sort_keys=True) + "\n") + assert crossed == _wire.expected(name) + + +@pytest.mark.parametrize("name", sorted(_wire.CASES)) +def test_given_each_case_when_built_from_a_source_then_it_crosses_byte_for_byte_as_by_connection_name(name: str) -> None: + from_owner, from_name = _wire.CASES[name](by_owner), _wire.CASES[name](by_name) + assert _raw(from_owner) == _raw(from_name) + + +def test_given_every_committed_wire_file_when_listing_them_then_each_has_its_case() -> None: + assert sorted(path.stem for path in WIRE.glob("*.json")) == sorted(_wire.CASES) + + +def test_given_a_transform_passed_as_a_function_when_built_either_way_then_both_jobs_cross_alike() -> None: + def page(rows: Any, ctx: Any) -> Any: + return rows + + from_name, from_owner = (make().paginate("/orders", paginator=sl.single(), transform=page) for make in (by_name, by_owner)) + assert from_name.__sqlload_http_job__() == from_owner.__sqlload_http_job__() + assert json.loads(from_name.__sqlload_http_job__())["transform"]["name"].endswith(".page") + + +@pytest.mark.parametrize( + ("make", "expected_message"), + [ + (lambda: sl.http(), "sl.http needs a connection: pass connection=, or a source that sets one"), + (lambda: sl.http(Owner("shop")), "sl.http needs a connection: set connection= on source shop or pass connection="), + (lambda: sl.http(connection="shop_api", auth="x"), "sl.http no longer takes auth: set auth on [connections.shop_api]"), + ], + ids=["no-connection", "source-without-connection", "moved-setting"], +) +def test_given_no_connection_or_a_moved_setting_when_making_a_client_then_it_says_what_to_set(make: Any, expected_message: str) -> None: + with pytest.raises((ValueError, TypeError)) as raised: + make() + assert expected_message in str(raised.value) + + +def test_given_a_fresh_interpreter_when_importing_the_package_then_no_engine_module_loads() -> None: + code = "import sys, sqlload_api; assert not any(name.split('.')[0] == 'sqlload' for name in sys.modules), sorted(sys.modules)" + done = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True) + assert done.returncode == 0, done.stderr + + +def _raw(item: Any) -> Any: + if hasattr(item, "__sqlload_http_job__"): + return item.__sqlload_http_job__() + if hasattr(item, "__sqlload_json__"): + return item.__sqlload_json__() + return item.__sqlload_checkpoint__() + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/packages/sqlload/pyproject.toml b/packages/sqlload/pyproject.toml index 88b7a565d..0c854526c 100644 --- a/packages/sqlload/pyproject.toml +++ b/packages/sqlload/pyproject.toml @@ -18,7 +18,12 @@ classifiers = [ "Topic :: Database", ] # orjson writes gathered dict rows as JSON bytes, which Rust parses without the GIL. -dependencies = ["orjson>=3.10", "tzdata; sys_platform == \"win32\""] +dependencies = [ + # The functions that describe data and requests, in pure Python; released with sqlload at the same version. + "sqlload-api==0.84.0", # x-release-please-version + "orjson>=3.10", + "tzdata; sys_platform == \"win32\"", +] [project.optional-dependencies] # MotherDuck targets and sources: MotherDuck accepts DuckDB 1.4.1 to 1.5.6 (raise the bound as MotherDuck does), not the @@ -51,6 +56,7 @@ include = [{ path = "unixODBC-*.tar.gz", format = "sdist" }] cache-keys = [ { file = "pyproject.toml" }, { file = "python/**/*.py" }, + { file = "../sqlload-api/python/**/*.py" }, { file = "../../Cargo.toml" }, { file = "../../Cargo.lock" }, { file = "../../crates/*/Cargo.toml" }, diff --git a/packages/sqlload/python/sqlload/__init__.py b/packages/sqlload/python/sqlload/__init__.py index f69b3c6e6..d55c747db 100644 --- a/packages/sqlload/python/sqlload/__init__.py +++ b/packages/sqlload/python/sqlload/__init__.py @@ -18,6 +18,9 @@ def orders(ctx: sl.Context): The table loads into `shop__orders` (`{source}__{table}`, or the `table_name` the source or table sets). +The functions that describe data and requests (`sl.http`, `sl.json`, `sl.field`, `sl.checkpoint`, ...) come from the +pure-Python `sqlload_api` package, re-exported here unchanged. + A table function yields dicts, lists of dicts, `sl.json(...)` / `sl.ndjson(...)` bytes, Arrow data (pyarrow, polars, pandas), or `sl.http(...)` jobs that run in Rust; SQLLoad detects which. A `state="logged"` table can yield `sl.checkpoint(position)` between them. @@ -28,8 +31,7 @@ def orders(ctx: sl.Context): import sysconfig from importlib.metadata import version -from sqlload._data import checkpoint, field, json, key, ndjson, parent -from sqlload._http import ( +from sqlload_api import ( CellName, Cells, Http, @@ -45,9 +47,10 @@ def orders(ctx: sl.Context): page_number, single, ) +from sqlload_api import checkpoint, field, json, key, ndjson, parent from sqlload._declare import Context, Source, Table, source, table from sqlload._rename import Column, RenameContext, rename -from sqlload._transform import TransformContext, transform +from sqlload_api import TransformContext, transform __version__: str = version("sqlload") diff --git a/packages/sqlload/python/sqlload/_native.pyi b/packages/sqlload/python/sqlload/_native.pyi index c1561d198..94f2595d2 100644 --- a/packages/sqlload/python/sqlload/_native.pyi +++ b/packages/sqlload/python/sqlload/_native.pyi @@ -30,22 +30,6 @@ def cross( file). """ -class JsonData: - def __new__( - cls, - data: bytes | bytearray, - *, - lines: bool = False, - path: str | None = None, - fields: str | None = None, - keep_record: str | None = None, - ) -> JsonData: ... - @property - def lines(self) -> bool: ... - @property - def path(self) -> str | None: ... - def __len__(self) -> int: ... - class BatchStream(Iterator[Any]): def __iter__(self) -> BatchStream: ... def __next__(self) -> Any: ... diff --git a/packages/sqlload/python/sqlload/_rename.py b/packages/sqlload/python/sqlload/_rename.py index 2cec64d46..86b17b71c 100644 --- a/packages/sqlload/python/sqlload/_rename.py +++ b/packages/sqlload/python/sqlload/_rename.py @@ -9,7 +9,7 @@ from dataclasses import dataclass from typing import Any, TypeVar, overload -from sqlload._registry import Registry +from sqlload_api._registry import Registry _Function = TypeVar("_Function", bound=Callable[..., Any]) diff --git a/packages/sqlload/python/sqlload/_runtime.py b/packages/sqlload/python/sqlload/_runtime.py index cd40d1aa3..6c4da34a9 100644 --- a/packages/sqlload/python/sqlload/_runtime.py +++ b/packages/sqlload/python/sqlload/_runtime.py @@ -20,11 +20,11 @@ from zoneinfo import ZoneInfo from sqlload._declare import Connection, Context, Source, Table -from sqlload._http import Job -from sqlload._data import checkpoint -from sqlload._http_paths import literal_paths from sqlload._rename import RENAMES, Column, RenameContext, renamed -from sqlload._transform import TRANSFORMS, TransformContext, returned_items +from sqlload_api._data import checkpoint +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) diff --git a/packages/sqlload/tests/test_api_wire.py b/packages/sqlload/tests/test_api_wire.py new file mode 100644 index 000000000..5b54213c5 --- /dev/null +++ b/packages/sqlload/tests/test_api_wire.py @@ -0,0 +1,38 @@ +"""`sqlload` re-exports `sqlload_api` unchanged, and a job built from a SQLLoad source crosses as one built by connection name.""" + +from typing import Any + +import pytest +import sqlload_api +from sqlload_api import _wire + +import sqlload as sl + +SHOP = sl.source("shop", connection="shop_api", write_strategy="replace") + + +def from_source(**options: Any) -> sqlload_api.Http: + return sl.http(SHOP, **options) + + +def by_name(**options: Any) -> sqlload_api.Http: + return sqlload_api.http(connection="shop_api", **options) + + +@pytest.mark.parametrize("name", sorted(_wire.CASES)) +def test_given_each_case_when_built_from_a_sqlload_source_then_it_crosses_as_the_committed_wire_and_as_by_name(name: str) -> None: + from_sqlload, from_api = _wire.CASES[name](from_source), _wire.CASES[name](by_name) + assert _wire.crossed(from_sqlload) == _wire.expected(name) + assert _wire.crossed(from_sqlload) == _wire.crossed(from_api) + + +@pytest.mark.parametrize( + "name", + [name for name in sl.__all__ if name in sqlload_api.__all__ and name != "__version__"], +) +def test_given_a_name_sqlload_re_exports_when_compared_then_it_is_sqlload_apis_own(name: str) -> None: + assert getattr(sl, name) is getattr(sqlload_api, name) + + +def test_given_both_packages_when_comparing_versions_then_they_match() -> None: + assert sl.__version__ == sqlload_api.__version__ diff --git a/packages/sqlload/tests/test_crossing.py b/packages/sqlload/tests/test_crossing.py index c9bb964c8..358336dcd 100644 --- a/packages/sqlload/tests/test_crossing.py +++ b/packages/sqlload/tests/test_crossing.py @@ -18,6 +18,7 @@ import sqlload as sl from sqlload import _native +from sqlload_api import JsonData CROSSINGS = ["walk", "serialise"] TEXT = string.ascii_letters + " \"\\\n\t/é😀" @@ -199,7 +200,7 @@ def test_given_json_data_when_constructed_then_ndjson_takes_no_path() -> None: assert sl.json("[]", path="items").path == "items" assert sl.ndjson(memoryview(b"{}")).lines with pytest.raises(ValueError, match="NDJSON"): - _native.JsonData(b"", lines=True, path="items") + JsonData(b"", lines=True, path="items") def test_given_polars_and_pandas_frames_when_crossed_then_they_match_pyarrow() -> None: @@ -422,20 +423,32 @@ def test_given_fields_when_json_and_ndjson_cross_then_only_those_values_load_ren @pytest.mark.parametrize( ("make", "expected_text"), [ - (lambda: sl.json(b"[]", fields={"id": "id"}), 'field path "id" is not a path'), (lambda: sl.ndjson(b"", keep_record="raw"), "keep_record needs fields"), (lambda: sl.json(b"[]", fields={"id": 1}), "takes a path such as"), (lambda: sl.json(b"[]", fields={1: "$.id"}), "names columns with text"), (lambda: sl.json(b"[]", fields={"id": sl.field("$.id", required="yes")}), "required takes True or False"), (lambda: sl.json(b"[]", fields=[("id", "$.id")]), "fields takes a mapping"), ], - ids=["path-without-root", "keep-record-alone", "path-not-text", "name-not-text", "required-not-bool", "fields-not-a-mapping"], + ids=["keep-record-alone", "path-not-text", "name-not-text", "required-not-bool", "fields-not-a-mapping"], ) def test_given_bad_fields_when_building_json_data_then_it_fails_at_once(make: Any, expected_text: str) -> None: with pytest.raises((ValueError, TypeError), match=expected_text): make() +@pytest.mark.parametrize( + ("item", "expected_text"), + [ + (sl.json(b"[]", fields={"id": "id"}), 'field path "id" is not a path'), + (sl.ndjson(b"{}", fields={"items": "$.items[*]"}), "uses the wildcard"), + ], + ids=["path-without-root", "wildcard"], +) +def test_given_a_field_path_the_engine_refuses_when_its_json_data_crosses_then_the_read_fails_naming_it(item: Any, expected_text: str) -> None: + with pytest.raises(ValueError, match=expected_text): + read(iter([item])) + + def test_given_a_required_field_when_a_row_lacks_it_then_the_read_fails_naming_the_row() -> None: with pytest.raises(ValueError, match="row 2: field id needs a value at \\$.id"): read(iter([sl.ndjson(b'{"id":1}\n{"other":2}', fields={"id": sl.field("$.id", required=True)})])) diff --git a/packages/sqlload/tests/test_transforms.py b/packages/sqlload/tests/test_transforms.py index d3f907e6a..1d0a43d8c 100644 --- a/packages/sqlload/tests/test_transforms.py +++ b/packages/sqlload/tests/test_transforms.py @@ -542,7 +542,7 @@ def test_a_sheets_range_goes_through_its_transform_into_tidy_rows(tmp_path: Path def test_a_function_passed_as_transform_resolves_to_itself_when_two_files_register_its_name(tmp_path: Path) -> None: - from sqlload._registry import Registry + from sqlload_api._registry import Registry registry = Registry("@sl.transform") modules = [] @@ -563,7 +563,7 @@ def test_a_function_passed_as_transform_resolves_to_itself_when_two_files_regist def test_a_function_passed_as_transform_is_released_when_the_run_finishes() -> None: from sqlload._runtime import finish_run - from sqlload._transform import TRANSFORMS + from sqlload_api._transform import TRANSFORMS def page_transform() -> Any: return lambda rows, ctx: rows @@ -581,7 +581,7 @@ def page_transform() -> Any: def test_a_transform_whose_file_cant_be_read_is_versioned_by_its_code() -> None: from sqlload._runtime import transform_version - from sqlload._transform import TRANSFORMS + from sqlload_api._transform import TRANSFORMS def version_of(body: str) -> str | None: namespace: dict[str, Any] = {} diff --git a/release-please-config.json b/release-please-config.json index 67c7914b4..905db01cf 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -19,7 +19,8 @@ "extra-files": [ { "type": "generic", "path": "Cargo.toml" }, { "type": "generic", "path": "packages/sqlload/pyproject.toml" }, - { "type": "generic", "path": "packages/sqlload-cli/pyproject.toml" } + { "type": "generic", "path": "packages/sqlload-cli/pyproject.toml" }, + { "type": "generic", "path": "packages/sqlload-api/pyproject.toml" } ] } } diff --git a/website/src/content/docs/docs/guides/caller-connections.mdx b/website/src/content/docs/docs/guides/caller-connections.mdx new file mode 100644 index 000000000..987e1e082 --- /dev/null +++ b/website/src/content/docs/docs/guides/caller-connections.mdx @@ -0,0 +1,78 @@ +--- +title: "Loading through your own connection" +description: "Embed the sqlload Rust library and load into a warehouse through a connection your program already holds, with SQLLoad planning and rendering every statement." +--- + +A program that embeds the `sqlload` crate can load into a warehouse through a connection it +already holds, instead of one SQLLoad opens from `[connections]`. SQLLoad still plans the load, +renders every statement in the warehouse's SQL and decides every write. Your program runs those +statements on its own connection, with its own credentials, and takes the rows in the files SQLLoad +writes. + +No project file can name such a connection. Your program attaches it by name when it parses the +project, and targets use that name as any other connection: + +```rust +use std::collections::BTreeMap; +use sqlload::adapters::session::models::SessionConnection; +use sqlload::column_types::models::Warehouse; +use sqlload::project::main::parse_python_project::parse_python_project; + +let sessions = BTreeMap::from([( + "warehouse".to_owned(), + SessionConnection { + warehouse: Warehouse::Snowflake, + motherduck: false, + database: Some("ANALYTICS".to_owned()), + caller: my_connection, // an Arc + }, +)]); +let project = parse_python_project(&text, &lookup, (&[], sessions))?; +``` + +```toml +[targets.dev] +connection = "warehouse" # attached by the program +loader_schema = "RAW" +``` + +`connect_targets`, `plan_project`, `apply_project` and `load_tables` then work as for any target. +Run them on threads with 8 MiB of stack, the workers of a Tokio runtime built with +`thread_stack_size(8 * 1024 * 1024)` and the thread that blocks on the load: a debug build's load +goes deeper than Tokio's 2 MiB default. + +## What your connection does + +`CallerConnection::open` returns a session for SQLLoad alone. SQLLoad opens one per table it +loads, holding that table's temporary tables and transactions, and drops it when the table is +done. A session must: + +- run each statement in autocommit; SQLLoad sends `BEGIN`, `COMMIT` and `ROLLBACK` itself, and + rolls back when a statement inside a transaction fails, a failed `COMMIT` included. A Snowflake + session with autocommit off is refused when it opens; +- have the database tables load into as its current database (DuckDB); +- allow SQLLoad to set session parameters (a Snowflake session runs in UTC, as SQLLoad's own do), + so it must not be one your program uses for other work at the same time. + +How rows reach the warehouse depends on the warehouse: + +| Warehouse | Rows go in as | +|-----------|---------------| +| DuckDB, MotherDuck | Parquet files on this machine, read with `read_parquet` | +| Snowflake | Parquet files `PUT` on the user stage (`@~/sqlload/...`), then `COPY INTO`, then `REMOVE` | +| Postgres | A binary `COPY ... FROM STDIN`, through `CallerSession::copy_in` | +| BigQuery, ClickHouse, Databricks | Parquet files your session loads with its own client, through `CallerSession::load_parquet` | + +A session reports a failure as a `SessionError`: `transient` when a rerun may pass, and +`not_found` when what a query names doesn't exist, such as a BigQuery dataset before its first load. + +## What changes + +Every write strategy, staging table and swap, schema change, `on_schema_change`, check and +cursor works as it does on SQLLoad's own connection. A few routes need SQLLoad's own connection +and are not taken: + +- The warehouse never reads a files source's files itself through your connection: SQLLoad reads + them and sends the rows. +- Rows are not streamed into Snowflake without files. +- A DuckDB target has no memory budget from SQLLoad; your connection's settings apply. diff --git a/website/src/content/docs/docs/sources/python.mdx b/website/src/content/docs/docs/sources/python.mdx index 3cdbcb45d..dfdf21b8a 100644 --- a/website/src/content/docs/docs/sources/python.mdx +++ b/website/src/content/docs/docs/sources/python.mdx @@ -342,7 +342,7 @@ thread-safe. Set `parallel_tables=True` on the source when its client is. | Function | Meaning | |----------|---------| -| `sl.http(source, *, headers=None, connection=None)` | Requests to the source's `http` connection, or to `connection`, adding `headers` to the connection's. How requests authenticate, their `rate_limit` and `max_in_flight`, and their `retries` are set on the [connection](/docs/configuration/#http); passing `auth`, `rate_limit`, `max_in_flight` or `retries` to `sl.http` fails, naming the connection key to set. | +| `sl.http(source=None, *, headers=None, connection=None)` | Requests to the source's `http` connection, or to `connection` (all it needs without a source), adding `headers` to the connection's. How requests authenticate, their `rate_limit` and `max_in_flight`, and their `retries` are set on the [connection](/docs/configuration/#http); passing `auth`, `rate_limit`, `max_in_flight` or `retries` to `sl.http` fails, naming the connection key to set. | | `api.paginate(path, *, paginator, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, select_missing="fail", error_path=None, transform=None)` | Every page of `path`. `select` is where the rows are: `$`, or a dotted path such as `$.data.items`. A response without the `select` path fails the load, naming what the response holds; `select_missing="empty"` reads it as no rows instead. See [A missing select path](#a-missing-select-path). `error_path` is where the API reports an error in a successful response; see [Errors in a successful response](#errors-in-a-successful-response). `fields` and `keep_record` pick and rename each row's values; see [Fields](#fields). For `method` and `json_body`, see [POST with a JSON body](#post-with-a-json-body). `cells=` turns each row's list of cells into columns; see [Rows of cells](#rows-of-cells). `transform` reshapes each page's rows in Python before they load; see [Transforming each page](#transforming-each-page). | | `api.fan_out(path, *, over, concurrency=8, paginator=None, params=None, select=None, on_status=None, fields=None, keep_record=None, method="GET", json_body=None, key=None, cells=None, batch=None, select_missing="fail", error_path=None, transform=None)` | `path` once per key of `over`, up to `concurrency` at a time, while keys still arrive. `select_missing` and `error_path` are as for `paginate`. `over` is a paginate whose `select` picks keys (`$.items[*].id` fills `{id}`), or a list: a value fills the path's one placeholder, and a dict fills placeholders by name. `over` can also be another `fan_out`; see [Multi-level fan-out](#multi-level-fan-out). `method` and `json_body` are as for `paginate`. Keys also fill `{placeholders}` in `json_body`, and `batch` sends several keys per request; see [Keys in a POST body](#keys-in-a-post-body). `transform` is as for `paginate`, called once per page of each key. | @@ -816,3 +816,22 @@ To inspect or correct a logged position, see [`sqlload logged-state`](/docs/cli/ | `@sl.transform`, `@sl.transform("name")` | Registers a function under its own name, or the one given, as a transform for a [files](/docs/sources/files/#transforming-each-file) or [Google Sheets](/docs/sources/google-sheets/#transforming-each-range) table's `transform = "name"`, or an `sl.http` job's [`transform=`](#transforming-each-page). Returns the function unchanged. | | `@sl.rename`, `@sl.rename("name")` | Registers a function under its own name, or the one given, for a table's `rename`. It gets the columns as `sl.Column`s (`position`, `source`, `default`) and an `sl.RenameContext` (`source`, `table`), and returns the names it changes by position. See [rename](/docs/concepts/nested-data/#rename). | | `sl.TransformContext` | The `ctx` a transform gets: `unit` (`"file"`, `"range"` or `"page"`), `table`, and the unit's details. | + +## Without the engine + +`sl.http` and its paginators, `sl.json`, `sl.ndjson`, `sl.field`, `sl.parent`, `sl.key`, `sl.checkpoint` and +`@sl.transform` come from [`sqlload-api`](https://pypi.org/project/sqlload-api/), a pure-Python package `sqlload` depends +on and re-exports: `sl.http` is `sqlload_api.http`. It holds no compiled code, so a tool that runs SQLLoad's engine in its +own process can build the same items without loading a second one, naming the connection instead of a source: + +```python +import sqlload_api + +api = sqlload_api.http(connection="shop_api") +orders = api.paginate("/orders", paginator=sqlload_api.next_link("$.next"), select="$.items") +``` + +A job built this way is the same, byte for byte, as one built with `sl.http(source)` from a source whose connection is +`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. diff --git a/website/src/sidebar.json b/website/src/sidebar.json index ce78762c9..171b8709e 100644 --- a/website/src/sidebar.json +++ b/website/src/sidebar.json @@ -18,6 +18,7 @@ "docs/guides/python", "docs/guides/reload-a-window", "docs/guides/orchestrators", + "docs/guides/caller-connections", "docs/guides/from-dlt" ] },