From 20418a28e780f3154133776d57ab03c9f6ab0f01 Mon Sep 17 00:00:00 2001 From: Felipe Gutierrez Date: Tue, 24 Nov 2026 14:40:39 -0500 Subject: [PATCH 1/2] Add multi-region schema check for SeaORM (port of Spring starter) Add a declarative locality marker and a startup schema check for the SeaORM path, mirroring the Spring Boot starter's multi-region check. - cockroachdb-macros: new #[derive(CrdbLocality)] with #[crdb(global)] / #[crdb(regional_by_row)] container markers and #[crdb(region)] field marker, generating impl CrdbLocality for Entity. - cockroachdb-core: new multiregion module with the pure diff logic (evaluate), report, identifier keyword-quoting, mode (none|warn|validate, default warn), and fails_startup. Contradictions fail even in warn. Reuses the ddl.rs fix-up builders (adds set_locality_regional_by_row_as). - cockroachdb-seaorm: describe/describe_plain turn entities into descriptors via the SeaORM metamodel; verify_multiregion loads the live schema (SHOW + information_schema, no crdb_internal) and runs the diff, returning Err on validate/contradiction and logging on warn. - Tests: full branch coverage of the diff (incl contradictions + keyword quoting) and a teeth-check for contradiction-fails-in-warn; derive + describe offline test; ignored live ITs that skip when the cluster has no regions. --- crates/cockroachdb-core/src/ddl.rs | 16 + crates/cockroachdb-core/src/lib.rs | 5 + crates/cockroachdb-core/src/multiregion.rs | 917 ++++++++++++++++++ crates/cockroachdb-macros/Cargo.toml | 4 +- crates/cockroachdb-macros/src/lib.rs | 137 ++- crates/cockroachdb-seaorm/Cargo.toml | 2 + crates/cockroachdb-seaorm/src/lib.rs | 6 + crates/cockroachdb-seaorm/src/multiregion.rs | 247 +++++ .../cockroachdb-seaorm/tests/multiregion.rs | 168 ++++ 9 files changed, 1500 insertions(+), 2 deletions(-) create mode 100644 crates/cockroachdb-core/src/multiregion.rs create mode 100644 crates/cockroachdb-seaorm/src/multiregion.rs create mode 100644 crates/cockroachdb-seaorm/tests/multiregion.rs diff --git a/crates/cockroachdb-core/src/ddl.rs b/crates/cockroachdb-core/src/ddl.rs index a70b3a0..98628fc 100644 --- a/crates/cockroachdb-core/src/ddl.rs +++ b/crates/cockroachdb-core/src/ddl.rs @@ -37,6 +37,18 @@ pub fn set_locality_regional_by_row(table: &str) -> String { format!("ALTER TABLE {} SET LOCALITY REGIONAL BY ROW", ident(table)) } +/// `ALTER TABLE SET LOCALITY REGIONAL BY ROW AS `. +/// +/// For a REGIONAL BY ROW table homed by an explicit column rather than the implicit +/// `crdb_region`. +pub fn set_locality_regional_by_row_as(table: &str, region_column: &str) -> String { + format!( + "ALTER TABLE {} SET LOCALITY REGIONAL BY ROW AS {}", + ident(table), + ident(region_column) + ) +} + /// `ALTER TABLE
SET LOCALITY GLOBAL`. pub fn set_locality_global(table: &str) -> String { format!("ALTER TABLE {} SET LOCALITY GLOBAL", ident(table)) @@ -79,6 +91,10 @@ mod tests { set_locality_regional_by_row("accounts"), "ALTER TABLE \"accounts\" SET LOCALITY REGIONAL BY ROW" ); + assert_eq!( + set_locality_regional_by_row_as("accounts", "region"), + "ALTER TABLE \"accounts\" SET LOCALITY REGIONAL BY ROW AS \"region\"" + ); assert_eq!( set_locality_global("ref_data"), "ALTER TABLE \"ref_data\" SET LOCALITY GLOBAL" diff --git a/crates/cockroachdb-core/src/lib.rs b/crates/cockroachdb-core/src/lib.rs index c37894b..0106677 100644 --- a/crates/cockroachdb-core/src/lib.rs +++ b/crates/cockroachdb-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod health; pub mod isolation; pub mod metrics; pub mod middleware; +pub mod multiregion; pub mod region; pub mod retry; @@ -34,5 +35,9 @@ pub use follower::{ pub use health::{Health, HealthChecker, HealthStatus}; pub use isolation::IsolationLevel; pub use metrics::{InMemoryRecorder, MetricsRecorder, Snapshot, Snapshotter}; +pub use multiregion::{ + evaluate, fails_startup, CrdbLocality, DeclaredLocality, Kind, Mode, MultiregionReport, + MultiregionState, MultiregionTable, TableInfo, TableName, +}; pub use region::{RegionContext, RegionResolver, StaticRegionResolver, CRDB_REGION_COLUMN}; pub use retry::RetryPolicy; diff --git a/crates/cockroachdb-core/src/multiregion.rs b/crates/cockroachdb-core/src/multiregion.rs new file mode 100644 index 0000000..916d99a --- /dev/null +++ b/crates/cockroachdb-core/src/multiregion.rs @@ -0,0 +1,917 @@ +//! Multi-region schema check — the pure, driver-agnostic half. +//! +//! Compares an application's declared entity locality (`#[derive(CrdbLocality)]`, +//! see `cockroachdb-macros`) against the live multi-region configuration of its +//! database and tables, and suggests SQL for every difference. It only produces +//! strings; it never touches a connection — the SeaORM adapter loads the live +//! [`MultiregionState`] and calls [`evaluate`]. +//! +//! Faithful port of the Spring Boot starter's `MultiregionCheck`: same SHOW / +//! `information_schema` reads (no `crdb_internal`), same both-directions diff, same +//! contradiction rules. The fix-up SQL is built from the shared [`crate::ddl`] +//! builders. + +use crate::ddl; +use std::collections::{HashMap, HashSet}; + +const REGION_TYPE: &str = "crdb_internal_region"; +const IMPLICIT_REGION_COLUMN: &str = "crdb_region"; +const REGIONAL_BY_ROW: &str = "REGIONAL BY ROW"; +const OVERVIEW: &str = "https://docs.cockroachlabs.com/docs/stable/multiregion-overview"; +const CONTRADICTION: &str = "Contradiction: "; + +/// How the check reacts to problems. [`Mode::Warn`] is the default. +/// +/// A *contradiction* (an entity that declares one locality while its table has the +/// other, or entities that disagree about the same table) fails startup in every +/// mode but [`Mode::None`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Mode { + /// No check. + None, + /// Log any problems, with SQL that fixes them, and continue. A contradiction + /// still fails. + #[default] + Warn, + /// Fail on any problem. + Validate, +} + +impl Mode { + /// Lower-case name, for the report header. + pub fn as_str(self) -> &'static str { + match self { + Mode::None => "none", + Mode::Warn => "warn", + Mode::Validate => "validate", + } + } +} + +/// The locality an entity declares, via `#[derive(CrdbLocality)]`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeclaredLocality { + /// `#[crdb(global)]` — the table should be `GLOBAL`. + Global, + /// `#[crdb(regional_by_row)]` — the table should be `REGIONAL BY ROW`, by the + /// `#[crdb(region)]` field's column when one is given. + RegionalByRow { + /// DB column name of the `#[crdb(region)]` field, or `None` for the + /// implicit `crdb_region`. + region_column: Option, + }, +} + +/// Implemented by `#[derive(CrdbLocality)]` on a SeaORM entity's `Model`, for the +/// generated `Entity` type. Supplies the declared locality the check diffs against +/// the live table. +pub trait CrdbLocality { + /// The declared locality of this entity. + fn crdb_locality() -> DeclaredLocality; +} + +/// What an entity's declaration expects of its table; [`Kind::None`] for an entity +/// with no locality marker. [`Kind::Both`] marks an entity (or set of entities on +/// one table) that declares conflicting localities. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// No locality marker. + None, + /// Declared `GLOBAL`. + Global, + /// Declared `REGIONAL BY ROW`. + RegionalByRow, + /// Declares both — a contradiction. + Both, +} + +/// An entity's table and what its locality marker, if any, expects of it. Names +/// are as CockroachDB stores them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MultiregionTable { + /// The entity type name, for messages. + pub entity: String, + /// The table's schema, or `None` for the connection's current schema. + pub schema: Option, + /// The table name. + pub table: String, + /// What the marker expects; [`Kind::None`] for an unmarked entity. + pub kind: Kind, + /// The `#[crdb(region)]` column, or `None`. + pub region_column: Option, +} + +/// A schema-qualified table name, as CockroachDB stores it. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TableName { + /// Schema. + pub schema: String, + /// Table. + pub table: String, +} + +/// The live facts about one table. +#[derive(Debug, Clone, Default)] +pub struct TableInfo { + /// Locality as `SHOW TABLES` reports it; `None` outside a multi-region database. + pub locality: Option, + /// Column types (`information_schema.columns.crdb_sql_type`), read only for the + /// columns the check needs. + pub column_types: HashMap, +} + +/// What the check reads from CockroachDB. Loaded by the SeaORM adapter. +#[derive(Debug, Clone)] +pub struct MultiregionState { + /// The current database. + pub database: String, + /// The schema unqualified names resolve to. + pub current_schema: String, + /// The database's primary region, or `None` when it is not multi-region. + pub primary_region: Option, + /// The cluster's node regions; empty when no node has a region locality. + pub cluster_regions: Vec, + /// The checked tables that exist, by schema and name. + pub tables: HashMap, + /// Keywords that must be quoted when used as an identifier. + pub keywords: HashSet, +} + +/// The problems the check found, and SQL that fixes them. +#[derive(Debug, Clone, Default)] +pub struct MultiregionReport { + problems: Vec, + statements: Vec, + contradictions: usize, +} + +impl MultiregionReport { + fn problem(&mut self, problem: impl Into) { + self.problems.push(problem.into()); + } + + fn contradiction(&mut self, problem: impl Into) { + self.problems + .push(format!("{CONTRADICTION}{}", problem.into())); + self.contradictions += 1; + } + + fn statement(&mut self, statement: impl Into) { + self.statements.push(statement.into()); + } + + /// The problems found. + pub fn problems(&self) -> &[String] { + &self.problems + } + + /// The suggested SQL. + pub fn statements(&self) -> &[String] { + &self.statements + } + + /// Whether the check found nothing. + pub fn is_empty(&self) -> bool { + self.problems.is_empty() + } + + /// Whether any problem is a contradiction. + pub fn has_contradictions(&self) -> bool { + self.contradictions > 0 + } + + /// The report as one message. + pub fn format(&self, mode: Mode) -> String { + let mut out = format!( + "CockroachDB multiregion check (mode={}) found {} {}:", + mode.as_str(), + self.problems.len(), + if self.problems.len() == 1 { + "problem" + } else { + "problems" + } + ); + for problem in &self.problems { + out.push_str("\n - "); + out.push_str(&problem.replace('\n', "\n ")); + } + if self.contradictions > 0 { + out.push_str( + "\n\nContradictions stop startup in every mode but none: the annotations and the \ + schema disagree about where rows live, so one of them is wrong.", + ); + } + if !self.statements.is_empty() { + out.push_str( + "\n\nSuggested SQL (review, then add to a migration; or alter the annotations):", + ); + for statement in &self.statements { + out.push_str("\n "); + out.push_str(statement); + } + } + out.push_str(&format!("\n\nSee also: {OVERVIEW}")); + out + } +} + +/// Whether a non-empty `report` should fail startup under `mode`: validate fails on +/// any problem, and a contradiction fails in every mode but none. This is the +/// decision the SeaORM entry point makes — isolated here so it is unit-testable +/// without a database. +pub fn fails_startup(mode: Mode, report: &MultiregionReport) -> bool { + !report.is_empty() && (mode == Mode::Validate || report.has_contradictions()) +} + +/// Lists every difference between `tables` and `state`, with SQL to fix the schema +/// or a description of the marker to fix. `tables` holds every entity, marked or +/// not: a `GLOBAL` or `REGIONAL BY ROW` table needs its marker too. +pub fn evaluate(state: &MultiregionState, tables: &[MultiregionTable]) -> MultiregionReport { + let mut report = MultiregionReport::default(); + let keywords = &state.keywords; + let multiregion = state.primary_region.is_some(); + let annotated = tables.iter().filter(|t| t.kind != Kind::None).count(); + + if !multiregion && annotated > 0 { + let database = quote(&state.database, keywords); + let names = tables + .iter() + .filter(|t| t.kind != Kind::None) + .map(|t| t.entity.clone()) + .collect::>() + .join(", "); + let affected = format!( + "#[crdb(global)]/#[crdb(regional_by_row)] on {} ({names}) have no effect.", + count(annotated, "entity", "entities") + ); + if state.cluster_regions.is_empty() { + report.problem(format!( + "Database {database} is not multi-region; {affected}\nThe cluster has no regions, \ + so the database can't be made multi-region yet: start every node with \ + --locality=region=." + )); + } else { + report.problem(format!( + "Database {database} is not multi-region; {affected}\nThe cluster has regions: {}. \ + Choose the primary region deliberately; the SQL below uses the first one.", + state.cluster_regions.join(", ") + )); + report.statement(format!( + "{};", + ddl::set_primary_region(&state.database, &state.cluster_regions[0]) + )); + for region in &state.cluster_regions[1..] { + report.statement(format!("{};", ddl::add_region(&state.database, region))); + } + } + } + + // Group entities by their resolved table, preserving first-seen order. + let mut order: Vec = Vec::new(); + let mut by_table: HashMap> = HashMap::new(); + for table in tables { + let name = name_of(table, &state.current_schema); + by_table + .entry(name.clone()) + .or_insert_with(|| { + order.push(name.clone()); + Vec::new() + }) + .push(table); + } + + for name in &order { + let entities = &by_table[name]; + let qualified = format!( + "{}.{}", + quote(&name.schema, keywords), + quote(&name.table, keywords) + ); + let info = state.tables.get(name); + + let marked: Vec<&MultiregionTable> = entities + .iter() + .copied() + .filter(|t| t.kind != Kind::None) + .collect(); + let mut kinds: Vec = Vec::new(); + for t in &marked { + if !kinds.contains(&t.kind) { + kinds.push(t.kind); + } + } + + if kinds.is_empty() { + unannotated(&mut report, &qualified, info, entities, multiregion); + } else if kinds.len() > 1 || kinds.contains(&Kind::Both) { + conflicting(&mut report, &qualified, &marked); + } else { + let table = marked[0]; + match table.kind { + Kind::Global => global(&mut report, name, &qualified, info, table, multiregion), + _ => regional_by_row( + &mut report, + state, + name, + table, + &qualified, + info, + multiregion, + ), + } + } + } + report +} + +fn global( + report: &mut MultiregionReport, + name: &TableName, + qualified: &str, + info: Option<&TableInfo>, + table: &MultiregionTable, + multiregion: bool, +) { + let Some(info) = info else { + missing(report, qualified, "#[crdb(global)]", table); + return; + }; + let locality = info.locality.as_deref(); + if !multiregion || locality != Some("GLOBAL") { + if multiregion { + let loc = locality.unwrap_or(""); + let problem = format!( + "Table {qualified} (#[crdb(global)] {}) is {loc}, not GLOBAL.", + table.entity + ); + if regional_by_row_column(loc).is_some() { + report.contradiction(problem); + } else { + report.problem(problem); + } + } + report.statement(format!("{};", ddl::set_locality_global(&name.table))); + } +} + +/// An entity with no locality marker whose table is `GLOBAL` or `REGIONAL BY ROW`: +/// the code, not the schema, needs fixing. +fn unannotated( + report: &mut MultiregionReport, + qualified: &str, + info: Option<&TableInfo>, + entities: &[&MultiregionTable], + multiregion: bool, +) { + if !multiregion { + return; + } + let Some(info) = info else { + return; + }; + let names = entities + .iter() + .map(|t| t.entity.clone()) + .collect::>() + .join(", "); + let locality = info.locality.as_deref().unwrap_or(""); + if locality == "GLOBAL" { + report.problem(format!( + "Table {qualified} is GLOBAL, but entity {names} has no #[crdb(global)]. Add \ + #[crdb(global)] to it." + )); + } else if let Some(column) = regional_by_row_column(locality) { + report.problem(format!( + "Table {qualified} is {locality}, but entity {names} has no #[crdb(regional_by_row)]. \ + Add #[crdb(regional_by_row)] to it, and #[crdb(region)] to the field mapped to \ + {column} so rows are homed in the transaction's region." + )); + } +} + +fn conflicting(report: &mut MultiregionReport, qualified: &str, entities: &[&MultiregionTable]) { + if entities.len() == 1 { + report.contradiction(format!( + "Entity {} is annotated with both #[crdb(global)] and #[crdb(regional_by_row)]; keep \ + one.", + entities[0].entity + )); + return; + } + let described = entities + .iter() + .map(|t| { + let marker = match t.kind { + Kind::Global => "#[crdb(global)]", + Kind::RegionalByRow => "#[crdb(regional_by_row)]", + _ => "#[crdb(global)] and #[crdb(regional_by_row)]", + }; + format!("{} ({marker})", t.entity) + }) + .collect::>() + .join(", "); + report.contradiction(format!( + "Table {qualified} is mapped by entities with conflicting annotations: {described}. \ + Annotate them alike." + )); +} + +#[allow(clippy::too_many_arguments)] +fn regional_by_row( + report: &mut MultiregionReport, + state: &MultiregionState, + name: &TableName, + table: &MultiregionTable, + qualified: &str, + info: Option<&TableInfo>, + multiregion: bool, +) { + let Some(info) = info else { + missing(report, qualified, "#[crdb(regional_by_row)]", table); + return; + }; + let locality = info.locality.as_deref().unwrap_or(""); + let wanted_column = table.region_column.as_deref(); + let current_column = regional_by_row_column(locality); + if multiregion + && current_column.is_some() + && (wanted_column.is_none() || wanted_column == current_column.as_deref()) + { + return; + } + + let column = wanted_column.unwrap_or(IMPLICIT_REGION_COLUMN); + let quoted_column = quote(column, &state.keywords); + let col_type = info.column_types.get(column); + let description = format!( + "Table {qualified} (#[crdb(regional_by_row)] {})", + table.entity + ); + let (target, stmt) = if column == IMPLICIT_REGION_COLUMN { + ( + REGIONAL_BY_ROW.to_string(), + ddl::set_locality_regional_by_row(&name.table), + ) + } else { + ( + format!("{REGIONAL_BY_ROW} AS {quoted_column}"), + ddl::set_locality_regional_by_row_as(&name.table, column), + ) + }; + let is_global = multiregion && locality == "GLOBAL"; + if is_global { + report.contradiction(format!("{description} is GLOBAL, not {target}.")); + } + if let Some(ty) = col_type { + if !is_region_type(ty) { + report.problem(format!( + "{description}: column {quoted_column} is {ty}, but REGIONAL BY ROW needs a \ + {REGION_TYPE} column. Change it with your migrations." + )); + return; + } + } else if column != IMPLICIT_REGION_COLUMN { + report.problem(format!( + "{description}: column {quoted_column} of the #[crdb(region)] field does not exist. \ + Create it, as a {REGION_TYPE} column, with your migrations." + )); + return; + } + + if multiregion && !is_global { + report.problem(format!("{description} is {locality}, not {target}.")); + } + report.statement(format!("{stmt}; -- rewrites the table")); +} + +fn missing( + report: &mut MultiregionReport, + qualified: &str, + marker: &str, + table: &MultiregionTable, +) { + report.problem(format!( + "Table {qualified} ({marker} {}) does not exist. Create it with your migrations.", + table.entity + )); +} + +/// The region column of a `REGIONAL BY ROW` locality, or `None` for any other +/// locality. +fn regional_by_row_column(locality: &str) -> Option { + let rest = locality.strip_prefix(REGIONAL_BY_ROW)?.trim(); + if rest.is_empty() { + return Some(IMPLICIT_REGION_COLUMN.to_string()); + } + let after = rest.strip_prefix("AS ")?; + parse(after.trim()).into_iter().next() +} + +fn is_region_type(ty: &str) -> bool { + ty == REGION_TYPE || ty.ends_with(&format!(".{REGION_TYPE}")) +} + +fn name_of(table: &MultiregionTable, current_schema: &str) -> TableName { + TableName { + schema: table + .schema + .clone() + .unwrap_or_else(|| current_schema.to_string()), + table: table.table.clone(), + } +} + +fn count(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +// --- Identifier parsing/quoting, as CockroachDB treats names --- + +/// Whether `name` can be written as a plain, unquoted identifier (`[a-z_][a-z0-9_$]*`). +fn is_plain(name: &str) -> bool { + let mut chars = name.chars(); + match chars.next() { + Some(c) if c.is_ascii_lowercase() || c == '_' => {} + _ => return false, + } + chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '$') +} + +/// Quotes `name` when it can't be written as a plain identifier or is a keyword. +fn quote(name: &str, keywords: &HashSet) -> String { + if is_plain(name) && !keywords.contains(name) { + name.to_string() + } else { + format!("\"{}\"", name.replace('"', "\"\"")) + } +} + +/// Splits a possibly qualified, possibly quoted name such as `app."Orders"` into +/// its parts, as CockroachDB stores them: unquoted names fold to lower case, +/// quoted names are kept verbatim. +fn parse(rendered: &str) -> Vec { + let mut parts = Vec::new(); + let mut part = String::new(); + let mut in_quotes = false; + let mut quoted = false; + let chars: Vec = rendered.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if in_quotes { + if c != '"' { + part.push(c); + } else if i + 1 < chars.len() && chars[i + 1] == '"' { + part.push('"'); + i += 1; + } else { + in_quotes = false; + } + } else if c == '"' { + in_quotes = true; + quoted = true; + } else if c == '.' { + parts.push(finish(&part, quoted)); + part.clear(); + quoted = false; + } else { + part.push(c); + } + i += 1; + } + parts.push(finish(&part, quoted)); + parts +} + +fn finish(part: &str, quoted: bool) -> String { + if quoted { + part.to_string() + } else { + part.trim().to_lowercase() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kw() -> HashSet { + ["order", "select"].into_iter().map(String::from).collect() + } + + fn state( + primary: Option<&str>, + regions: &[&str], + tables: &[(&str, &str, Option<&str>)], + ) -> MultiregionState { + let mut map = HashMap::new(); + for (schema, table, locality) in tables { + map.insert( + TableName { + schema: schema.to_string(), + table: table.to_string(), + }, + TableInfo { + locality: locality.map(String::from), + column_types: HashMap::new(), + }, + ); + } + MultiregionState { + database: "app".into(), + current_schema: "public".into(), + primary_region: primary.map(String::from), + cluster_regions: regions.iter().map(|s| s.to_string()).collect(), + tables: map, + keywords: kw(), + } + } + + fn entity( + name: &str, + table: &str, + kind: Kind, + region_column: Option<&str>, + ) -> MultiregionTable { + MultiregionTable { + entity: name.into(), + schema: None, + table: table.into(), + kind, + region_column: region_column.map(String::from), + } + } + + // --- identifier quoting --- + + #[test] + fn quote_plain_keyword_and_special() { + let k = kw(); + assert_eq!(quote("accounts", &k), "accounts"); + assert_eq!(quote("order", &k), "\"order\""); // keyword + assert_eq!(quote("Orders", &k), "\"Orders\""); // uppercase -> not plain + assert_eq!(quote("we\"ird", &k), "\"we\"\"ird\""); + assert_eq!(quote("", &k), "\"\""); + } + + #[test] + fn parse_qualified_quoted() { + assert_eq!(parse("app.\"Orders\""), vec!["app", "Orders"]); + assert_eq!(parse("PUBLIC"), vec!["public"]); // unquoted folds to lower + assert_eq!(parse("\"Mixed\""), vec!["Mixed"]); + } + + #[test] + fn rbr_column_parsing() { + assert_eq!( + regional_by_row_column("REGIONAL BY ROW").as_deref(), + Some("crdb_region") + ); + assert_eq!( + regional_by_row_column("REGIONAL BY ROW AS \"Region\"").as_deref(), + Some("Region") + ); + assert_eq!( + regional_by_row_column("REGIONAL BY ROW AS region").as_deref(), + Some("region") + ); + assert_eq!(regional_by_row_column("GLOBAL"), None); + assert_eq!( + regional_by_row_column("REGIONAL BY TABLE IN \"us-east1\""), + None + ); + } + + // --- database-level --- + + #[test] + fn not_multiregion_with_regions_suggests_primary_and_add() { + let s = state( + None, + &["us-east1", "us-west1"], + &[("public", "ideas", None)], + ); + let tables = vec![entity("Idea", "ideas", Kind::RegionalByRow, None)]; + let r = evaluate(&s, &tables); + assert!(!r.is_empty()); + assert!(!r.has_contradictions()); + assert!(r.problems()[0].contains("is not multi-region")); + let sql = r.statements().join("\n"); + assert!(sql.contains("SET PRIMARY REGION 'us-east1';")); + assert!(sql.contains("ADD REGION 'us-west1';")); + assert!(sql.contains("REGIONAL BY ROW; -- rewrites the table")); + } + + #[test] + fn not_multiregion_without_regions_explains() { + let s = state(None, &[], &[("public", "ideas", None)]); + let tables = vec![entity("Idea", "ideas", Kind::Global, None)]; + let r = evaluate(&s, &tables); + assert!(r.problems()[0].contains("cluster has no regions")); + // No ALTER DATABASE statements, but the table locality fix still appears. + let sql = r.statements().join("\n"); + assert!(!sql.contains("PRIMARY REGION")); + assert!(sql.contains("SET LOCALITY GLOBAL;")); + } + + // --- global() --- + + #[test] + fn global_ok_is_silent() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ref", Some("GLOBAL"))], + ); + let r = evaluate(&s, &[entity("Ref", "ref", Kind::Global, None)]); + assert!(r.is_empty()); + } + + #[test] + fn global_on_rbr_table_is_contradiction() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ref", Some("REGIONAL BY ROW"))], + ); + let r = evaluate(&s, &[entity("Ref", "ref", Kind::Global, None)]); + assert!(r.has_contradictions()); + assert!(r.problems()[0].starts_with(CONTRADICTION)); + assert!(r + .statements() + .iter() + .any(|s| s.contains("SET LOCALITY GLOBAL"))); + } + + #[test] + fn global_missing_table() { + let s = state(Some("us-east1"), &["us-east1"], &[]); + let r = evaluate(&s, &[entity("Ref", "ref", Kind::Global, None)]); + assert!(r.problems()[0].contains("does not exist")); + assert!(!r.has_contradictions()); + } + + // --- regional_by_row() --- + + #[test] + fn rbr_on_global_table_is_contradiction() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("GLOBAL"))], + ); + let r = evaluate(&s, &[entity("Idea", "ideas", Kind::RegionalByRow, None)]); + assert!(r.has_contradictions()); + assert!(r.problems()[0].contains("is GLOBAL, not REGIONAL BY ROW")); + } + + #[test] + fn rbr_matches_is_silent() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("REGIONAL BY ROW"))], + ); + let r = evaluate(&s, &[entity("Idea", "ideas", Kind::RegionalByRow, None)]); + assert!(r.is_empty()); + } + + #[test] + fn rbr_wrong_column_type_reported_no_statement() { + let mut s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("REGIONAL BY ROW"))], + ); + let info = s + .tables + .get_mut(&TableName { + schema: "public".into(), + table: "ideas".into(), + }) + .unwrap(); + info.column_types.insert("region".into(), "STRING".into()); + let r = evaluate( + &s, + &[entity("Idea", "ideas", Kind::RegionalByRow, Some("region"))], + ); + assert!(r.problems()[0].contains("needs a crdb_internal_region column")); + } + + #[test] + fn rbr_region_type_column_matches() { + let mut s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("REGIONAL BY ROW AS region"))], + ); + let info = s + .tables + .get_mut(&TableName { + schema: "public".into(), + table: "ideas".into(), + }) + .unwrap(); + info.column_types + .insert("region".into(), "crdb_internal_region".into()); + let r = evaluate( + &s, + &[entity("Idea", "ideas", Kind::RegionalByRow, Some("region"))], + ); + assert!(r.is_empty()); + } + + // --- unannotated (reverse direction) --- + + #[test] + fn table_global_but_entity_unmarked() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ref", Some("GLOBAL"))], + ); + let r = evaluate(&s, &[entity("Ref", "ref", Kind::None, None)]); + assert!(r.problems()[0].contains("has no #[crdb(global)]")); + assert!(r.statements().is_empty()); + } + + #[test] + fn table_rbr_but_entity_unmarked() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("REGIONAL BY ROW"))], + ); + let r = evaluate(&s, &[entity("Idea", "ideas", Kind::None, None)]); + assert!(r.problems()[0].contains("has no #[crdb(regional_by_row)]")); + } + + // --- conflicting --- + + #[test] + fn single_entity_both_markers_is_contradiction() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("GLOBAL"))], + ); + let r = evaluate(&s, &[entity("Idea", "ideas", Kind::Both, None)]); + assert!(r.has_contradictions()); + assert!(r.problems()[0].contains("both #[crdb(global)] and #[crdb(regional_by_row)]")); + } + + #[test] + fn two_entities_same_table_conflict_is_contradiction() { + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ideas", Some("GLOBAL"))], + ); + let r = evaluate( + &s, + &[ + entity("A", "ideas", Kind::Global, None), + entity("B", "ideas", Kind::RegionalByRow, None), + ], + ); + assert!(r.has_contradictions()); + assert!(r.problems()[0].contains("conflicting annotations")); + } + + // --- fails_startup (teeth-check) --- + + #[test] + fn fails_startup_rules() { + // A plain problem (not a contradiction) only fails in validate. + let s = state( + Some("us-east1"), + &["us-east1"], + &[("public", "ref", Some("REGIONAL BY TABLE IN \"us-east1\""))], + ); + let warn_only = evaluate(&s, &[entity("Ref", "ref", Kind::Global, None)]); + assert!(!warn_only.is_empty()); + assert!(!warn_only.has_contradictions()); + assert!(!fails_startup(Mode::Warn, &warn_only)); + assert!(fails_startup(Mode::Validate, &warn_only)); + + // A contradiction fails even in warn. If this assert flips, the + // contradiction-fails-in-warn guarantee has been reverted. + let contradiction = evaluate( + &state( + Some("us-east1"), + &["us-east1"], + &[("public", "ref", Some("REGIONAL BY ROW"))], + ), + &[entity("Ref", "ref", Kind::Global, None)], + ); + assert!(contradiction.has_contradictions()); + assert!(fails_startup(Mode::Warn, &contradiction)); + + // Empty report never fails. + assert!(!fails_startup( + Mode::Validate, + &MultiregionReport::default() + )); + } +} diff --git a/crates/cockroachdb-macros/Cargo.toml b/crates/cockroachdb-macros/Cargo.toml index 347c61c..d392105 100644 --- a/crates/cockroachdb-macros/Cargo.toml +++ b/crates/cockroachdb-macros/Cargo.toml @@ -13,11 +13,13 @@ authors.workspace = true proc-macro = true [dependencies] -syn = { workspace = true } +syn = { workspace = true, features = ["derive"] } quote = { workspace = true } proc-macro2 = { workspace = true } [dev-dependencies] cockroachdb-sqlx = { workspace = true } +cockroachdb-core = { workspace = true } +sea-orm = { version = "1", default-features = false, features = ["macros"] } sqlx = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } diff --git a/crates/cockroachdb-macros/src/lib.rs b/crates/cockroachdb-macros/src/lib.rs index 1f7bd29..7e0e11e 100644 --- a/crates/cockroachdb-macros/src/lib.rs +++ b/crates/cockroachdb-macros/src/lib.rs @@ -10,7 +10,7 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, Ident, ItemFn}; +use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident, ItemFn}; /// Wraps an `async fn` body in a retrying transaction. /// @@ -131,3 +131,138 @@ impl syn::parse::Parse for MacroArgs { Ok(Self { pool, staleness }) } } + +/// Declares a SeaORM entity's multi-region locality, the analogue of Spring's +/// `@GlobalTable` / `@RegionalByRow` / `@CrdbRegion`. +/// +/// Put it on the entity's `Model` struct alongside `DeriveEntityModel`; it generates +/// `impl cockroachdb_core::multiregion::CrdbLocality for Entity`, which the SeaORM +/// adapter's `verify_multiregion` check diffs against the live table. Requires a +/// `cockroachdb-core` dependency (the generated code names it by path). +/// +/// Container attribute (exactly one required): +/// - `#[crdb(global)]` — the table should be `GLOBAL`. +/// - `#[crdb(regional_by_row)]` — the table should be `REGIONAL BY ROW`. +/// +/// Field attribute (only with `regional_by_row`): +/// - `#[crdb(region)]` — marks the region column. The declared column name is the +/// field's name. +/// +/// ```ignore +/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel, CrdbLocality)] +/// #[sea_orm(table_name = "ideas")] +/// #[crdb(regional_by_row)] +/// pub struct Model { +/// #[sea_orm(primary_key)] +/// pub id: i64, +/// pub title: String, +/// #[crdb(region)] +/// pub region: String, +/// } +/// ``` +#[proc_macro_derive(CrdbLocality, attributes(crdb))] +pub fn derive_crdb_locality(item: TokenStream) -> TokenStream { + let input = parse_macro_input!(item as DeriveInput); + match expand_locality(&input) { + Ok(tokens) => tokens.into(), + Err(err) => err.to_compile_error().into(), + } +} + +fn expand_locality(input: &DeriveInput) -> syn::Result { + let mut global = false; + let mut regional_by_row = false; + for attr in &input.attrs { + if attr.path().is_ident("crdb") { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("global") { + global = true; + Ok(()) + } else if meta.path.is_ident("regional_by_row") { + regional_by_row = true; + Ok(()) + } else { + Err(meta.error("expected `global` or `regional_by_row`")) + } + })?; + } + } + + if global && regional_by_row { + return Err(syn::Error::new_spanned( + &input.ident, + "a type cannot be both #[crdb(global)] and #[crdb(regional_by_row)]", + )); + } + if !global && !regional_by_row { + return Err(syn::Error::new_spanned( + &input.ident, + "#[derive(CrdbLocality)] needs #[crdb(global)] or #[crdb(regional_by_row)]", + )); + } + + let Data::Struct(data) = &input.data else { + return Err(syn::Error::new_spanned( + &input.ident, + "#[derive(CrdbLocality)] can only be applied to a struct", + )); + }; + + // ponytail: the region column is taken from the field name — SeaORM's default + // column name. A `#[sea_orm(column_name = "...")]` override on the region field + // is not read; rename the field to match if you need a different column. + let mut region_column: Option = None; + if let Fields::Named(named) = &data.fields { + for field in &named.named { + let mut is_region = false; + for attr in &field.attrs { + if attr.path().is_ident("crdb") { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("region") { + is_region = true; + Ok(()) + } else { + Err(meta.error("expected `region`")) + } + })?; + } + } + if is_region { + if !regional_by_row { + return Err(syn::Error::new_spanned( + field, + "#[crdb(region)] is only valid with #[crdb(regional_by_row)]", + )); + } + if region_column.is_some() { + return Err(syn::Error::new_spanned( + field, + "only one field may be #[crdb(region)]", + )); + } + region_column = Some(field.ident.as_ref().unwrap().to_string()); + } + } + } + + let body = if global { + quote! { ::cockroachdb_core::multiregion::DeclaredLocality::Global } + } else { + let column = match region_column { + Some(c) => quote! { ::core::option::Option::Some(::std::string::String::from(#c)) }, + None => quote! { ::core::option::Option::None }, + }; + quote! { + ::cockroachdb_core::multiregion::DeclaredLocality::RegionalByRow { region_column: #column } + } + }; + + Ok(quote! { + #[automatically_derived] + impl ::cockroachdb_core::multiregion::CrdbLocality for Entity { + fn crdb_locality() -> ::cockroachdb_core::multiregion::DeclaredLocality { + #body + } + } + }) +} diff --git a/crates/cockroachdb-seaorm/Cargo.toml b/crates/cockroachdb-seaorm/Cargo.toml index d94efa6..14b4a06 100644 --- a/crates/cockroachdb-seaorm/Cargo.toml +++ b/crates/cockroachdb-seaorm/Cargo.toml @@ -16,4 +16,6 @@ sea-orm = { version = "1", default-features = false, features = ["sqlx-postgres" tokio = { workspace = true } [dev-dependencies] +cockroachdb-macros = { workspace = true } +sea-orm = { version = "1", default-features = false, features = ["macros"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } diff --git a/crates/cockroachdb-seaorm/src/lib.rs b/crates/cockroachdb-seaorm/src/lib.rs index 47379ac..e05e412 100644 --- a/crates/cockroachdb-seaorm/src/lib.rs +++ b/crates/cockroachdb-seaorm/src/lib.rs @@ -27,7 +27,13 @@ use sea_orm::{ use std::future::Future; use std::pin::Pin; +pub mod multiregion; + pub use cockroachdb_core as core; +pub use multiregion::{ + describe, describe_plain, verify_multiregion, CrdbLocality, DeclaredLocality, Kind, Mode, + MultiregionReport, MultiregionTable, +}; /// Extracts the Postgres `SQLSTATE` from a SeaORM error, if present. fn sql_state(err: &DbErr) -> Option { diff --git a/crates/cockroachdb-seaorm/src/multiregion.rs b/crates/cockroachdb-seaorm/src/multiregion.rs new file mode 100644 index 0000000..4271203 --- /dev/null +++ b/crates/cockroachdb-seaorm/src/multiregion.rs @@ -0,0 +1,247 @@ +//! Multi-region schema check for SeaORM entities — the driver half. +//! +//! [`describe`] turns a SeaORM entity marked with `#[derive(CrdbLocality)]` into a +//! [`MultiregionTable`] descriptor; [`verify_multiregion`] loads the live schema and +//! runs the pure [`cockroachdb_core::multiregion::evaluate`] diff. This mirrors the +//! Spring Boot starter's startup check, on the SeaORM path. +//! +//! It is **opt-in**: call [`verify_multiregion`] after [`crate::connect`], passing the +//! entities to check. In [`Mode::Warn`] (the default) it logs problems and continues; +//! in [`Mode::Validate`], or on a contradiction in any mode but [`Mode::None`], it +//! returns `Err` so the caller can fail startup. +//! +//! ```no_run +//! # use sea_orm::DatabaseConnection; +//! # use cockroachdb_seaorm::{describe, verify_multiregion, Mode}; +//! # mod ideas { use sea_orm::entity::prelude::*; +//! # #[derive(Clone, Debug, PartialEq, DeriveEntityModel)] +//! # #[sea_orm(table_name = "ideas")] pub struct Model { #[sea_orm(primary_key)] pub id: i64 } +//! # #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {} +//! # impl ActiveModelBehavior for ActiveModel {} +//! # impl ::cockroachdb_core::multiregion::CrdbLocality for Entity { +//! # fn crdb_locality() -> ::cockroachdb_core::multiregion::DeclaredLocality { +//! # ::cockroachdb_core::multiregion::DeclaredLocality::Global } } } +//! # async fn demo(db: DatabaseConnection) -> Result<(), sea_orm::DbErr> { +//! let report = verify_multiregion(&db, Mode::Warn, vec![describe::()]).await?; +//! assert!(report.is_empty() || !report.has_contradictions()); +//! # Ok(()) } +//! ``` + +use cockroachdb_core::multiregion::{ + evaluate, fails_startup, MultiregionState, TableInfo, TableName, +}; +use sea_orm::{ + ConnectionTrait, DatabaseBackend, DatabaseConnection, DbErr, EntityTrait, Statement, Value, +}; +use std::collections::{HashMap, HashSet}; + +pub use cockroachdb_core::multiregion::{ + CrdbLocality, DeclaredLocality, Kind, Mode, MultiregionReport, MultiregionTable, +}; + +const PG: DatabaseBackend = DatabaseBackend::Postgres; + +/// Describes a marked entity for the check: its table, schema, declared locality, and +/// region column. `E` must be a SeaORM entity with `#[derive(CrdbLocality)]`. +pub fn describe() -> MultiregionTable +where + E: EntityTrait + CrdbLocality, +{ + let entity = E::default(); + let (kind, region_column) = match E::crdb_locality() { + DeclaredLocality::Global => (Kind::Global, None), + DeclaredLocality::RegionalByRow { region_column } => (Kind::RegionalByRow, region_column), + }; + MultiregionTable { + entity: std::any::type_name::().to_string(), + schema: entity.schema_name().map(str::to_string), + table: entity.table_name().to_string(), + kind, + region_column, + } +} + +/// Describes an unmarked entity, so the check can also report a `GLOBAL` or +/// `REGIONAL BY ROW` table whose entity is missing its marker (the reverse +/// direction). `E` only needs to be a SeaORM entity. +pub fn describe_plain() -> MultiregionTable +where + E: EntityTrait, +{ + let entity = E::default(); + MultiregionTable { + entity: std::any::type_name::().to_string(), + schema: entity.schema_name().map(str::to_string), + table: entity.table_name().to_string(), + kind: Kind::None, + region_column: None, + } +} + +/// Checks `tables` against the live multi-region schema of `db`. +/// +/// Returns an empty report when `mode` is [`Mode::None`], when `tables` is empty, or +/// when the database is not CockroachDB (the check skips quietly). Otherwise loads the +/// schema, diffs it, and — if there are problems — either returns `Err` (validate, or +/// any contradiction) or logs to stderr and returns the report (warn). +pub async fn verify_multiregion( + db: &DatabaseConnection, + mode: Mode, + tables: Vec, +) -> Result { + if mode == Mode::None || tables.is_empty() { + return Ok(MultiregionReport::default()); + } + if !is_cockroachdb(db).await? { + eprintln!("CockroachDB multiregion check skipped: the database is not CockroachDB"); + return Ok(MultiregionReport::default()); + } + let state = load(db, &tables).await?; + let report = evaluate(&state, &tables); + if report.is_empty() { + return Ok(report); + } + if fails_startup(mode, &report) { + return Err(DbErr::Custom(report.format(mode))); + } + eprintln!("{}", report.format(mode)); + Ok(report) +} + +/// Whether `db` is CockroachDB. The check skips other databases quietly. +async fn is_cockroachdb(db: &DatabaseConnection) -> Result { + let row = db + .query_one(Statement::from_string(PG, "SELECT version()")) + .await?; + Ok(row + .and_then(|r| r.try_get_by::(0usize).ok()) + .map(|v| v.contains("CockroachDB")) + .unwrap_or(false)) +} + +fn name_of(table: &MultiregionTable, current_schema: &str) -> TableName { + TableName { + schema: table + .schema + .clone() + .unwrap_or_else(|| current_schema.to_string()), + table: table.table.clone(), + } +} + +/// Reads what [`evaluate`] needs. Uses `SHOW` statements and `information_schema`, +/// never `crdb_internal`, matching the Spring starter. +async fn load( + db: &DatabaseConnection, + tables: &[MultiregionTable], +) -> Result { + let row = db + .query_one(Statement::from_string( + PG, + "SELECT current_database(), current_schema()", + )) + .await? + .ok_or_else(|| { + DbErr::Custom("multiregion check: current_database() returned no row".into()) + })?; + let database: String = row.try_get_by::(0usize)?; + let current_schema: String = row + .try_get_by::, _>(1usize)? + .unwrap_or_else(|| "public".to_string()); + + let primary_region = db + .query_one(Statement::from_sql_and_values( + PG, + "SELECT primary_region FROM [SHOW DATABASES] WHERE database_name = $1", + [Value::from(database.clone())], + )) + .await? + .and_then(|r| r.try_get_by::, _>(0usize).ok().flatten()); + + let mut cluster_regions = Vec::new(); + for r in db + .query_all(Statement::from_string( + PG, + "SELECT region FROM [SHOW REGIONS FROM CLUSTER] ORDER BY region", + )) + .await? + { + cluster_regions.push(r.try_get_by::(0usize)?); + } + + let mut keywords = HashSet::new(); + for r in db + .query_all(Statement::from_string( + PG, + "SELECT word FROM pg_get_keywords() WHERE catcode IN ('R', 'T')", + )) + .await? + { + keywords.insert(r.try_get_by::(0usize)?); + } + + let wanted: HashSet = tables.iter().map(|t| name_of(t, ¤t_schema)).collect(); + + let mut found: HashMap = HashMap::new(); + for r in db + .query_all(Statement::from_string( + PG, + "SELECT schema_name, table_name, locality FROM [SHOW TABLES] WHERE type = 'table'", + )) + .await? + { + let name = TableName { + schema: r.try_get_by::(0usize)?, + table: r.try_get_by::(1usize)?, + }; + if wanted.contains(&name) { + found.insert( + name, + TableInfo { + locality: r.try_get_by::, _>(2usize)?, + column_types: HashMap::new(), + }, + ); + } + } + + for table in tables { + if table.kind != Kind::RegionalByRow { + continue; + } + let name = name_of(table, ¤t_schema); + if !found.contains_key(&name) { + continue; + } + let mut types = HashMap::new(); + for r in db + .query_all(Statement::from_sql_and_values( + PG, + "SELECT column_name, crdb_sql_type FROM information_schema.columns \ + WHERE table_catalog = current_database() AND table_schema = $1 AND table_name = $2", + [ + Value::from(name.schema.clone()), + Value::from(name.table.clone()), + ], + )) + .await? + { + types.insert( + r.try_get_by::(0usize)?, + r.try_get_by::(1usize)?, + ); + } + if let Some(info) = found.get_mut(&name) { + info.column_types = types; + } + } + + Ok(MultiregionState { + database, + current_schema, + primary_region, + cluster_regions, + tables: found, + keywords, + }) +} diff --git a/crates/cockroachdb-seaorm/tests/multiregion.rs b/crates/cockroachdb-seaorm/tests/multiregion.rs new file mode 100644 index 0000000..b42af67 --- /dev/null +++ b/crates/cockroachdb-seaorm/tests/multiregion.rs @@ -0,0 +1,168 @@ +//! Multi-region check tests. +//! +//! The `describe` test exercises the `#[derive(CrdbLocality)]` macro + metamodel +//! read offline (no database), under a plain `cargo test`. The `#[ignore]`d tests +//! need a live CockroachDB cluster: +//! +//! ```bash +//! CRDB_URL=postgres://... cargo test -p cockroachdb-seaorm -- --ignored +//! ``` + +use cockroachdb_seaorm::{describe, describe_plain, verify_multiregion, Kind, Mode}; + +// A GLOBAL entity on table `ref_data`. +mod ref_global { + use cockroachdb_macros::CrdbLocality; + use sea_orm::entity::prelude::*; + + #[derive(Clone, Debug, PartialEq, DeriveEntityModel, CrdbLocality)] + #[sea_orm(table_name = "ref_data")] + #[crdb(global)] + pub struct Model { + #[sea_orm(primary_key)] + pub id: i64, + pub name: String, + } + + #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] + pub enum Relation {} + + impl ActiveModelBehavior for ActiveModel {} +} + +// A REGIONAL BY ROW entity on table `ideas`, homed by the `region` column. +mod ideas_rbr { + use cockroachdb_macros::CrdbLocality; + use sea_orm::entity::prelude::*; + + #[derive(Clone, Debug, PartialEq, DeriveEntityModel, CrdbLocality)] + #[sea_orm(table_name = "ideas")] + #[crdb(regional_by_row)] + pub struct Model { + #[sea_orm(primary_key)] + pub id: i64, + pub title: String, + #[crdb(region)] + pub region: String, + } + + #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] + pub enum Relation {} + + impl ActiveModelBehavior for ActiveModel {} +} + +// A REGIONAL BY ROW entity on table `ref_data` (no region column): used to force a +// GLOBAL-table-vs-RBR-entity contradiction. +mod ref_rbr { + use cockroachdb_macros::CrdbLocality; + use sea_orm::entity::prelude::*; + + #[derive(Clone, Debug, PartialEq, DeriveEntityModel, CrdbLocality)] + #[sea_orm(table_name = "ref_data")] + #[crdb(regional_by_row)] + pub struct Model { + #[sea_orm(primary_key)] + pub id: i64, + pub name: String, + } + + #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] + pub enum Relation {} + + impl ActiveModelBehavior for ActiveModel {} +} + +#[test] +fn describe_reads_declared_locality_from_the_derive() { + let g = describe::(); + assert_eq!(g.table, "ref_data"); + assert_eq!(g.kind, Kind::Global); + assert!(g.region_column.is_none()); + + let r = describe::(); + assert_eq!(r.table, "ideas"); + assert_eq!(r.kind, Kind::RegionalByRow); + assert_eq!(r.region_column.as_deref(), Some("region")); + + let plain = describe_plain::(); + assert_eq!(plain.kind, Kind::None); + assert_eq!(plain.table, "ideas"); +} + +fn dsn() -> String { + std::env::var("CRDB_URL") + .unwrap_or_else(|_| "postgres://root@localhost:26257/defaultdb?sslmode=disable".into()) +} + +fn is_multiregion_unavailable(e: &sea_orm::DbErr) -> bool { + // A single-node cluster started without --locality has no regions, so declaring + // one fails (42xxx / 42602); the message mentions "region". Mirrors the SQLx + // example's skip. + e.to_string().to_lowercase().contains("region") +} + +#[tokio::test] +#[ignore = "requires a live CockroachDB cluster (set CRDB_URL)"] +async fn warn_reports_non_multiregion_database() { + use sea_orm::ConnectionTrait; + let db = sea_orm::Database::connect(dsn()).await.expect("connect"); + db.execute_unprepared("CREATE TABLE IF NOT EXISTS ref_data (id INT PRIMARY KEY, name STRING)") + .await + .expect("create table"); + + // On a non-multi-region database the GLOBAL marker has no effect: a plain + // problem, not a contradiction, so warn returns Ok with a non-empty report. + let report = verify_multiregion(&db, Mode::Warn, vec![describe::()]) + .await + .expect("warn mode returns Ok on a plain (non-contradiction) problem"); + assert!(!report.is_empty()); + assert!(!report.has_contradictions()); + assert!(report + .problems() + .iter() + .any(|p| p.contains("not multi-region"))); +} + +#[tokio::test] +#[ignore = "requires a MULTI-REGION CockroachDB cluster (set CRDB_URL)"] +async fn contradiction_fails_even_in_warn() { + use sea_orm::ConnectionTrait; + let db = sea_orm::Database::connect(dsn()).await.expect("connect"); + db.execute_unprepared("CREATE TABLE IF NOT EXISTS ref_data (id INT PRIMARY KEY, name STRING)") + .await + .expect("create table"); + + let dbname: String = db + .query_one(sea_orm::Statement::from_string( + sea_orm::DatabaseBackend::Postgres, + "SELECT current_database()", + )) + .await + .expect("db name") + .expect("row") + .try_get_by::(0usize) + .expect("name"); + + // Make the database multi-region and the table GLOBAL. On a single-node cluster + // with no regions this fails — skip, there is nothing to prove. + let setup = format!("ALTER DATABASE \"{dbname}\" SET PRIMARY REGION 'us-east1'"); + if let Err(e) = db.execute_unprepared(&setup).await { + if is_multiregion_unavailable(&e) { + eprintln!("skipping: cluster has no regions configured (single-node)"); + return; + } + panic!("set primary region: {e}"); + } + db.execute_unprepared("ALTER TABLE ref_data SET LOCALITY GLOBAL") + .await + .expect("set global"); + + // The table is GLOBAL but the entity declares REGIONAL BY ROW: a contradiction, + // which must fail even in warn mode. + let result = verify_multiregion(&db, Mode::Warn, vec![describe::()]).await; + assert!( + result.is_err(), + "a contradiction must fail startup even in warn mode" + ); +} From 1b548d6b0113e97aa3706074ec85b8a63785787f Mon Sep 17 00:00:00 2001 From: Felipe Gutierrez Date: Tue, 24 Nov 2026 15:19:29 -0500 Subject: [PATCH 2/2] Bump version 0.1.0 -> 0.2.0 for multi-region annotation check release --- Cargo.toml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0495dbb..3cd2cc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ members = [ # "crates/cockroachdb-testing", [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" rust-version = "1.75" license = "Apache-2.0" @@ -43,11 +43,11 @@ serde_json = "1" # Internal crates: `path` is used for local dev/build; `version` + `registry` # are what `cargo package` records so consumers resolve them from the Pages feed. -cockroachdb-core = { path = "crates/cockroachdb-core", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-sqlx = { path = "crates/cockroachdb-sqlx", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-macros = { path = "crates/cockroachdb-macros", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-cdc = { path = "crates/cockroachdb-cdc", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-ai = { path = "crates/cockroachdb-ai", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-continuum = { path = "crates/cockroachdb-continuum", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-seaorm = { path = "crates/cockroachdb-seaorm", version = "0.1.0", registry = "cockroachlabs" } -cockroachdb-testing = { path = "crates/cockroachdb-testing", version = "0.1.0", registry = "cockroachlabs" } +cockroachdb-core = { path = "crates/cockroachdb-core", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-sqlx = { path = "crates/cockroachdb-sqlx", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-macros = { path = "crates/cockroachdb-macros", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-cdc = { path = "crates/cockroachdb-cdc", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-ai = { path = "crates/cockroachdb-ai", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-continuum = { path = "crates/cockroachdb-continuum", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-seaorm = { path = "crates/cockroachdb-seaorm", version = "0.2.0", registry = "cockroachlabs" } +cockroachdb-testing = { path = "crates/cockroachdb-testing", version = "0.2.0", registry = "cockroachlabs" }