schema.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /**
  2. * Schema + open-time helpers for the SQLite storage backend: the physical
  3. * layout version, the database open/configure sequence (permissions, pragmas,
  4. * version stamp/reject), and the unit metadata tables. Unit record tables are
  5. * created per descriptor in `unit.ts`.
  6. * @module @deepseek-ai/dsh-storage-sqlite/schema
  7. */
  8. import { DatabaseSync } from 'node:sqlite'
  9. import { mkdir, open } from 'node:fs/promises'
  10. import { dirname, resolve } from 'node:path'
  11. import { StorageError } from '@deepseek-ai/dsh-storage'
  12. /**
  13. * The on-disk physical layout version, stored in `PRAGMA user_version`.
  14. * Orthogonal to each unit's own `version` (stamped per unit in the `units`
  15. * row). Bumped only on a breaking change to the table layout; any other
  16. * stamped version rejects — this unreleased format has no migrations.
  17. */
  18. export const STORAGE_SQLITE_SCHEMA_VERSION = 1
  19. /**
  20. * Journal modes the backend will run under. `wal` is the default; the
  21. * rollback-journal modes (`delete`/`truncate`/`persist`) exist for
  22. * filesystems where WAL's shared-memory files do not work (network mounts).
  23. * `memory`/`off` are excluded: dropping journal durability silently
  24. * contradicts the durability clause of the KV backend contract.
  25. */
  26. export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist'
  27. /* jscpd:ignore-start -- deliberately mirrors the session-persistence-sqlite /
  28. session-query-sqlite open sequence; this group is the third user, and the
  29. shared medium helper is deferred to the log-facet migration so the session
  30. packages stay untouched this phase (see the domain KV storage Agent Note's
  31. reuse audit). */
  32. /**
  33. * Exclusively create a missing database file with owner-only permissions.
  34. * Existing files retain their modes, and errors other than `EEXIST` propagate.
  35. * `DatabaseSync` reopens by path, so this does not protect confidentiality or
  36. * integrity when another principal can replace the database entry in its
  37. * parent directory.
  38. */
  39. async function createDatabaseFile(path: string): Promise<void> {
  40. try {
  41. const handle = await open(path, 'wx', 0o600)
  42. await handle.close()
  43. } catch (error) {
  44. if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
  45. }
  46. }
  47. /**
  48. * Open the database and apply its schema and pragmas. Missing directories and
  49. * database files are created owner-only (`:memory:` skips filesystem setup).
  50. * A zero `user_version` is stamped with {@link STORAGE_SQLITE_SCHEMA_VERSION};
  51. * every other non-current version rejects rather than being migrated in place.
  52. * @param path - the SQLite database file to open, or `:memory:`.
  53. * @param journalMode - validated journal pragma.
  54. * @returns the open handle with pragmas applied and the unit metadata tables ensured.
  55. */
  56. export async function openDatabase(path: string, journalMode: JournalMode): Promise<DatabaseSync> {
  57. const actual = path === ':memory:' ? path : resolve(path)
  58. if (actual !== ':memory:') {
  59. await mkdir(dirname(actual), { recursive: true, mode: 0o700 })
  60. await createDatabaseFile(actual)
  61. }
  62. const db = new DatabaseSync(actual)
  63. try {
  64. configureDatabase(db, actual, journalMode)
  65. return db
  66. } catch (error: unknown) {
  67. db.close()
  68. throw error
  69. }
  70. }
  71. function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalMode): void {
  72. db.exec('PRAGMA foreign_keys = ON')
  73. // The validated union is safe to interpolate into a non-bindable PRAGMA.
  74. db.exec(`PRAGMA journal_mode = ${journalMode.toUpperCase()}`)
  75. // `PRAGMA user_version` always returns exactly one row { user_version }.
  76. const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number }
  77. if (onDisk !== 0 && onDisk !== STORAGE_SQLITE_SCHEMA_VERSION) {
  78. throw new StorageError(
  79. 'version-mismatch',
  80. `storage database at "${path}" has schema version ${onDisk}, incompatible with this build (${STORAGE_SQLITE_SCHEMA_VERSION})`,
  81. )
  82. }
  83. /* jscpd:ignore-end */
  84. db.exec(`
  85. CREATE TABLE IF NOT EXISTS units (
  86. name TEXT PRIMARY KEY,
  87. version INTEGER NOT NULL
  88. ) STRICT
  89. `)
  90. db.exec(`
  91. CREATE TABLE IF NOT EXISTS unit_globals (
  92. unit TEXT PRIMARY KEY REFERENCES units(name),
  93. value TEXT NOT NULL
  94. ) STRICT
  95. `)
  96. if (onDisk === 0) {
  97. // Stamp fresh databases LAST: the stamp asserts the layout is complete,
  98. // so a failure above must leave the medium unstamped (a re-open after
  99. // the obstruction is cleared retries materialization from scratch).
  100. db.exec(`PRAGMA user_version = ${STORAGE_SQLITE_SCHEMA_VERSION}`)
  101. }
  102. }
  103. /**
  104. * Physical table name for one unit table. Both segments are validated against
  105. * `UNIT_NAME_RE` before reaching this, so the result is safe to interpolate
  106. * into DDL and prepared-statement text.
  107. * @param unit - Validated unit name.
  108. * @param table - Validated table name.
  109. * @returns the `u_<unit>_<table>` identifier.
  110. */
  111. export function recordTableName(unit: string, table: string): string {
  112. return `u_${unit}_${table}`
  113. }