//! Package-owned table shapes. Legacy declaration fragments preserve the shipped //! SQL bytes; imports use the same renderer with the SQL-fragment door closed. use crate::error::{Result, StoreError}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PackageColumn { pub name: String, #[serde(rename = "type")] pub sql_type: String, #[serde(default)] pub default: Option, #[serde(default = "yes")] pub nullable: bool, #[serde(default)] pub primary_key: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub declaration: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub position: Option, } fn yes() -> bool { true } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LegacyConstraint { pub declaration: String, pub position: usize, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged, deny_unknown_fields)] pub enum PackageIndex { Legacy(String), Declared { name: String, columns: Vec, #[serde(default)] unique: bool, }, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged, deny_unknown_fields)] pub enum PackageFullText { Legacy(String), Declared { name: String, columns: Vec }, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PackageTable { pub name: String, pub columns: Vec, #[serde(default)] pub constraints: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub prefix: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub suffix: Option, #[serde(default)] pub indexes: Vec, #[serde(default)] pub full_text: Vec, #[serde(default)] pub triggers: Vec, } fn refuse(message: impl Into) -> StoreError { StoreError::refused(message.into()) } fn ident(name: &str) -> Result { if name.is_empty() || !name .bytes() .enumerate() .all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && b.is_ascii_digit())) { return Err(refuse(format!("invalid package SQL identifier {name:?}"))); } Ok(format!("\"{name}\"")) } fn literal(value: &str) -> bool { if value == "NULL" || value.parse::().is_ok() { return true; } if value.parse::().is_ok_and(|v| v.is_finite()) { return true; } let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) else { return false; }; let mut chars = inner.chars(); while let Some(ch) = chars.next() { if ch == '\'' && chars.next() != Some('\'') { return false; } } true } fn column_sql(column: &PackageColumn) -> Result { let mut sql = format!("{} {}", ident(&column.name)?, column.sql_type); if !matches!( column.sql_type.as_str(), "TEXT" | "INTEGER" | "REAL" | "NUMERIC" | "BLOB" ) { return Err(refuse("unsupported package column type")); } if column.primary_key { sql.push_str(" PRIMARY KEY"); } if !column.nullable { sql.push_str(" NOT NULL"); } if let Some(default) = &column.default { if !literal(default) { return Err(refuse("package defaults must be SQL literals")); } sql.push_str(" DEFAULT "); sql.push_str(default); } Ok(sql) } fn selected_columns(columns: &[String], table: &PackageTable) -> Result { if columns.is_empty() { return Err(refuse("package index needs columns")); } columns .iter() .map(|name| { if !table.columns.iter().any(|c| &c.name == name) { return Err(refuse(format!("unknown index column {name}"))); } ident(name) }) .collect::>>() .map(|v| v.join(", ")) } /// Emit tables, FTS, indexes, then triggers. Only compiled built-ins may carry /// legacy fragments; imported packages are declarative data, never SQL programs. pub fn generate(tables: &[PackageTable], trusted_builtin: bool) -> Result> { let (mut creates, mut fts, mut indexes, mut triggers) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); let mut names = BTreeSet::new(); for table in tables { let name = ident(&table.name)?; if !names.insert(&table.name) { return Err(refuse("duplicate package table")); } if table.columns.is_empty() { return Err(refuse("package table needs columns")); } let mut columns = BTreeSet::new(); for column in &table.columns { ident(&column.name)?; if !columns.insert(&column.name) { return Err(refuse("duplicate package column")); } } if trusted_builtin && table.prefix.is_some() { let mut parts = BTreeMap::new(); for column in &table.columns { let position = column .position .ok_or_else(|| refuse("legacy column needs position"))?; if parts .insert( position, column .declaration .clone() .ok_or_else(|| refuse("legacy column needs declaration"))?, ) .is_some() { return Err(refuse("duplicate declaration position")); } } for constraint in &table.constraints { if parts .insert(constraint.position, constraint.declaration.clone()) .is_some() { return Err(refuse("duplicate constraint position")); } } if parts.keys().copied().ne(0..parts.len()) { return Err(refuse("non-contiguous declaration positions")); } creates.push(format!( "{}{}{}", table.prefix.as_ref().unwrap(), parts.into_values().collect::>().join(","), table .suffix .as_deref() .ok_or_else(|| refuse("legacy table needs suffix"))? )); } else { if table.prefix.is_some() || table.suffix.is_some() || !table.constraints.is_empty() || !table.triggers.is_empty() || table .columns .iter() .any(|c| c.declaration.is_some() || c.position.is_some()) { return Err(refuse("imported shapes cannot carry SQL fragments")); } creates.push(format!( "CREATE TABLE {name} ({})", table .columns .iter() .map(column_sql) .collect::>>()? .join(", ") )); } for index in &table.indexes { match index { PackageIndex::Legacy(sql) if trusted_builtin => indexes.push(sql.clone()), PackageIndex::Legacy(_) => return Err(refuse("imported index cannot carry SQL")), PackageIndex::Declared { name: index, columns, unique, } => indexes.push(format!( "CREATE {}INDEX {} ON {name} ({})", if *unique { "UNIQUE " } else { "" }, ident(index)?, selected_columns(columns, table)? )), } } for full_text in &table.full_text { match full_text { PackageFullText::Legacy(sql) if trusted_builtin => fts.push(sql.clone()), PackageFullText::Legacy(_) => { return Err(refuse("imported full-text index cannot carry SQL")) } PackageFullText::Declared { name: index, columns, } => { let index = ident(index)?; let fields = selected_columns(columns, table)?; fts.push(format!("CREATE VIRTUAL TABLE {index} USING fts5({fields}, content='{table_name}', content_rowid='rowid')", table_name=table.name)); let new = columns .iter() .map(|c| format!("new.\"{c}\"")) .collect::>() .join(", "); let old = columns .iter() .map(|c| format!("old.\"{c}\"")) .collect::>() .join(", "); triggers.push(format!("CREATE TRIGGER {} AFTER INSERT ON {name} BEGIN INSERT INTO {index}(rowid, {fields}) VALUES (new.rowid, {new}); END", ident(&format!("{}_ai", table.name))?)); triggers.push(format!("CREATE TRIGGER {} AFTER DELETE ON {name} BEGIN INSERT INTO {index}({index}, rowid, {fields}) VALUES ('delete', old.rowid, {old}); END", ident(&format!("{}_ad", table.name))?)); triggers.push(format!("CREATE TRIGGER {} AFTER UPDATE ON {name} BEGIN INSERT INTO {index}({index}, rowid, {fields}) VALUES ('delete', old.rowid, {old}); INSERT INTO {index}(rowid, {fields}) VALUES (new.rowid, {new}); END", ident(&format!("{}_au", table.name))?)); } } } if trusted_builtin { triggers.extend(table.triggers.iter().cloned()); } } creates.extend(fts); creates.extend(indexes); creates.extend(triggers); Ok(creates) } /// Every built-in table's storage, by the id of the table it serves: the SQL /// shapes `scripts/package-tables.py` extracts from `ddl.rs`, and the engine /// bound to it. A built-in's schema is code (72nd amendment, 21 Oct 2026): it /// is the store's, never read from a tool definition. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Builtin { #[serde(default)] engine: Option, tables: Vec, } fn builtins() -> &'static BTreeMap { static BUILTINS: std::sync::OnceLock> = std::sync::OnceLock::new(); BUILTINS.get_or_init(|| serde_json::from_str(include_str!("builtin_tables.json")).expect("compiled built-in tables")) } /// Native storage belongs to a compiled id/engine binding, never to seeding /// provenance. pub fn compiled_engine(id: &str) -> Option<&'static str> { builtins().get(id)?.engine.as_deref() } /// The compiled storage of the built-in table `id`; `None` for any other. pub fn compiled_shape(id: &str) -> Option<&'static [PackageTable]> { builtins().get(id).map(|builtin| builtin.tables.as_slice()) } pub fn has_engine(definition: &serde_json::Value) -> bool { definition["id"].as_str().and_then(compiled_engine) .is_some_and(|engine| Some(engine) == definition["engine"].as_str()) } pub fn builtin_shapes() -> Result)>> { Ok(builtins().iter().map(|(id, builtin)| (id.clone(), builtin.tables.clone())).collect()) } /// The SQL object owning a statement. FTS ownership comes from its content table. pub fn statement_table(sql: &str) -> Option { let clean = |word: &str| { word.trim_matches(|c| matches!(c, '"' | '`' | '(' | ')' | ',')) .to_owned() }; if sql.starts_with("CREATE VIRTUAL TABLE ") { let at = sql.find("content=").or_else(|| sql.find("content ="))?; let rest = &sql[at..]; return Some(rest.split('\'').nth(1)?.into()); } // Words are read only as far as the name: a table's columns and a // trigger's body are never split (every step reads every statement). if sql.starts_with("CREATE TABLE ") { let words = sql.split_whitespace().take(6).collect::>(); return words .get(if words.get(2) == Some(&"IF") { 5 } else { 2 }) .map(|w| clean(w)); } let mut words = sql.split_whitespace(); words.find(|w| *w == "ON")?; words.next().map(clean) } pub fn core_statements() -> Result> { let owned: BTreeSet = builtin_shapes()? .into_iter() .flat_map(|(_, tables)| tables.into_iter().map(|t| t.name)) .collect(); Ok(super::ddl::SCHEMA_DDL .iter() .copied() .filter(|sql| !statement_table(sql).is_some_and(|name| owned.contains(&name))) .collect()) } /// Substitute package-generated statements in the original ordering, preserving /// the file's current DDL exactly while the core remains hand-written. pub fn fresh_schema() -> Result> { static SCHEMA: std::sync::LazyLock, String>> = std::sync::LazyLock::new(|| build_fresh_schema().map_err(|error| error.to_string())); SCHEMA .as_ref() .cloned() .map_err(|error| refuse(error.clone())) } fn build_fresh_schema() -> Result> { let packages = builtin_shapes()?; let owned: BTreeSet<_> = packages .iter() .flat_map(|(_, tables)| tables.iter().map(|t| t.name.clone())) .collect(); let mut generated = BTreeMap::new(); for (_, tables) in packages { for sql in generate(&tables, true)? { if generated.insert(object_name(&sql)?, sql).is_some() { return Err(refuse("duplicate package object")); } } } super::ddl::SCHEMA_DDL .iter() .map(|sql| { if statement_table(sql).is_some_and(|name| owned.contains(&name)) { generated .remove(&object_name(sql)?) .ok_or_else(|| refuse("package omitted a declared schema object")) } else { Ok((*sql).into()) } }) .collect() } fn object_name(sql: &str) -> Result { // The name is at most the seventh word (`CREATE UNIQUE INDEX IF NOT // EXISTS `): the words past it are never read, and splitting a // whole table's statement to reach it cost the kit import seconds. let words: Vec<_> = sql.split_whitespace().take(7).collect(); let mut at = if words.get(1) == Some(&"UNIQUE") || words.get(1) == Some(&"VIRTUAL") { 3 } else { 2 }; if words.get(at) == Some(&"IF") { at += 3; } words .get(at) .map(|word| word.trim_matches('"').to_owned()) .ok_or_else(|| refuse("missing schema object name")) } /// Every name the core schema holds: its objects and its search indexes' /// shadow tables. `SCHEMA_DDL` is compiled in, so this is read once a /// process: [`validate_ownership`] runs for every package of every step, and /// reading the whole DDL each time was a third of a kit import (6 Nov 2026, /// 838 calls, 14 of its 41 s in a debug build). fn reserved_names() -> Result<&'static BTreeSet> { static RESERVED: std::sync::LazyLock, String>> = std::sync::LazyLock::new(|| read_reserved_names().map_err(|error| error.to_string())); RESERVED.as_ref().map_err(|error| refuse(error.clone())) } fn read_reserved_names() -> Result> { let mut reserved: BTreeSet = super::ddl::SCHEMA_DDL .iter() .map(|sql| object_name(sql)) .collect::>()?; for sql in super::ddl::SCHEMA_DDL .iter() .filter(|sql| sql.starts_with("CREATE VIRTUAL TABLE ")) { let name = object_name(sql)?; reserved.extend( ["_data", "_idx", "_docsize", "_config", "_content"] .map(|suffix| format!("{name}{suffix}")), ); } Ok(reserved) } /// All schema object names are reserved, including indexes and FTS shadows. pub fn validate_ownership(tables: &[PackageTable], occupied: &BTreeSet) -> Result<()> { let reserved = reserved_names()?; let mut claimed = BTreeSet::new(); for table in tables { let mut names = vec![table.name.clone()]; for index in &table.indexes { if let PackageIndex::Declared { name, .. } = index { names.push(name.clone()); } } for index in &table.full_text { if let PackageFullText::Declared { name, .. } = index { names.extend([ name.clone(), format!("{name}_data"), format!("{name}_idx"), format!("{name}_content"), format!("{name}_docsize"), format!("{name}_config"), ]); names.extend([ format!("{}_ai", table.name), format!("{}_ad", table.name), format!("{}_au", table.name), ]); } } for name in names { ident(&name)?; if name.starts_with('_') || reserved.contains(&name) || occupied.contains(&name) || !claimed.insert(name.clone()) { return Err(refuse(format!( "package cannot claim table or object {name}" ))); } } } Ok(()) } pub const CORE_SHA256: &str = "3f63b745a25c1cef3654dfd6a7dbdceb0fdb6a0cd25067e669b428141ead16ba"; pub struct CoreMove { pub sha256: &'static str, pub name: &'static str, pub ledger_note: &'static str, } pub const CORE_MOVES: &[CoreMove] = &[ CoreMove { sha256: "aa8bbb479a193b9ba522c33a04bc8fea74ba2f038a84dc200dbf34f26610bbd0", name: "schema136_additive_daily_batch", ledger_note: "1612470d-33f3-44dd-a39e-7f66d2417910", }, CoreMove { // Extraction registers the existing placement-proposal table as package // owned. Physical DDL and stored rows are unchanged; the ledger names // the core/package boundary move rather than silently re-pinning core. sha256: "6a32cf98fcd8e6c0bcf5059c1a2693e5ffcb5956feca8a206d24ebdc9d676352", name: "package_placement_proposal_ownership", ledger_note: "9df149b5-b997-49d4-8eb7-d18873b32bf7", }, CoreMove { sha256: "1d0c1a7d1d3dfa7e437a83448e387d8494e7e809404a3a737d44560efb915c3d", name: "schema137_additive_daily_batch", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // The 138 batch; extraction also registers the existing filing-proposal // table as package owned (filing_proposal.json), physical DDL unchanged. sha256: "cfeccffea10ce8be0938d3b7206cf11c3986186efc7e02f4be2c29d364486e88", name: "schema138_additive_daily_batch", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { sha256: "8306d2627fccd828918c5009ed0c079eef92b9cfd7dcbeccaccdae98463ef717", name: "schema139_one_row_money_and_reader_scope", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { sha256: "eda17e4df607e545a9887b43ca5f59ac0f47d319efbe176f17d9bf813847efa6", name: "schema140_ai_job_queue_after_read_indexes", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { sha256: "f440115bac05dd719db900f9af94d2cc424d5b4a24f17872c78b4f2e640d06f0", name: "schema140_native_ai_column_appends", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 141: cotton_invites gains recipient and hands_over by native append; // the rights CHECK is frozen and 'owner' stays a code rule until the // next floor move (architect, 19 Oct 2026). sha256: "a15849c8be59ac6dad8cf5e6fb8e3c015eefaebe909ade80d1fe601c9f92f2f9", name: "schema141_handover_invite_appends", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 142: the copy keeps no rule the object does not know on the rows it // serves — cotton_documents.status_changed_at and // cotton_events.collection_id take null, and cotton_notes' managed_by // CHECK and cotton_money_accounts' kind CHECK go (27 Oct 2026: 259 // served receipts sat parked on a phone, refused by them). sha256: "6a3431a02a84ef2589cb66df3fc490314bb6a4dfdedf54a7c3cb472853e47ae6", name: "schema142_the_copy_keeps_no_rule_the_object_does_not", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 147: cotton_secrets' kind CHECK goes (the object's definition decides // a secret's kinds: codes, wifi and addresses join) and Cotton Keys' // columns arrive: favourite_at, uses, passkey_id, changed_at, // history_enc (12 Nov 2026). sha256: "748e831842a4902bd528363d12a81cecb5a1ffb4005e737c2c3854d34ead7fdb", name: "schema147_keys_kinds_are_the_objects", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 151 (TRIM, 21 Nov 2026): a receipt the object served is kept as its // identity while its row says it — _writes gains implied, _field_sets // holds the shared field-name sets, _trim how far the in-place trim // walked (receipts::implied). Added only. sha256: "811a30ba12e1e2079c44b38701ecdd75716aae075f59c412b3755e5d8f29b92d", name: "schema151_served_receipts_kept_as_their_identity", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 154 (DELETE FAST, 24 Nov 2026): _fts_purge, the search indexes an // erase left words in, merged in the background (fts_purge); an erase // deletes from the index plainly. Added only, device-local. sha256: "a6f1b759656954c5a9a38b96a827de3c3a756962014e0288ab100316f0d3d326", name: "schema154_erased_words_purged_in_the_background", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 156 (HIDDEN, 26 Nov 2026): cotton_groups gains hidden (0 or 1, default // 0), a category of his films hidden in Cinemas, by native append. sha256: "212bab2855d8460cb189959e33650ed882b776cbf2183999af0398010b334543", name: "schema156_hidden_categories", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, CoreMove { // 157 (MAIL PREDICATE phase 2 and PHASE 2 PHONE 2, 27 Nov 2026): // cotton_emails gains landed_at; the device-local _mail_cuts (with // made_at and state), _mail_landed beside the mail row and _mail_own; // the sender index gains id. Added only. sha256: "a5e9adc75510c9ee55c6aeb8aef22bfcb20875a478f2e6ebae919849b9f78944", name: "schema157_mail_cuts", ledger_note: "3122ae83-97eb-4b3f-bd79-827634d1c25a", }, ]; /// Install a package's real tables atomically. An existing owned shape is left /// intact; changes to it belong to the add-only package-move path in phase 2. /// All database object collisions are checked before the first CREATE. pub fn install( db: &crate::driver::Driver, tables: &[PackageTable], previous: &[PackageTable], ) -> Result<()> { let generated = generate(tables, false)?; generate(previous, false)?; let mut owned: BTreeSet<_> = previous.iter().map(|t| t.name.clone()).collect(); for table in previous { for index in &table.full_text { if let PackageFullText::Declared { name, .. } = index { owned.insert(name.clone()); owned.extend( ["_data", "_idx", "_docsize", "_config", "_content"] .map(|suffix| format!("{name}{suffix}")), ); } } } db.transaction(|db| { let existing = crate::create::schema_objects(db)?; let all = db.all("SELECT name, tbl_name FROM sqlite_master", &[])?; let occupied = all .iter() .filter(|row| !owned.contains(row.text("tbl_name").unwrap_or(""))) .filter_map(|row| row.text("name").map(str::to_owned)) .collect(); validate_ownership(tables, &occupied)?; for old in previous { if let Some(new) = tables.iter().find(|t| t.name == old.name) { if old != new { return Err(refuse(format!( "table {} needs an add-only package shape move", old.name ))); } } else { return Err(refuse(format!("package may not drop table {}", old.name))); } } for sql in &generated { let name = object_name(sql)?; if let Some(object) = existing.iter().find(|object| object.name == name) { if super::package_shape::without_added(&object.sql).0 != *sql { return Err(refuse(format!( "existing object {name} differs from the package shape" ))); } } else { db.exec(sql)?; } } Ok(()) }) } fn definition_id(name: &str) -> bool { name.bytes().next().is_some_and(|b| b.is_ascii_lowercase()) && name .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') } /// Derive physical storage for an imported definition from its declared columns. /// Metadata is kept beside typed values; required input and defaults are the /// engine's, and every storage column is nullable. /// Takes JSON to keep the store independent of cotton-core's presentation types. pub fn from_definition(definition: &serde_json::Value) -> Result> { let id = definition["id"] .as_str() .ok_or_else(|| refuse("definition needs id"))?; ident(id)?; if !definition_id(id) { return Err(refuse("invalid definition id")); } if id.starts_with('_') || !definition["engine"].is_null() { return Err(refuse( "only data-only tool definitions derive storage from columns", )); } let name = format!("cotton_{id}"); let raw_columns = definition["columns"] .as_array() .ok_or_else(|| refuse("definition needs columns"))?; // The project and a hand-made order are the definition's own columns // (its `project` and `order` keys); who last wrote the record is // `record_byline`, since `byline` is a name a tool's own column may use. let metadata = [ ("id", "TEXT", None, true, true), ("workspace_id", "TEXT", None, true, false), ("created_at", "TEXT", None, true, false), ("updated_at", "TEXT", None, true, false), ("deleted_at", "TEXT", None, true, false), ("record_byline", "TEXT", None, true, false), ("_hlc", "TEXT", Some("''"), false, false), ("_born", "TEXT", None, true, false), ]; let mut columns = metadata .into_iter() .map( |(name, sql_type, default, nullable, primary_key)| PackageColumn { name: name.into(), sql_type: sql_type.into(), default: default.map(str::to_owned), nullable, primary_key, declaration: None, position: None, }, ) .collect::>(); let mut indexed = BTreeSet::from(["updated_at".to_owned()]); let mut searchable = Vec::new(); let search = definition["search"].as_array(); let mut keys = BTreeSet::new(); for column in raw_columns { let key = column["key"] .as_str() .ok_or_else(|| refuse("column needs key"))?; ident(key)?; if !definition_id(key) { return Err(refuse("invalid definition column key")); } if key.starts_with('_') || !keys.insert(key) { return Err(refuse("duplicate or reserved definition column")); } let kind = column["type"] .as_str() .ok_or_else(|| refuse("column needs type"))?; let sql_type = match kind { // A size in bytes is a number the definition says in its units // (ColumnType::Bytes); stored as any number is. "number" | "bytes" => "NUMERIC", "amount" | "bool" => "INTEGER", "text" | "longtext" | "account_number" | "date" | "time" | "choice" | "link" | "photo" | "file" | "url" | "place" => "TEXT", _ => return Err(refuse(format!("unknown definition column type {kind}"))), }; // A definition's default is the engine's, applied when a record is // made: storage is nullable, so a revision may change a default freely // and the package shape step never meets a changed one. if let Some(metadata) = columns.iter_mut().find(|c| c.name == key) { if key == "id" || metadata.sql_type != sql_type { return Err(refuse(format!( "column {key} conflicts with record metadata" ))); } } else { columns.push(PackageColumn { name: key.into(), sql_type: sql_type.into(), nullable: true, default: None, primary_key: false, declaration: None, position: None, }); } if kind == "link" || column["indexed"] == true { indexed.insert(key.into()); } if matches!(kind, "text" | "longtext") && search.is_some_and(|search| search.iter().any(|field| field == key)) { searchable.push(key.into()); } } // A retired column stays in storage with every value it holds: the // definition no longer draws or writes it, and a revision only adds. for column in definition["retired"].as_array().into_iter().flatten() { let key = column["key"].as_str().ok_or_else(|| refuse("retired column needs key"))?; ident(key)?; if !definition_id(key) || !keys.insert(key) { return Err(refuse("a retired column is no longer a column")); } let sql_type = match column["type"].as_str().unwrap_or_default() { "number" | "bytes" => "NUMERIC", "amount" | "bool" => "INTEGER", "text" | "longtext" | "account_number" | "date" | "time" | "choice" | "link" | "photo" | "file" | "url" | "place" => "TEXT", kind => return Err(refuse(format!("unknown retired column type {kind}"))), }; columns.push(PackageColumn { name: key.into(), sql_type: sql_type.into(), nullable: true, default: None, primary_key: false, declaration: None, position: None, }); } for slot in ["project", "order"] { if let Some(key) = definition[slot].as_str() { if !columns.iter().any(|c| c.name == key) { return Err(refuse(format!( "definition {slot} names unknown column {key}" ))); } indexed.insert(key.into()); } } let indexes = indexed .into_iter() .map(|column| PackageIndex::Declared { name: format!("idx_{name}_{column}"), columns: vec![column], unique: false, }) .collect(); let full_text = if searchable.is_empty() { Vec::new() } else { vec![PackageFullText::Declared { name: format!("fts_{name}"), columns: searchable, }] }; let tables = vec![PackageTable { name, columns, constraints: Vec::new(), prefix: None, suffix: None, indexes, full_text, triggers: Vec::new(), }]; validate_ownership(&tables, &BTreeSet::new())?; generate(&tables, false)?; Ok(tables) }