diff --git a/crates/sqlload/src/loader/_helpers/destination.rs b/crates/sqlload/src/loader/_helpers/destination.rs index 391a98c53..cb069d45a 100644 --- a/crates/sqlload/src/loader/_helpers/destination.rs +++ b/crates/sqlload/src/loader/_helpers/destination.rs @@ -58,7 +58,7 @@ use crate::loader::_helpers::table_plan::{change_lines, schema_statements}; use crate::loader::constants::{CATALOG_CONFLICT, CATALOG_CONFLICT_TRIES, COALESCED_BYTES}; use crate::loader::errors::LoaderError; use crate::loader::models::SourceReader; -use crate::loader::models::{CommitRange, Publisher}; +use crate::loader::models::{CommitRange, Publisher, PythonFeed, PythonLoad}; use crate::loader::models::{Cuts, Pending, Pieces, RowGroupSeen}; use crate::loader::models::{ FilesSink, FilesSource, LiveFiles, LoadRun, ProjectPlan, TablePlan, TableSpec, UnreadSharing, @@ -1769,3 +1769,32 @@ impl Publisher { }; } } + +/// `result`, after dropping the table `feed`'s load created in a SQL destination when `result` failed and nothing has committed to it, so a load that fails at its end (a declared column under `on_schema_change = "fail"`) leaves no empty table it made; a table that existed at plan, a files target and a table with commits are left as they are. +pub(crate) async fn unpublished_on_error( + (feed, load): (&PythonFeed, &PythonLoad<'_>), + result: Result, +) -> Result { + let error = match result { + Ok(found) => return Ok(found), + Err(error) => error, + }; + let committed = feed + .publisher + .as_ref() + .is_some_and(|publisher| publisher.commits > 0); + if load.table.exists || committed || feed.table.output.is_some() { + return Err(error); + } + let destination = feed + .publisher + .as_ref() + .map_or(load.destination, |publisher| &publisher.destination); + let name = + sql_adapter(feed.table.spec.warehouse).render_qualified_name(&feed.table.spec.destination); + let drop = format!("DROP TABLE IF EXISTS {name}"); + if let Err(dropped) = execute_ddl(destination, vec![drop]).await { + tracing::warn!(error = %dropped, table = %name, "cannot drop the table the failed load created"); + } + Err(error) +} diff --git a/crates/sqlload/src/loader/_helpers/publish.rs b/crates/sqlload/src/loader/_helpers/publish.rs index 90caa6140..c8c0b50d9 100644 --- a/crates/sqlload/src/loader/_helpers/publish.rs +++ b/crates/sqlload/src/loader/_helpers/publish.rs @@ -1601,6 +1601,7 @@ pub(crate) async fn publish_table( transforms, names: name_lines(&table.spec.names.columns), warnings: Vec::new(), + missing_columns: Vec::new(), }) } diff --git a/crates/sqlload/src/loader/_helpers/python.rs b/crates/sqlload/src/loader/_helpers/python.rs index 764eca9dd..1056de7da 100644 --- a/crates/sqlload/src/loader/_helpers/python.rs +++ b/crates/sqlload/src/loader/_helpers/python.rs @@ -34,6 +34,7 @@ use crate::load_naming::main::metadata_name::metadata_name; use crate::load_naming::main::name_lines::name_lines; use crate::load_naming::main::named_batch::named_batch; use crate::load_naming::models::{Compat, LoadedNames, MetadataRole, NameMemo, RenameColumn}; +use crate::loader::_helpers::destination::unpublished_on_error; use crate::loader::_helpers::publish::created_at_commit; use crate::loader::_helpers::publish::replaces_roots; use crate::loader::_helpers::publish::staged_columns; @@ -41,6 +42,7 @@ use crate::loader::_helpers::resolve::{KnownNames, host_rename, resolve_known}; use crate::loader::_helpers::run_log::{log_empty_run, record_numbered, run_entry}; use crate::loader::_helpers::specs::is_child_column; use crate::loader::_helpers::specs::null_cursor_problem; +use crate::loader::_helpers::specs::python_missing; use crate::loader::_helpers::table_plan::append_problem; use crate::loader::_helpers::table_plan::change_lines; use crate::loader::_helpers::table_plan::replan_columns; @@ -782,13 +784,13 @@ impl PythonFeed { rows: 0, changes: Vec::new(), note: Some(NO_DATA_NOTE.to_owned()), - after_load: None, - replaced_keys: None, - transforms: Vec::new(), - names: Vec::new(), warnings: std::mem::take(&mut self.warnings), + ..TableLoaded::default() }); } + let found = python_missing(&load.table.spec, &self.merged, self.rows); + let (missing, warned) = unpublished_on_error((self, load), found).await?; + self.warnings.extend(warned); let unsettled = self.publisher.is_none() || self .merged @@ -826,6 +828,7 @@ impl PythonFeed { transforms: Vec::new(), names: name_lines(&self.names.columns), warnings: std::mem::take(&mut self.warnings), + missing_columns: missing, }) } diff --git a/crates/sqlload/src/loader/_helpers/render.rs b/crates/sqlload/src/loader/_helpers/render.rs index c6939ab53..8fdbeb0ba 100644 --- a/crates/sqlload/src/loader/_helpers/render.rs +++ b/crates/sqlload/src/loader/_helpers/render.rs @@ -1,7 +1,6 @@ use crate::load_naming::main::name_lines::name_lines; use crate::load_naming::models::NameChange; use crate::loader::constants::{FIX_LABEL, REASON_LABEL, ROUTE_LABEL, SOURCE_LABEL}; -use crate::loader::models::UnreadSource; use crate::project::models::CheckName; use crate::row_deletes::main::deletes_note::deletes_note; use crate::run_log::models::RunEvent; @@ -37,7 +36,7 @@ use crate::loader::constants::{ use crate::loader::models::{ CommitRule, FilesOutput, FilesSource, ObjectChange, PlanDetail, PlanItem, PlanView, ProjectPlan, PythonTable, RunReport, RunResult, RunSummary, SourceEnd, TableOutcome, TablePlan, - TableResult, TableSpec, TallyLine, WarehouseRoute, WarehouseSource, WholeReason, + TableResult, TableSpec, TallyLine, UnreadSource, WarehouseRoute, WarehouseSource, WholeReason, }; use crate::number_text::main::thousands::thousands; use crate::project::models::BatchStep; @@ -1349,6 +1348,7 @@ fn sections(plan: &ProjectPlan, text: bool) -> PlanView { .map(|warning| error_item(warning, &[])) .chain(ready.iter().filter_map(|table| warning_item(table))) .collect(), + missing_columns: plan.missing_columns(), } } @@ -1525,6 +1525,7 @@ fn table_result(outcome: &TableOutcome) -> TableResult { Ok(loaded) => loaded.warnings.clone(), Err(_) => Vec::new(), }, + missing_columns: outcome.missing_columns(), peak_memory_bytes: outcome.peak_memory_bytes, } } diff --git a/crates/sqlload/src/loader/_helpers/sources.rs b/crates/sqlload/src/loader/_helpers/sources.rs index bdae4d7fe..8effa9a22 100644 --- a/crates/sqlload/src/loader/_helpers/sources.rs +++ b/crates/sqlload/src/loader/_helpers/sources.rs @@ -1089,7 +1089,7 @@ pub(crate) fn files_source_parts( .collect(); let overrides = source.tables.get(source_name); let rule = (naming, sql_adapter(warehouse).max_identifier_length()); - let pinned_only = pinned_unsampled(overrides, (&table, &added, rule), encoding.format)?; + let pinned_only = pinned_unsampled(overrides, (&table, &added, rule))?; if !table.objects.is_empty() { let problems = flattened_object_problems((source, overrides), (&table.columns, &table.objects)) @@ -1104,12 +1104,8 @@ pub(crate) fn files_source_parts( table.dropped.join(", ") ) }); - let notes: Vec = dropped - .into_iter() - .chain(pinned_only.iter().map(|name| { - format!("pinned column {name} was not seen in the sampled files (check the name)") - })) - .collect(); + let notes: Vec = dropped.into_iter().collect(); + let unsampled = pinned_only.clone(); let typed = table .columns .iter() @@ -1184,6 +1180,7 @@ pub(crate) fn files_source_parts( encoding, checks, notes, + unsampled, copy_to_internal_stage: source.copy_to_internal_stage, transform: None, archive: None, diff --git a/crates/sqlload/src/loader/_helpers/specs.rs b/crates/sqlload/src/loader/_helpers/specs.rs index 24b248adb..dad30b242 100644 --- a/crates/sqlload/src/loader/_helpers/specs.rs +++ b/crates/sqlload/src/loader/_helpers/specs.rs @@ -34,7 +34,8 @@ use crate::loader::_helpers::run_log::overlapping_files_problem; use crate::loader::_helpers::sources::sheet_rule; use crate::loader::_helpers::table_plan::source_cursor; use crate::loader::constants::{ - ODBC_SOURCE, PRIMARY_KEY, PRIMARY_KEY_PLACEHOLDER, SNOWFLAKE_SOURCE, UNNEST_ALL, + ODBC_SOURCE, PRIMARY_KEY, PRIMARY_KEY_PLACEHOLDER, PYTHON_MISSING_COLUMN, SNOWFLAKE_SOURCE, + UNNEST_ALL, }; use crate::loader::errors::LoaderError; use crate::loader::models::{ @@ -60,6 +61,7 @@ use crate::row_batches::main::merge_schema::merge_schema; use crate::row_batches::models::{Flatten, Unnest}; use crate::row_deletes::main::deletes_problems::deletes_problems; use crate::row_deletes::main::deletes_spec::deletes_spec; +use crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings; use crate::schema_plan::models::{ColumnOrigin, DesiredColumn}; use crate::sheets_source::models::SheetRead; use crate::similar_names::main::close_name::close_name; @@ -569,6 +571,7 @@ pub(crate) fn build_spec( transform: None, parses, timezone, + missing_columns: Vec::new(), }) } @@ -1800,13 +1803,12 @@ pub(crate) fn path_values( Ok((values, types)) } -/// Columns a JSON or CSV source's table pins in `columns` that sampling did not see, so a key found only in older files can be pinned; a name close to a sampled one (a typo, or another case) is an error, and a `mask` key alone never adds a column. A pin naming a sampled column by the name `rule`'s naming gives it is one sampling saw. +/// Columns a files source's table pins in `columns` that no sampled file holds (its JSON or CSV records, or its Parquet footers), which load as NULL where the files lack them unless `on_schema_change = "fail"` refuses them, so a key found only in older files can be pinned; a name close to a sampled one (a typo, or another case) is an error, and a `mask` key alone never adds a column. A pin naming a sampled column by the name `rule`'s naming gives it is one sampling saw. pub(crate) fn pinned_unsampled( overrides: Option<&TableOverride>, (table, added, rule): (&FilesTable, &[&str], NameRule), - format: SourceFormat, ) -> Result, LoaderError> { - let Some(overrides) = overrides.filter(|_| format != SourceFormat::Parquet) else { + let Some(overrides) = overrides else { return Ok(Vec::new()); }; let sampled: Vec<&str> = table @@ -1836,6 +1838,40 @@ pub(crate) fn pinned_unsampled( Ok(unsampled) } +/// The declared columns none of a Python table's `rows` rows had (its yielded fields merged as `merged`), and a warning for each; or, under `on_schema_change = "fail"`, the failure. A table that yielded no rows lacks none. +pub(crate) fn python_missing( + spec: &TableSpec, + merged: &Schema, + rows: u64, +) -> Result<(Vec, Vec), LoaderError> { + let missing = match rows { + 0 => Vec::new(), + _ => missing_declared(spec, merged), + }; + let warnings = missing_columns_warnings(&missing, PYTHON_MISSING_COLUMN, spec.on_schema_change) + .map_err(LoaderError::Invalid)?; + Ok((missing, warnings)) +} + +/// The columns `spec` declares (pinned in `columns`, or parsed) that no field of `merged` is, ignoring case, by the name each loads as; a child table's and a masked column's are left out, as a masked column the rows lack fails the table already. +fn missing_declared(spec: &TableSpec, merged: &Schema) -> Vec { + let had = |name: &str| { + merged + .fields() + .iter() + .any(|field| field.name().eq_ignore_ascii_case(name)) + }; + let mut missing: Vec = Vec::new(); + for name in spec.pinned.keys().chain(spec.parses.keys()) { + let left_out = + spec.child_pinned.contains_key(name) || spec.masked.columns.contains_key(name); + if !left_out && !had(name) && !missing.contains(name) { + missing.push(name.clone()); + } + } + missing +} + /// The read columns of a files source: the file's types, or the pinned ones (converted while reading); a parsed column reads as text, for `parse` to convert. pub(crate) fn files_read_columns(spec: &TableSpec) -> Result, Vec> { let mut problems: Vec = Vec::new(); diff --git a/crates/sqlload/src/loader/_helpers/table_plan.rs b/crates/sqlload/src/loader/_helpers/table_plan.rs index f4fb33165..b32d4fe89 100644 --- a/crates/sqlload/src/loader/_helpers/table_plan.rs +++ b/crates/sqlload/src/loader/_helpers/table_plan.rs @@ -66,6 +66,7 @@ use crate::loader::_helpers::sources::plan_files; use crate::loader::_helpers::sources::{FilesPlanRequest, LoadedSource, with_live_types}; use crate::loader::_helpers::specs::files_read_columns; use crate::loader::constants::CHECKS_LOADER_WARNING; +use crate::loader::constants::FILES_MISSING_COLUMN; use crate::loader::constants::KEPT_TABLES_RELOAD_PROBLEM; use crate::loader::constants::RANGE_NEEDS_CURSOR; use crate::loader::errors::LoaderError; @@ -104,6 +105,7 @@ use crate::routing::models::Store; use crate::row_batches::models::Unnest; use crate::schema_plan::constants::{CDC_PREFIX, CDC_UNCHANGED_COLUMN, MERGE_ROW_COLUMN}; use crate::schema_plan::main::metadata_columns::metadata_columns; +use crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings; use crate::schema_plan::main::plan_schema::plan_schema; use crate::schema_plan::models::Blocked; use crate::schema_plan::models::ColumnChange; @@ -220,6 +222,24 @@ pub(crate) fn blocked_plan(reasons: Vec) -> SchemaPlan { } } +/// `plan` with the declared columns its files table's sampled files lack as its spec's `missing_columns`, each a warning as it loads as NULL; under `on_schema_change = "fail"` the table is blocked instead. A table blocked already, and any other, is returned as it is. +fn with_missing_columns(mut plan: TablePlan) -> TablePlan { + let unsampled = match &plan.spec.files { + Some(files) if !files.unsampled.is_empty() && plan.schema.blocked.is_none() => { + files.unsampled.clone() + } + _ => return plan, + }; + match missing_columns_warnings(&unsampled, FILES_MISSING_COLUMN, plan.spec.on_schema_change) { + Ok(warnings) => { + plan.schema.warnings.extend(warnings); + plan.spec.missing_columns = unsampled; + } + Err(problem) => plan.schema = blocked_plan(vec![problem]), + } + plan +} + /// A table that cannot load, for `reasons`. pub(crate) fn blocked_table(spec: &TableSpec, reasons: Vec) -> TablePlan { TablePlan { @@ -244,7 +264,7 @@ pub(crate) fn blocked_table(spec: &TableSpec, reasons: Vec) -> TablePlan } } -/// One table's plan against its live destination table; a Python table's live columns count as its source's, since it has no catalog. A setting naming no column blocks the table after its live table is read, so a table that exists still counts as existing for `new_tables` and the first-load check. +/// One table's plan against its live destination table; a Python table's live columns count as its source's, since it has no catalog, and a files table's declared columns its sampled files lack follow `on_schema_change`. A setting naming no column blocks the table after its live table is read, so a table that exists still counts as existing for `new_tables` and the first-load check. pub(crate) async fn plan_table( spec: &TableSpec, destination: &Destination, @@ -273,7 +293,8 @@ pub(crate) async fn plan_table( plan.schema.warnings.extend(ignored_batch(&plan)); plan.schema.warnings.extend(ignored_concurrency(&plan)); let plan = with_run_log(plan, destination, options.reload || options.ranged()).await?; - with_transform_version(plan, destination).await + let plan = with_transform_version(plan, destination).await?; + Ok(with_missing_columns(plan)) } /// Why the plan cannot write `spec` as `schema` plans it, when nothing blocked it first: its `cursor_column`, when `unwritten_cursor` names it, or a `newest_by` column is not among the columns written, or has no order. A Python table's columns are known only once it yields, so its `newest_by` is not checked here. diff --git a/crates/sqlload/src/loader/constants.rs b/crates/sqlload/src/loader/constants.rs index 640fb70ad..8ce7376f6 100644 --- a/crates/sqlload/src/loader/constants.rs +++ b/crates/sqlload/src/loader/constants.rs @@ -217,3 +217,10 @@ pub const CATALOG_CONFLICT: &str = "Catalog write-write conflict"; /// How often a table's create refused for [`CATALOG_CONFLICT`] is tried, 20 ms apart: the other connection's create commits within moments. pub const CATALOG_CONFLICT_TRIES: u32 = 10; + +/// Where a files table's declared columns are looked for at plan, and what happens to one none of them holds, for [`missing_columns_warnings`](crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings). +pub const FILES_MISSING_COLUMN: (&str, &str) = + ("the sampled files", "rows without it load as NULL"); + +/// Where a Python table's declared columns are looked for once it has loaded, and what happened to one none of them held. +pub const PYTHON_MISSING_COLUMN: (&str, &str) = ("the rows", "it loaded as NULL"); diff --git a/crates/sqlload/src/loader/main/_load_table.rs b/crates/sqlload/src/loader/main/_load_table.rs index b0418d000..ec96dc37e 100644 --- a/crates/sqlload/src/loader/main/_load_table.rs +++ b/crates/sqlload/src/loader/main/_load_table.rs @@ -4,12 +4,13 @@ use crate::adapters::dispatch::models::Destination; use crate::batch_plan::main::source_readers::source_readers; use crate::loader::_helpers::publish::publish_table; use crate::loader::_helpers::sources::open_source; -use crate::loader::constants::NO_PYTHON_HOST; +use crate::loader::constants::{FILES_MISSING_COLUMN, NO_PYTHON_HOST}; use crate::loader::errors::LoaderError; use crate::loader::main::_load_python::load_python; use crate::loader::models::{LoadRun, PythonLoad, SourceReader, TableLoaded, TablePlan}; use crate::row_deletes::main::apply_tombstones::apply_tombstones; use crate::row_deletes::main::scan_plan::scan_plan; +use crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings; use crate::time_text::main::now_utc_text::now_utc_text; /// Load one table; returns its name as reported and what the load did. @@ -47,10 +48,8 @@ pub(in crate::loader) async fn load_one( let reader = open_source(project, source, source_readers(planned)).await?; let loaded = publish_table(&reader, planned, (destination, run)).await?; let note = marked_rows(&reader, planned, (destination, run), loaded.note.clone()); - TableLoaded { - note: note.await?, - ..loaded - } + let note = note.await?; + with_files_missing(planned, TableLoaded { note, ..loaded }) } }; Ok((name, loaded)) @@ -79,3 +78,16 @@ async fn marked_rows( .collect(); Ok((!notes.is_empty()).then(|| notes.join(" "))) } + +/// What a files table's load did, `loaded`, with the declared columns its plan found missing and their warnings. +fn with_files_missing(planned: &TablePlan, mut loaded: TableLoaded) -> TableLoaded { + let spec = &planned.spec; + let warnings = missing_columns_warnings( + &spec.missing_columns, + FILES_MISSING_COLUMN, + spec.on_schema_change, + ); + loaded.warnings.extend(warnings.unwrap_or_default()); + loaded.missing_columns = spec.missing_columns.clone(); + loaded +} diff --git a/crates/sqlload/src/loader/models.rs b/crates/sqlload/src/loader/models.rs index 3b6a0aeed..b99f5aa1b 100644 --- a/crates/sqlload/src/loader/models.rs +++ b/crates/sqlload/src/loader/models.rs @@ -249,6 +249,8 @@ pub struct TableSpec { pub parses: BTreeMap, /// The zone of the times without an offset that a parse without its own `tz` reads, and whose setting it is; `None` reads them as UTC. pub timezone: Option<(chrono_tz::Tz, SettingOrigin)>, + /// The declared columns the data lacks, as `columns` names them: a files table's pins no sampled file holds, found at plan. Each loads as NULL at its declared type, with a warning, unless `on_schema_change = "fail"` refuses the table; never dropped. A Python table's are found only as it loads (see [`TableLoaded::missing_columns`]). + pub missing_columns: Vec, } impl TableSpec { @@ -428,8 +430,10 @@ pub struct FilesSource { pub encoding: FilesEncoding, /// Column names and patterns JSON and CSV reads check keys and headers against. pub checks: TextChecks, - /// Notes `plan` shows on the table, such as pinned columns no sampled file has. + /// Notes `plan` shows on the table, such as loader columns dropped from the files. pub notes: Vec, + /// The columns `columns` pins that no sampled file holds, as `columns` names them; `on_schema_change` decides whether the table loads them as NULL (see [`TableSpec::missing_columns`]). + pub unsampled: Vec, /// `copy_to_internal_stage`: files no external stage reads are uploaded unchanged to an internal stage, and loaded from there by the warehouse. pub copy_to_internal_stage: bool, /// How each file is read for its table's `transform`; `None` without one, when `table`'s columns are the files'. @@ -710,6 +714,20 @@ pub struct UnreadSharing { } impl ProjectPlan { + /// Each table that can load whose declared columns the data lacks, with those columns, which load as NULL; a Python table's are known only once it loads. + pub fn missing_columns(&self) -> Vec { + self.tables + .iter() + .filter(|table| { + table.schema.blocked.is_none() && !table.spec.missing_columns.is_empty() + }) + .map(|table| MissingColumns { + table: table.outcome_name(), + columns: table.spec.missing_columns.clone(), + }) + .collect() + } + /// Whether everything that stops the plan is something a rerun may get past: no table is blocked, and every problem is a source that could not be reached. pub fn only_retryable_problems(&self) -> bool { self.tables @@ -935,6 +953,14 @@ impl TableOutcome { } } + /// The declared columns the data lacked, which loaded as NULL; none when the table failed. + pub fn missing_columns(&self) -> Vec { + match &self.loaded { + Ok(loaded) => loaded.missing_columns.clone(), + Err(_) => Vec::new(), + } + } + /// Whether this table needs nothing a rerun cannot give it: it loaded, or its failure is retryable. pub fn passes_on_rerun(&self) -> bool { match &self.loaded { @@ -967,8 +993,10 @@ pub struct TableLoaded { pub transforms: Vec, /// A line per column `rename` named or numbering numbered. pub names: Vec, - /// What the load warns of: a Python table's rows outside the cursor window it skipped or loaded. + /// What the load warns of: a Python table's rows outside the cursor window it skipped or loaded, and declared columns the data lacked. pub warnings: Vec, + /// The declared columns the data lacked, which loaded as NULL at their declared types: a files table's from its plan, a Python table's from the rows it yielded. + pub missing_columns: Vec, } /// What a load's reads need to run a table's `transform`: the host, and where each call's time goes. @@ -1443,6 +1471,9 @@ pub struct PlanView { pub skipped: Vec, pub errors: Vec, pub warnings: Vec, + /// Each table to load whose declared columns the data lacks, which load as NULL; left out when there is none. A Python table's are known only once it loads. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub missing_columns: Vec, /// How long each connection and discovery took before the plan. pub phases: Vec, /// The run's memory budget and how it is shared. @@ -1452,6 +1483,15 @@ pub struct PlanView { pub memory_asks: bool, } +/// A table's declared columns that the data lacks, as `plan --json` lists them. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct MissingColumns { + /// The table, named as a load's result names it. + pub table: String, + /// The columns, as `columns` names them. + pub columns: Vec, +} + /// One line of the tally `apply` and `load` end with: `created`, `altered`, `loaded` or `failed`, the object, and what happened. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TallyLine { @@ -1569,6 +1609,9 @@ pub struct TableResult { /// What the load warns of, such as rows outside a cursor window; left out when there is nothing. #[serde(skip_serializing_if = "Vec::is_empty")] pub warnings: Vec, + /// The declared columns the data lacked, which loaded as NULL at their declared types; left out when there is none. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub missing_columns: Vec, /// The most memory the process held while the table loaded, in bytes; only under `--memory-per-table`. #[serde(skip_serializing_if = "Option::is_none")] pub peak_memory_bytes: Option, diff --git a/crates/sqlload/src/loader/tests/helpers.rs b/crates/sqlload/src/loader/tests/helpers.rs index 0ec01cee1..5960697b9 100644 --- a/crates/sqlload/src/loader/tests/helpers.rs +++ b/crates/sqlload/src/loader/tests/helpers.rs @@ -679,6 +679,7 @@ fn files_spec(store: StoreKind) -> Result { encoding: FilesEncoding::default(), checks: TextChecks::default(), notes: Vec::new(), + unsampled: Vec::new(), copy_to_internal_stage: false, transform: None, archive: None, diff --git a/crates/sqlload/src/loader/tests/test_python_columns.rs b/crates/sqlload/src/loader/tests/test_python_columns.rs index 4cd37b365..ca6be9cdd 100644 --- a/crates/sqlload/src/loader/tests/test_python_columns.rs +++ b/crates/sqlload/src/loader/tests/test_python_columns.rs @@ -2,14 +2,17 @@ use crate::column_types::models::ColumnType; use crate::column_types::models::Warehouse; use crate::load_naming::models::Naming; use crate::loader::_helpers::python::fitting_type; +use crate::loader::constants::FILES_MISSING_COLUMN; use crate::loader::tests::helpers::{ crossed_schema, inferred_columns, integer_code, live_paths, lower_case_rows, problems_for, spelling, }; use crate::loader::tests::test_types::{ ChildPathsTestCase, DeclaredProblemsTestCase, FittingTypeTestCase, InferredTableTestCase, - SourceSpellingTestCase, + MissingColumnsTestCase, SourceSpellingTestCase, }; +use crate::project::models::OnSchemaChange; +use crate::schema_plan::main::missing_columns_warnings::missing_columns_warnings; #[test] fn given_an_inferred_and_a_live_type_when_choosing_then_the_live_type_wins_when_the_values_fit() { @@ -289,3 +292,60 @@ fn given_live_child_tables_when_reading_their_paths_then_each_warehouses_spellin } Ok(()) } + +#[test] +fn given_declared_columns_the_data_lacks_when_on_schema_change_decides_then_each_warns_or_the_table_fails() + { + let test_cases = [ + MissingColumnsTestCase { + description: "append_new_columns loads each as NULL, with a warning", + missing: &["coupon", "region"], + on_schema_change: OnSchemaChange::AppendNewColumns, + expected_result: Ok(&[ + "declared column coupon is in none of the sampled files, so rows without it load as NULL", + "declared column region is in none of the sampled files, so rows without it load as NULL", + ]), + }, + MissingColumnsTestCase { + description: "ignore loads it as NULL too, with a warning", + missing: &["coupon"], + on_schema_change: OnSchemaChange::Ignore, + expected_result: Ok(&[ + "declared column coupon is in none of the sampled files, so rows without it load as NULL", + ]), + }, + MissingColumnsTestCase { + description: "fail refuses the table", + missing: &["coupon"], + on_schema_change: OnSchemaChange::Fail, + expected_result: Err( + "declared column coupon is in none of the sampled files and on_schema_change = \"fail\"; add it to the data, or remove it from columns", + ), + }, + MissingColumnsTestCase { + description: "fail with nothing missing refuses nothing", + missing: &[], + on_schema_change: OnSchemaChange::Fail, + expected_result: Ok(&[]), + }, + ]; + for test_case in test_cases { + let missing: Vec = test_case + .missing + .iter() + .map(|name| (*name).to_owned()) + .collect(); + let warned = + missing_columns_warnings(&missing, FILES_MISSING_COLUMN, test_case.on_schema_change); + let actual = warned + .as_ref() + .map(|lines| lines.iter().map(String::as_str).collect::>()) + .map_err(String::as_str); + assert_eq!( + actual, + test_case.expected_result.map(<[&str]>::to_vec), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlload/src/loader/tests/test_types.rs b/crates/sqlload/src/loader/tests/test_types.rs index be5764205..010e9b0e9 100644 --- a/crates/sqlload/src/loader/tests/test_types.rs +++ b/crates/sqlload/src/loader/tests/test_types.rs @@ -298,3 +298,11 @@ pub(crate) struct SelectedReaderTestCase { /// Why SQLLoad reads the rows instead, as `plan` shows it. pub(crate) expected_reason: Option<&'static str>, } + +pub(crate) struct MissingColumnsTestCase { + pub(crate) description: &'static str, + pub(crate) missing: &'static [&'static str], + pub(crate) on_schema_change: crate::project::models::OnSchemaChange, + /// The warnings, or the problem under `"fail"`. + pub(crate) expected_result: Result<&'static [&'static str], &'static str>, +} diff --git a/crates/sqlload/src/loader/tests/test_view_lines.rs b/crates/sqlload/src/loader/tests/test_view_lines.rs index 503c86d89..f86ee5783 100644 --- a/crates/sqlload/src/loader/tests/test_view_lines.rs +++ b/crates/sqlload/src/loader/tests/test_view_lines.rs @@ -132,6 +132,7 @@ fn given_a_plan_view_when_printing_it_then_it_follows_the_sqb_plan_layout() { skipped: Vec::new(), errors: plan_items(test_case.errors), warnings: plan_items(test_case.warnings), + missing_columns: Vec::new(), phases: Vec::new(), memory: test_case.memory.map(str::to_owned), memory_asks: false, diff --git a/crates/sqlload/src/schema_plan/main/missing_columns_warnings.rs b/crates/sqlload/src/schema_plan/main/missing_columns_warnings.rs new file mode 100644 index 000000000..0991fe871 --- /dev/null +++ b/crates/sqlload/src/schema_plan/main/missing_columns_warnings.rs @@ -0,0 +1,28 @@ +//! What `on_schema_change` makes of declared columns the data lacks: each loads as NULL at its declared type with a warning, unless `"fail"` refuses the table; a declared column is never dropped. + +use crate::project::models::OnSchemaChange; + +/// What `on_schema_change` makes of the declared columns `missing` that the data lacks (`place`, as `the sampled files`, saying where they were looked for, and `loads` what happens to them): a warning for each, as the column loads as NULL at its declared type; or, under `"fail"`, why the table cannot load. Nothing is missing, nothing is said. +pub fn missing_columns_warnings( + missing: &[String], + (place, loads): (&str, &str), + on_schema_change: OnSchemaChange, +) -> Result, String> { + let lines = missing + .iter() + .map(|name| format!("declared column {name} is in none of {place}")); + match on_schema_change { + _ if missing.is_empty() => Ok(Vec::new()), + OnSchemaChange::Fail => Err(lines + .map(|line| { + format!( + "{line} and on_schema_change = \"fail\"; add it to the data, or remove it from columns" + ) + }) + .collect::>() + .join("; ")), + OnSchemaChange::AppendNewColumns | OnSchemaChange::Ignore => { + Ok(lines.map(|line| format!("{line}, so {loads}")).collect()) + } + } +} diff --git a/crates/sqlload/src/schema_plan/main/mod.rs b/crates/sqlload/src/schema_plan/main/mod.rs index 343f04ec8..4a66819c0 100644 --- a/crates/sqlload/src/schema_plan/main/mod.rs +++ b/crates/sqlload/src/schema_plan/main/mod.rs @@ -1,2 +1,3 @@ pub mod metadata_columns; +pub mod missing_columns_warnings; pub mod plan_schema; diff --git a/crates/sqlload/tests/loader/helpers.rs b/crates/sqlload/tests/loader/helpers.rs index 3165facca..576de8679 100644 --- a/crates/sqlload/tests/loader/helpers.rs +++ b/crates/sqlload/tests/loader/helpers.rs @@ -321,6 +321,16 @@ pub(crate) fn parquet_bytes(file: &ParquetFile) -> Result Ok(bytes::Bytes::from(buffer)) } +/// Two rows of `id` and `score` as a Parquet file, whatever `_text` says: a text files scenario's Parquet file. +pub(crate) fn two_scores_parquet(_text: &str) -> Result { + parquet_bytes(&ParquetFile { + key: "part-0.parquet", + ids: &[1, 2], + score: 1.0, + extra: None, + }) +} + /// A `delete_insert` files source into DuckDB with one partition of `test_case.files` files that alone have an `extra` column (outside the newest files the plan samples), then that partition's neighbour rewritten; the check query's result. pub(crate) async fn run_large_partition( directory: &std::path::Path, diff --git a/crates/sqlload/tests/loader/test_text_files_to_duckdb.rs b/crates/sqlload/tests/loader/test_text_files_to_duckdb.rs index a9443737d..0fa4651c3 100644 --- a/crates/sqlload/tests/loader/test_text_files_to_duckdb.rs +++ b/crates/sqlload/tests/loader/test_text_files_to_duckdb.rs @@ -3,7 +3,7 @@ use sqlload_testkit::seaweedfs::main::start_seaweedfs::start_seaweedfs; use crate::helpers::{ after_sample, codes_after_sample, duckdb_text, gzip, local_store, plain, run_async, - run_sqlload, run_text_files_scenario, seaweedfs_store, words, zstd, + run_sqlload, run_text_files_scenario, seaweedfs_store, two_scores_parquet, words, zstd, }; use crate::test_types::{ FilesSettingsChangeTestCase, PipedOutputTestCase, TargetSettingsFilesTestCase, TextFile, @@ -146,6 +146,55 @@ const NO_ROWS: &str = "SELECT CAST(count(*) AS VARCHAR) FROM raw.scores"; const NO_TABLE: &str = "SELECT CAST(count(*) AS VARCHAR) FROM information_schema.tables WHERE table_name = 'scores'"; +/// Two NDJSON rows with no `coupon`. +const TWO_ROWS_NDJSON: TextFile = TextFile { + key: "part-0.ndjson", + contents: "{\"id\":1}\n{\"id\":2}\n", + encode: plain, +}; + +/// The same two rows as Parquet. +const TWO_ROWS_PARQUET: TextFile = TextFile { + key: "part-0.parquet", + contents: "", + encode: two_scores_parquet, +}; + +/// Rows, rows with a `coupon`, and the `coupon` column's type. +const MISSING_COUPON_CHECK: &str = "SELECT count(*) || ',' || count(coupon) || ',' || (SELECT data_type FROM information_schema.columns WHERE table_name = 'scores' AND column_name = 'coupon') FROM raw.scores"; + +const MISSING_COUPON_WARNING: &str = + "declared column coupon is in none of the sampled files, so rows without it load as NULL"; + +const MISSING_COUPON_FAILURE: &str = + "declared column coupon is in none of the sampled files and on_schema_change = \"fail\""; + +/// One run of two rows without `coupon`, whose plan warns of it. +const NDJSON_WARNED: &[TextFilesRun] = &[TextFilesRun { + files: &[TWO_ROWS_NDJSON], + expected_error: "", + expected_plan: MISSING_COUPON_WARNING, +}]; + +/// One run of two rows without `coupon`, whose plan and load fail of it. +const NDJSON_FAILED: &[TextFilesRun] = &[TextFilesRun { + files: &[TWO_ROWS_NDJSON], + expected_error: MISSING_COUPON_FAILURE, + expected_plan: MISSING_COUPON_FAILURE, +}]; + +const PARQUET_WARNED: &[TextFilesRun] = &[TextFilesRun { + files: &[TWO_ROWS_PARQUET], + expected_error: "", + expected_plan: MISSING_COUPON_WARNING, +}]; + +const PARQUET_FAILED: &[TextFilesRun] = &[TextFilesRun { + files: &[TWO_ROWS_PARQUET], + expected_error: MISSING_COUPON_FAILURE, + expected_plan: MISSING_COUPON_FAILURE, +}]; + #[test] fn given_json_and_csv_files_when_loading_into_duckdb_then_rows_partitions_and_json_load() -> Result<(), String> { @@ -301,7 +350,7 @@ fn given_json_and_csv_files_when_loading_into_duckdb_then_rows_partitions_and_js runs: &[TextFilesRun { files: &[LATE_KEY], expected_error: "", - expected_plan: "note pinned column coupon_code was not seen in the sampled files (check the name)", + expected_plan: "declared column coupon_code is in none of the sampled files, so rows without it load as NULL", }], check_query: "SELECT count(*) || ',' || count(coupon_code) || ',' || max(coupon_code) FROM raw.scores", expected_result: "10001,1,x", @@ -325,7 +374,7 @@ fn given_json_and_csv_files_when_loading_into_duckdb_then_rows_partitions_and_js runs: &[TextFilesRun { files: &[LATE_KEY], expected_error: "", - expected_plan: "note pinned column coupon_code was not seen in the sampled files", + expected_plan: "declared column coupon_code is in none of the sampled files", }], check_query: "SELECT count(coupon_code) || ',' || (max(coupon_code) = sha256('x')) FROM raw.scores", expected_result: "1,true", @@ -517,6 +566,84 @@ fn given_json_and_csv_files_when_loading_into_duckdb_then_rows_partitions_and_js }) } +#[test] +fn given_a_declared_column_missing_from_the_files_when_loading_then_on_schema_change_decides() +-> Result<(), String> { + let test_cases = [ + TextFilesScenarioTestCase { + description: "NDJSON, append_new_columns: the declared column loads as NULL at its declared type, with a warning", + store: local_store, + settings: "format = \"ndjson\"\nwrite_strategy = \"append\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: NDJSON_WARNED, + check_query: MISSING_COUPON_CHECK, + expected_result: "2,0,DATE", + }, + TextFilesScenarioTestCase { + description: "NDJSON, ignore: the declared column still loads as NULL at its declared type", + store: local_store, + settings: "format = \"ndjson\"\nwrite_strategy = \"append\"\non_schema_change = \"ignore\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: NDJSON_WARNED, + check_query: MISSING_COUPON_CHECK, + expected_result: "2,0,DATE", + }, + TextFilesScenarioTestCase { + description: "NDJSON, fail: the plan refuses the table and nothing loads", + store: local_store, + settings: "format = \"ndjson\"\nwrite_strategy = \"append\"\non_schema_change = \"fail\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: NDJSON_FAILED, + check_query: NO_TABLE, + expected_result: "0", + }, + TextFilesScenarioTestCase { + description: "Parquet read by DuckDB, append_new_columns: the declared column loads as NULL at its declared type, with a warning", + store: local_store, + settings: "format = \"parquet\"\nwrite_strategy = \"append\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: PARQUET_WARNED, + check_query: MISSING_COUPON_CHECK, + expected_result: "2,0,DATE", + }, + TextFilesScenarioTestCase { + description: "Parquet read by SQLLoad, append_new_columns: the same", + store: local_store, + settings: "format = \"parquet\"\nwrite_strategy = \"append\"\ntest_loader_route = true\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: PARQUET_WARNED, + check_query: MISSING_COUPON_CHECK, + expected_result: "2,0,DATE", + }, + TextFilesScenarioTestCase { + description: "Parquet, ignore: the declared column still loads as NULL at its declared type", + store: local_store, + settings: "format = \"parquet\"\nwrite_strategy = \"append\"\non_schema_change = \"ignore\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: PARQUET_WARNED, + check_query: MISSING_COUPON_CHECK, + expected_result: "2,0,DATE", + }, + TextFilesScenarioTestCase { + description: "Parquet, fail: the plan refuses the table and nothing loads", + store: local_store, + settings: "format = \"parquet\"\nwrite_strategy = \"append\"\non_schema_change = \"fail\"\n[sources.scores.tables.scores]\ncolumns = { coupon = \"date\" }\n", + runs: PARQUET_FAILED, + check_query: NO_TABLE, + expected_result: "0", + }, + ]; + run_async(|| async move { + for test_case in test_cases { + let directory = + std::env::temp_dir().join(format!("sqlload-missing-{}", uuid::Uuid::new_v4())); + let result = run_text_files_scenario("", &directory, &test_case).await; + let _ = std::fs::remove_dir_all(&directory); + assert_eq!( + result?.as_deref(), + Some(test_case.expected_result), + "{}", + test_case.description + ); + } + Ok(()) + }) +} + #[test] fn given_plan_and_load_piped_when_colour_is_left_on_then_no_output_has_an_escape_code() -> Result<(), String> { diff --git a/packages/sqlload/tests/test_python_sources.py b/packages/sqlload/tests/test_python_sources.py index 4cd67aaba..6077e71cb 100644 --- a/packages/sqlload/tests/test_python_sources.py +++ b/packages/sqlload/tests/test_python_sources.py @@ -5,6 +5,7 @@ import subprocess import sys import textwrap +from datetime import date from decimal import Decimal from pathlib import Path from typing import Any @@ -888,6 +889,96 @@ def test_given_a_pin_added_to_an_existing_table_when_planning_then_the_add_colum assert "add column code varchar(8) -> VARCHAR (the length limit is not enforced)" in planned.stdout, planned.stdout +@pytest.mark.parametrize( + "settings", + ["write_strategy='append'", "write_strategy='append', on_schema_change='ignore'"], + ids=["append_new_columns", "ignore"], +) +def test_given_a_declared_column_no_row_has_when_loading_then_it_loads_as_null_at_its_declared_type_with_a_warning(tmp_path: Path, settings: str) -> None: + project = make_project(tmp_path, DUCKDB_PROJECT, f"shop.table(description='Test table.', {settings}, columns={{'coupon': 'date'}})(rows)\n") + give(project, "rows", [{"id": 1}, {"id": 2}]) + done = load(project, "--json") + table = json.loads(done.stdout)["tables"][0] + assert table["missing_columns"] == ["coupon"], done.stdout + assert table["warnings"] == ["declared column coupon is in none of the rows, so it loaded as NULL"], done.stdout + assert query(project, 'SELECT count(*), count(coupon) FROM "RAW"."shop__rows"') == [(2, 0)] + assert query(project, "SELECT data_type FROM information_schema.columns WHERE table_name = 'shop__rows' AND column_name = 'coupon'") == [("DATE",)] + + +def test_given_a_declared_column_no_row_has_and_on_schema_change_fail_when_loading_then_the_table_fails_and_nothing_loads(tmp_path: Path) -> None: + project = make_project(tmp_path, DUCKDB_PROJECT, "shop.table(description='Test table.', write_strategy='append', on_schema_change='fail', columns={'coupon': 'date'})(rows)\n") + give(project, "rows", [{"id": 1}, {"id": 2}]) + done = sqlload(project, "load") + assert done.returncode == 1, done.stdout + done.stderr + assert 'declared column coupon is in none of the rows and on_schema_change = "fail"' in done.stdout + done.stderr, done.stdout + done.stderr + assert query(project, "SELECT count(*) FROM information_schema.tables WHERE table_name = 'shop__rows'") == [(0,)] + + +@pytest.mark.parametrize( + ("first", "expected_rows"), + [(None, None), ([{"id": 1, "coupon": "2026-01-01"}], [(1, date(2026, 1, 1))])], + ids=["first load", "existing table"], +) +def test_given_a_replace_whose_rows_lack_a_declared_column_under_on_schema_change_fail_when_loading_then_the_old_table_stays_as_it_was( + tmp_path: Path, first: list[dict[str, Any]] | None, expected_rows: list[tuple[Any, ...]] | None +) -> None: + tables = "shop.table(description='Test table.', write_strategy='replace', {settings}columns={{'coupon': 'date'}})(rows)\n" + project = make_project(tmp_path, DUCKDB_PROJECT, tables.format(settings="")) + if first is not None: + give(project, "rows", first) + load(project) + (project / "sources" / "shop.py").write_text(SHOP_MODULE.replace("{tables}", tables.format(settings="on_schema_change='fail', "))) + give(project, "rows", [{"id": 7}, {"id": 8}]) + done = sqlload(project, "load") + assert done.returncode == 1, done.stdout + done.stderr + assert 'declared column coupon is in none of the rows and on_schema_change = "fail"' in done.stdout + done.stderr, done.stdout + done.stderr + if expected_rows is None: + assert query(project, "SELECT count(*) FROM information_schema.tables WHERE table_name = 'shop__rows'") == [(0,)] + else: + assert query(project, 'SELECT id, coupon FROM "RAW"."shop__rows" ORDER BY id') == expected_rows + + +FILES_SOURCE = """ +[connections.drop] +kind = "filesystem" +root = "drop" + +[sources.events] +kind = "files" +connection = "drop" +path = "events/" +format = "ndjson" +description = "Test table." +write_strategy = "append" + +[sources.events.tables.events] +columns = { coupon = "date" } +""" + + +def test_given_a_files_table_declaring_a_column_no_file_has_when_planning_and_loading_with_json_then_both_list_it(tmp_path: Path) -> None: + project = make_project(tmp_path, DUCKDB_PROJECT + FILES_SOURCE, "") + (project / "drop" / "events").mkdir(parents=True) + (project / "drop" / "events" / "part-0.ndjson").write_text('{"id": 1}\n') + planned = sqlload(project, "plan", "--json", "events") + assert planned.returncode == 0, planned.stdout + planned.stderr + missing = json.loads(planned.stdout)["missing_columns"] + assert [entry["columns"] for entry in missing] == [["coupon"]], planned.stdout + done = load(project, "--json", "events") + table = json.loads(done.stdout)["tables"][0] + assert (table["table"], table["missing_columns"]) == (missing[0]["table"], ["coupon"]), done.stdout + assert table["warnings"] == ["declared column coupon is in none of the sampled files, so rows without it load as NULL"], done.stdout + + +def test_given_a_declared_column_only_null_in_every_row_when_loading_then_it_keeps_its_declared_type_without_a_warning(tmp_path: Path) -> None: + project = make_project(tmp_path, DUCKDB_PROJECT, "shop.table(description='Test table.', write_strategy='append', on_schema_change='fail', columns={'coupon': 'date'})(rows)\n") + give(project, "rows", [{"id": 1, "coupon": None}, {"id": 2, "coupon": None}]) + done = load(project, "--json") + table = json.loads(done.stdout)["tables"][0] + assert ("missing_columns" in table, "warnings" in table) == (False, False), done.stdout + assert query(project, "SELECT data_type FROM information_schema.columns WHERE table_name = 'shop__rows' AND column_name = 'coupon'") == [("DATE",)] + + @pytest.mark.parametrize( ("settings", "rows", "message"), [ diff --git a/website/src/content/docs/docs/concepts/contracts.mdx b/website/src/content/docs/docs/concepts/contracts.mdx index 21aaa9c3a..e49082e37 100644 --- a/website/src/content/docs/docs/concepts/contracts.mdx +++ b/website/src/content/docs/docs/concepts/contracts.mdx @@ -51,6 +51,41 @@ Objects (1) sqlload apply SQLLoad never drops columns from a destination table. +### Declared columns the data lacks + +A column declared in `columns` that the data doesn't hold follows `on_schema_change` too: + +| `on_schema_change` | A declared column missing from the data | +|--------------------|-----------------------------------------| +| `append_new_columns` (default) | Loads as `NULL` at its declared type, with a warning. | +| `ignore` | Loads as `NULL` at its declared type, with a warning. | +| `fail` | Stops the table. | + +A files table looks for its declared columns in the files `plan` samples (their Parquet footers, or +their JSON and CSV records), so a column only older files hold can still be declared, and loads +where they hold it. With `fail`, such a column fails `plan` even when older files hold it, as no +sampled file does. + +A Python table's columns are known once its function has yielded every row, so the warning comes +with the load, and `fail` stops the table at its end. A `replace` swaps its new rows in only after +the whole load, so the table keeps its old rows; a table the failed load created is dropped again, +unless rows were committed to it. An `append` that committed several times on the way (about every +1 GB, or once per `batch_size` window) keeps the rows those commits loaded; only the rows after the +last commit are left out. + +A name close to one the data holds, such as `Email` for `email`, still fails as a likely typo. + +```console +$ sqlload plan orders +… +Warnings (1) +└── orders + └── declared column coupon is in none of the sampled files, so rows without it load as NULL +``` + +`plan --json` lists the columns under `missing_columns`, one entry per table, and `load --json` on +each table it loaded. The column is never dropped from the table. + ### Wider types A pinned type wider than the live column widens it: