Skip to content
Merged
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
31 changes: 30 additions & 1 deletion crates/sqlload/src/loader/_helpers/destination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<T>(
(feed, load): (&PythonFeed, &PythonLoad<'_>),
result: Result<T, LoaderError>,
) -> Result<T, LoaderError> {
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)
}
1 change: 1 addition & 0 deletions crates/sqlload/src/loader/_helpers/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
})
}

Expand Down
11 changes: 7 additions & 4 deletions crates/sqlload/src/loader/_helpers/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ 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;
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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
})
}

Expand Down
5 changes: 3 additions & 2 deletions crates/sqlload/src/loader/_helpers/render.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
}
}

Expand Down Expand Up @@ -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,
}
}
Expand Down
11 changes: 4 additions & 7 deletions crates/sqlload/src/loader/_helpers/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -1104,12 +1104,8 @@ pub(crate) fn files_source_parts(
table.dropped.join(", ")
)
});
let notes: Vec<String> = 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<String> = dropped.into_iter().collect();
let unsampled = pinned_only.clone();
let typed = table
.columns
.iter()
Expand Down Expand Up @@ -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,
Expand Down
44 changes: 40 additions & 4 deletions crates/sqlload/src/loader/_helpers/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -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;
Expand Down Expand Up @@ -569,6 +571,7 @@ pub(crate) fn build_spec(
transform: None,
parses,
timezone,
missing_columns: Vec::new(),
})
}

Expand Down Expand Up @@ -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<Vec<String>, LoaderError> {
let Some(overrides) = overrides.filter(|_| format != SourceFormat::Parquet) else {
let Some(overrides) = overrides else {
return Ok(Vec::new());
};
let sampled: Vec<&str> = table
Expand Down Expand Up @@ -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<String>, Vec<String>), 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<String> {
let had = |name: &str| {
merged
.fields()
.iter()
.any(|field| field.name().eq_ignore_ascii_case(name))
};
let mut missing: Vec<String> = 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<ReadColumn>, Vec<String>> {
let mut problems: Vec<String> = Vec::new();
Expand Down
25 changes: 23 additions & 2 deletions crates/sqlload/src/loader/_helpers/table_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -220,6 +222,24 @@ pub(crate) fn blocked_plan(reasons: Vec<String>) -> 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<String>) -> TablePlan {
TablePlan {
Expand All @@ -244,7 +264,7 @@ pub(crate) fn blocked_table(spec: &TableSpec, reasons: Vec<String>) -> 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,
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions crates/sqlload/src/loader/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
22 changes: 17 additions & 5 deletions crates/sqlload/src/loader/main/_load_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
}
Loading
Loading