From d8c40046d7d4b7d2100a7e65c9bf765d5f264645 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:29:46 +0000 Subject: [PATCH 1/2] feat!: a bounded loader run loads its window in the cursor's type, or fails --start-cursor/--end-cursor on a loader SQLLoad runs reached it as a timestamp whatever the loader's cursor type. For a DATE cursor SQLLoad blocked the table, and SQLBuild read the run as a success with no rows, so `OK rows=0` and nothing loaded. - A loader's window now reaches SQLLoad in the type its source declares for the cursor column, which SQLLoad checks against that column: dates for a DATE cursor, and timestamps, integers or numbers for those cursors, so a DECIMAL cursor's window loads too. - A bound that doesn't fit a date, timestamp or integer cursor (a time of day for a DATE cursor, integers for a timestamp cursor, timestamps for an integer cursor), or any bound on a text cursor, fails the run before anything loads, naming the loader and its cursor type. - A table SQLLoad plans but doesn't load, such as one it blocks, fails with SQLLoad's reason, naming the table. This applies to `load:` projects as well as loaders. BREAKING CHANGE: a load whose table SQLLoad blocked used to report success with zero rows and now fails with the reason, and window bounds that don't fit a loader's declared cursor type now fail the run before it loads. To upgrade, give --start-cursor/--end-cursor in the cursor's type (dates for a DATE cursor) and fix what the reported reason names. --- .../src/bindings/_helpers/loader_binding.rs | 4 +- .../src/runs/_helpers/tables.rs | 39 ++- .../src/runs/constants.rs | 3 + .../src/runs/main/run_project.rs | 5 +- .../sqlbuild/references/docs/cli/load.md | 8 +- .../docs/concepts/python-nodes/loaders.md | 43 ++- src/sqlbuild/executor/build/main/_execute.py | 7 +- .../executor/load/_helpers/engine_runs.py | 28 +- .../executor/load/_helpers/loader_windows.py | 92 +++++++ .../load/classes/engine_loader_run.py | 10 +- src/sqlbuild/executor/load/constants.py | 9 + .../executor/load/main/_cursor_window.py | 43 ++- src/sqlbuild/executor/load/models.py | 17 +- src/sqlbuild/executor/load/types.py | 7 + .../_helpers/ingress_execution.py | 9 +- .../cli/commands/main/load/_test_types.py | 29 ++ .../cli/commands/main/load/helpers.py | 97 +++++++ .../main/load/test_loader_cursor_bounds.py | 254 ++++++++++++++++++ .../cli/commands/main/postgres/_test_types.py | 11 + .../postgres/test_loader_cursor_bounds.py | 106 ++++++++ website/src/content/docs/docs/cli/load.mdx | 8 +- .../docs/concepts/python-nodes/loaders.mdx | 43 ++- 22 files changed, 811 insertions(+), 61 deletions(-) create mode 100644 src/sqlbuild/executor/load/_helpers/loader_windows.py create mode 100644 src/sqlbuild/executor/load/types.py create mode 100644 tests/e2e/src/sqlbuild/cli/commands/main/load/test_loader_cursor_bounds.py create mode 100644 tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_loader_cursor_bounds.py diff --git a/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs b/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs index 058470342f..0c9ee3683e 100644 --- a/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs +++ b/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs @@ -13,7 +13,7 @@ use crate::bindings::_helpers::run_binding::{run_report, session_connections}; use crate::runs::main::run_project::run_project; use crate::runs::models::LoaderHost; -/// Load `loader` (an `EngineLoaderRun`: its project text, Python source, reload and cursor window) through `sessions`; the report `run_sqlload_project` gives. +/// Load `loader` (an `EngineLoaderRun`: its project text, Python source, reload and cursor window, typed by family or in the cursor's own type) through `sessions`; the report `run_sqlload_project` gives. #[pyfunction] #[pyo3(signature = (*, loader, sessions))] pub(crate) fn run_sqlload_loader( @@ -27,6 +27,8 @@ pub(crate) fn run_sqlload_loader( })?; let options = PlanOptions { reload: loader.getattr("reload")?.extract()?, + start_cursor: text("start_cursor")?, + end_cursor: text("end_cursor")?, typed_cursors: TypedCursors { start_ts: text("start_cursor_ts")?, end_ts: text("end_cursor_ts")?, diff --git a/crates/sqlbuild-python-load/src/runs/_helpers/tables.rs b/crates/sqlbuild-python-load/src/runs/_helpers/tables.rs index 1a698e9f8b..9ccc78bf57 100644 --- a/crates/sqlbuild-python-load/src/runs/_helpers/tables.rs +++ b/crates/sqlbuild-python-load/src/runs/_helpers/tables.rs @@ -1,10 +1,11 @@ //! Which required destination tables a plan leaves out, and the plan lines SQLBuild shows. use sqlbuild_load::loads::main::load_message::load_message; -use sqlload::loader::models::ProjectPlan; +use sqlload::loader::models::{ProjectPlan, TablePlan}; use sqlload::project::models::ProjectConfig; -use crate::runs::constants::{PLAN_SUMMARY_MARKS, SQLLOAD_COMMAND}; +use crate::runs::constants::{NO_OUTCOME, PLAN_SUMMARY_MARKS, SQLLOAD_COMMAND}; +use crate::runs::models::LoadedTable; /// The destination table of every table `plan` loads or leaves as it is, in plan order. pub(crate) fn planned_tables(plan: &ProjectPlan) -> Vec { @@ -22,6 +23,40 @@ pub(crate) fn planned_tables(plan: &ProjectPlan) -> Vec { .collect() } +/// A failure for each table `plan` loads that `loaded` holds no outcome for: a blocked table with why SQLLoad blocked it, so a load that never ran is never a success. +pub(crate) fn unloaded_tables( + project: &ProjectConfig, + plan: &ProjectPlan, + loaded: &[LoadedTable], +) -> Vec { + plan.tables + .iter() + .filter(|table| !has_outcome(loaded, table)) + .map(|table| { + let reasons: Vec = match &table.schema.blocked { + Some(blocked) => blocked.reasons.clone(), + None => vec![NO_OUTCOME.to_owned()], + }; + LoadedTable { + table: table.outcome_name(), + loaded: Err(format!( + "{}: {}", + table.outcome_name(), + load_messages(project, reasons).join("; ") + )), + changes: Vec::new(), + warnings: Vec::new(), + retryable: false, + } + }) + .collect() +} + +fn has_outcome(loaded: &[LoadedTable], table: &TablePlan) -> bool { + let name: String = table.outcome_name(); + loaded.iter().any(|done| done.table == name) +} + /// The names in `required` that `planned` doesn't hold, in `required`'s order. pub(crate) fn missing_tables(required: &[String], planned: &[String]) -> Vec { required diff --git a/crates/sqlbuild-python-load/src/runs/constants.rs b/crates/sqlbuild-python-load/src/runs/constants.rs index d1cbf4a8af..dabf39977e 100644 --- a/crates/sqlbuild-python-load/src/runs/constants.rs +++ b/crates/sqlbuild-python-load/src/runs/constants.rs @@ -9,3 +9,6 @@ pub(crate) const SQLLOAD_COMMAND: &str = " sqlload "; /// What a loader's host answers for `rename`: a loader names its columns on the source it fills. pub(crate) const RENAME_PROBLEM: &str = "a @loader takes no rename function; name its columns on the source it fills"; +/// Why a table SQLLoad planned and left unblocked fails when its load reports no outcome. +pub(crate) const NO_OUTCOME: &str = + "SQLLoad planned this table but reported no outcome for it, so nothing was loaded"; diff --git a/crates/sqlbuild-python-load/src/runs/main/run_project.rs b/crates/sqlbuild-python-load/src/runs/main/run_project.rs index 3a11641aaa..83fd12c157 100644 --- a/crates/sqlbuild-python-load/src/runs/main/run_project.rs +++ b/crates/sqlbuild-python-load/src/runs/main/run_project.rs @@ -15,7 +15,9 @@ use std::sync::Arc; use sqlload::python_sources::types::PythonHost; use crate::runs::_helpers::stack::on_load_stack; -use crate::runs::_helpers::tables::{load_messages, missing_tables, planned_tables}; +use crate::runs::_helpers::tables::{ + load_messages, missing_tables, planned_tables, unloaded_tables, +}; use crate::runs::models::{LoadedTable, ProjectRun}; /// Each selected table's load of the project `text` with the `python` sources `host` runs; nothing loads when the plan lacks a `required` table. @@ -73,6 +75,7 @@ pub fn run_project( retryable: outcome.retryable, }); } + tables.extend(unloaded_tables(&project, &plan, &tables)); Ok(ProjectRun { tables, planned, diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/load.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/load.md index 69389b3a23..8488e3f787 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/load.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/load.md @@ -35,8 +35,8 @@ sqb --project-dir load [flags] | `--exclude` | Selectors to leave out | | `--reload` | Reload managed sources from scratch: each table is rebuilt from what its loader returns, with `ctx.is_reload` `True` and `ctx.cursor_value` `None` | | `--concurrency` | Number of worker connections (default: from settings or 1) | -| `--start-cursor` | Where loaders' cursor windows start, as `ctx.cursor_value`: an integer, or an ISO timestamp. Every selected loader needs a `cursor_column`; otherwise the run fails before loading, naming the loader | -| `--end-cursor` | Where they end, not included, as `ctx.cursor_end`; typed the same way as `--start-cursor` | +| `--start-cursor` | Where loaders' cursor windows start, included, as `ctx.cursor_value`: a date, an ISO timestamp or an integer, in the [cursor column's type](../concepts/python-nodes/loaders.md#loading-a-chosen-window). Every selected loader needs a `cursor_column`; otherwise the run fails before loading, naming the loader | +| `--end-cursor` | Where they end, not included, as `ctx.cursor_end`; given the same way as `--start-cursor` | | `--start-cursor-ts`, `--end-cursor-ts` | The window's bounds as ISO timestamps | | `--start-cursor-int`, `--end-cursor-int` | The window's bounds as integers | | `--json` | Output results as JSON | @@ -65,8 +65,8 @@ sqb load --select load:shop # Reload all sources (full refresh behavior) sqb load --reload -# Override cursor bounds -sqb load --start-cursor "2026-05-01T00:00:00" +# Load one week of a loader with a DATE cursor +sqb load --select raw_daily_sales --start-cursor 2026-05-01 --end-cursor 2026-05-08 ``` ## Selection diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md index 1deae49226..725df7a16e 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md @@ -235,11 +235,9 @@ def raw_order_events(ctx): ``` `ctx.cursor_value` is the current `MAX(cursor_column)` of the target, or `None` on the first load, -so the loader fetches only new or updated data. `--start-cursor` and `--end-cursor` on -[`sqb load`](../../cli/load.md) and `sqb build` set the window instead; every loader the run loads -then needs a `cursor_column`, and one without fails the run before anything loads. A row outside the window fails -the load, so a loader fetches only what the window covers. The source it fills declares its columns -as any managed source does: +so the loader fetches only new or updated data. A row outside the window fails the load, so a +loader fetches only what the window covers. The source it fills declares its columns as any +managed source does: ```yaml sources: @@ -283,6 +281,41 @@ def raw_payments(ctx): ctx.state = page.next_sync_token ``` +### Loading a chosen window + +`--start-cursor` and `--end-cursor` on [`sqb load`](../../cli/load.md) and `sqb build` set a +loader's window instead of the target's maximum. The loader reads from `--start-cursor`, included, +up to `--end-cursor`, not included; with `delete_insert`, those rows replace the window's rows in +the target: + +```bash +sqb load --select raw_daily_sales --start-cursor 2026-05-01 --end-cursor 2026-05-08 +``` + +A loader with a `write_strategy` gets the bounds as `ctx.cursor_value` and `ctx.cursor_end`, in +the type the source declares for the cursor column: + +| Cursor column type | Give the bounds as | `ctx.cursor_value` is | +|--------------------|--------------------|-----------------------| +| `DATE` | Dates, such as `2026-05-01` | `datetime.date` | +| Timestamp | ISO timestamps, such as `2026-05-01T06:00:00` | `datetime.datetime` | +| Integer | Integers, such as `1500` | `int` | + +Details: + +- Every loader the run loads needs a `cursor_column`; one without fails the run before anything + loads, naming the loader. +- A bound that doesn't fit one of these cursor types, such as a time of day for a `DATE` cursor, + fails the run before anything loads, naming the loader and its cursor type. So does a text + cursor, whose values would compare as text. +- A cursor of another declared type, such as `DECIMAL`, takes the bounds in that type. +- When the source doesn't declare the cursor column's type, the bounds arrive as timestamps or + integers, and the loaded table's column decides whether they fit. Declare the type so a `DATE` + cursor takes dates. +- A [self-managed loader](#self-managed-loaders) gets the bounds as timestamps or integers. +- When SQLLoad can't load a table, such as for a bound that doesn't fit its column, the loader + fails with the reason and names the table. + ## Loading from an HTTP API A loader that names an `http` [source connection](../project-configuration.md#warehouse-and-source-connections) with diff --git a/src/sqlbuild/executor/build/main/_execute.py b/src/sqlbuild/executor/build/main/_execute.py index 5092d1dff0..6f1fef8fec 100644 --- a/src/sqlbuild/executor/build/main/_execute.py +++ b/src/sqlbuild/executor/build/main/_execute.py @@ -39,7 +39,7 @@ from sqlbuild.executor.dynamic_pauses.main.hold_dynamic_models import ( hold_dynamic_models, ) -from sqlbuild.executor.load.main._cursor_window import refuse_loaders_without_cursor +from sqlbuild.executor.load.main._cursor_window import refuse_unusable_windows from sqlbuild.executor.load.models import LoadExecutionResult from sqlbuild.executor.migrations.main._apply import apply_model_migrations from sqlbuild.executor.migrations.main._apply_columns import apply_column_migrations @@ -65,9 +65,9 @@ def execute_build_plan( loaded_sources: list[SourceEntry] = [ plan.source_map[entry.key.name] for entry in plan.source_load_entries ] - _ = refuse_loaders_without_cursor( + _ = refuse_unusable_windows( loaders=( - (source.loader, source.cursor_column) + (source.loader, source.cursor_column, source) for source in loaded_sources if source.loader is not None ), @@ -77,6 +77,7 @@ def execute_build_plan( runtime.start_cursor_int, runtime.end_cursor_int, ), + dialect=adapter.adapter_name, ) hold: DynamicHold | None = hold_dynamic_models( plan=plan, adapter=adapter, runtime=runtime, connection_config=connection_config diff --git a/src/sqlbuild/executor/load/_helpers/engine_runs.py b/src/sqlbuild/executor/load/_helpers/engine_runs.py index bd4cf988f1..883e714584 100644 --- a/src/sqlbuild/executor/load/_helpers/engine_runs.py +++ b/src/sqlbuild/executor/load/_helpers/engine_runs.py @@ -5,7 +5,6 @@ import json import time from collections.abc import Callable, Mapping -from datetime import datetime from itertools import chain from typing import Any, cast @@ -13,6 +12,7 @@ from sqlbuild._native import DiscoveredLoaderFunction, SourceEntry from sqlbuild.executor.load._helpers.execution import load_resource_kind +from sqlbuild.executor.load._helpers.loader_windows import declared_cursor_type, loader_window from sqlbuild.executor.load.classes.engine_loader_run import EngineLoaderRun from sqlbuild.executor.load.classes.loader_context import LoaderContext from sqlbuild.executor.load.constants import ( @@ -23,6 +23,7 @@ ) from sqlbuild.executor.load.models import ( EngineLoaderInputs, + LoaderCursorWindow, LoaderRunState, LoadExecutionResult, LoadRuntimeParams, @@ -62,6 +63,20 @@ def started(read: Mapping[str, Any]) -> tuple[Context, object]: function=loader_function.function, context=context, providers=runtime.providers ) + window: LoaderCursorWindow = loader_window( + loader=loader_function.name, + cursor=( + loader_function.cursor_column, + declared_cursor_type(source=source_entry, cursor_column=loader_function.cursor_column), + ), + window=( + runtime.start_cursor_ts, + runtime.end_cursor_ts, + runtime.start_cursor_int, + runtime.end_cursor_int, + ), + dialect=sqlbuild.adapter.adapter_name, + ) return EngineLoaderRun( inputs=EngineLoaderInputs( name=loader_function.name, @@ -74,10 +89,7 @@ def started(read: Mapping[str, Any]) -> tuple[Context, object]: ) ), reload=runtime.is_reload, - start_cursor_ts=_cursor_text(runtime.start_cursor_ts), - end_cursor_ts=_cursor_text(runtime.end_cursor_ts), - start_cursor_int=_cursor_text(runtime.start_cursor_int), - end_cursor_int=_cursor_text(runtime.end_cursor_int), + window=window, ), start=started, ) @@ -142,9 +154,3 @@ def _run_source( settings["tables"][name].setdefault("write_strategy", INTERMEDIATE_WRITE_STRATEGY) paths: dict[str, Any] | None = literal_paths(callable_, context_clients=HTTP_CONTEXT_CLIENTS) return {**declared, "http_paths": {} if paths is None else {name: paths}} - - -def _cursor_text(value: datetime | int | None) -> str | None: - if value is None: - return None - return value.isoformat() if isinstance(value, datetime) else str(value) diff --git a/src/sqlbuild/executor/load/_helpers/loader_windows.py b/src/sqlbuild/executor/load/_helpers/loader_windows.py new file mode 100644 index 0000000000..48c002cb6e --- /dev/null +++ b/src/sqlbuild/executor/load/_helpers/loader_windows.py @@ -0,0 +1,92 @@ +"""One loader's cursor window in its cursor's type, as SQLLoad takes it.""" + +from __future__ import annotations + +from datetime import UTC, datetime, time + +from sqlbuild._native import SourceEntry +from sqlbuild.adapter.contract.types import TypeFamily +from sqlbuild.adapter.type_system.main.normalize_type import normalize_type +from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.load.constants import CURSOR_WINDOW_HELP, TIME_CURSOR_FAMILIES +from sqlbuild.executor.load.models import LoaderCursorWindow +from sqlbuild.executor.load.types import CursorWindow + + +def declared_cursor_type(*, source: SourceEntry | None, cursor_column: str | None) -> str | None: + """The type `source` declares for `cursor_column`, if it declares one.""" + + if source is None or cursor_column is None: + return None + return next( + ( + column.type + for column in source.columns + if column.name.casefold() == cursor_column.casefold() + ), + None, + ) + + +def loader_window( + *, + loader: str, + cursor: tuple[str | None, str | None], + window: CursorWindow, + dialect: str, +) -> LoaderCursorWindow: + """`window` for `loader`'s `cursor` (column, declared type): typed by family if undeclared.""" + + start_ts, end_ts, start_int, end_int = window + column, cursor_type = cursor + if cursor_type is None or all(value is None for value in window): + return LoaderCursorWindow( + start_ts=_text(start_ts), + end_ts=_text(end_ts), + start_int=_text(start_int), + end_int=_text(end_int), + ) + family: TypeFamily = normalize_type(type_sql=cursor_type, dialect=dialect).family + named: str = f"loader '{loader}' has cursor {column} of type {cursor_type}" + integers: bool = start_int is not None or end_int is not None + if family == TypeFamily.STRING: + raise ExecutorInputError( + f"{named}, which --start-cursor/--end-cursor can't bound: its values compare as text", + help="leave its source out with --exclude", + ) + if family == TypeFamily.INTEGER and not integers: + raise ExecutorInputError( + f"{named}, but --start-cursor/--end-cursor are timestamps", help=CURSOR_WINDOW_HELP + ) + if family in TIME_CURSOR_FAMILIES and start_ts is None and end_ts is None: + raise ExecutorInputError( + f"{named}, but --start-cursor/--end-cursor are integers", help=CURSOR_WINDOW_HELP + ) + if family == TypeFamily.DATE: + return LoaderCursorWindow( + start=_date_text(named=named, flag="--start-cursor", value=start_ts), + end=_date_text(named=named, flag="--end-cursor", value=end_ts), + ) + if family in TIME_CURSOR_FAMILIES or not integers: + return LoaderCursorWindow(start=_text(start_ts), end=_text(end_ts)) + return LoaderCursorWindow(start=_text(start_int), end=_text(end_int)) + + +def _date_text(*, named: str, flag: str, value: datetime | None) -> str | None: + """`value` as a date, when it is midnight UTC.""" + + if value is None: + return None + utc: datetime = value if value.tzinfo is None else value.astimezone(UTC) + if utc.time() != time(0): + raise ExecutorInputError( + f"{named}, but {flag} {value.isoformat()} has a time of day", + help=f"give a date, such as {utc.date().isoformat()}", + ) + return utc.date().isoformat() + + +def _text(value: datetime | int | None) -> str | None: + if value is None: + return None + return value.isoformat() if isinstance(value, datetime) else str(value) diff --git a/src/sqlbuild/executor/load/classes/engine_loader_run.py b/src/sqlbuild/executor/load/classes/engine_loader_run.py index 308366dd20..51d8914379 100644 --- a/src/sqlbuild/executor/load/classes/engine_loader_run.py +++ b/src/sqlbuild/executor/load/classes/engine_loader_run.py @@ -26,10 +26,12 @@ def __init__( self.project: str = inputs.project self.source: str = inputs.source self.reload: bool = inputs.reload - self.start_cursor_ts: str | None = inputs.start_cursor_ts - self.end_cursor_ts: str | None = inputs.end_cursor_ts - self.start_cursor_int: str | None = inputs.start_cursor_int - self.end_cursor_int: str | None = inputs.end_cursor_int + self.start_cursor_ts: str | None = inputs.window.start_ts + self.end_cursor_ts: str | None = inputs.window.end_ts + self.start_cursor_int: str | None = inputs.window.start_int + self.end_cursor_int: str | None = inputs.window.end_int + self.start_cursor: str | None = inputs.window.start + self.end_cursor: str | None = inputs.window.end self._start: Callable[[Mapping[str, Any]], tuple[Context, object]] = start self.context: Context | None = None self.skipped: LoaderSkipResult | None = None diff --git a/src/sqlbuild/executor/load/constants.py b/src/sqlbuild/executor/load/constants.py index b7fcb5f974..9780f7d90d 100644 --- a/src/sqlbuild/executor/load/constants.py +++ b/src/sqlbuild/executor/load/constants.py @@ -3,6 +3,8 @@ from datetime import date from decimal import Decimal +from sqlbuild.adapter.contract.types import TypeFamily + LOADER_RELATION_QUALIFIER_SEPARATOR: str = "." LOADER_SESSION: str = "sqlbuild_warehouse" INTERMEDIATE_WRITE_STRATEGY: str = "replace" @@ -17,3 +19,10 @@ (float, "float"), (Decimal, "decimal"), ) +TIME_CURSOR_FAMILIES: frozenset[TypeFamily] = frozenset( + {TypeFamily.DATE, TypeFamily.TIMESTAMP, TypeFamily.DATETIME} +) +CURSOR_WINDOW_HELP: str = ( + "give --start-cursor/--end-cursor in the loader's cursor type, or leave its source out " + "with --exclude" +) diff --git a/src/sqlbuild/executor/load/main/_cursor_window.py b/src/sqlbuild/executor/load/main/_cursor_window.py index db5ef28752..ab95c87842 100644 --- a/src/sqlbuild/executor/load/main/_cursor_window.py +++ b/src/sqlbuild/executor/load/main/_cursor_window.py @@ -1,25 +1,42 @@ -"""Refusing a cursor window that a loader the run loads cannot apply.""" +"""Refusing a cursor window that a loader the run loads cannot take.""" from __future__ import annotations from collections.abc import Iterable +from sqlbuild._native import SourceEntry from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.load._helpers.execution import row_write_entry +from sqlbuild.executor.load._helpers.loader_windows import declared_cursor_type, loader_window +from sqlbuild.executor.load.types import CursorWindow -def refuse_loaders_without_cursor( - *, loaders: Iterable[tuple[str, str | None]], window: Iterable[object | None] +def refuse_unusable_windows( + *, + loaders: Iterable[tuple[str, str | None, SourceEntry | None]], + window: CursorWindow, + dialect: str, ) -> None: - """Refuse a cursor `window` when one of `loaders`, as (name, cursor_column), has no cursor.""" + """Refuse a cursor `window` one of `loaders`, as (name, cursor_column, source), can't take.""" if all(value is None for value in window): return - names: list[str] = sorted({name for name, cursor_column in loaders if cursor_column is None}) - if not names: - return - quoted: str = ", ".join(f"'{name}'" for name in names) - raise ExecutorInputError( - f"--start-cursor/--end-cursor set a cursor window, but loader {quoted} " - "declares no cursor_column, so the window would not apply to it", - help="set cursor_column on the @loader, or leave its source out with --exclude", - ) + listed: list[tuple[str, str | None, SourceEntry | None]] = list(loaders) + names: list[str] = sorted({name for name, cursor_column, _ in listed if cursor_column is None}) + if names: + quoted: str = ", ".join(f"'{name}'" for name in names) + raise ExecutorInputError( + f"--start-cursor/--end-cursor set a cursor window, but loader {quoted} " + "declares no cursor_column, so the window would not apply to it", + help="set cursor_column on the @loader, or leave its source out with --exclude", + ) + for name, cursor_column, source in listed: + if source is None or row_write_entry(source).write_strategy is None: + continue + declared: str | None = declared_cursor_type(source=source, cursor_column=cursor_column) + _ = loader_window( + loader=name, + cursor=(cursor_column, declared), + window=window, + dialect=dialect, + ) diff --git a/src/sqlbuild/executor/load/models.py b/src/sqlbuild/executor/load/models.py index 6c41793311..438d6749c3 100644 --- a/src/sqlbuild/executor/load/models.py +++ b/src/sqlbuild/executor/load/models.py @@ -269,6 +269,18 @@ class LoadRuntimeParams: loader_projects: Mapping[str, tuple[str, str]] = field(default_factory=dict) +@dataclass(frozen=True) +class LoaderCursorWindow: + """One loader's window as SQLLoad takes it: typed by family, or in the declared cursor type.""" + + start_ts: str | None = None + end_ts: str | None = None + start_int: str | None = None + end_int: str | None = None + start: str | None = None + end: str | None = None + + @dataclass(frozen=True) class EngineLoaderInputs: """What one loader's engine run loads: its project, Python source and cursor window.""" @@ -277,10 +289,7 @@ class EngineLoaderInputs: project: str source: str reload: bool - start_cursor_ts: str | None = None - end_cursor_ts: str | None = None - start_cursor_int: str | None = None - end_cursor_int: str | None = None + window: LoaderCursorWindow @dataclass(frozen=True) diff --git a/src/sqlbuild/executor/load/types.py b/src/sqlbuild/executor/load/types.py new file mode 100644 index 0000000000..22650371a2 --- /dev/null +++ b/src/sqlbuild/executor/load/types.py @@ -0,0 +1,7 @@ +"""Types for source loader execution.""" + +from __future__ import annotations + +from datetime import datetime + +type CursorWindow = tuple[datetime | None, datetime | None, int | None, int | None] diff --git a/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py b/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py index 1d1609bb3c..aa56b1fcf9 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py @@ -21,7 +21,7 @@ from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.compiler.python_nodes.types import PythonNodeKind, PythonNodeStatus, SkipMode from sqlbuild.errors.contracts.exceptions import ExecutorInputError -from sqlbuild.executor.load.main._cursor_window import refuse_loaders_without_cursor +from sqlbuild.executor.load.main._cursor_window import refuse_unusable_windows from sqlbuild.executor.load.main._execute import execute_source_load from sqlbuild.executor.load.main._persist_result import persist_loader_result from sqlbuild.executor.load.main._resource_kind import load_resource_kind @@ -92,15 +92,15 @@ def execute_ingress_python_loader_nodes( if python_graph.nodes_by_name[name].kind == PythonNodeKind.LOADER ) sql_stage_loaded: list[SourceEntry] = [source_map[name] for name in sql_stage_sources] - _ = refuse_loaders_without_cursor( + _ = refuse_unusable_windows( loaders=( *( - (name, loader_by_name[name].cursor_column) + (name, loader_by_name[name].cursor_column, source_by_loader_name.get(name)) for name in ingress_loader_names if name in loader_by_name ), *( - (source.loader, source.cursor_column) + (source.loader, source.cursor_column, source) for source in sql_stage_loaded if source.loader is not None ), @@ -111,6 +111,7 @@ def execute_ingress_python_loader_nodes( runtime.start_cursor_int, runtime.end_cursor_int, ), + dialect=runtime.adapter.adapter_name, ) lifecycle_nodes: tuple[LifecycleExecutionNode, ...] = build_ingress_lifecycle_nodes( plan=PythonSqlRunLifecyclePlan( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/_test_types.py index 3d089d5b3b..bf543dbe68 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/load/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/_test_types.py @@ -174,3 +174,32 @@ class LoaderWindowSettingE2ETestCase: description: str option: str expected_error_fragment: str + + +@dataclass(frozen=True) +class LoaderCursorBoundsE2ETestCase: + """A full load of a `delete_insert` loader whose source declares `columns` over `values`, then + a load bounded by `bounds`: its outcome, the loader's calls and the rows.""" + + description: str + columns: str + values: str + bounds: tuple[str, ...] + expected_return_code: int + expected_fragment: str + expected_calls: tuple[str, ...] + expected_rows: tuple[tuple[object, ...], ...] + + +@dataclass(frozen=True) +class IntermediateLoaderCursorBoundsE2ETestCase: + """A full load through an intermediate loader with cursor `cursor_type` over `values`, then a + load bounded by `bounds` that is refused: the message, the loader's calls and the rows.""" + + description: str + cursor_type: str + values: str + bounds: tuple[str, ...] + expected_fragment: str + expected_calls: tuple[str, ...] + expected_rows: tuple[tuple[object, ...], ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py index bea12742e0..31216309a8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py @@ -561,3 +561,100 @@ def build_round_trip_cursor_project_files() -> dict[str, str]: files["python/nodes/assets/fetch_scores/asset.py"] = _FETCH_SCORES_ASSET files["python/nodes/assets/__init__.py"] = "from .fetch_scores.asset import fetch_scores\n" return files + + +LOADER_CALLS_FILE: str = "target/loader_calls.txt" +_CURSOR_BOUNDS_LOADER: str = '''import datetime +import decimal +import pathlib + +from sqlbuild.loaders import loader + +VALUES = {values} + + +@loader({options}) +def {name}(ctx): + """One sale per cursor value, marked with the load that read it.""" + with pathlib.Path(__file__).parents[4].joinpath("{calls}").open("a") as calls: + calls.write(f"{{ctx.cursor_value!r}} {{ctx.cursor_end!r}}\\n") + start, end = ctx.cursor_value, ctx.cursor_end + return [ + {{"sale_key": value, "pass": "full" if end is None else "bounded"}} + for value in VALUES + if (start is None or value >= start) and (end is None or value < end) + ] +''' + + +def declared_cursor_columns(*, cursor_type: str) -> str: + """The cursor bounds source's `columns:` block, with cursor `sale_key` of `cursor_type`.""" + + return ( + " columns:\n" + f" - name: sale_key\n type: {cursor_type}\n" + " - name: pass\n type: TEXT\n" + ) + + +def build_cursor_bounds_project_files(*, columns: str, values: str) -> dict[str, str]: + """A `delete_insert` loader on cursor `sale_key` over the Python list `values` that records + each window it reads in `LOADER_CALLS_FILE`; its source declares the `columns:` block given.""" + + return { + "sqlbuild_project.toml": ( + 'name = "cursor_bounds"\nadapter = "duckdb"\n\n' + '[connection]\ndatabase = "cursor_bounds.duckdb"\n' + ), + "sql/sources/raw.yml": ( + "sources:\n - name: raw_sales\n description: Sales.\n managed: true\n" + columns + ), + "python/nodes/loaders/__init__.py": "from .raw_sales.loader import raw_sales\n", + "python/nodes/loaders/raw_sales/loader.py": _CURSOR_BOUNDS_LOADER.format( + options='write_strategy="delete_insert", cursor_column="sale_key"', + name="raw_sales", + values=values, + calls=LOADER_CALLS_FILE, + ), + } + + +_FROM_INTERMEDIATE_LOADER: str = """from sqlbuild.loaders import loader + +from python.nodes.loaders.fetch_sales.loader import fetch_sales + + +@loader(depends_on=[fetch_sales], cursor_column="sale_key") +def raw_sales(ctx): + \"\"\"The sales `fetch_sales` read.\"\"\" + sales = ctx.loader(fetch_sales) + ctx.execute_sql( + f"CREATE OR REPLACE TABLE {ctx.destination} AS " + f"SELECT sale_key, pass FROM {sales.destination}" + ) +""" + + +def build_intermediate_cursor_bounds_project_files( + *, cursor_type: str, values: str +) -> dict[str, str]: + """`build_cursor_bounds_project_files` with the recording loader moved to an intermediate + `delete_insert` loader `fetch_sales` with cursor `sale_key` of `cursor_type`, which a + self-managed `raw_sales` copies.""" + + columns: str = ( + f'columns=[{{"name": "sale_key", "type": "{cursor_type}"}}, ' + '{"name": "pass", "type": "TEXT"}]' + ) + return build_cursor_bounds_project_files(columns="", values=values) | { + "python/nodes/loaders/__init__.py": ( + "from .fetch_sales.loader import fetch_sales\nfrom .raw_sales.loader import raw_sales\n" + ), + "python/nodes/loaders/fetch_sales/loader.py": _CURSOR_BOUNDS_LOADER.format( + options=f'write_strategy="delete_insert", cursor_column="sale_key", {columns}', + name="fetch_sales", + values=values, + calls=LOADER_CALLS_FILE, + ), + "python/nodes/loaders/raw_sales/loader.py": _FROM_INTERMEDIATE_LOADER, + } diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/test_loader_cursor_bounds.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_loader_cursor_bounds.py new file mode 100644 index 0000000000..be8040da7e --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_loader_cursor_bounds.py @@ -0,0 +1,254 @@ +"""Real-CLI coverage of a bounded load of a loader SQLLoad runs: the window in its cursor's type.""" + +from __future__ import annotations + +import datetime +import subprocess +from decimal import Decimal +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.load._test_types import ( + IntermediateLoaderCursorBoundsE2ETestCase, + LoaderCursorBoundsE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.load.helpers import ( + LOADER_CALLS_FILE, + build_cursor_bounds_project_files, + build_intermediate_cursor_bounds_project_files, + declared_cursor_columns, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( + prepare_inline_project, + query_duckdb, + run_sqb, +) + +_DAYS: str = "[datetime.date(2026, 1, day) for day in range(1, 7)]" +_MIDNIGHTS: str = "[datetime.datetime(2026, 1, day) for day in range(1, 7)]" +_FULL_CALL: str = "None None" + + +_DAY_KEYS: tuple[datetime.date, ...] = tuple(datetime.date(2026, 1, day) for day in range(1, 7)) +_MIDNIGHT_KEYS: tuple[datetime.datetime, ...] = tuple( + datetime.datetime(2026, 1, day) for day in range(1, 7) +) +_INTEGER_KEYS: tuple[int, ...] = tuple(range(1, 7)) +_WINDOW_PASSES: tuple[str, ...] = ("full", "bounded", "bounded", "bounded", "full", "full") +_FULL_PASSES: tuple[str, ...] = ("full",) * 6 +_UNCHANGED_DAYS: tuple[tuple[object, ...], ...] = tuple(zip(_DAY_KEYS, _FULL_PASSES, strict=True)) + + +@pytest.mark.parametrize( + "test_case", + [ + LoaderCursorBoundsE2ETestCase( + description="a DATE cursor's window loads its dates, the end excluded", + columns=declared_cursor_columns(cursor_type="DATE"), + values=_DAYS, + bounds=("--start-cursor", "2026-01-02", "--end-cursor", "2026-01-05"), + expected_return_code=0, + expected_fragment="rows=3", + expected_calls=(_FULL_CALL, "datetime.date(2026, 1, 2) datetime.date(2026, 1, 5)"), + expected_rows=tuple(zip(_DAY_KEYS, _WINDOW_PASSES, strict=True)), + ), + LoaderCursorBoundsE2ETestCase( + description="a timestamp cursor's window loads its timestamps, the end excluded", + columns=declared_cursor_columns(cursor_type="TIMESTAMP"), + values=_MIDNIGHTS, + bounds=( + "--start-cursor", + "2026-01-02T00:00:00", + "--end-cursor", + "2026-01-05T00:00:00", + ), + expected_return_code=0, + expected_fragment="rows=3", + expected_calls=( + _FULL_CALL, + "datetime.datetime(2026, 1, 2, 0, 0) datetime.datetime(2026, 1, 5, 0, 0)", + ), + expected_rows=tuple(zip(_MIDNIGHT_KEYS, _WINDOW_PASSES, strict=True)), + ), + LoaderCursorBoundsE2ETestCase( + description="an integer cursor's window loads its integers, the end excluded", + columns=declared_cursor_columns(cursor_type="BIGINT"), + values="list(range(1, 7))", + bounds=("--start-cursor", "2", "--end-cursor", "5"), + expected_return_code=0, + expected_fragment="rows=3", + expected_calls=(_FULL_CALL, "2 5"), + expected_rows=tuple(zip(_INTEGER_KEYS, _WINDOW_PASSES, strict=True)), + ), + LoaderCursorBoundsE2ETestCase( + description="a time of day for a DATE cursor is refused before the loader runs", + columns=declared_cursor_columns(cursor_type="DATE"), + values=_DAYS, + bounds=("--start-cursor", "2026-01-02T05:00:00"), + expected_return_code=1, + expected_fragment=( + "loader 'raw_sales' has cursor sale_key of type DATE, but --start-cursor " + "2026-01-02T05:00:00 has a time of day" + ), + expected_calls=(_FULL_CALL,), + expected_rows=_UNCHANGED_DAYS, + ), + LoaderCursorBoundsE2ETestCase( + description="integer bounds for a DATE cursor are refused before the loader runs", + columns=declared_cursor_columns(cursor_type="DATE"), + values=_DAYS, + bounds=("--start-cursor-int", "2", "--end-cursor-int", "5"), + expected_return_code=1, + expected_fragment=( + "loader 'raw_sales' has cursor sale_key of type DATE, but " + "--start-cursor/--end-cursor are integers" + ), + expected_calls=(_FULL_CALL,), + expected_rows=_UNCHANGED_DAYS, + ), + LoaderCursorBoundsE2ETestCase( + description="timestamp bounds for an integer cursor are refused before the loader runs", + columns=declared_cursor_columns(cursor_type="BIGINT"), + values="list(range(1, 7))", + bounds=("--start-cursor", "2026-01-02"), + expected_return_code=1, + expected_fragment=( + "loader 'raw_sales' has cursor sale_key of type BIGINT, but " + "--start-cursor/--end-cursor are timestamps" + ), + expected_calls=(_FULL_CALL,), + expected_rows=tuple(zip(_INTEGER_KEYS, _FULL_PASSES, strict=True)), + ), + LoaderCursorBoundsE2ETestCase( + description="a DECIMAL cursor's window loads its numbers, the end excluded", + columns=declared_cursor_columns(cursor_type="DECIMAL(10,2)"), + values="[decimal.Decimal(key) for key in range(1, 7)]", + bounds=("--start-cursor", "2", "--end-cursor", "5"), + expected_return_code=0, + expected_fragment="rows=3", + expected_calls=(_FULL_CALL, "Decimal('2') Decimal('5')"), + expected_rows=tuple( + zip((Decimal(key) for key in _INTEGER_KEYS), _WINDOW_PASSES, strict=True) + ), + ), + LoaderCursorBoundsE2ETestCase( + description="a text cursor is refused before the loader runs", + columns=declared_cursor_columns(cursor_type="VARCHAR"), + values="[f'2026-01-0{day}' for day in range(1, 7)]", + bounds=("--start-cursor", "2026-01-02", "--end-cursor", "2026-01-05"), + expected_return_code=1, + expected_fragment=( + "loader 'raw_sales' has cursor sale_key of type VARCHAR, which " + "--start-cursor/--end-cursor can't bound: its values compare as text" + ), + expected_calls=(_FULL_CALL,), + expected_rows=tuple( + zip((f"2026-01-0{day}" for day in range(1, 7)), _FULL_PASSES, strict=True) + ), + ), + LoaderCursorBoundsE2ETestCase( + description="a table SQLLoad plans but can't load fails the loader, naming the table", + columns="", + values=_DAYS, + bounds=("--start-cursor", "2026-01-02", "--end-cursor", "2026-01-05"), + expected_return_code=1, + expected_fragment="main.raw_sales: --start-cursor-ts 2026-01-02T00:00:00 has a time", + expected_calls=(_FULL_CALL,), + expected_rows=_UNCHANGED_DAYS, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_loaded_cursor_loader_when_loading_a_window_then_it_loads_the_window_or_fails( + tmp_path: Path, test_case: LoaderCursorBoundsE2ETestCase +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="cursor_bounds", + repo_files=build_cursor_bounds_project_files( + columns=test_case.columns, values=test_case.values + ), + ) + + first: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "load"), project_dir=project_dir + ) + bounded: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "load", *test_case.bounds), project_dir=project_dir + ) + + assert first.returncode == 0, first.stdout + first.stderr + output: str = bounded.stdout + bounded.stderr + assert bounded.returncode == test_case.expected_return_code, output + assert test_case.expected_fragment in output + calls: list[str] = (project_dir / LOADER_CALLS_FILE).read_text().splitlines() + assert tuple(calls) == test_case.expected_calls + rows: list[tuple[object, ...]] = query_duckdb( + db_path=project_dir / "cursor_bounds.duckdb", + sql="SELECT sale_key, pass FROM raw_sales ORDER BY sale_key", + ) + assert tuple(rows) == test_case.expected_rows + + +@pytest.mark.parametrize( + "test_case", + [ + IntermediateLoaderCursorBoundsE2ETestCase( + description="a text cursor on an intermediate loader is refused before it runs", + cursor_type="VARCHAR", + values="[f'2026-01-0{day}' for day in range(1, 7)]", + bounds=("--start-cursor", "2026-01-02"), + expected_fragment=( + "loader 'fetch_sales' has cursor sale_key of type VARCHAR, which " + "--start-cursor/--end-cursor can't bound: its values compare as text" + ), + expected_calls=(_FULL_CALL,), + expected_rows=tuple( + zip((f"2026-01-0{day}" for day in range(1, 7)), _FULL_PASSES, strict=True) + ), + ), + IntermediateLoaderCursorBoundsE2ETestCase( + description="a time of day for an intermediate DATE cursor is refused before it runs", + cursor_type="DATE", + values=_DAYS, + bounds=("--start-cursor", "2026-01-02T05:00:00"), + expected_fragment=( + "loader 'fetch_sales' has cursor sale_key of type DATE, but --start-cursor " + "2026-01-02T05:00:00 has a time of day" + ), + expected_calls=(_FULL_CALL,), + expected_rows=_UNCHANGED_DAYS, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_intermediate_cursor_loader_when_its_window_is_refused_then_it_never_runs( + tmp_path: Path, test_case: IntermediateLoaderCursorBoundsE2ETestCase +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="cursor_bounds", + repo_files=build_intermediate_cursor_bounds_project_files( + cursor_type=test_case.cursor_type, values=test_case.values + ), + ) + + first: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "load"), project_dir=project_dir + ) + bounded: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "load", *test_case.bounds), project_dir=project_dir + ) + + assert first.returncode == 0, first.stdout + first.stderr + output: str = bounded.stdout + bounded.stderr + assert bounded.returncode == 1, output + assert test_case.expected_fragment in output + calls: list[str] = (project_dir / LOADER_CALLS_FILE).read_text().splitlines() + assert tuple(calls) == test_case.expected_calls + rows: list[tuple[object, ...]] = query_duckdb( + db_path=project_dir / "cursor_bounds.duckdb", + sql="SELECT sale_key, pass FROM raw_sales ORDER BY sale_key", + ) + assert tuple(rows) == test_case.expected_rows diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py index 215d057d2b..8ad1a6a38c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py @@ -243,3 +243,14 @@ class PostgresNativeColumnTypesE2ETestCase: rows: str expected_types: tuple[tuple[str, str], ...] expected_rows: tuple[tuple[object, ...], ...] + + +@dataclass(frozen=True) +class PostgresLoaderCursorBoundsE2ETestCase: + """A full load of a DATE-cursor `delete_insert` loader into Postgres, then a load bounded by + `bounds`: the loader's calls and the table's rows.""" + + description: str + bounds: tuple[str, ...] + expected_calls: tuple[str, ...] + expected_rows: tuple[tuple[object, ...], ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_loader_cursor_bounds.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_loader_cursor_bounds.py new file mode 100644 index 0000000000..c9f9561da0 --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_loader_cursor_bounds.py @@ -0,0 +1,106 @@ +"""A bounded load of a DATE-cursor loader into Postgres replaces exactly the window's rows.""" + +from __future__ import annotations + +import datetime +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.load.helpers import ( + LOADER_CALLS_FILE, + build_cursor_bounds_project_files, + declared_cursor_columns, +) +from tests.e2e.src.sqlbuild.cli.commands.main.postgres._test_types import ( + PostgresLoaderCursorBoundsE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.postgres.helpers import ( + build_postgres_project_toml, + build_unique_schema_name, + cleanup_postgres_schema, + ensure_postgres_schema_ready, + fetch_postgres_rows, + relation_name, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + + +@pytest.mark.parametrize( + "test_case", + [ + PostgresLoaderCursorBoundsE2ETestCase( + description="a DATE cursor's window replaces its dates, the end excluded", + bounds=("--start-cursor", "2026-01-02", "--end-cursor", "2026-01-05"), + expected_calls=( + "None None", + "datetime.date(2026, 1, 2) datetime.date(2026, 1, 5)", + ), + expected_rows=tuple( + (datetime.date(2026, 1, day), mark) + for day, mark in enumerate( + ("full", "bounded", "bounded", "bounded", "full", "full"), start=1 + ) + ), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_date_cursor_loader_when_loading_a_date_window_into_postgres_then_it_loads_it( + tmp_path: Path, + test_case: PostgresLoaderCursorBoundsE2ETestCase, + postgres_e2e_config: dict[str, object], +) -> None: + schema_name: str = build_unique_schema_name(prefix="sqb_cursor_bounds") + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="cursor_bounds", + repo_files=build_cursor_bounds_project_files( + columns=declared_cursor_columns(cursor_type="DATE"), + values="[datetime.date(2026, 1, day) for day in range(1, 7)]", + ), + ) + (project_dir / "sqlbuild_project.toml").write_text( + build_postgres_project_toml( + project_name="cursor_bounds", schema_name=schema_name, config=postgres_e2e_config + ), + encoding="utf-8", + ) + ensure_postgres_schema_ready(schema_name=schema_name, config=postgres_e2e_config) + + try: + first: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "load"), project_dir=project_dir + ) + bounded: subprocess.CompletedProcess[str] = run_sqb( + command=( + "--no-color", + "load", + "--start-cursor", + "2026-01-02", + "--end-cursor", + "2026-01-05", + ), + project_dir=project_dir, + ) + rows: tuple[tuple[object, ...], ...] = fetch_postgres_rows( + config=postgres_e2e_config, + sql=( + "SELECT sale_key, pass FROM " + f"{relation_name(schema_name=schema_name, name='raw_sales')} ORDER BY sale_key" + ), + ) + + assert first.returncode == 0, first.stdout + first.stderr + assert bounded.returncode == 0, bounded.stdout + bounded.stderr + assert "rows=3" in bounded.stdout + bounded.stderr + calls: list[str] = (project_dir / LOADER_CALLS_FILE).read_text().splitlines() + assert tuple(calls) == test_case.expected_calls + assert rows == test_case.expected_rows + finally: + cleanup_postgres_schema(schema_name=schema_name, config=postgres_e2e_config) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/website/src/content/docs/docs/cli/load.mdx b/website/src/content/docs/docs/cli/load.mdx index 2ff9f589ed..909cb77063 100644 --- a/website/src/content/docs/docs/cli/load.mdx +++ b/website/src/content/docs/docs/cli/load.mdx @@ -24,8 +24,8 @@ sqb --project-dir load [flags] | `--exclude` | Selectors to leave out | | `--reload` | Reload managed sources from scratch: each table is rebuilt from what its loader returns, with `ctx.is_reload` `True` and `ctx.cursor_value` `None` | | `--concurrency` | Number of worker connections (default: from settings or 1) | -| `--start-cursor` | Where loaders' cursor windows start, as `ctx.cursor_value`: an integer, or an ISO timestamp. Every selected loader needs a `cursor_column`; otherwise the run fails before loading, naming the loader | -| `--end-cursor` | Where they end, not included, as `ctx.cursor_end`; typed the same way as `--start-cursor` | +| `--start-cursor` | Where loaders' cursor windows start, included, as `ctx.cursor_value`: a date, an ISO timestamp or an integer, in the [cursor column's type](/docs/concepts/python-nodes/loaders#loading-a-chosen-window). Every selected loader needs a `cursor_column`; otherwise the run fails before loading, naming the loader | +| `--end-cursor` | Where they end, not included, as `ctx.cursor_end`; given the same way as `--start-cursor` | | `--start-cursor-ts`, `--end-cursor-ts` | The window's bounds as ISO timestamps | | `--start-cursor-int`, `--end-cursor-int` | The window's bounds as integers | | `--json` | Output results as JSON | @@ -54,8 +54,8 @@ sqb load --select load:shop # Reload all sources (full refresh behavior) sqb load --reload -# Override cursor bounds -sqb load --start-cursor "2026-05-01T00:00:00" +# Load one week of a loader with a DATE cursor +sqb load --select raw_daily_sales --start-cursor 2026-05-01 --end-cursor 2026-05-08 ``` ## Selection diff --git a/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx b/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx index 921483df0f..31e68386a9 100644 --- a/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx +++ b/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx @@ -213,11 +213,9 @@ def raw_order_events(ctx): ``` `ctx.cursor_value` is the current `MAX(cursor_column)` of the target, or `None` on the first load, -so the loader fetches only new or updated data. `--start-cursor` and `--end-cursor` on -[`sqb load`](/docs/cli/load) and `sqb build` set the window instead; every loader the run loads -then needs a `cursor_column`, and one without fails the run before anything loads. A row outside the window fails -the load, so a loader fetches only what the window covers. The source it fills declares its columns -as any managed source does: +so the loader fetches only new or updated data. A row outside the window fails the load, so a +loader fetches only what the window covers. The source it fills declares its columns as any +managed source does: ```yaml sources: @@ -261,6 +259,41 @@ def raw_payments(ctx): ctx.state = page.next_sync_token ``` +### Loading a chosen window + +`--start-cursor` and `--end-cursor` on [`sqb load`](/docs/cli/load) and `sqb build` set a +loader's window instead of the target's maximum. The loader reads from `--start-cursor`, included, +up to `--end-cursor`, not included; with `delete_insert`, those rows replace the window's rows in +the target: + +```bash +sqb load --select raw_daily_sales --start-cursor 2026-05-01 --end-cursor 2026-05-08 +``` + +A loader with a `write_strategy` gets the bounds as `ctx.cursor_value` and `ctx.cursor_end`, in +the type the source declares for the cursor column: + +| Cursor column type | Give the bounds as | `ctx.cursor_value` is | +|--------------------|--------------------|-----------------------| +| `DATE` | Dates, such as `2026-05-01` | `datetime.date` | +| Timestamp | ISO timestamps, such as `2026-05-01T06:00:00` | `datetime.datetime` | +| Integer | Integers, such as `1500` | `int` | + +Details: + +- Every loader the run loads needs a `cursor_column`; one without fails the run before anything + loads, naming the loader. +- A bound that doesn't fit one of these cursor types, such as a time of day for a `DATE` cursor, + fails the run before anything loads, naming the loader and its cursor type. So does a text + cursor, whose values would compare as text. +- A cursor of another declared type, such as `DECIMAL`, takes the bounds in that type. +- When the source doesn't declare the cursor column's type, the bounds arrive as timestamps or + integers, and the loaded table's column decides whether they fit. Declare the type so a `DATE` + cursor takes dates. +- A [self-managed loader](#self-managed-loaders) gets the bounds as timestamps or integers. +- When SQLLoad can't load a table, such as for a bound that doesn't fit its column, the loader + fails with the reason and names the table. + ## Loading from an HTTP API A loader that names an `http` [source connection](/docs/concepts/project-configuration#warehouse-and-source-connections) with From 69f2f0bd0e9be922e834819b30b7c18b99ef0593 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:37:50 +0000 Subject: [PATCH 2/2] fix: ClickHouse loads pin a declared type as ClickHouse stores it A source column declared TIMESTAMP on ClickHouse was handed to SQLLoad pinned as native("TIMESTAMP"). ClickHouse stores it as DateTime and reports that back, so SQLLoad saw the column drift on the next load and blocked the table. Declared types are now pinned under ClickHouse's own name for them, as toTypeName prints it. ClickHouse's DateTime with a precision is DateTime64 of that precision, and plain DateTime at precision 0. A cursor SQLLoad keeps as a warehouse-native type reached the loader as text, since SQLLoad has no portable kind to read it in. It is now read as an untyped cursor is on a first load, so ISO timestamps, dates and integers arrive as such. --- .../_helpers/dialects/clickhouse_types.rs | 19 ++++ ...s_dialect_type.rs => dialect_type_name.rs} | 9 +- .../src/analysis_route/main/mod.rs | 2 +- .../tests/test_clickhouse_dialect.rs | 20 ++++ .../src/loads/_helpers/column_types.rs | 12 +-- .../loads/tests/test_sqlload_column_type.rs | 10 +- .../executor/load/_helpers/engine_runs.py | 13 ++- src/sqlbuild/executor/load/constants.py | 2 + .../commands/main/clickhouse/_test_types.py | 11 +++ .../clickhouse/test_loader_cursor_bounds.py | 93 +++++++++++++++++++ 10 files changed, 177 insertions(+), 14 deletions(-) rename crates/sqlbuild-analysis/src/analysis_route/main/{names_dialect_type.rs => dialect_type_name.rs} (65%) create mode 100644 tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_loader_cursor_bounds.py diff --git a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/clickhouse_types.rs b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/clickhouse_types.rs index 53a4dbcae9..cb63752bf9 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/clickhouse_types.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/clickhouse_types.rs @@ -251,6 +251,7 @@ pub(crate) fn clickhouse_type(spelling: &str) -> Option { ("Decimal", None) => Some(CLICKHOUSE_DECIMAL_DEFAULT.to_owned()), ("Decimal", Some(arguments)) => decimal(arguments), ("FixedString", None) => None, + ("DateTime", Some(arguments)) => date_time(arguments), (_, None) => Some(family.to_owned()), (_, Some(_)) if CLICKHOUSE_NUMBER_FAMILIES @@ -271,6 +272,24 @@ pub(crate) fn clickhouse_type(spelling: &str) -> Option { } } +/// `DateTime(arguments)` as ClickHouse stores it: a precision above 0 makes it `DateTime64`, a precision of 0 drops it. +fn date_time(arguments: &str) -> Option { + let listed: String = listed(arguments); + let (first, rest): (&str, Option<&str>) = match listed.split_once(", ") { + Some((first, rest)) => (first, Some(rest)), + None => (listed.as_str(), None), + }; + let Ok(precision) = first.parse::() else { + return Some(format!("DateTime({listed})")); + }; + Some(match (precision, rest) { + (0, None) => "DateTime".to_owned(), + (0, Some(zone)) => format!("DateTime({zone})"), + (_, None) => format!("DateTime64({precision})"), + (_, Some(zone)) => format!("DateTime64({precision}, {zone})"), + }) +} + /// The family a type name or alias stands for, matched with case where ClickHouse does. fn family(words: &str) -> Option<&'static str> { if let Some(exact) = CLICKHOUSE_EXACT_FAMILIES diff --git a/crates/sqlbuild-analysis/src/analysis_route/main/names_dialect_type.rs b/crates/sqlbuild-analysis/src/analysis_route/main/dialect_type_name.rs similarity index 65% rename from crates/sqlbuild-analysis/src/analysis_route/main/names_dialect_type.rs rename to crates/sqlbuild-analysis/src/analysis_route/main/dialect_type_name.rs index 613fce9564..f74c263f9a 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/main/names_dialect_type.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/main/dialect_type_name.rs @@ -1,19 +1,20 @@ -//! Whether a type spelling names one of a dialect's own warehouse types. +//! A type spelling as a dialect's warehouse names it, when it is one of the warehouse's own types. use crate::analysis_route::_helpers::dialects::clickhouse_types::clickhouse_type; use crate::analysis_route::constants::{ARRAY_SUFFIX, CLICKHOUSE_DIALECT, DIALECT_TYPE_NAMES}; -/// Whether `spelling` is a type `dialect`'s warehouse knows: ClickHouse's as `toTypeName` reads it, others by base name. +/// `spelling` as `dialect`'s warehouse names the type, or `None` when it doesn't know it: ClickHouse's as `toTypeName` reads it, so an alias such as `TIMESTAMP` is `DateTime`; others as written, known by base name. #[must_use] -pub fn names_dialect_type(dialect: &str, spelling: &str) -> bool { +pub fn dialect_type_name(dialect: &str, spelling: &str) -> Option { if dialect == CLICKHOUSE_DIALECT { - return clickhouse_type(spelling).is_some(); + return clickhouse_type(spelling); } let base: String = base_name(spelling); DIALECT_TYPE_NAMES .iter() .find(|(name, _)| *name == dialect) .is_some_and(|(_, names)| names.contains(&base.as_str())) + .then(|| spelling.trim().to_owned()) } /// The upper-cased words before a type's arguments (`(`, `<`) and array suffixes. diff --git a/crates/sqlbuild-analysis/src/analysis_route/main/mod.rs b/crates/sqlbuild-analysis/src/analysis_route/main/mod.rs index c559960adc..2cd31370fa 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/main/mod.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/main/mod.rs @@ -1,7 +1,7 @@ pub mod aligned_offset; pub mod analysis_route; +pub mod dialect_type_name; pub mod fast_lineage; -pub mod names_dialect_type; pub mod native_gap; pub(crate) mod native_outcomes; pub mod native_revalidation; diff --git a/crates/sqlbuild-analysis/src/analysis_route/tests/test_clickhouse_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/tests/test_clickhouse_dialect.rs index 88459627ea..49d3e864d5 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/tests/test_clickhouse_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/tests/test_clickhouse_dialect.rs @@ -249,6 +249,26 @@ fn given_clickhouse_contract_types_when_matching_then_aliases_compare_as_the_eng nullable_into_non_null: false, }, }, + TypeMatchTestCase { + description: "a TIMESTAMP with precision is the engine's DateTime64", + declared: "TIMESTAMP(3)", + inferred: Some("DateTime64(3)"), + inferred_nullable: false, + expected_match: TypeMatch::Compared { + same_type: true, + nullable_into_non_null: false, + }, + }, + TypeMatchTestCase { + description: "a zoned DateTime with precision 0 is the engine's DateTime in that zone", + declared: "DateTime(0, 'UTC')", + inferred: Some("DateTime('UTC')"), + inferred_nullable: false, + expected_match: TypeMatch::Compared { + same_type: true, + nullable_into_non_null: false, + }, + }, TypeMatchTestCase { description: "a declared BIGINT is the engine's Int64", declared: "BIGINT", diff --git a/crates/sqlbuild-load/src/loads/_helpers/column_types.rs b/crates/sqlbuild-load/src/loads/_helpers/column_types.rs index e3817f1663..eb4a982898 100644 --- a/crates/sqlbuild-load/src/loads/_helpers/column_types.rs +++ b/crates/sqlbuild-load/src/loads/_helpers/column_types.rs @@ -1,6 +1,6 @@ //! Declared column types as SQLLoad reads them: its own logical types, or the warehouse's own pinned verbatim. -use sqlbuild_analysis::analysis_route::main::names_dialect_type::names_dialect_type; +use sqlbuild_analysis::analysis_route::main::dialect_type_name::dialect_type_name; use sqlload::adapters::contract::types::SqlAdapter; use sqlload::adapters::dispatch::main::dialect::sql_adapter::sql_adapter; use sqlload::column_types::main::parse_type::parse_type; @@ -9,15 +9,15 @@ use sqlload::column_types::models::Warehouse; use crate::loads::constants::{NATIVE_CLOSE, NATIVE_OPEN}; use crate::warehouses::main::warehouse_dialect::warehouse_dialect; -/// `declared` as SQLLoad takes it in `warehouse`: as written when SQLLoad reads it, `native("...")` when only the warehouse knows it, so declared types are literal. +/// `declared` as SQLLoad takes it in `warehouse`: as written when SQLLoad reads it, `native("...")` of the warehouse's own name for it when only the warehouse knows it, so declared types are literal and match the type the warehouse reports back. pub(crate) fn sqlload_column_type(declared: &str, warehouse: Warehouse) -> String { let written: &str = declared.trim(); match parse_type(written, &[warehouse]) { Ok(_logical) => written.to_owned(), - Err(_unread) if names_dialect_type(warehouse_dialect(warehouse), written) => { - pinned(written) - } - Err(_refused) => written.to_owned(), + Err(_unread) => match dialect_type_name(warehouse_dialect(warehouse), written) { + Some(named) => pinned(&named), + None => written.to_owned(), + }, } } diff --git a/crates/sqlbuild-load/src/loads/tests/test_sqlload_column_type.rs b/crates/sqlbuild-load/src/loads/tests/test_sqlload_column_type.rs index 549640de07..ef89e68fed 100644 --- a/crates/sqlbuild-load/src/loads/tests/test_sqlload_column_type.rs +++ b/crates/sqlbuild-load/src/loads/tests/test_sqlload_column_type.rs @@ -39,10 +39,16 @@ fn given_a_declared_type_when_handing_it_to_sqlload_then_only_a_warehouse_type_i expected_sqlload_type: r#"native("Nullable(Int64)")"#, }, SqlloadColumnTypeTestCase { - description: "ClickHouse's own TIMESTAMP, which SQLLoad refuses, is pinned as written", + description: "ClickHouse's TIMESTAMP alias is pinned as the DateTime ClickHouse reports", warehouse: Warehouse::ClickHouse, declared: "TIMESTAMP", - expected_sqlload_type: r#"native("TIMESTAMP")"#, + expected_sqlload_type: r#"native("DateTime")"#, + }, + SqlloadColumnTypeTestCase { + description: "an alias inside a ClickHouse wrapper is pinned by its family name", + warehouse: Warehouse::ClickHouse, + declared: "Nullable(TIMESTAMP(3))", + expected_sqlload_type: r#"native("Nullable(DateTime64(3))")"#, }, SqlloadColumnTypeTestCase { description: "Snowflake's TIMESTAMP, which follows the account's mapping, is pinned", diff --git a/src/sqlbuild/executor/load/_helpers/engine_runs.py b/src/sqlbuild/executor/load/_helpers/engine_runs.py index 883e714584..db3a98be9f 100644 --- a/src/sqlbuild/executor/load/_helpers/engine_runs.py +++ b/src/sqlbuild/executor/load/_helpers/engine_runs.py @@ -19,7 +19,9 @@ HTTP_CONTEXT_CLIENTS, INTERMEDIATE_WRITE_STRATEGY, LOADER_NAMING, + NATIVE_CURSOR_TYPE_PREFIX, NOT_CALLED, + UNKNOWN_CURSOR_TYPE, ) from sqlbuild.executor.load.models import ( EngineLoaderInputs, @@ -51,7 +53,7 @@ def started(read: Mapping[str, Any]) -> tuple[Context, object]: context: LoaderContext = cast( LoaderContext, LoaderContext.from_read( - read, + _portable_cursor(read), logger=sqlbuild.logger, sqlbuild=sqlbuild, connection_name=read.get("connection"), @@ -95,6 +97,15 @@ def started(read: Mapping[str, Any]) -> tuple[Context, object]: ) +def _portable_cursor(read: Mapping[str, Any]) -> Mapping[str, Any]: + """`read` with a warehouse-native cursor read as untyped, so its bounds arrive typed.""" + + cursor: Mapping[str, Any] = read.get("cursor") or {} + if not str(cursor.get("column_type") or "").startswith(NATIVE_CURSOR_TYPE_PREFIX): + return read + return {**read, "cursor": {**cursor, "column_type": UNKNOWN_CURSOR_TYPE}} + + def engine_result( *, report: Mapping[str, Any], diff --git a/src/sqlbuild/executor/load/constants.py b/src/sqlbuild/executor/load/constants.py index 9780f7d90d..77d986ae99 100644 --- a/src/sqlbuild/executor/load/constants.py +++ b/src/sqlbuild/executor/load/constants.py @@ -12,6 +12,8 @@ NOT_CALLED: object = object() HTTP_CONTEXT_CLIENTS: frozenset[str] = frozenset({"http"}) TIMESTAMP_TZ_TYPE: str = "timestamp_tz" +NATIVE_CURSOR_TYPE_PREFIX: str = "native(" +UNKNOWN_CURSOR_TYPE: str = "unknown" TIMESTAMP_NTZ_TYPE: str = "timestamp_ntz" CURSOR_VALUE_TYPES: tuple[tuple[type, str], ...] = ( (date, "date"), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/_test_types.py index 4d8a4a013f..933cf26ed7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/_test_types.py @@ -389,3 +389,14 @@ class ClickHouseNativeColumnTypesE2ETestCase: rows: str expected_types: tuple[tuple[str, str], ...] expected_rows: tuple[tuple[object, ...], ...] + + +@dataclass(frozen=True) +class ClickHouseLoaderCursorBoundsE2ETestCase: + """A TIMESTAMP-cursor `delete_insert` loader loaded into ClickHouse three times: in full, + again from the table's own maximum, then bounded by `bounds`: its calls and the table's rows.""" + + description: str + bounds: tuple[str, ...] + expected_calls: tuple[str, ...] + expected_rows: tuple[tuple[object, ...], ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_loader_cursor_bounds.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_loader_cursor_bounds.py new file mode 100644 index 0000000000..b7290570af --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_loader_cursor_bounds.py @@ -0,0 +1,93 @@ +"""A TIMESTAMP-cursor loader on ClickHouse reloads from its table's maximum and loads a window.""" + +from __future__ import annotations + +import datetime +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.clickhouse._test_types import ( + ClickHouseLoaderCursorBoundsE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.clickhouse.helpers import ( + build_clickhouse_project_toml, + build_unique_schema_name, + cleanup_clickhouse_schema, + create_clickhouse_schema, + fetch_clickhouse_rows, +) +from tests.e2e.src.sqlbuild.cli.commands.main.load.helpers import ( + LOADER_CALLS_FILE, + build_cursor_bounds_project_files, + declared_cursor_columns, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + + +@pytest.mark.parametrize( + "test_case", + [ + ClickHouseLoaderCursorBoundsE2ETestCase( + description="a TIMESTAMP cursor reads its DateTime maximum, then its window", + bounds=("--start-cursor", "2026-01-02", "--end-cursor", "2026-01-05"), + expected_calls=( + "None None", + "datetime.datetime(2026, 1, 6, 0, 0) None", + "datetime.datetime(2026, 1, 2, 0, 0) datetime.datetime(2026, 1, 5, 0, 0)", + ), + expected_rows=tuple( + (datetime.datetime(2026, 1, day), mark) + for day, mark in enumerate( + ("full", "bounded", "bounded", "bounded", "full", "full"), start=1 + ) + ), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_timestamp_cursor_loader_when_loading_into_clickhouse_then_each_load_reads_its_window( + tmp_path: Path, + test_case: ClickHouseLoaderCursorBoundsE2ETestCase, + clickhouse_e2e_config: dict[str, object], +) -> None: + schema_name: str = build_unique_schema_name(prefix="sqb_cursor_bounds") + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="cursor_bounds", + repo_files=build_cursor_bounds_project_files( + columns=declared_cursor_columns(cursor_type="TIMESTAMP"), + values="[datetime.datetime(2026, 1, day) for day in range(1, 7)]", + ), + ) + (project_dir / "sqlbuild_project.toml").write_text( + build_clickhouse_project_toml( + project_name="cursor_bounds", schema_name=schema_name, config=clickhouse_e2e_config + ), + encoding="utf-8", + ) + create_clickhouse_schema(config=clickhouse_e2e_config, schema_name=schema_name) + + try: + loads: list[subprocess.CompletedProcess[str]] = [ + run_sqb(command=("--no-color", "load", *bounds), project_dir=project_dir) + for bounds in ((), (), test_case.bounds) + ] + rows: tuple[tuple[object, ...], ...] = fetch_clickhouse_rows( + config=clickhouse_e2e_config, + sql=f"SELECT sale_key, pass FROM {schema_name}.raw_sales ORDER BY sale_key", + ) + + assert [load.returncode for load in loads] == [0, 0, 0], "\n".join( + load.stdout + load.stderr for load in loads + ) + calls: list[str] = (project_dir / LOADER_CALLS_FILE).read_text().splitlines() + assert tuple(calls) == test_case.expected_calls + assert rows == test_case.expected_rows + finally: + cleanup_clickhouse_schema(config=clickhouse_e2e_config, schema_name=schema_name) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"])