use sqlx::{PgConnection, Row, query}; use super::authority::MigrationError; use super::schema_guard::{ constraint_expression, normalize_definition, relation_exists, schema_error, }; const IMPORT_EVENT_NAMES: &[&str] = &[ "onboarding_import_eligible", "onboarding_import_published", "onboarding_agent_activated", ]; const CONTEXT_COLUMNS: &[(&str, &str, bool)] = &[ ("workspace_id", "text", false), ("application_idempotency_key", "text", false), ("plan_digest", "text", false), ("selected_operation_id", "text", true), ("selected_operation_version", "integer", true), ("registered_at", "timestamp with time zone", false), ("selected_at", "timestamp with time zone", true), ]; pub(super) async fn validate_v15_absent( connection: &mut PgConnection, ) -> Result { if relation_exists(connection, "onboarding_import_selections").await? { return Ok(false); } if named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? { return Ok(false); } if !relation_exists(connection, "product_events").await? { return Ok(true); } let name_check = constraint_expression(connection, "product_events", "product_events_name_check").await?; Ok(!normalize_definition(&name_check).contains("onboarding_import_eligible")) } pub(super) async fn validate_v15_onboarding_import_selection( connection: &mut PgConnection, ) -> Result<(), MigrationError> { validate_context_columns(connection).await?; validate_context_constraints(connection).await?; validate_context_index(connection).await?; if !named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? { return Err(schema_error(15)); } for (table, constraint) in [ ("product_events", "product_events_name_check"), ( "product_event_daily_rollups", "product_event_daily_rollups_name_check", ), ] { let definition = normalize_definition(&constraint_expression(connection, table, constraint).await?); for event_name in IMPORT_EVENT_NAMES { if !definition.contains(event_name) { return Err(schema_error(15)); } } } Ok(()) } async fn validate_context_columns(connection: &mut PgConnection) -> Result<(), MigrationError> { for (name, data_type, nullable) in CONTEXT_COLUMNS { let row = query( "select data_type, is_nullable, column_default, datetime_precision, collation_name from information_schema.columns where table_schema = current_schema() and table_name = 'onboarding_import_selections' and column_name = $1", ) .bind(name) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let Some(row) = row else { return Err(schema_error(15)); }; let actual_type = row .try_get::("data_type") .map_err(|_| MigrationError::storage("preflight.schema"))?; let actual_nullable = row .try_get::("is_nullable") .map_err(|_| MigrationError::storage("preflight.schema"))?; let default = row .try_get::, _>("column_default") .map_err(|_| MigrationError::storage("preflight.schema"))?; let precision = row .try_get::, _>("datetime_precision") .map_err(|_| MigrationError::storage("preflight.schema"))?; let collation = row .try_get::, _>("collation_name") .map_err(|_| MigrationError::storage("preflight.schema"))?; if actual_type != *data_type || actual_nullable != if *nullable { "YES" } else { "NO" } || default.is_some() || (*data_type == "timestamp with time zone" && precision != Some(6)) || collation.is_some() { return Err(schema_error(15)); } } Ok(()) } async fn validate_context_constraints(connection: &mut PgConnection) -> Result<(), MigrationError> { for (name, kind, required) in [ ( "onboarding_import_selections_pkey", "p", &["primarykeyworkspace_id"][..], ), ( "onboarding_import_selections_workspace_id_fkey", "f", &[ "foreignkeyworkspace_id", "referencesworkspacesid", "ondeletecascade", ][..], ), ( "onboarding_import_selections_operation_fk", "f", &[ "foreignkeyworkspace_id,selected_operation_id", "referencesoperationsworkspace_id,id", ][..], ), ( "onboarding_import_selections_application_fk", "f", &[ "foreignkeyworkspace_id,application_idempotency_key", "referencesimport_plan_applicationsworkspace_id,idempotency_key", "ondeletecascade", ][..], ), ] { let definition = constraint_definition(connection, name).await?; if !constraint_is_type(connection, name, kind).await? { return Err(schema_error(15)); } for snippet in required { if !definition.contains(snippet) { return Err(schema_error(15)); } } } // `ON DELETE NO ACTION` is the FK default and Postgres omits it from // `pg_get_constraintdef`; assert the raw delete action instead so a // selected Operation hard-delete cannot silently cascade the report. if constraint_delete_action(connection, "onboarding_import_selections_operation_fk") .await? .as_deref() != Some("a") { return Err(schema_error(15)); } for (name, required) in [ ( "onboarding_import_selections_application_key_check", &[ "octet_lengthapplication_idempotency_key>=1", "octet_lengthapplication_idempotency_key<=256", ][..], ), ( "onboarding_import_selections_plan_digest_check", &["plan_digest~'^[0-9a-f]{64}$'"][..], ), ( "onboarding_import_selections_version_check", &[ "selected_operation_versionisnull", "selected_operation_version>0", ][..], ), ( "onboarding_import_selections_selection_shape_check", &["selected_operation_idisnull", "selected_atisnull"][..], ), ] { let definition = normalize_definition( &constraint_expression(connection, "onboarding_import_selections", name).await?, ); if required .iter() .any(|snippet| !definition.contains(&normalize_definition(snippet))) { return Err(schema_error(15)); } } Ok(()) } async fn validate_context_index(connection: &mut PgConnection) -> Result<(), MigrationError> { let row = query( "select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready, i.indisunique, i.indnkeyatts, pg_get_indexdef(i.indexrelid, 1, true) as first_column, pg_get_indexdef(i.indexrelid, 2, true) as second_column, pg_get_expr(i.indpred, i.indrelid) as predicate from pg_catalog.pg_index i join pg_catalog.pg_class idx on idx.oid = i.indexrelid join pg_catalog.pg_class t on t.oid = i.indrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace join pg_catalog.pg_am am on am.oid = idx.relam where n.nspname = current_schema() and idx.relname = 'onboarding_import_selections_operation_idx'", ) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let valid = row.is_some_and(|row| { row.try_get::("table_name").ok().as_deref() == Some("onboarding_import_selections") && row.try_get::("access_method").ok().as_deref() == Some("btree") && row.try_get::("indisvalid").ok() == Some(true) && row.try_get::("indisready").ok() == Some(true) && row.try_get::("indisunique").ok() == Some(false) && row.try_get::("indnkeyatts").ok() == Some(2) && row.try_get::("first_column").ok().as_deref() == Some("workspace_id") && row.try_get::("second_column").ok().as_deref() == Some("selected_operation_id") && row .try_get::, _>("predicate") .ok() .flatten() .is_none() }); if valid { Ok(()) } else { Err(schema_error(15)) } } async fn constraint_definition( connection: &mut PgConnection, constraint: &str, ) -> Result { query( "select pg_get_constraintdef(c.oid, true) as definition from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = 'onboarding_import_selections' and c.conname = $1", ) .bind(constraint) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .ok_or_else(|| schema_error(15))? .try_get::("definition") .map(|definition| normalize_definition(&definition)) .map_err(|_| MigrationError::storage("preflight.schema")) } async fn constraint_delete_action( connection: &mut PgConnection, constraint: &str, ) -> Result, MigrationError> { query( "select c.confdeltype::text as action from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = 'onboarding_import_selections' and c.conname = $1", ) .bind(constraint) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .map(|row| { row.try_get::("action") .map_err(|_| MigrationError::storage("preflight.schema")) }) .transpose() } async fn constraint_is_type( connection: &mut PgConnection, constraint: &str, kind: &str, ) -> Result { query( "select exists ( select 1 from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = 'onboarding_import_selections' and c.conname = $1 and c.contype = $2 ) as present", ) .bind(constraint) .bind(kind) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("present") .map_err(|_| MigrationError::storage("preflight.schema")) } async fn named_constraint_exists( connection: &mut PgConnection, table: &str, constraint: &str, ) -> Result { query( "select exists ( select 1 from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = $1 and c.conname = $2 ) as present", ) .bind(table) .bind(constraint) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("present") .map_err(|_| MigrationError::storage("preflight.schema")) }