1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
use core::fmt;
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use anyhow::Context;
use spacetimedb_primitives::Constraints;
use crate::database_logger::SystemLogger;
use crate::error::DBError;
use crate::execution_context::ExecutionContext;
use super::datastore::locking_tx_datastore::MutTxId;
use super::relational_db::RelationalDB;
use spacetimedb_sats::db::def::{ConstraintDef, TableDef, TableSchema};
use spacetimedb_sats::hash::Hash;
#[derive(thiserror::Error, Debug)]
pub enum UpdateDatabaseError {
#[error("incompatible schema changes for: {tables:?}")]
IncompatibleSchema { tables: Vec<String> },
#[error(transparent)]
Database(#[from] DBError),
}
pub fn update_database(
stdb: &RelationalDB,
tx: MutTxId,
proposed_tables: Vec<TableDef>,
fence: u128,
module_hash: Hash,
system_logger: &SystemLogger,
) -> anyhow::Result<Result<MutTxId, UpdateDatabaseError>> {
let ctx = ExecutionContext::internal(stdb.address());
let (tx, res) = stdb.with_auto_rollback::<_, _, anyhow::Error>(&ctx, tx, |tx| {
let existing_tables = stdb.get_all_tables_mut(tx)?;
match schema_updates(existing_tables, proposed_tables)? {
SchemaUpdates::Updates { new_tables } => {
for (name, schema) in new_tables {
system_logger.info(&format!("Creating table `{}`", name));
stdb.create_table(tx, schema)
.with_context(|| format!("failed to create table {}", name))?;
}
}
SchemaUpdates::Tainted(tainted) => {
system_logger.error("Module update rejected due to schema mismatch");
let mut tables = Vec::with_capacity(tainted.len());
for t in tainted {
system_logger.warn(&format!("{}: {}", t.table_name, t.reason));
tables.push(t.table_name);
}
return Ok(Err(UpdateDatabaseError::IncompatibleSchema { tables }));
}
}
// Update the module hash. Morally, this should be done _after_ calling
// the `update` reducer, but that consumes our transaction context.
stdb.set_program_hash(tx, fence, module_hash)?;
Ok(Ok(()))
})?;
Ok(stdb.rollback_on_err(&ctx, tx, res).map(|(tx, ())| tx))
}
/// The reasons a table can become [`Tainted`].
#[derive(Debug, Eq, PartialEq)]
pub enum TaintReason {
/// The (row) schema changed, and we don't know how to go from A to B.
IncompatibleSchema,
/// The table is no longer present in the new schema.
Orphaned,
}
impl fmt::Display for TaintReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::IncompatibleSchema => "incompatible schema",
Self::Orphaned => "orphaned",
})
}
}
/// A table with name `table_name` marked tainted for reason [`TaintReason`].
#[derive(Debug, PartialEq)]
pub struct Tainted {
pub table_name: String,
pub reason: TaintReason,
}
#[derive(Debug)]
pub enum SchemaUpdates {
/// The schema cannot be updated due to conflicts.
Tainted(Vec<Tainted>),
/// The schema can be updates.
Updates {
/// Tables to create.
new_tables: HashMap<String, TableDef>,
},
}
/// Compute the diff between the current and proposed schema.
///
/// Compares all `existing_tables` loaded from the [`RelationalDB`] against the
/// proposed [`TableDef`]s. The proposed schemas are assumed to represent the
/// full schema information extracted from an STDB module.
///
/// Tables in the latter whose schema differs from the former are returned as
/// [`SchemaUpdates::Tainted`]. Tables also become tainted if they are
/// no longer present in the proposed schema (they are said to be "orphaned"),
/// although this restriction may be lifted in the future.
///
/// If no tables become tainted, the database may safely be updated using the
/// information in [`SchemaUpdates::Updates`].
pub fn schema_updates(
existing_tables: Vec<Cow<'_, TableSchema>>,
proposed_tables: Vec<TableDef>,
) -> anyhow::Result<SchemaUpdates> {
let mut new_tables = HashMap::new();
let mut tainted_tables = Vec::new();
let mut known_tables: BTreeMap<String, Cow<TableSchema>> = existing_tables
.into_iter()
.map(|schema| (schema.table_name.clone(), schema))
.collect();
for proposed_schema_def in proposed_tables {
let proposed_table_name = &proposed_schema_def.table_name;
if let Some(known_schema) = known_tables.remove(proposed_table_name) {
let known_schema_def = TableDef::from(known_schema.as_ref().clone());
if !equiv(&known_schema_def, &proposed_schema_def) {
log::warn!("Schema incompatible: {proposed_table_name}");
log::debug!("Existing: {known_schema_def:?}");
log::debug!("Proposed: {proposed_schema_def:?}");
tainted_tables.push(Tainted {
table_name: proposed_table_name.to_owned(),
reason: TaintReason::IncompatibleSchema,
});
}
} else {
new_tables.insert(proposed_table_name.to_owned(), proposed_schema_def);
}
}
// We may at some point decide to drop orphaned tables automatically,
// but for now it's an incompatible schema change
for orphan in known_tables.into_keys() {
if !orphan.starts_with("st_") {
tainted_tables.push(Tainted {
table_name: orphan,
reason: TaintReason::Orphaned,
});
}
}
let res = if tainted_tables.is_empty() {
SchemaUpdates::Updates { new_tables }
} else {
SchemaUpdates::Tainted(tainted_tables)
};
Ok(res)
}
/// Compares two [`TableDef`] values for equivalence.
///
/// One side of the comparison is assumed to come from a module, the other from
/// the existing database.
///
/// Two [`TableDef`] values are considered equivalent if their fields are equal,
/// except:
///
/// - `indexes` are never equal, because they only exist in the database
/// - `sequences` are never equal, because they only exist in the database
/// - `constraints` are delicate:
///
/// - The number of `constraints` obtained from the module will always be the
/// same as the number of columns, emitting [`Constraints::unset()`] if no
/// specific constraint is defined.
///
/// - Indexes defined using `#[spacetimedb(index, ..)]` will not have a
/// corresponding [`Constraints::indexed()`] constraint (it will be unset).
/// The schema obtained from the database **will** have one such constraint,
/// however.
///
/// - The other possibilities (primary key, autoinc, unique) will have a
/// [`ConstraintDef`] in the module's schema, but no corresponding index
/// or sequence definitions.
///
/// There is no stable API to migrate such changes, so we won't try.
///
/// Thus:
///
/// - `indexes` and `sequences` are ignored
/// - `constraints` are compared sans unset or indexed-only definitions
///
/// A return value of `false` indicates that the table definitions are not
/// compatible.
fn equiv(a: &TableDef, b: &TableDef) -> bool {
let TableDef {
table_name,
columns,
indexes: _,
constraints,
sequences: _,
table_type,
table_access,
} = a;
// Constraints may not be in the same order, depending on whether the
// `TableDef` was loaded from the db catalog or the module.
fn as_set(constraints: &[ConstraintDef]) -> BTreeSet<&ConstraintDef> {
constraints
.iter()
.filter(|c| {
![Constraints::unset(), Constraints::indexed()]
.iter()
.any(|val| val == &c.constraints)
})
.collect()
}
table_name == &b.table_name
&& table_type == &b.table_type
&& table_access == &b.table_access
&& columns == &b.columns
&& as_set(constraints) == as_set(&b.constraints)
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::bail;
use spacetimedb_primitives::{ColId, Constraints, TableId};
use spacetimedb_sats::db::auth::{StAccess, StTableType};
use spacetimedb_sats::AlgebraicType;
use spacetimedb_sats::db::def::{ColumnDef, ColumnSchema};
#[test]
fn test_updates_new_table() -> anyhow::Result<()> {
let current = vec![Cow::Owned(TableSchema::new(
TableId(42),
"Person".into(),
vec![ColumnSchema {
table_id: TableId(42),
col_pos: ColId(0),
col_name: "name".into(),
col_type: AlgebraicType::String,
}],
vec![],
vec![],
vec![],
StTableType::User,
StAccess::Public,
))];
let proposed = vec![
TableDef::new(
"Person".into(),
vec![ColumnDef {
col_name: "name".into(),
col_type: AlgebraicType::String,
}],
),
TableDef::new(
"Pet".into(),
vec![ColumnDef {
col_name: "furry".into(),
col_type: AlgebraicType::Bool,
}],
),
];
match schema_updates(current, proposed.clone())? {
SchemaUpdates::Tainted(tainted) => bail!("unexpectedly tainted: {tainted:#?}"),
SchemaUpdates::Updates { new_tables } => {
assert_eq!(new_tables.len(), 1);
assert_eq!(new_tables.get("Pet"), proposed.last());
Ok(())
}
}
}
#[test]
fn test_updates_schema_mismatch() -> anyhow::Result<()> {
let current = vec![Cow::Owned(
TableDef::new(
"Person".into(),
vec![ColumnDef {
col_name: "name".into(),
col_type: AlgebraicType::String,
}],
)
.into_schema(TableId(42)),
)];
let proposed = vec![TableDef::new(
"Person".into(),
vec![
ColumnDef {
col_name: "id".into(),
col_type: AlgebraicType::U32,
},
ColumnDef {
col_name: "name".into(),
col_type: AlgebraicType::String,
},
],
)
.with_column_constraint(Constraints::identity(), ColId(0))];
match schema_updates(current, proposed)? {
SchemaUpdates::Tainted(tainted) => {
assert_eq!(tainted.len(), 1);
assert_eq!(
tainted[0],
Tainted {
table_name: "Person".into(),
reason: TaintReason::IncompatibleSchema,
}
);
Ok(())
}
up @ SchemaUpdates::Updates { .. } => {
bail!("unexpectedly not tainted: {up:#?}");
}
}
}
#[test]
fn test_updates_orphaned_table() -> anyhow::Result<()> {
let current = vec![Cow::Owned(
TableDef::new(
"Person".into(),
vec![ColumnDef {
col_name: "name".into(),
col_type: AlgebraicType::String,
}],
)
.into_schema(TableId(42)),
)];
let proposed = vec![TableDef::new(
"Pet".into(),
vec![ColumnDef {
col_name: "furry".into(),
col_type: AlgebraicType::Bool,
}],
)];
match schema_updates(current, proposed)? {
SchemaUpdates::Tainted(tainted) => {
assert_eq!(tainted.len(), 1);
assert_eq!(
tainted[0],
Tainted {
table_name: "Person".into(),
reason: TaintReason::Orphaned,
}
);
Ok(())
}
up @ SchemaUpdates::Updates { .. } => {
bail!("unexpectedly not tainted: {up:#?}")
}
}
}
}