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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ pub(crate) fn clickhouse_type(spelling: &str) -> Option<String> {
("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
Expand All @@ -271,6 +272,24 @@ pub(crate) fn clickhouse_type(spelling: &str) -> Option<String> {
}
}

/// `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<String> {
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::<u8>() 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> {
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.
Expand Down
2 changes: 1 addition & 1 deletion crates/sqlbuild-analysis/src/analysis_route/main/mod.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 6 additions & 6 deletions crates/sqlbuild-load/src/loads/_helpers/column_types.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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(),
},
}
}

Expand Down
10 changes: 8 additions & 2 deletions crates/sqlbuild-load/src/loads/tests/test_sqlload_column_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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")?,
Expand Down
39 changes: 37 additions & 2 deletions crates/sqlbuild-python-load/src/runs/_helpers/tables.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
Expand All @@ -22,6 +23,40 @@ pub(crate) fn planned_tables(plan: &ProjectPlan) -> Vec<String> {
.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<LoadedTable> {
plan.tables
.iter()
.filter(|table| !has_outcome(loaded, table))
.map(|table| {
let reasons: Vec<String> = 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<String> {
required
Expand Down
3 changes: 3 additions & 0 deletions crates/sqlbuild-python-load/src/runs/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
5 changes: 4 additions & 1 deletion crates/sqlbuild-python-load/src/runs/main/run_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -73,6 +75,7 @@ pub fn run_project(
retryable: outcome.retryable,
});
}
tables.extend(unloaded_tables(&project, &plan, &tables));
Ok(ProjectRun {
tables,
planned,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ sqb --project-dir <path> 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 |
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions src/sqlbuild/executor/build/main/_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
),
Expand All @@ -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
Expand Down
Loading
Loading