diff --git a/crates/sqlbuild-analysis/src/assembly/target_checks/errors.rs b/crates/sqlbuild-analysis/src/assembly/target_checks/errors.rs index 676d125075..264e78c925 100644 --- a/crates/sqlbuild-analysis/src/assembly/target_checks/errors.rs +++ b/crates/sqlbuild-analysis/src/assembly/target_checks/errors.rs @@ -17,6 +17,12 @@ pub enum TargetError { PreservedLoaderSchema(String), /// A target, by name, whose schema is `preserve` and that names no loader schema. PreservedNodeResults(String), + /// A `preserve` target whose adapter, by name, has no default schema, so the named SQLBuild tables have none. + PreservedOwnTables { + target: String, + adapter: String, + tables: &'static str, + }, /// Two resources that write one relation on a target. DuplicateRelation(DuplicateRelation), } diff --git a/crates/sqlbuild-analysis/src/assembly/target_checks/main/target_error_message.rs b/crates/sqlbuild-analysis/src/assembly/target_checks/main/target_error_message.rs index f9156b712b..74ff99b9f9 100644 --- a/crates/sqlbuild-analysis/src/assembly/target_checks/main/target_error_message.rs +++ b/crates/sqlbuild-analysis/src/assembly/target_checks/main/target_error_message.rs @@ -53,6 +53,16 @@ pub fn target_error_message(error: &TargetError) -> String { results of loaders, assets and checks. Set targets.{target}.loader_schema; \ Python node results are kept there." ), + TargetError::PreservedOwnTables { + target, + adapter, + tables, + } => format!( + "Target '{target}' sets schema = '{PRESERVE_TARGET_VALUE}', so each model keeps its own \ + schema, and the {adapter} adapter has no default schema, so SQLBuild has no schema for \ + its {tables}. Add loader_schema = \"...\" to [targets.{target}] in \ + sqlbuild_project.toml; SQLBuild keeps its own tables there." + ), TargetError::DuplicateRelation(duplicate) => format!( "{} writes {} and {} to the same relation '{}', so one would overwrite the other. \ Set a different alias on one of them.", diff --git a/crates/sqlbuild-analysis/src/assembly/target_checks/tests/test_target_checks.rs b/crates/sqlbuild-analysis/src/assembly/target_checks/tests/test_target_checks.rs index 9378afb426..8eb0be493f 100644 --- a/crates/sqlbuild-analysis/src/assembly/target_checks/tests/test_target_checks.rs +++ b/crates/sqlbuild-analysis/src/assembly/target_checks/tests/test_target_checks.rs @@ -81,6 +81,15 @@ fn given_target_error_when_formatting_then_matches_python_message() { }), expected_message: "The project writes model 'a' and model 'b' to the same relation 'main.orders', so one would overwrite the other. Set a different alias on one of them.", }, + MessageTestCase { + description: "a Snowflake preserve target without a loader schema for its cost history", + error: TargetError::PreservedOwnTables { + target: "prod".to_owned(), + adapter: "snowflake".to_owned(), + tables: "resource cost history", + }, + expected_message: "Target 'prod' sets schema = 'preserve', so each model keeps its own schema, and the snowflake adapter has no default schema, so SQLBuild has no schema for its resource cost history. Add loader_schema = \"...\" to [targets.prod] in sqlbuild_project.toml; SQLBuild keeps its own tables there.", + }, ]; for test_case in test_cases { diff --git a/crates/sqlbuild-python-compile/src/compile_driver/models.rs b/crates/sqlbuild-python-compile/src/compile_driver/models.rs index bdc58049f7..1122439038 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/models.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/models.rs @@ -1,18 +1,25 @@ //! Public records of compile driver. use crate::compile_driver::_helpers::setup::model_free_locations::model_free_locations; +use crate::compile_driver::_helpers::setup::targets::planner_error; use pyo3::IntoPyObjectExt; use pyo3::prelude::Bound; use pyo3::prelude::Py; use pyo3::prelude::PyAny; +use pyo3::prelude::PyAnyMethods; use pyo3::prelude::PyResult; use pyo3::prelude::Python; use pyo3::types::PyBool; use sqlbuild_analysis::assembly::project::types::ObjectKey; -use sqlbuild_analysis::assembly::target_checks::constants::PRESERVE_TARGET_VALUE; +use sqlbuild_analysis::assembly::target_checks::constants::{ + PRESERVE_TARGET_VALUE, PRESERVED_NODE_RESULTS_CODE, +}; +use sqlbuild_analysis::assembly::target_checks::errors::TargetError; +use sqlbuild_analysis::assembly::target_checks::main::target_error_message::target_error_message; use sqlbuild_analysis::job_settings::models::NodeJobSettings; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::records::main::construct::new_record_with::new_record_with; +use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; use std::collections::BTreeMap; @@ -81,6 +88,12 @@ pub struct TargetSettingsValues { } impl TargetSettingsValues { + /// The selected target's name; none without named targets. + #[must_use] + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + /// The resolved schema managed loader data goes to. #[must_use] pub fn loader_schema(&self) -> Option<&str> { @@ -115,6 +128,33 @@ impl TargetSettingsValues { ) } + /// Where SQLBuild keeps its own `tables` for the target, as `node_locations` picks; raises S105 when a `preserve` schema resolves none. + pub fn own_table_locations<'py>( + &self, + adapter: &Bound<'py, PyAny>, + tables: &'static str, + ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)> { + let (database, schema) = self.node_locations(adapter)?; + if !schema.is_none() || self.schema.as_deref() != Some(PRESERVE_TARGET_VALUE) { + return Ok((database, schema)); + } + let target: String = self.name.clone().unwrap_or_default(); + Err(planner_error( + adapter.py(), + target_error_message(&TargetError::PreservedOwnTables { + target: target.clone(), + adapter: native_field(adapter, "adapter_name")?.extract()?, + tables, + }), + PRESERVED_NODE_RESULTS_CODE, + Some(format!( + "to keep SQLBuild's own tables in a schema, set this in sqlbuild_project.toml:\n \ + [targets.{target}]\n \ + loader_schema = \"my_schema\"" + )), + )) + } + /// The `TargetSettings` record: a `preserve` location reads `None` with its flag set. pub fn record<'py>(&self, py: Python<'py>) -> PyResult> { let located = |value: &Option| -> PyResult> { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/completion.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/completion.rs index bef57314eb..344665cb65 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/completion.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/completion.rs @@ -39,6 +39,8 @@ use sqlbuild_python_base::records::main::construct::new_record_with::new_record_ use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_compile::compile_driver::main::setup::plan_has_executable_work::plan_has_executable_work; +use sqlbuild_python_compile::compile_driver::main::setup::project_target_settings::project_target_settings; +use sqlbuild_python_compile::compile_driver::models::TargetSettingsValues; use sqlbuild_python_compile::compile_outputs::main::write_python_check_runtime_target::write_python_check_runtime_target; use sqlbuild_python_compile::compile_outputs::main::write_runtime_target::write_runtime_target; use sqlbuild_python_front::cost_context::main::cost_aware::cost_aware; @@ -63,6 +65,8 @@ pub(crate) struct CostRequest<'py> { pub(crate) started_at: Bound<'py, PyAny>, pub(crate) completed_at: Bound<'py, PyAny>, pub(crate) overrides: Vec<(&'static str, Bound<'py, PyAny>)>, + /// Whether this build ran work whose costs it records, so a `preserve` target needs a schema for them. + pub(crate) records_costs: bool, } /// `finalize_build_cost(BuildCostFinalization(...))`. @@ -82,23 +86,29 @@ fn cost_finalization<'py>( ) -> PyResult> { let py: Python<'py> = context.py(); let project: Bound<'py, PyAny> = native_field(pipeline, "project")?; + let adapter: Bound<'py, PyAny> = context.get("adapter")?; + let target: TargetSettingsValues = project_target_settings( + &context.get("discovered_inputs")?, + &project, + (&context.get("connection_config")?, &adapter), + )?; + let (target_database, target_schema) = + if cost.records_costs && cost_aware(&adapter)? && reports_cost_capability(&adapter)? { + target.own_table_locations(&adapter, "resource cost history")? + } else { + target.node_locations(&adapter)? + }; let mut fields: Vec<(&str, Bound<'py, PyAny>)> = vec![ ("project_dir", context.get("effective_project_dir")?), ("adapter_name", context.get("adapter_name")?), - ("adapter", context.get("adapter")?), + ("adapter", adapter), ("connection_config", context.get("connection_config")?), ( "target_name", native_field(&project, "effective_target_name")?, ), - ( - "target_database", - native_field(&project, "effective_target_database")?, - ), - ( - "target_schema", - native_field(&project, "effective_target_schema")?, - ), + ("target_database", target_database), + ("target_schema", target_schema), ("run_id", native_field(&project, "run_id")?), ("build_status", text(py, cost.status)), ("started_at", cost.started_at), @@ -135,6 +145,7 @@ fn finished_build_cost<'py>( started_at: started_at.clone(), completed_at: completed_at.clone(), overrides, + records_costs: true, }; let adapter: Bound<'py, PyAny> = context.get("adapter")?; if !cost_aware(&adapter)? || !reports_cost_capability(&adapter)? { @@ -196,6 +207,7 @@ pub(crate) fn record_pending_cost<'py>( ("cost_status", cost_status(py, "PENDING")?), ("cost_message", text(py, PENDING_MESSAGE)), ], + records_costs: true, }, )?; Ok(started_at) @@ -305,6 +317,7 @@ fn finalize_no_work(context: &BuildContext<'_>, pipeline: &Bound<'_, PyAny>) -> ("collect", boolean(py, false)), ("had_executable_work", boolean(py, false)), ], + records_costs: false, }, )?; let result: Bound<'_, PyAny> = call_with( @@ -379,6 +392,7 @@ pub(crate) fn finalize_exceptional_cost( ("cost_status", cost_status(py, "PARTIAL")?), ("cost_message", text(py, INTERRUPTED_MESSAGE)), ], + records_costs: true, }, ) })(); diff --git a/crates/sqlbuild-python/src/bindings/_helpers/diff_report/query.rs b/crates/sqlbuild-python/src/bindings/_helpers/diff_report/query.rs index 31ee9916eb..f0741f128b 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/diff_report/query.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/diff_report/query.rs @@ -1,6 +1,5 @@ //! Raw-query `sqb diff`: preparation, artifact materialization, comparison and cleanup. -use sqlbuild_python_base::positional_record; use std::time::Instant; use pyo3::exceptions::PyException; @@ -19,6 +18,7 @@ use crate::bindings::_helpers::command_runtime::connection::resolve_project_conn use crate::bindings::_helpers::diff_report::support::call; use crate::bindings::_helpers::diff_report::support::cli_error; use crate::bindings::_helpers::diff_report::support::error_text; +use crate::bindings::_helpers::diff_report::support::matches_native; use crate::bindings::_helpers::diff_report::support::object; use crate::bindings::_helpers::diff_report::support::progress_line; use crate::bindings::_helpers::diff_report::tolerances::cli_tolerance_overrides; @@ -34,7 +34,8 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_base::types::CompilerDetach; -use sqlbuild_python_compile::compile_attachment::main::effective_target_namespace::effective_target_namespace; +use sqlbuild_python_compile::compile_driver::main::setup::selected_target_settings::selected_target_settings; +use sqlbuild_python_compile::compile_driver::models::TargetSettingsValues; use sqlbuild_python_front::compile_attachment::main::build_effective_runtime_config::build_effective_runtime_config; use sqlbuild_python_front::contracts::main::resolve_effective_adapter_name::resolve_effective_adapter_name; @@ -165,15 +166,17 @@ fn read_only_query( Ok(normalized.to_owned()) } -positional_record! { - extract; - /// The target name, target, database and schema a raw-query diff resolves. - struct ResolvedNamespace<'py> { - target_name: Bound<'py, PyAny>, - _target: Bound<'py, PyAny>, - database: Bound<'py, PyAny>, - schema: Bound<'py, PyAny>, - } +/// A planner refusal, such as S105, as the diff's user error with its own code and help. +fn planner_refusal(py: Python<'_>, error: &PyErr) -> PyResult { + let value = error.value(py); + Ok(user_failure( + py, + DiffUserError { + message: value.getattr("message")?.extract()?, + code: value.getattr("code")?.extract()?, + help: value.getattr("help")?.extract()?, + }, + )) } /// Resolve raw SQL, the active target namespace, the adapter and its connection. @@ -197,17 +200,27 @@ pub(crate) fn prepare_query_diff<'py>( ], )?), )?; - let namespace: Bound<'py, PyAny> = effective_target_namespace( + let runtime: Bound<'py, PyTuple> = build_effective_runtime_config( + discovered, + Some(selected_target.clone()).filter(|value| !value.is_none()), + Some(cli_vars.clone()).filter(|value| !value.is_none()), + ) + .and_then(|value| pyo3::IntoPyObjectExt::into_bound_py_any(value, py))? + .cast_into()?; + let target: TargetSettingsValues = selected_target_settings( (discovered, &selected_target), - (&adapter_name, &config, &adapter), - )? - .into_any(); - let ResolvedNamespace { - target_name, - database, - schema, - .. - }: ResolvedNamespace<'py> = namespace.extract()?; + &adapter_name, + (&config, &runtime.get_item(1)?, &adapter), + )?; + let (database, schema) = target + .own_table_locations(&adapter, "query diff scratch tables") + .map_err( + |error| match matches_native(py, &error, ErrorId::PlannerInput) { + Ok(true) => planner_refusal(py, &error).unwrap_or_else(|failed| failed), + Ok(false) => error, + Err(failed) => failed, + }, + )?; if schema.is_none() { return Err(failure( py, @@ -230,13 +243,6 @@ pub(crate) fn prepare_query_diff<'py>( )?; let left_sql: String = read_only_query(py, &left_sql, "left", &adapter)?; let right_sql: String = read_only_query(py, &right_sql, "right", &adapter)?; - let runtime: Bound<'py, PyTuple> = build_effective_runtime_config( - discovered, - Some(selected_target.clone()).filter(|value| !value.is_none()), - Some(cli_vars.clone()).filter(|value| !value.is_none()), - ) - .and_then(|value| pyo3::IntoPyObjectExt::into_bound_py_any(value, py))? - .cast_into()?; let label = |name: &str, default: &str| -> PyResult { let value: Bound<'py, PyAny> = native_field(request, name)?; let text: String = if value.is_truthy()? { @@ -268,7 +274,7 @@ pub(crate) fn prepare_query_diff<'py>( "right_label", &object(py, label("right_label", "right query")?)?, ), - ("selected_target", &target_name), + ("selected_target", &object(py, target.name())?), ("database", &database), ("schema", &schema), ("run_id", &runtime.get_item(2)?), diff --git a/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_phases.rs b/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_phases.rs index 804ecedbca..666ac927ed 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_phases.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_phases.rs @@ -5,6 +5,7 @@ use sqlbuild_host::entries::models::{AdapterHost, ExecutorHost}; use sqlbuild_python_base::boundary::main::keywords::keywords; use sqlbuild_python_base::native_host::main::connection_failure::connection_failure; use sqlbuild_python_compile::compile_driver::main::setup::build_compiled_project::build_compiled_project; +use sqlbuild_python_compile::compile_driver::main::setup::project_target_settings::project_target_settings; use std::time::Instant; use pyo3::IntoPyObject; @@ -14,7 +15,7 @@ use pyo3::types::{PyBool, PyDict, PyDictMethods}; use crate::bindings::_helpers::command_runtime::invocation::resolve_adapter_connection_context; use crate::bindings::_helpers::janitor::janitor_facts::Warehouse; use crate::bindings::_helpers::janitor::janitor_planning::{ - JanitorSettings, RelationScope, build_plan, + JanitorSettings, OwnTablesLocation, RelationScope, build_plan, }; use crate::bindings::_helpers::janitor::janitor_usage::{UsageSettings, check_janitor_usage}; use sqlbuild_python_base::boundary::main::call_with::call_with; @@ -237,6 +238,16 @@ pub(crate) fn build_janitor_execution_plan<'py>( let janitor: Bound<'py, PyAny> = native_field(invocation, "discovered_inputs")? .getattr("project_config")? .getattr("janitor")?; + let (own_database, own_schema) = project_target_settings( + &native_field(invocation, "discovered_inputs")?, + &compiled.project, + (&compiled.connection_config, &compiled.adapter), + )? + .node_locations(&compiled.adapter)?; + let own_tables: OwnTablesLocation = own_schema + .extract::>()? + .map(|schema| Ok::<_, PyErr>((own_database.extract()?, schema))) + .transpose()?; let plan: Bound<'py, PyAny> = within( &lifecycle(py, ("janitor", "janitor_candidate_planning"))?, |lifecycle| { @@ -255,6 +266,7 @@ pub(crate) fn build_janitor_execution_plan<'py>( adapter: compiled.adapter.clone(), connection: connection.clone(), }, + own_tables.clone(), ), &JanitorSettings { retention_days: native_field(settings, "retention_days")?.extract()?, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_planning.rs b/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_planning.rs index aa673d42cc..0b5021f9a0 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_planning.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/janitor/janitor_planning.rs @@ -63,6 +63,9 @@ pub(crate) struct JanitorSettings { pub(crate) early_old_name_view_drops: Vec, } +/// The `(database, schema)` SQLBuild keeps its own tables in for the target, when it has one. +pub(crate) type OwnTablesLocation = Option<(Option, String)>; + /// Relations scanned or protected beyond the project's target schemas. pub(crate) struct RelationScope { pub(crate) scan_keys: Vec, @@ -139,14 +142,14 @@ fn candidate_records<'py>(candidates: &[Candidate<'py>]) -> PyResult( - project: &Bound<'py, PyAny>, + (project, own_schema): (&Bound<'py, PyAny>, Option), warehouse: &Warehouse<'py>, now: &Bound<'py, PyAny>, ) -> PyResult>> { let py: Python<'py> = warehouse.py(); - let Some(schema) = target_location(project, "effective_target_schema")? else { + let Some(schema) = own_schema else { return Ok(Vec::new()); }; let max_age: Bound<'py, PyAny> = days(py, LEFTOVER_REVIEW_SCHEMA_AGE_DAYS)?; @@ -203,9 +206,9 @@ fn artifact_only_plan<'py>( ) } -/// Build the desired-versus-warehouse cleanup plan for the project's target schemas. +/// Build the desired-versus-warehouse cleanup plan for the project's target schemas and the location of SQLBuild's own tables. pub(crate) fn build_plan<'py>( - (project, warehouse): (&Bound<'py, PyAny>, &Warehouse<'py>), + (project, warehouse, own_tables): (&Bound<'py, PyAny>, &Warehouse<'py>, OwnTablesLocation), settings: &JanitorSettings, scope: &RelationScope, ) -> PyResult> { @@ -223,17 +226,15 @@ pub(crate) fn build_plan<'py>( push_artifact_schema(database.clone(), schema.clone()); } } - if let Some(schema) = target_location(project, "effective_target_schema")? { - push_artifact_schema( - target_location(project, "effective_target_database")?, - schema, - ); + let own_schema: Option = own_tables.as_ref().map(|(_, schema)| schema.clone()); + if let Some((database, schema)) = own_tables { + push_artifact_schema(database, schema); } let now: Bound<'py, PyAny> = now_utc(py)?; let (artifacts, artifact_skips) = query_diff_artifact_candidates(warehouse, &artifact_schemas, &now)?; let review_schemas: Vec> = - review_schema_candidates(project, warehouse, &now)?; + review_schema_candidates((project, own_schema), warehouse, &now)?; if target_schemas.is_empty() { let scanned: usize = artifact_schemas.len(); return artifact_only_plan( @@ -430,11 +431,16 @@ pub(crate) fn build_janitor_plan_binding<'py>( adapter: arguments.value("adapter")?, connection: arguments.value("connection")?, }; - build_plan( - (&arguments.value("project")?, &warehouse), - &settings, - &scope, - ) + let project: Bound<'py, PyAny> = arguments.value("project")?; + let own_tables: OwnTablesLocation = target_location(&project, "effective_target_schema")? + .map(|schema| { + Ok::<_, pyo3::PyErr>(( + target_location(&project, "effective_target_database")?, + schema, + )) + }) + .transpose()?; + build_plan((&project, &warehouse, own_tables), &settings, &scope) } /// A strict archive name the janitor expires by its embedded UTC timestamp. diff --git a/crates/sqlbuild-python/src/bindings/_helpers/review_command/command.rs b/crates/sqlbuild-python/src/bindings/_helpers/review_command/command.rs index 7bdc4355bc..9d31b87a2c 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/review_command/command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/review_command/command.rs @@ -44,6 +44,7 @@ use crate::bindings::_helpers::review_command::support::{ error_parts, failed_error, invocation_id, phase, plan_error, progress_stream, utc_now_compact, }; use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_compile::compile_driver::main::setup::project_target_settings::project_target_settings; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; use sqlbuild_python_output::recall::main::write_stdout_bytes::write_stdout_bytes; @@ -443,21 +444,28 @@ fn open_review<'py>( report: &ReviewReport, ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>, ReviewSchema)> { let py: Python<'py> = request.py(); - let (discovered, adapter, _) = compiled; + let (discovered, adapter, graph) = compiled; let run_id: String = report .invocation_id .clone() .unwrap_or_else(|| format!("{:x}", std::process::id())); - let schema: ReviewSchema = review_schema( - py, - (project, settings, &report.plan.validated), - (utc_now_compact(py)?, &report.baseline.head, &run_id), - )?; let config: Bound<'py, PyAny> = connection_config( request, (&(&project.project_dir).into_pyobject(py)?, discovered), settings, )?; + let (_, marker_schema) = project_target_settings( + discovered, + &native_field(graph, "project")?, + (&config, adapter), + )? + .own_table_locations(adapter, "review ownership markers")?; + let schema: ReviewSchema = review_schema( + py, + (project, settings, &report.plan.validated), + (utc_now_compact(py)?, &report.baseline.head, &run_id), + marker_schema.extract()?, + )?; let connection: Bound<'py, PyAny> = adapter.call_method1("connect", (&config,))?; Ok((config, connection, schema)) } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/review_command/planning.rs b/crates/sqlbuild-python/src/bindings/_helpers/review_command/planning.rs index 1387fecf1a..34f3a4f566 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/review_command/planning.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/review_command/planning.rs @@ -82,8 +82,6 @@ pub(crate) struct ReviewProject { pub(crate) databases: BTreeMap, /// The active target's expanded database, unless it keeps each node's own database. pub(crate) target_database: Option, - /// The active target's expanded schema. - pub(crate) target_schema: Option, } fn strings(value: &Bound<'_, PyAny>) -> PyResult> { @@ -552,7 +550,6 @@ pub(crate) fn review_project<'py>( stateful, databases, target_database, - target_schema: nullable_text(&native_field(&project, "effective_target_schema")?)?, }; Ok((review, (discovered, adapter, graph))) } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/review_command/schema.rs b/crates/sqlbuild-python/src/bindings/_helpers/review_command/schema.rs index 99aba3c21c..7e8d29bd54 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/review_command/schema.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/review_command/schema.rs @@ -34,13 +34,14 @@ pub(crate) struct ReviewSchema { created_at: ArchiveTimestamp, } -/// This run's review schema, refusing nodes that set a database when the target sets none. +/// This run's review schema, with its marker in `marker_schema`, refusing nodes that set a database when the target sets none. pub(crate) fn review_schema( py: Python<'_>, (project, settings, validated): (&ReviewProject, &ReviewSettings, &[String]), ((created_at, compact), head, run_id): ((ArchiveTimestamp, String), &str, &str), + marker_schema: Option, ) -> PyResult { - let Some(marker_schema) = project.target_schema.clone() else { + let Some(marker_schema) = marker_schema else { return Err(review_error( py, "C771", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py index 7dd50fff42..ff6944cc08 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py @@ -1909,3 +1909,14 @@ class ReturningSnapshotKeyTestCase: description: str rounds: tuple[str, ...] expected_stale_valid_from: str + + +@dataclass(frozen=True) +class PreservedTargetOwnTablesE2ETestCase: + """A `preserve` target, the adapter it builds with, and where SQLBuild's own tables must go.""" + + description: str + target_lines: str + adapter_has_default_schema: bool + expected_own_schema: str | None + expected_error: str = "" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_preserve_target_own_tables.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_preserve_target_own_tables.py new file mode 100644 index 0000000000..4183a1f130 --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_preserve_target_own_tables.py @@ -0,0 +1,180 @@ +"""CLI e2e coverage: where a `preserve` target keeps SQLBuild's own tables, never in a schema named preserve.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( + PreservedTargetOwnTablesE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( + prepare_inline_project, + query_duckdb, + run_sqb, +) + +_COST_ADAPTER: str = ( + "from decimal import Decimal\n\n" + "from sqlbuild.adapter.contract.classes.resource_costs import ResourceCostsMixin\n" + "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n" + "from sqlbuild.cost.models import RunCostSummary\n" + "from sqlbuild.cost.types import CostCapability, CostStatus\n\n\n" + "class DuckDbCostAdapter(ResourceCostsMixin, DuckDbAdapter):\n" + ' adapter_name = "duckdb_costs"\n\n' + " def cost_capability(self):\n" + " return CostCapability.SNOWFLAKE_QUERY_HISTORY\n\n" + " def collect_run_cost(self, **kwargs):\n" + " return RunCostSummary(\n" + " status=CostStatus.COMPLETE,\n" + ' usd_per_credit=kwargs["usd_per_credit"],\n' + ' rate_source=kwargs["rate_source"],\n' + " )\n" +) +_NO_DEFAULT_SCHEMA: str = "\n def default_schema(self):\n return None\n" +_DIFF_QUERIES: tuple[str, ...] = ( + "--left-query", + "SELECT order_id, amount_cents FROM marts.orders", + "--right-query", + "SELECT order_id, amount_cents + 1 AS amount_cents FROM marts.orders", + "--key", + "order_id", +) + + +def _preserve_project(tmp_path: Path, test_case: PreservedTargetOwnTablesE2ETestCase) -> Path: + adapter: str = _COST_ADAPTER + ( + "" if test_case.adapter_has_default_schema else _NO_DEFAULT_SCHEMA + ) + return prepare_inline_project( + tmp_path=tmp_path, + project_name="preserve_own_tables", + repo_files={ + "sqlbuild_project.toml": ( + 'name = "preserve_own_tables"\nadapter = "duckdb_costs"\ndefault_target = "live"\n\n' + '[connection]\ndatabase = "warehouse.duckdb"\n\n' + f"[targets.live]\n{test_case.target_lines}\n" + '[defaults]\nmaterialized = "table"\nschema = "marts"\n\n' + "[rules]\nselect = []\n" + ), + "sql/models/orders.sql": ( + 'MODEL (description "Orders.");\n\n' + "SELECT 1 AS order_id, 100 AS amount_cents\n" + "UNION ALL\nSELECT 2 AS order_id, 200 AS amount_cents\n" + ), + "python/adapters/duckdb_costs.py": adapter, + }, + ) + + +def _schemas(db_path: Path) -> set[str]: + rows = query_duckdb(db_path=db_path, sql="SELECT schema_name FROM information_schema.schemata") + return {str(row[0]) for row in rows} + + +def _tables(db_path: Path, name: str) -> set[str]: + rows = query_duckdb( + db_path=db_path, + sql=f"SELECT table_schema FROM information_schema.tables WHERE table_name = '{name}'", + ) + return {str(row[0]) for row in rows} + + +@pytest.mark.parametrize( + "test_case", + [ + PreservedTargetOwnTablesE2ETestCase( + description="own tables go to the loader schema", + target_lines='schema = "preserve"\nloader_schema = "sqlbuild_state"\n', + adapter_has_default_schema=True, + expected_own_schema="sqlbuild_state", + ), + PreservedTargetOwnTablesE2ETestCase( + description="own tables go to the adapter's default schema without a loader schema", + target_lines='schema = "preserve"\n', + adapter_has_default_schema=True, + expected_own_schema="main", + ), + PreservedTargetOwnTablesE2ETestCase( + description="no loader schema and no adapter default schema refuses before running", + target_lines='schema = "preserve"\n', + adapter_has_default_schema=False, + expected_own_schema=None, + expected_error=( + "error[S105]: Target 'live' sets schema = 'preserve', so each model keeps its own " + "schema, and the duckdb_costs adapter has no default schema" + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_preserve_target_when_building_and_diffing_then_own_tables_avoid_a_preserve_schema( + tmp_path: Path, + test_case: PreservedTargetOwnTablesE2ETestCase, +) -> None: + project_dir: Path = _preserve_project(tmp_path, test_case) + db_path: Path = project_dir / "warehouse.duckdb" + + build: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build"), project_dir=project_dir + ) + diff: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "diff", *_DIFF_QUERIES), project_dir=project_dir + ) + + if test_case.expected_own_schema is None: + assert build.returncode != 0, build.stdout + build.stderr + assert test_case.expected_error in build.stdout + build.stderr, build.stdout + build.stderr + assert "resource cost history" in build.stdout + build.stderr + assert not db_path.exists() or not _tables(db_path, "orders") + assert diff.returncode != 0, diff.stdout + diff.stderr + assert test_case.expected_error in diff.stdout + diff.stderr, diff.stdout + diff.stderr + no_work: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build", "--exclude", "orders"), project_dir=project_dir + ) + assert no_work.returncode == 0, no_work.stdout + no_work.stderr + return + assert build.returncode == 0, build.stdout + build.stderr + assert diff.returncode == 1, diff.stdout + diff.stderr + assert "order_id=1 | 100 -> 101" in diff.stdout, diff.stdout + diff.stderr + assert "Query diff immediate cleanup OK" in diff.stderr, diff.stderr + assert "preserve" not in _schemas(db_path) + assert _tables(db_path, "orders") == {"marts"} + assert _tables(db_path, "_sqlbuild_resource_costs") == {test_case.expected_own_schema} + rows = query_duckdb( + db_path=db_path, + sql=f"SELECT COUNT(*) FROM {test_case.expected_own_schema}._sqlbuild_resource_costs", + ) + assert rows[0][0] > 0 + + +def test_given_snowflake_preserve_target_without_loader_schema_when_diffing_then_s105_names_the_fix( + tmp_path: Path, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="snowflake_preserve", + repo_files={ + "sqlbuild_project.toml": ( + 'name = "snowflake_preserve"\nadapter = "snowflake"\ndefault_target = "prod"\n\n' + '[connection]\naccount = "example-account"\nuser = "builder"\n' + 'password = "unused"\nwarehouse = "TRANSFORM_WH"\n\n' + '[targets.prod]\ndatabase = "ANALYTICS"\nschema = "preserve"\n' + ), + }, + ) + + diff: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "diff", *_DIFF_QUERIES), project_dir=project_dir + ) + + output: str = diff.stdout + diff.stderr + assert diff.returncode == 3, output + assert ( + "error[S105]: Target 'prod' sets schema = 'preserve', so each model keeps its own schema, " + "and the snowflake adapter has no default schema, so SQLBuild has no schema for its query " + 'diff scratch tables. Add loader_schema = "..." to [targets.prod] in sqlbuild_project.toml' + ) in output, output + assert "Query diff connection" not in output, output 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 8ad1a6a38c..1eac06607d 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 @@ -254,3 +254,12 @@ class PostgresLoaderCursorBoundsE2ETestCase: bounds: tuple[str, ...] expected_calls: tuple[str, ...] expected_rows: tuple[tuple[object, ...], ...] + + +@dataclass(frozen=True) +class PostgresPreservedOwnTablesE2ETestCase: + """A `preserve` target on Postgres and the schema SQLBuild's own tables must go to.""" + + description: str + loader_schema: bool + expected_own_schema: str | None diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_preserve_target_own_tables.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_preserve_target_own_tables.py new file mode 100644 index 0000000000..0e748c301a --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_preserve_target_own_tables.py @@ -0,0 +1,132 @@ +"""Postgres e2e coverage: a `preserve` target keeps SQLBuild's own tables out of a schema named preserve.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.postgres._test_types import ( + PostgresPreservedOwnTablesE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.postgres.helpers import ( + build_unique_schema_name, + cleanup_postgres_schema, + execute_postgres_sql, + fetch_postgres_rows, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + +_COST_ADAPTER: str = ( + "from sqlbuild.adapter.contract.classes.resource_costs import ResourceCostsMixin\n" + "from sqlbuild.adapters.postgres.classes.postgres_adapter import PostgresAdapter\n" + "from sqlbuild.cost.models import RunCostSummary\n" + "from sqlbuild.cost.types import CostCapability, CostStatus\n\n\n" + "class PostgresCostAdapter(ResourceCostsMixin, PostgresAdapter):\n" + ' adapter_name = "postgres_costs"\n\n' + " def cost_capability(self):\n" + " return CostCapability.SNOWFLAKE_QUERY_HISTORY\n\n" + " def collect_run_cost(self, **kwargs):\n" + " return RunCostSummary(\n" + " status=CostStatus.COMPLETE,\n" + ' usd_per_credit=kwargs["usd_per_credit"],\n' + ' rate_source=kwargs["rate_source"],\n' + " )\n" +) + + +def _own_table_schemas(config: dict[str, object]) -> set[str]: + rows = fetch_postgres_rows( + sql=( + "SELECT table_schema FROM information_schema.tables " + "WHERE table_name = '_sqlbuild_resource_costs'" + ), + config=config, + ) + return {str(row[0]) for row in rows} + + +@pytest.mark.parametrize( + "test_case", + [ + PostgresPreservedOwnTablesE2ETestCase( + description="own tables and diff scratch tables go to the loader schema", + loader_schema=True, + expected_own_schema=None, + ), + PostgresPreservedOwnTablesE2ETestCase( + description="own tables and diff scratch tables go to public without a loader schema", + loader_schema=False, + expected_own_schema="public", + ), + ], + ids=lambda case: case.description, +) +def test_given_preserve_target_when_building_and_diffing_on_postgres_then_no_preserve_schema( + tmp_path: Path, + test_case: PostgresPreservedOwnTablesE2ETestCase, + postgres_e2e_config: dict[str, object], +) -> None: + model_schema: str = build_unique_schema_name(prefix="sqlbuild_preserve_models") + state_schema: str = build_unique_schema_name(prefix="sqlbuild_preserve_state") + expected_own_schema: str = test_case.expected_own_schema or state_schema + loader_line: str = f'loader_schema = "{state_schema}"\n' if test_case.loader_schema else "" + config: dict[str, object] = postgres_e2e_config + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="postgres_preserve_own_tables", + repo_files={ + "sqlbuild_project.toml": ( + 'name = "postgres_preserve_own_tables"\nadapter = "postgres_costs"\n' + 'default_target = "live"\n\n[connection]\n' + f'host = "{config["host"]}"\nport = {config["port"]}\n' + f'dbname = "{config["dbname"]}"\nuser = "{config["user"]}"\n' + f'password = "{config["password"]}"\n\n' + f'[targets.live]\nschema = "preserve"\n{loader_line}\n' + f'[defaults]\nmaterialized = "table"\nschema = "{model_schema}"\n\n' + "[rules]\nselect = []\n" + ), + "sql/models/orders.sql": ( + 'MODEL (description "Orders.");\n\n' + "SELECT 1 AS order_id, 100 AS amount_cents\n" + "UNION ALL\nSELECT 2 AS order_id, 200 AS amount_cents\n" + ), + "python/adapters/postgres_costs.py": _COST_ADAPTER, + }, + ) + + try: + build: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build"), project_dir=project_dir + ) + diff: subprocess.CompletedProcess[str] = run_sqb( + command=( + "--no-color", + "diff", + "--left-query", + f"SELECT order_id, amount_cents FROM {model_schema}.orders", + "--right-query", + f"SELECT order_id, amount_cents + 1 AS amount_cents FROM {model_schema}.orders", + "--key", + "order_id", + ), + project_dir=project_dir, + ) + + assert build.returncode == 0, build.stdout + build.stderr + assert f"Query diff materialization OK ({expected_own_schema};" in diff.stderr, ( + diff.stdout + diff.stderr + ) + assert "Query diff immediate cleanup OK (2 removed" in diff.stderr, diff.stderr + assert not fetch_postgres_rows( + sql="SELECT 1 FROM information_schema.schemata WHERE schema_name = 'preserve'", + config=config, + ) + assert _own_table_schemas(config) == {expected_own_schema} + finally: + execute_postgres_sql( + sql="DROP TABLE IF EXISTS public._sqlbuild_resource_costs", config=config + ) + cleanup_postgres_schema(schema_name=model_schema, config=config) + cleanup_postgres_schema(schema_name=state_schema, config=config) diff --git a/website/src/content/docs/docs/cli/janitor.mdx b/website/src/content/docs/docs/cli/janitor.mdx index a7f9f11598..d5ecdf805e 100644 --- a/website/src/content/docs/docs/cli/janitor.mdx +++ b/website/src/content/docs/docs/cli/janitor.mdx @@ -145,8 +145,8 @@ name belongs to one. A compatibility view that no longer exists is recorded as d [`sqb review`](/docs/cli/review) builds into a schema it creates and drops for one run. When a review couldn't drop its schema, the janitor drops it once the timestamp in its name is more than 24 -hours old, so a running review is never touched. Only schemas with a review ownership marker in the -active target schema's `_sqlbuild_fingerprints` table are dropped; a schema whose name only looks +hours old, so a running review is never touched. Only schemas with a review ownership marker where +[`sqb review`](/docs/cli/review) writes it are dropped; a schema whose name only looks like a review schema is left alone. ### State history pruning diff --git a/website/src/content/docs/docs/cli/review.mdx b/website/src/content/docs/docs/cli/review.mdx index 055d477710..0212be6b3e 100644 --- a/website/src/content/docs/docs/cli/review.mdx +++ b/website/src/content/docs/docs/cli/review.mdx @@ -97,8 +97,10 @@ A review builds into a schema named `___` in example `review_20261023t101500z_3f9c2ab_4e1d0a`. Lowercase is how warehouses that fold unquoted names to lowercase store it, and warehouses that fold to uppercase compare schema names without case, so the review, the existence checks and the janitor all find the same schema. Before creating -it, the review writes an ownership marker to the active target schema's `_sqlbuild_fingerprints` -table, and it refuses a schema that already exists. +it, the review writes an ownership marker to the `_sqlbuild_fingerprints` table of the active +target's schema, or with `schema = "preserve"` of +[SQLBuild's own tables](/docs/concepts/project-configuration#sqlbuilds-own-tables-on-a-preserve-target), +and it refuses a schema that already exists. Every model and seed the review builds goes to the review schema in the active target's database, including nodes that set their own `database`. When the active target sets no database, or sets it diff --git a/website/src/content/docs/docs/concepts/adapters/snowflake.mdx b/website/src/content/docs/docs/concepts/adapters/snowflake.mdx index c70987eee4..fc2b167ab6 100644 --- a/website/src/content/docs/docs/concepts/adapters/snowflake.mdx +++ b/website/src/content/docs/docs/concepts/adapters/snowflake.mdx @@ -254,7 +254,12 @@ warehouse-size credit rate, and estimates USD from a price per credit. The price "est."; a region not in SQLBuild's table is priced as AWS US East. The rate sheet or list price is looked up once per account per UTC day and kept in -`target/cost/credit_price.json`. Each row of `_sqlbuild_resource_costs` records the price it used +`target/cost/credit_price.json`. Builds record costs in a `_sqlbuild_resource_costs` table in the +target's schema. A target with `schema = "preserve"` keeps it in its `loader_schema`; without one, +Snowflake has no default schema for it, so any build with work to run stops with `S105` before +running anything (see +[SQLBuild's own tables](/docs/concepts/project-configuration#sqlbuilds-own-tables-on-a-preserve-target)). +Each row of `_sqlbuild_resource_costs` records the price it used in `usd_per_credit` and where it came from in `usd_per_credit_source` (`config`, `rate_sheet` or `list_price`). SQLBuild adds both columns to an existing table the first time it writes to it; rows recorded before then leave them empty. Use `sqb cost`, `sqb cost latest`, `sqb cost `, or diff --git a/website/src/content/docs/docs/concepts/diff.mdx b/website/src/content/docs/docs/concepts/diff.mdx index 3b3000d64b..8b36fbf0a8 100644 --- a/website/src/content/docs/docs/concepts/diff.mdx +++ b/website/src/content/docs/docs/concepts/diff.mdx @@ -344,8 +344,9 @@ stable digest so an operator can still identify them without flooding terminal o ### Stable query results and cleanup -SQLBuild materializes each raw query once in the selected target's default schema before comparing -it. Artifacts use a reserved run-owned name and are dropped immediately when the command finishes, +SQLBuild materializes each raw query once in the selected target's schema before comparing it; a +target with `schema = "preserve"` uses the schema of +[SQLBuild's own tables](/docs/concepts/project-configuration#sqlbuilds-own-tables-on-a-preserve-target). Artifacts use a reserved run-owned name and are dropped immediately when the command finishes, including after comparison errors. Each successfully created artifact publishes an immutable `query_diff_artifact` fingerprint. The diff --git a/website/src/content/docs/docs/concepts/project-configuration.mdx b/website/src/content/docs/docs/concepts/project-configuration.mdx index 83df547931..b044cb03b4 100644 --- a/website/src/content/docs/docs/concepts/project-configuration.mdx +++ b/website/src/content/docs/docs/concepts/project-configuration.mdx @@ -231,7 +231,7 @@ A target is a named build context - the database and schema you build into, plus | Field | Description | |-------|-------------| | `schema` | Schema for all models in this target; required for named targets | -| `loader_schema` | Default write schema for managed source loaders; falls back to `schema`. Required when `schema` is `preserve` and the project has loaders, assets or checks, because their [results](/docs/concepts/python-nodes/overview#result-persistence) go there | +| `loader_schema` | Default write schema for managed source loaders; falls back to `schema`. With `schema = "preserve"`, also where SQLBuild keeps [its own tables](#sqlbuilds-own-tables-on-a-preserve-target); required then if the project has loaders, assets or checks, because their [results](/docs/concepts/python-nodes/overview#result-persistence) go there | | `database` | Database for all models in this target | | `connection` | Name from `[connections.]` used for endpoint, authentication, and compute; optional when exactly one named connection without `kind` is defined; it must be a warehouse connection (see [Warehouse and source connections](#warehouse-and-source-connections)) | | `vars` | Target-specific project variables | @@ -288,6 +288,22 @@ target `schema` puts every model in that schema, so two models with the same `al schemas land on one relation. Commands that compile the project stop with `S106`, naming the target, both resources and the relation; set a different `alias` on one of them. +### SQLBuild's own tables on a preserve target + +A target with `schema = "preserve"` keeps each model's own schema, so it names no schema for the +tables SQLBuild writes for itself: Snowflake resource costs (`_sqlbuild_resource_costs`), +[`sqb diff`](/docs/concepts/diff#stable-query-results-and-cleanup) query scratch tables, and +[`sqb review`](/docs/cli/review) ownership markers. SQLBuild never creates a schema named +`preserve` for them. They go to: + +| Target | Schema of SQLBuild's own tables | +|--------|---------------------------------| +| `loader_schema` set | `loader_schema` | +| No `loader_schema`, adapter with a default schema | The adapter's default schema, such as `main` on DuckDB or `public` on PostgreSQL | +| No `loader_schema`, adapter without one, such as Snowflake, BigQuery or Databricks | None: a query diff, a review, or on Snowflake any build with work to run stops with `S105` before running anything. Add `loader_schema = "..."` to the target | + +A target `database` of `preserve` keeps them in the connection's database. + A compile checks the selected target and every other target with the same project variables and `env_file`, unless a model's config reads `CTX:run.target`. Other targets are checked when you compile them, as is a target whose schema or database depends on each model.