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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/sqlbuild-analysis/src/assembly/target_checks/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
42 changes: 41 additions & 1 deletion crates/sqlbuild-python-compile/src/compile_driver/models.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -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<Bound<'py, PyAny>> {
let located = |value: &Option<String>| -> PyResult<Bound<'py, PyAny>> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(...))`.
Expand All @@ -82,23 +86,29 @@ fn cost_finalization<'py>(
) -> PyResult<Bound<'py, PyAny>> {
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),
Expand Down Expand Up @@ -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)? {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
},
)
})();
Expand Down
64 changes: 35 additions & 29 deletions crates/sqlbuild-python/src/bindings/_helpers/diff_report/query.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -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<PyErr> {
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.
Expand All @@ -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,
Expand All @@ -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<String> {
let value: Bound<'py, PyAny> = native_field(request, name)?;
let text: String = if value.is_truthy()? {
Expand Down Expand Up @@ -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)?),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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::<Option<String>>()?
.map(|schema| Ok::<_, PyErr>((own_database.extract()?, schema)))
.transpose()?;
let plan: Bound<'py, PyAny> = within(
&lifecycle(py, ("janitor", "janitor_candidate_planning"))?,
|lifecycle| {
Expand All @@ -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()?,
Expand Down
Loading
Loading