//! Idempotent and converging PostgreSQL seed of an official sheet's working DRAFT //! (`packages/anatomy/src/curation/seed.ts`). Runs as the database owner in `supabase db //! reset` and in the PGlite harness. A fresh database gets the draft through //! `private.insert_sheet_draft` (audited, null actor); a database still holding an older draft //! as the sheet's only version gets its content replaced in place. Published rows are never //! touched and nothing is published: that stays a human act through `publish_sheet_version`. use super::targets::fail; use crate::anatomy::svg::number::is_js_space; use crate::curation::PipelineError; use crate::curation::legacy::types::AssetRecord; pub const DOCUMENT_DOLLAR_TAG: &str = "$equine_doc$"; const SHEET_DESCRIPTION: &str = "Fiche anatomique officielle du cheval (import des données historiques, brouillon à valider)"; pub const DRAFT_CHANGE_NOTE: &str = "Révision de travail 4c (audit anatomique et ostéopathique) sur l’import des données historiques"; pub struct DraftSeedParams<'a> { pub sheet_id: &'a str, pub assets: &'a [AssetRecord], /// `document.json` text, embedded verbatim in a dollar-quoted literal. pub document_json: &'a str, pub change_note: &'a str, } /// Only ever fed fixed values; doubled quotes keep it literal-safe. fn sql_text(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } /// The second line still names the TypeScript generator: it is part of the frozen seed bytes /// (sha256 `c5a24312…ed1e`, the R5.1 ledger), so it stays as written; the generator is this /// module since R5.6 and `packages/anatomy` left at R5.7 (RUST.md §11.23). fn header() -> String { [ "-- Official equine anatomical sheet: working revision, DRAFT.", "-- Generated by `pnpm import:equine` (packages/anatomy): do not edit by hand.", "-- Idempotent and converging. Never publishes: the version stays in status", "-- draft until a platform admin validates REVIEW-REPORT.md and publishes it.", ] .join("\n") } fn sheet_insert(sheet_id: &str) -> String { [ "insert into public.anatomical_sheets".to_owned(), " (id, species_id, name, slug, description, creator_user_id, is_official, visibility)" .to_owned(), "values (".to_owned(), format!( " {}, 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval',", sql_text(sheet_id) ), format!(" {},", sql_text(SHEET_DESCRIPTION)), " null, true, 'private'".to_owned(), ")".to_owned(), "on conflict (id) do nothing;".to_owned(), ] .join("\n") } fn asset_inserts(sheet_id: &str, assets: &[AssetRecord]) -> String { let rows: Vec = assets .iter() .map(|a| { format!( " ({}, {}, {}, {}, 'image/svg+xml', {})", sql_text(&a.svg_asset_id), sql_text(sheet_id), sql_text(&a.sha256), a.byte_size, sql_text(&a.file) ) }) .collect(); [ "insert into public.anatomical_sheet_assets".to_owned(), " (id, sheet_id, sha256, byte_size, content_type, file_name)".to_owned(), "values".to_owned(), rows.join(",\n"), "on conflict (sheet_id, sha256) do nothing;".to_owned(), ] .join("\n") } /// `trimEnd`: the JavaScript white space and line terminators. fn trim_end_js(text: &str) -> &str { text.trim_end_matches(is_js_space) } fn document_literal(document_json: &str) -> Result { if document_json.contains(DOCUMENT_DOLLAR_TAG) { return Err(fail(format!( "document JSON contains the dollar-quote tag {DOCUMENT_DOLLAR_TAG}" ))); } Ok(format!( "{DOCUMENT_DOLLAR_TAG}{}{DOCUMENT_DOLLAR_TAG}::jsonb", trim_end_js(document_json) )) } fn draft_insert(params: &DraftSeedParams<'_>, literal: &str) -> String { let sheet = sql_text(params.sheet_id); [ "select private.insert_sheet_draft(".to_owned(), " null,".to_owned(), format!(" {sheet},"), format!(" {literal},"), format!(" {}", sql_text(params.change_note)), ")".to_owned(), "where not exists (".to_owned(), format!(" select 1 from public.anatomical_sheet_versions where sheet_id = {sheet}"), ");".to_owned(), ] .join("\n") } /// Only when the sheet's single version is a draft whose content differs; the document /// literal is read once through the derived table. fn draft_converge(params: &DraftSeedParams<'_>, literal: &str) -> String { let sheet = sql_text(params.sheet_id); [ "update public.anatomical_sheet_versions v".to_owned(), format!( "set content = d.content, change_note = {}", sql_text(params.change_note) ), format!("from (select {literal} as content) d"), format!("where v.sheet_id = {sheet} and v.status = 'draft'"), " and v.content <> d.content".to_owned(), " and (select count(*) from public.anatomical_sheet_versions o".to_owned(), format!(" where o.sheet_id = {sheet}) = 1;"), ] .join("\n") } pub fn render_draft_seed_sql(params: &DraftSeedParams<'_>) -> Result { let literal = document_literal(params.document_json)?; let parts = [ header(), sheet_insert(params.sheet_id), asset_inserts(params.sheet_id, params.assets), draft_insert(params, &literal), draft_converge(params, &literal), ]; Ok(format!("{}\n", parts.join("\n\n"))) }