1use super::*;
2use rusqlite::OpenFlags;
3
4const COMPATIBILITY_METADATA_VERSION: i64 = 30;
5
6pub(super) struct SchemaState {
7 pub(super) revision: i64,
8 minimum_compatible: Option<i64>,
9}
10
11impl SchemaState {
12 pub(super) fn ensure_supported(&self) -> Result<()> {
13 let reason = if self.revision < SCHEMA_VERSION {
14 StoreSchemaMismatchReason::NeedsMigration
15 } else if let Some(minimum_compatible) = self.minimum_compatible {
16 if minimum_compatible <= SCHEMA_VERSION {
17 return Ok(());
18 }
19 StoreSchemaMismatchReason::Incompatible { minimum_compatible }
20 } else {
21 StoreSchemaMismatchReason::InvalidCompatibilityMetadata
22 };
23 Err(StoreSchemaMismatch {
24 found: self.revision,
25 supported: SCHEMA_VERSION,
26 reason,
27 }
28 .into())
29 }
30}
31
32pub(super) fn read_schema_state(connection: &Connection) -> Result<SchemaState> {
35 let snapshot = connection
36 .unchecked_transaction()
37 .context("start database compatibility snapshot")?;
38 let revision: i64 = snapshot
39 .query_row("PRAGMA user_version", [], |row| row.get(0))
40 .context("read database migration revision")?;
41 let minimum_compatible = if revision >= COMPATIBILITY_METADATA_VERSION {
42 let invalid = || StoreSchemaMismatch {
43 found: revision,
44 supported: SCHEMA_VERSION,
45 reason: StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
46 };
47 let (count, singleton, floor, recorded): (i64, Option<i64>, Option<i64>, Option<i64>) =
48 snapshot
49 .query_row(
50 "SELECT count(*), min(singleton), min(minimum_compatible_version),
51 (SELECT max(version) FROM schema_migrations)
52 FROM schema_compatibility",
53 [],
54 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
55 )
56 .map_err(|error| {
57 let structural = match &error {
61 rusqlite::Error::SqliteFailure(code, _) => {
62 code.code == rusqlite::ErrorCode::Unknown
63 }
64 _ => true,
65 };
66 let error = anyhow::Error::new(error);
67 if structural {
68 error.context(invalid())
69 } else {
70 error.context("read database compatibility metadata")
71 }
72 })?;
73 if count != 1
74 || singleton != Some(1)
75 || recorded != Some(revision)
76 || !floor
77 .is_some_and(|floor| (COMPATIBILITY_METADATA_VERSION..=revision).contains(&floor))
78 {
79 return Err(invalid().into());
80 }
81 floor
82 } else {
83 None
84 };
85 snapshot
86 .commit()
87 .context("finish database compatibility snapshot")?;
88 Ok(SchemaState {
89 revision,
90 minimum_compatible,
91 })
92}
93
94pub fn database_path() -> PathBuf {
95 data_dir().join("mj.sqlite3")
96}
97
98pub(super) fn open_writer(path: &Path) -> Result<Connection> {
99 if let Some(parent) = path.parent() {
100 fs::create_dir_all(parent)
101 .with_context(|| format!("create Mjolnir data directory {}", parent.display()))?;
102 }
103 let connection = Connection::open(path)
104 .with_context(|| format!("open Mjolnir database {}", path.display()))?;
105 connection.busy_timeout(Duration::from_secs(5))?;
106 connection.execute_batch(
107 "PRAGMA foreign_keys = ON;
108 PRAGMA journal_mode = WAL;
109 PRAGMA synchronous = FULL;",
110 )?;
111 verify_schema_once(path, &connection)?;
112 Ok(connection)
113}
114
115pub(super) fn open(path: &Path) -> Result<Connection> {
116 open_writer(path)
117}
118
119#[cfg(not(test))]
123pub(super) fn open_reader(path: &Path) -> Result<Connection> {
124 open_reader_strict(path)
125}
126
127#[cfg(test)]
128pub(super) fn open_reader(path: &Path) -> Result<Connection> {
129 open_writer(path)
133}
134
135#[cfg_attr(test, allow(dead_code))]
136fn open_reader_strict(path: &Path) -> Result<Connection> {
137 let connection = Connection::open_with_flags(
138 path,
139 OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
140 )
141 .with_context(|| format!("open Mjolnir database read-only {}", path.display()))?;
142 connection.busy_timeout(Duration::from_secs(5))?;
143 connection.execute_batch(
144 "PRAGMA foreign_keys = ON;
145 PRAGMA query_only = ON;",
146 )?;
147 read_schema_state(&connection)?.ensure_supported()?;
148 Ok(connection)
149}
150
151fn verified_schemas() -> &'static Mutex<HashSet<PathBuf>> {
155 static VERIFIED: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
156 VERIFIED.get_or_init(|| Mutex::new(HashSet::new()))
157}
158
159fn schema_cache_key(path: &Path) -> PathBuf {
162 let Some(parent) = path
163 .parent()
164 .filter(|parent| !parent.as_os_str().is_empty())
165 else {
166 return path.to_owned();
167 };
168 match (fs::canonicalize(parent), path.file_name()) {
169 (Ok(canonical), Some(name)) => canonical.join(name),
170 _ => path.to_owned(),
171 }
172}
173
174fn verify_schema_once(path: &Path, connection: &Connection) -> Result<()> {
179 let key = schema_cache_key(path);
180 let mut verified = verified_schemas()
181 .lock()
182 .unwrap_or_else(PoisonError::into_inner);
183 let state = read_schema_state(connection)?;
184 if state.revision > SCHEMA_VERSION
185 || (state.revision == SCHEMA_VERSION && verified.contains(&key))
186 {
187 return state.ensure_supported();
189 }
190 migrate_schema(connection)?;
193 read_schema_state(connection)?.ensure_supported()?;
194 verified.insert(key);
195 Ok(())
196}
197
198#[cfg(test)]
202pub(super) fn forget_verified_schema(path: &Path) {
203 verified_schemas()
204 .lock()
205 .unwrap_or_else(PoisonError::into_inner)
206 .remove(&schema_cache_key(path));
207}
208
209const BASELINE_SCHEMA_VERSION: i64 = 33;
213
214const BASELINE_MINIMUM_COMPATIBLE_VERSION: i64 = 32;
217
218fn migrate_schema(connection: &Connection) -> Result<()> {
219 let state = read_schema_state(connection)?;
220 let version = state.revision;
221 if version > SCHEMA_VERSION {
222 return state.ensure_supported();
223 }
224 if version == 0 {
225 create_baseline_schema(connection)?;
226 } else if version < BASELINE_SCHEMA_VERSION {
227 bail!(
231 "Mjolnir database schema {version} was written by a Mjolnir release older than 2.7.2, \
232 which this build cannot upgrade; upgrade through any Mjolnir release from 2.7.2 \
233 through 2.9.x first, or start with a fresh data directory (--instance NAME or \
234 MJ_DATA_DIR)"
235 );
236 }
237 if version < 34 {
245 connection.execute_batch(
246 "BEGIN IMMEDIATE;
247 CREATE TABLE IF NOT EXISTS session_mount_access (
248 session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
249 source BLOB NOT NULL,
250 destination BLOB NOT NULL,
251 access TEXT NOT NULL CHECK(access IN ('rw')),
252 PRIMARY KEY(session_id, destination)
253 ) STRICT;
254 INSERT INTO schema_migrations(version, applied_at)
255 VALUES (34, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
256 PRAGMA user_version = 34;
257 COMMIT;",
258 )?;
259 }
260 if version < 35 {
267 connection.execute_batch(
268 "BEGIN IMMEDIATE;
269 ALTER TABLE sessions ADD COLUMN container_workspace TEXT;
270 INSERT INTO schema_migrations(version, applied_at)
271 VALUES (35, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
272 PRAGMA user_version = 35;
273 COMMIT;",
274 )?;
275 }
276 if version < 36 {
282 connection.execute_batch(
283 "BEGIN IMMEDIATE;
284 ALTER TABLE sessions ADD COLUMN build_cache_json TEXT;
285 INSERT INTO schema_migrations(version, applied_at)
286 VALUES (36, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
287 PRAGMA user_version = 36;
288 COMMIT;",
289 )?;
290 }
291 if version < 37 {
297 connection.execute_batch(
298 "BEGIN IMMEDIATE;
299 ALTER TABLE session_targets ADD COLUMN borrowed_from TEXT;
300 INSERT INTO schema_migrations(version, applied_at)
301 VALUES (37, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
302 PRAGMA user_version = 37;
303 COMMIT;",
304 )?;
305 }
306 let recorded: Option<i64> =
307 connection.query_row("SELECT max(version) FROM schema_migrations", [], |row| {
308 row.get(0)
309 })?;
310 if recorded != Some(SCHEMA_VERSION) {
311 bail!(
312 "Mjolnir database migration ledger {:?} does not match schema {}",
313 recorded,
314 SCHEMA_VERSION
315 );
316 }
317 Ok(())
318}
319
320fn create_baseline_schema(connection: &Connection) -> Result<()> {
324 connection.execute_batch("BEGIN IMMEDIATE;")?;
325 let created = (|| -> Result<()> {
326 let version: i64 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
327 if version != 0 {
328 return Ok(());
329 }
330 connection.execute_batch(include_str!("baseline.sql"))?;
331 connection.execute(
332 "INSERT INTO schema_compatibility(singleton, minimum_compatible_version) VALUES (1, ?1)",
333 [BASELINE_MINIMUM_COMPATIBLE_VERSION],
334 )?;
335 connection.execute(
336 "INSERT INTO schema_migrations(version, applied_at)
337 VALUES (?1, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
338 [BASELINE_SCHEMA_VERSION],
339 )?;
340 connection.pragma_update(None, "user_version", BASELINE_SCHEMA_VERSION)?;
341 Ok(())
342 })();
343 match created {
344 Ok(()) => connection
345 .execute_batch("COMMIT;")
346 .context("commit baseline database schema"),
347 Err(error) => {
348 if let Err(rollback) = connection.execute_batch("ROLLBACK;") {
349 tracing::warn!(%rollback, "could not roll back a failed baseline schema");
350 }
351 Err(error.context("create baseline database schema"))
352 }
353 }
354}
355
356#[cfg(test)]
357pub(super) fn advance_test_schema(path: &Path, revision: i64, minimum_compatible: i64) {
358 let connection = Connection::open(path).unwrap();
359 let transaction = connection.unchecked_transaction().unwrap();
360 transaction
361 .execute(
362 "UPDATE schema_compatibility SET minimum_compatible_version = ?1",
363 [minimum_compatible],
364 )
365 .unwrap();
366 transaction
367 .execute(
368 "INSERT INTO schema_migrations(version, applied_at) VALUES (?1, 'test')",
369 [revision],
370 )
371 .unwrap();
372 transaction
373 .pragma_update(None, "user_version", revision)
374 .unwrap();
375 transaction.commit().unwrap();
376 forget_verified_schema(path);
377}
378
379#[cfg(test)]
380mod reader_tests {
381 use super::*;
382
383 const MINIMUM_COMPATIBLE_VERSION: i64 = 32;
387
388 fn stamp_schema_version(path: &Path, version: i64) {
391 if version > SCHEMA_VERSION {
392 advance_test_schema(path, version, version);
393 return;
394 }
395 let connection = Connection::open(path).unwrap();
396 connection
397 .execute_batch(&format!("PRAGMA user_version = {version};"))
398 .unwrap();
399 connection
400 .execute(
401 "DELETE FROM schema_migrations WHERE version > ?1",
402 [version],
403 )
404 .unwrap();
405 if version == 30 {
406 connection
407 .execute(
408 "UPDATE schema_compatibility SET minimum_compatible_version = 30 WHERE singleton = 1",
409 [],
410 )
411 .unwrap();
412 }
413 drop(connection);
414 forget_verified_schema(path);
415 }
416
417 #[test]
418 fn older_readers_and_reopened_writers_preserve_a_compatible_future_schema() {
419 let directory = tempfile::tempdir().unwrap();
420 let path = directory.path().join("mj.sqlite3");
421 let connection = open_writer(&path).unwrap();
422 connection
423 .execute_batch(
424 "CREATE TABLE future_feature(value TEXT NOT NULL);
425 INSERT INTO future_feature VALUES ('preserve me');",
426 )
427 .unwrap();
428 drop(connection);
429 advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);
430
431 let reader = open_reader_strict(&path).unwrap();
432 assert_eq!(
433 reader
434 .query_row("SELECT value FROM future_feature", [], |row| row
435 .get::<_, String>(0))
436 .unwrap(),
437 "preserve me"
438 );
439 assert!(reader.execute("DELETE FROM future_feature", []).is_err());
440 drop(reader);
441
442 let raw = Connection::open(&path).unwrap();
445 raw.execute_batch("DROP TRIGGER api_session_error_updated;")
446 .unwrap();
447 drop(raw);
448 let writer = open_writer(&path).unwrap();
449 assert!(!writer.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name = 'api_session_error_updated')", [], |row| row.get::<_, bool>(0)).unwrap());
450 assert_eq!(
451 writer
452 .query_row("SELECT value FROM future_feature", [], |row| row
453 .get::<_, String>(0))
454 .unwrap(),
455 "preserve me"
456 );
457 let state = read_schema_state(&writer).unwrap();
458 assert_eq!(state.revision, SCHEMA_VERSION + 1);
459 assert_eq!(state.minimum_compatible, Some(SCHEMA_VERSION));
460 }
461
462 #[test]
463 fn invalid_compatibility_metadata_refuses_readers_and_writers() {
464 for alteration in [
465 "DROP TABLE schema_compatibility",
466 "DELETE FROM schema_compatibility",
467 "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET minimum_compatible_version = 0",
468 "UPDATE schema_compatibility SET minimum_compatible_version = 99999",
469 "PRAGMA ignore_check_constraints = ON; UPDATE schema_compatibility SET singleton = 2",
470 "PRAGMA ignore_check_constraints = ON; INSERT INTO schema_compatibility VALUES (2, 30)",
471 "DROP TABLE schema_compatibility; CREATE TABLE schema_compatibility(singleton, minimum_compatible_version); INSERT INTO schema_compatibility VALUES (1, 'invalid')",
472 "DELETE FROM schema_migrations WHERE version = (SELECT max(version) FROM schema_migrations)",
473 ] {
474 for future in [false, true] {
475 let directory = tempfile::tempdir().unwrap();
476 let path = directory.path().join("mj.sqlite3");
477 drop(open_writer(&path).unwrap());
478 if future {
479 advance_test_schema(&path, SCHEMA_VERSION + 1, SCHEMA_VERSION);
480 }
481 let raw = Connection::open(&path).unwrap();
482 raw.execute_batch(alteration).unwrap();
483 let before: i64 = raw
484 .query_row("PRAGMA schema_version", [], |row| row.get(0))
485 .unwrap();
486 for error in [
488 open_reader_strict(&path).unwrap_err(),
489 open_writer(&path).unwrap_err(),
490 ] {
491 let mismatch = error.downcast_ref::<StoreSchemaMismatch>().unwrap();
492 assert_eq!(
493 mismatch.reason,
494 StoreSchemaMismatchReason::InvalidCompatibilityMetadata,
495 "{alteration}"
496 );
497 }
498 forget_verified_schema(&path);
499 assert!(open_writer(&path).is_err(), "{alteration}");
500 let after: i64 = raw
501 .query_row("PRAGMA schema_version", [], |row| row.get(0))
502 .unwrap();
503 assert_eq!(
504 before, after,
505 "a rejected open repaired schema: {alteration}"
506 );
507 }
508 }
509 }
510
511 #[test]
512 fn a_failed_baseline_leaves_an_empty_store_that_a_retry_creates() {
513 let directory = tempfile::tempdir().unwrap();
514 let path = directory.path().join("mj.sqlite3");
515 let connection = Connection::open(&path).unwrap();
516 connection
518 .execute_batch("CREATE TABLE workspaces(conflict TEXT)")
519 .unwrap();
520
521 let error = migrate_schema(&connection).unwrap_err();
522
523 assert!(format!("{error:#}").contains("create baseline database schema"));
524 assert!(
525 connection.is_autocommit(),
526 "the failed baseline left a transaction open"
527 );
528 assert_eq!(read_schema_state(&connection).unwrap().revision, 0);
529 let tables: i64 = connection
530 .query_row(
531 "SELECT count(*) FROM sqlite_schema WHERE type = 'table'",
532 [],
533 |row| row.get(0),
534 )
535 .unwrap();
536 assert_eq!(tables, 1, "only the conflicting table remains");
537
538 connection.execute_batch("DROP TABLE workspaces").unwrap();
539 drop(connection);
540 let writer = open_writer(&path).unwrap();
541 let state = read_schema_state(&writer).unwrap();
542 assert_eq!(state.revision, SCHEMA_VERSION);
543 assert_eq!(state.minimum_compatible, Some(MINIMUM_COMPATIBLE_VERSION));
544 }
545
546 #[test]
547 fn a_store_from_before_the_baseline_is_refused_with_upgrade_advice() {
548 let directory = tempfile::tempdir().unwrap();
549 let path = directory.path().join("mj.sqlite3");
550 let connection = Connection::open(&path).unwrap();
551 connection
552 .execute_batch(&format!(
553 "PRAGMA user_version = {};",
554 COMPATIBILITY_METADATA_VERSION - 1
555 ))
556 .unwrap();
557 drop(connection);
558
559 let error = open_writer(&path).unwrap_err();
560
561 let message = format!("{error:#}");
562 assert!(message.contains("older than 2.7.2"), "{message}");
563 assert!(
564 message.contains("from 2.7.2 through 2.9.x"),
565 "advice must name the closed range of releases that can migrate: {message}"
566 );
567 }
568
569 #[test]
573 fn strict_reader_reports_a_newer_store_without_blaming_the_daemon() {
574 let directory = tempfile::tempdir().unwrap();
575 let path = directory.path().join("mj.sqlite3");
576 drop(open_writer(&path).unwrap());
577 stamp_schema_version(&path, SCHEMA_VERSION + 1);
578
579 let error = open_reader_strict(&path).unwrap_err();
580
581 let mismatch = error
582 .chain()
583 .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
584 .expect("the reader reports the mismatch as a typed cause");
585 assert_eq!(mismatch.found, SCHEMA_VERSION + 1);
586 assert_eq!(mismatch.supported, SCHEMA_VERSION);
587 let message = mismatch.to_string();
588 assert!(message.contains("upgrade Mjolnir"), "got {message}");
589 assert!(
590 !message.contains("start the Mjolnir daemon"),
591 "got {message}"
592 );
593 }
594
595 #[test]
598 fn strict_reader_keeps_the_migrate_advice_when_the_store_is_behind() {
599 let directory = tempfile::tempdir().unwrap();
600 let path = directory.path().join("mj.sqlite3");
601 drop(open_writer(&path).unwrap());
602 let raw = Connection::open(&path).unwrap();
603 raw.execute_batch(&format!(
604 "UPDATE schema_compatibility SET minimum_compatible_version = {0};
605 DELETE FROM schema_migrations WHERE version > {0};
606 INSERT OR IGNORE INTO schema_migrations(version, applied_at) VALUES ({0}, 'test');
607 PRAGMA user_version = {0};",
608 SCHEMA_VERSION - 1
609 ))
610 .unwrap();
611 drop(raw);
612
613 let error = open_reader_strict(&path).unwrap_err();
614
615 let mismatch = error
616 .chain()
617 .find_map(|cause| cause.downcast_ref::<StoreSchemaMismatch>())
618 .expect("the reader reports the mismatch as a typed cause");
619 assert_eq!(
620 mismatch.to_string(),
621 format!(
622 "Mjolnir database schema {} is not the supported schema {SCHEMA_VERSION}; \
623 start the Mjolnir daemon to migrate it",
624 SCHEMA_VERSION - 1
625 )
626 );
627 }
628
629 #[test]
630 fn strict_reader_rejects_mutation() {
631 let directory = tempfile::tempdir().unwrap();
632 let path = directory.path().join("mj.sqlite3");
633 drop(open_writer(&path).unwrap());
634
635 let reader = open_reader_strict(&path).unwrap();
636 let error = reader
637 .execute("CREATE TABLE forbidden(value TEXT)", [])
638 .unwrap_err();
639 assert!(
640 matches!(
641 error.sqlite_error_code(),
642 Some(rusqlite::ErrorCode::ReadOnly)
643 ),
644 "unexpected mutation error: {error}"
645 );
646 }
647}