server: config, migrations, redacted logging, /healthz entrypoint (#16)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
## SQLite open + forward-only migration runner (DESIGN 4.4, H13). DDL and version rule FIXED
|
||||
## owner-delegated, #16:
|
||||
## - `schema_migration(version, name, applied_at)` is the history table; `PRAGMA user_version`
|
||||
## carries the same latest version (external tools read it cheaply). They must agree, and
|
||||
## history is contiguous from 1, otherwise startup refuses.
|
||||
## - A DB whose user_version is above this build's latest is refused, never downgraded.
|
||||
## - One transaction per step: DDL + history row + user_version together. A failing step leaves
|
||||
## nothing behind; a fully migrated DB is not written to at all (re-open is a no-op).
|
||||
## - Engine settings: WAL, synchronous=NORMAL (Q12), busy_timeout=5000, foreign_keys=ON.
|
||||
## One connection, used under the server's global lock (4.3); this module does no locking itself.
|
||||
import std/[strutils, times]
|
||||
import db_connector/db_sqlite
|
||||
|
||||
type
|
||||
MigrationError* = object of CatchableError
|
||||
## The DB cannot be brought to this build's schema: newer DB, inconsistent history, or a
|
||||
## failed step (already rolled back).
|
||||
Migration* = object
|
||||
version*: int
|
||||
name*: string
|
||||
sql*: string
|
||||
MigrationRow* = tuple[version: int, name: string]
|
||||
|
||||
const
|
||||
MigrationHistoryDdl* = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migration (
|
||||
version INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
)"""
|
||||
migrations* = [
|
||||
Migration(version: 1, name: "meta", sql: """
|
||||
CREATE TABLE meta (
|
||||
k TEXT PRIMARY KEY,
|
||||
v TEXT NOT NULL
|
||||
)"""),
|
||||
]
|
||||
LatestVersion* = migrations[^1].version
|
||||
## Derived, so adding a step cannot leave it stale.
|
||||
|
||||
proc openDatabase*(path: string): DbConn =
|
||||
result = open(path, "", "", "")
|
||||
discard result.getAllRows(sql"PRAGMA journal_mode=WAL")
|
||||
result.exec(sql"PRAGMA synchronous=NORMAL")
|
||||
result.exec(sql"PRAGMA busy_timeout=5000")
|
||||
result.exec(sql"PRAGMA foreign_keys=ON")
|
||||
|
||||
proc schemaVersion*(db: DbConn): int =
|
||||
parseInt(db.getValue(sql"PRAGMA user_version"))
|
||||
|
||||
proc appliedMigrations*(db: DbConn): seq[MigrationRow] =
|
||||
for r in db.getAllRows(sql"SELECT version, name FROM schema_migration ORDER BY version"):
|
||||
result.add (version: parseInt(r[0]), name: r[1])
|
||||
|
||||
proc migrate*(db: DbConn): int =
|
||||
## Applies every step above the DB's version; returns how many ran (0 for an up-to-date DB).
|
||||
db.exec(sql(MigrationHistoryDdl))
|
||||
let version = schemaVersion(db)
|
||||
if version > LatestVersion:
|
||||
raise newException(MigrationError,
|
||||
"database schema version " & $version & " is newer than this server (" & $LatestVersion &
|
||||
"); refusing to run")
|
||||
let history = appliedMigrations(db)
|
||||
var historyProblem = ""
|
||||
if history.len != version:
|
||||
historyProblem = "user_version=" & $version & " but history has " & $history.len & " steps"
|
||||
else:
|
||||
for i, row in history:
|
||||
if row.version != i + 1:
|
||||
historyProblem = "history is not contiguous from 1 (found " & $row.version & " at step " & $(i + 1) & ")"
|
||||
elif row.version > migrations.len or row.name != migrations[row.version - 1].name:
|
||||
historyProblem = "step " & $row.version & " is recorded as \"" & row.name & "\""
|
||||
if historyProblem.len > 0:
|
||||
raise newException(MigrationError, "schema_migration and user_version disagree: " & historyProblem)
|
||||
|
||||
for m in migrations:
|
||||
if m.version <= version: continue
|
||||
db.exec(sql"BEGIN")
|
||||
try:
|
||||
db.exec(sql(m.sql))
|
||||
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, ?)",
|
||||
m.version, m.name, stamp)
|
||||
db.exec(sql("PRAGMA user_version = " & $m.version)) # PRAGMA does not take bound values
|
||||
db.exec(sql"COMMIT")
|
||||
inc result
|
||||
except CatchableError as e:
|
||||
try: db.exec(sql"ROLLBACK")
|
||||
except CatchableError: discard # the original error is the one worth reporting
|
||||
raise newException(MigrationError,
|
||||
"migration " & $m.version & " (" & m.name & ") failed: " & e.msg)
|
||||
Reference in New Issue
Block a user