//! V23 schema guard: version-keyed pinned Prompt dependencies (Story 3.16, FR-18). //! //! Схема V23 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в //! ожидаемой форме: `prompt_dependencies` с composite PK/FK на `prompt_versions`, //! `prompt_message_resource_refs` с упорядоченными точками вставки и guard-триггеры //! неизменяемости опубликованной версии на обеих таблицах. use sqlx::{PgConnection, Row, query}; use super::authority::MigrationError; use super::schema_guard::{normalize_definition, relation_exists}; const DEPENDENCIES: &str = "prompt_dependencies"; const RESOURCE_REFS: &str = "prompt_message_resource_refs"; const GUARD_FUNCTION: &str = "crank_reject_published_prompt_version_mutation"; const OWNED_RELATIONS: &[&str] = &[DEPENDENCIES, RESOURCE_REFS]; const DEPENDENCY_COLUMNS: &[(&str, &str, bool)] = &[ ("workspace_id", "text", false), ("prompt_id", "text", false), ("version", "integer", false), ("dependency_position", "integer", false), ("resource_id", "text", false), ("resource_version", "integer", false), ("digest", "text", false), ("kind", "text", false), ("mime_type", "text", false), ("source_class", "text", false), ("sensitivity", "text", false), ]; const REF_COLUMNS: &[(&str, &str, bool)] = &[ ("workspace_id", "text", false), ("prompt_id", "text", false), ("version", "integer", false), ("message_position", "integer", false), ("ref_position", "integer", false), ("dependency_position", "integer", false), ]; const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[ ( DEPENDENCIES, "prompt_dependencies_pkey", "p", "v23.dependencies_pkey", "primary key (workspace_id, prompt_id, version, dependency_position)", ), ( DEPENDENCIES, "prompt_dependencies_version_fkey", "f", "v23.dependencies_version_fkey", "foreign key (workspace_id, prompt_id, version) references prompt_versions(workspace_id, prompt_id, version) on delete cascade", ), ( RESOURCE_REFS, "prompt_message_resource_refs_pkey", "p", "v23.refs_pkey", "primary key (workspace_id, prompt_id, version, message_position, ref_position)", ), ( RESOURCE_REFS, "prompt_message_resource_refs_version_fkey", "f", "v23.refs_version_fkey", "foreign key (workspace_id, prompt_id, version) references prompt_versions(workspace_id, prompt_id, version) on delete cascade", ), ]; fn v23_error(stage: &'static str) -> MigrationError { MigrationError::new( "partial_sequence", stage, Some(23), "restore_known_good_backup", ) } /// Схема V23 отсутствует целиком (для current_version < 23). pub(super) async fn validate_v23_absent( connection: &mut PgConnection, ) -> Result { for relation in OWNED_RELATIONS { if relation_exists(connection, relation).await? { return Ok(false); } } if trigger_exists( connection, DEPENDENCIES, "prompt_dependencies_immutable_guard", ) .await? { return Ok(false); } Ok(true) } /// Схема V23 присутствует в ожидаемой форме (для current_version >= 23). pub(super) async fn validate_v23_prompt_dependencies( connection: &mut PgConnection, ) -> Result<(), MigrationError> { for relation in OWNED_RELATIONS { if !relation_exists(connection, relation).await? { return Err(v23_error("v23.relations")); } } for (table, columns) in [ (DEPENDENCIES, DEPENDENCY_COLUMNS), (RESOURCE_REFS, REF_COLUMNS), ] { validate_columns(connection, table, columns).await?; } for (table, constraint, kind, stage, expected) in DEFINITIONS { if !constraint_matches(connection, table, constraint, kind, expected).await? { return Err(v23_error(stage)); } } for (table, trigger) in [ (DEPENDENCIES, "prompt_dependencies_immutable_guard"), ( RESOURCE_REFS, "prompt_message_resource_refs_immutable_guard", ), ] { if !trigger_exists(connection, table, trigger).await? { return Err(v23_error("v23.immutable_trigger")); } } Ok(()) } async fn validate_columns( connection: &mut PgConnection, table: &str, columns: &[(&str, &str, bool)], ) -> Result<(), MigrationError> { let column_count: i64 = query( "select count(*)::bigint as count from information_schema.columns where table_schema = current_schema() and table_name = $1", ) .bind(table) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("count") .map_err(|_| MigrationError::storage("preflight.schema"))?; if column_count != i64::try_from(columns.len()).unwrap_or_default() { return Err(v23_error("v23.columns")); } for (column, data_type, nullable) in columns { let row = query( "select data_type, is_nullable from information_schema.columns where table_schema = current_schema() and table_name = $1 and column_name = $2", ) .bind(table) .bind(column) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let valid = row.is_some_and(|row| { row.try_get::("data_type").ok().as_deref() == Some(*data_type) && row.try_get::("is_nullable").ok().as_deref() == Some(if *nullable { "YES" } else { "NO" }) }); if !valid { return Err(v23_error("v23.columns")); } } Ok(()) } async fn constraint_matches( connection: &mut PgConnection, table: &str, constraint: &str, kind: &str, expected: &str, ) -> Result { let row = query( "select c.contype::text as kind, c.convalidated, 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 = $1 and c.conname = $2", ) .bind(table) .bind(constraint) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; Ok(row.is_some_and(|row| { row.try_get::("kind").ok().as_deref() == Some(kind) && row.try_get::("convalidated").ok() == Some(true) && row .try_get::("definition") .ok() .is_some_and(|definition| { normalize_definition(&definition) == normalize_definition(expected) }) })) } async fn trigger_exists( connection: &mut PgConnection, table: &str, trigger: &str, ) -> Result { query( "select exists ( select 1 from pg_catalog.pg_trigger tg join pg_catalog.pg_class t on t.oid = tg.tgrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace join pg_catalog.pg_proc p on p.oid = tg.tgfoid where n.nspname = current_schema() and t.relname = $1 and tg.tgname = $2 and p.proname = $3 and not tg.tgisinternal ) as present", ) .bind(table) .bind(trigger) .bind(GUARD_FUNCTION) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get::("present") .map_err(|_| MigrationError::storage("preflight.schema")) }