feat(db): typed wall storage, marker_seen and height backfill (#53)

This commit is contained in:
2026-11-19 22:03:11 +01:00
parent 6a443b4ec0
commit c1b1e9cf91
10 changed files with 551 additions and 45 deletions
+73 -1
View File
@@ -34,8 +34,14 @@
## the GM, and `player.remove` reassigns them before the DELETE (a raw delete raises instead of
## orphaning a record). `name_reveal` and `encountered` DO cascade on the player, because 6.1 deletes
## that player's reveals and encountered list with them.
## Step 8 ("wall record", Walls r1 / #53) rebuilds `wall` into the typed record of DESIGN 8 and adds
## `marker_seen`. The legacy `kind` column is dropped, not preserved: every row is mapped to today's
## behaviour (thickness 0, centre, both blocks on, both-way sight, no marker/door settings; a legacy
## door keeps its `open`). `height` and `label` are nullable and written as SQL literals because
## db_connector cannot bind NULL (4.4). The step's `data` hook is the height backfill: every entity
## and character whose `props_gm` lacks a `height` key gets `1.8`, and nothing else is touched (5.7).
## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[strutils, times]
import std/[json, strutils, times]
import db_connector/db_sqlite
type
@@ -48,8 +54,27 @@ type
stmts*: seq[string]
## One or more DDL statements, run in order inside the step's transaction.
## db_connector's exec() prepares a single statement, so they cannot be one string.
data*: proc(db: DbConn) {.nimcall.}
## Optional in-transaction data hook for what SQL cannot express portably (step 8's height
## backfill). Runs after `stmts` and before the history row, inside the same transaction.
MigrationRow* = tuple[version: int, name: string]
proc backfillHeights(db: DbConn) =
## Migration step 8's `data` hook (DESIGN 4.4, 5.7): every existing token and character gets
## `height: 1.8` in its GM bucket when that bucket is a JSON object without a `height` key.
## `eye_height` is never written (the 93% rule derives it) and a hand-set height is untouched.
for table in ["entity", "character"]:
for row in db.getAllRows(sql("SELECT id, props_gm FROM " & table)):
var props: JsonNode
try:
props = parseJson(row[1])
except CatchableError:
continue # unreadable props are left exactly as they are
if props.isNil or props.kind != JObject or props.hasKey("height"):
continue
props["height"] = newJFloat(1.8)
db.exec(sql("UPDATE " & table & " SET props_gm = ? WHERE id = ?"), $props, row[0])
const
MigrationHistoryDdl* = """
CREATE TABLE IF NOT EXISTS schema_migration (
@@ -180,6 +205,51 @@ CREATE TABLE encountered (
CREATE INDEX encountered_character ON encountered(character_id)""", """
ALTER TABLE entity ADD COLUMN character_id TEXT REFERENCES character(id)""", """
ALTER TABLE entity ADD COLUMN reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1))"""]),
Migration(version: 8, name: "wall record", stmts: @["""
ALTER TABLE wall RENAME TO wall_v1""", """
CREATE TABLE wall (
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
id INTEGER NOT NULL,
ax REAL NOT NULL, ay REAL NOT NULL,
bx REAL NOT NULL, by REAL NOT NULL,
thickness REAL NOT NULL DEFAULT 0 CHECK (thickness >= 0 AND thickness <= 256),
position TEXT NOT NULL DEFAULT 'center' CHECK (position IN ('center', 'left', 'right')),
blocks_sight INTEGER NOT NULL DEFAULT 1 CHECK (blocks_sight IN (0, 1)),
blocks_movement INTEGER NOT NULL DEFAULT 1 CHECK (blocks_movement IN (0, 1)),
sight_dir TEXT NOT NULL DEFAULT 'both' CHECK (sight_dir IN ('both', 'left', 'right')),
player_marker INTEGER NOT NULL DEFAULT 0 CHECK (player_marker IN (0, 1)),
door INTEGER NOT NULL DEFAULT 0 CHECK (door IN (0, 1)),
open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)),
secret INTEGER NOT NULL DEFAULT 0 CHECK (secret IN (0, 1)),
locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0, 1)),
height REAL NULL CHECK (height IS NULL OR (height > 0 AND height <= 100)),
label TEXT NULL CHECK (label IS NULL OR (length(label) >= 1 AND length(label) <= 64)),
flags TEXT NOT NULL DEFAULT '{}', -- JSON object, GM-defined, never interpreted
PRIMARY KEY (scene_id, id),
CHECK (open = 0 OR door = 1),
CHECK (secret = 0 OR (door = 1 AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1
AND sight_dir = 'both')),
CHECK (locked = 0 OR door = 1),
CHECK (sight_dir = 'both' OR blocks_sight = 1)
)""", """
INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, blocks_sight,
blocks_movement, sight_dir, player_marker, door, open, secret, locked,
height, label, flags)
SELECT scene_id, id, ax, ay, bx, by, 0, 'center', 1, 1, 'both', 0,
CASE kind WHEN 'door' THEN 1 ELSE 0 END,
CASE kind WHEN 'door' THEN open ELSE 0 END,
0, 0, NULL, NULL, flags
FROM wall_v1""", """
DROP TABLE wall_v1""", """
CREATE TABLE marker_seen (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
scene_id INTEGER NOT NULL,
wall_id INTEGER NOT NULL,
marker_id TEXT NOT NULL, -- the opaque per-player 12-character id on the wire
PRIMARY KEY (player_id, scene_id, wall_id),
UNIQUE (player_id, marker_id),
FOREIGN KEY (scene_id, wall_id) REFERENCES wall(scene_id, id) ON DELETE CASCADE
)"""], data: backfillHeights),
]
LatestVersion* = migrations[^1].version
## Derived, so adding a step cannot leave it stale.
@@ -238,6 +308,8 @@ proc migrate*(db: DbConn): int =
try:
for stmt in m.stmts:
db.exec(sql(stmt))
if m.data != nil:
m.data(db)
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)
+2 -1
View File
@@ -1925,7 +1925,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
sceneId = app.scene.id # the request's one read (#31)
# `candidate` is built here so its `flags` copy and its record copy both die under the lock;
# `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1).
let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get,
let candidate = WallRec(a: a.get, b: b.get, door: kind.get == wkDoor,
open: open.get, blocksSight: true, blocksMovement: true,
flags: detachedJson(flags.get))
# 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot
# taken before the write (the id is assigned by the write), and their outcome is applied only
+97 -18
View File
@@ -36,12 +36,30 @@ type
wkWall = "wall"
wkDoor = "door"
WallPosition* = enum
wpCenter = "center"
wpLeft = "left"
wpRight = "right"
SightDir* = enum
sdBoth = "both"
sdLeft = "left"
sdRight = "right"
WallRec* = object
## The typed wall record of DESIGN 8. The wire still carries the legacy `kind`/`open` pair in
## this round (#53); `kind` is derived from `door` and nothing else is exposed there yet (#54).
id*: int
a*, b*: Vec
kind*: WallKind
open*: bool
flags*: JsonNode ## JObject; never nil for a loaded or created wall
thickness*: float
position*: WallPosition
blocksSight*, blocksMovement*: bool
sightDir*: SightDir
playerMarker*: bool
door*, open*, secret*, locked*: bool
height*: Option[float] ## metres; none = full height (DESIGN 5.7)
label*: Option[string] ## GM-only free text, 1..64 code points (DESIGN 5.8)
flags*: JsonNode ## JObject; never nil for a loaded or created wall
SceneRec* = object
## The one v1 scene (Q3 FIXED). Walls are kept in id order (ids only grow, appends only).
@@ -90,6 +108,26 @@ const
SceneNameMaxLen* = 64
## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25).
proc defaultWall*(a, b: Vec): WallRec =
## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings.
WallRec(a: a, b: b, blocksSight: true, blocksMovement: true, flags: newJObject())
proc kind*(w: WallRec): WallKind =
## The legacy wire label for this round: only the door axis exists on it (#53). #54 replaces
## this with the full derived shape label.
if w.door: wkDoor else: wkWall
proc `kind=`*(w: var WallRec, k: WallKind) =
## Legacy update path (`wall.update {kind}`): a wall is never open; clearing the door switch
## also drops the door-only settings so the DB CHECK cannot see an impossible row.
if k == wkDoor:
w.door = true
else:
w.door = false
w.open = false
w.secret = false
w.locked = false
# ---------------------------------------------------------------------------------------------------
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
@@ -201,9 +239,12 @@ proc validWall*(sc: SceneRec, rec: WallRec): bool =
(rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b)
proc normalize*(rec: WallRec): WallRec =
## A wall is never open; only a door can be.
## A wall is never open; only a door can be, and a non-door stores no door-only settings.
result = rec
if result.kind == wkWall: result.open = false
if not result.door:
result.open = false
result.secret = false
result.locked = false
if result.flags.isNil: result.flags = newJObject()
proc wallIndex*(sc: SceneRec, id: int): Option[int] =
@@ -229,6 +270,20 @@ proc patched*(w: WallRec, patch: WallPatch): WallRec =
proc flagsText(node: JsonNode): string =
if node.isNil: "{}" else: $node
proc sqlLitText*(value: string): string =
## A SQL text literal (DESIGN 4.4): single quotes doubled. Used for `label`, which is nullable.
"'" & value.replace("'", "''") & "'"
proc sqlLitReal*(value: float): string =
## A fixed, locale-free SQL number literal. Used for `height`, which is nullable.
$value
proc sqlLitTextOrNull*(value: Option[string]): string =
if value.isSome: sqlLitText(value.get) else: "NULL"
proc sqlLitRealOrNull*(value: Option[float]): string =
if value.isSome: sqlLitReal(value.get) else: "NULL"
template authoringTransaction*(db: DbConn, body: untyped) =
## GM authoring durability (Q12): `synchronous=FULL` for this transaction, `NORMAL` again
## afterwards, whether the body succeeded or raised. `PRAGMA synchronous` cannot change inside a
@@ -260,16 +315,29 @@ proc storeScene*(db: DbConn, sc: SceneRec) =
writeSceneRow(db, sc)
proc insertRow(db: DbConn, sceneId: int, w: WallRec) =
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.kind,
(if w.open: 1 else: 0), flagsText(w.flags))
let height = sqlLitRealOrNull(w.height)
let label = sqlLitTextOrNull(w.label)
db.exec(sql("INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, " &
"blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret, " &
"locked, height, label, flags) " &
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " & height & ", " &
label & ", ?)"),
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags))
proc replaceRow(db: DbConn, sceneId: int, w: WallRec) =
db.exec(sql"""UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, kind = ?, open = ?, flags = ?
WHERE scene_id = ? AND id = ?""",
w.a.x, w.a.y, w.b.x, w.b.y, $w.kind, (if w.open: 1 else: 0), flagsText(w.flags),
sceneId, w.id)
let height = sqlLitRealOrNull(w.height)
let label = sqlLitTextOrNull(w.label)
db.exec(sql("UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, thickness = ?, position = ?, " &
"blocks_sight = ?, blocks_movement = ?, sight_dir = ?, player_marker = ?, " &
"door = ?, open = ?, secret = ?, locked = ?, height = " & height &
", label = " & label & ", flags = ? WHERE scene_id = ? AND id = ?"),
w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags), sceneId, w.id)
proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] =
## `wall.add`: assigns the scene's next wall id, persists and then appends to memory.
@@ -310,7 +378,7 @@ proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply =
## `door.set`: only a door can be opened or closed (`invalid` on a plain wall).
let idx = wallIndex(sc, id)
if idx.isNone: return waNotFound
if sc.walls[idx.get].kind != wkDoor: return waNotDoor
if sc.walls[idx.get].door == false: return waNotDoor
var stored = sc.walls[idx.get]
stored.open = open
authoringTransaction(db):
@@ -325,15 +393,25 @@ proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply =
proc rowToWall(row: Row): WallRec =
var flags: JsonNode
try:
flags = parseJson(row[7])
flags = parseJson(row[17])
except CatchableError:
flags = newJObject()
if flags.isNil or flags.kind != JObject: flags = newJObject()
WallRec(id: parseInt(row[0]),
a: (parseFloat(row[1]), parseFloat(row[2])),
b: (parseFloat(row[3]), parseFloat(row[4])),
kind: parseEnum[WallKind](row[5]),
open: row[6] == "1",
thickness: parseFloat(row[5]),
position: parseEnum[WallPosition](row[6]),
blocksSight: row[7] == "1",
blocksMovement: row[8] == "1",
sightDir: parseEnum[SightDir](row[9]),
playerMarker: row[10] == "1",
door: row[11] == "1",
open: row[12] == "1",
secret: row[13] == "1",
locked: row[14] == "1",
height: (if row[15].len == 0: none(float) else: some(parseFloat(row[15]))),
label: (if row[16].len == 0: none(string) else: some(row[16])),
flags: flags)
proc loadScene*(db: DbConn, sceneId = DefaultSceneId): Option[SceneRec] =
@@ -361,7 +439,8 @@ proc loadScene*(db: DbConn, sceneId = DefaultSceneId): Option[SceneRec] =
if result.isNone: return
var sc = result.get
for row in db.getAllRows(sql"""
SELECT id, ax, ay, bx, by, kind, open, flags
SELECT id, ax, ay, bx, by, thickness, position, blocks_sight, blocks_movement, sight_dir,
player_marker, door, open, secret, locked, height, label, flags
FROM wall WHERE scene_id = ? ORDER BY id""", sceneId):
sc.walls.add rowToWall(row)
result = some(sc)
+2 -2
View File
@@ -21,11 +21,11 @@ proc geometryWalls*(sc: SceneRec): seq[Wall] =
## The scene's walls as the vision code sees them: an open door does not block (5.1).
result = newSeqOfCap[Wall](sc.walls.len)
for w in sc.walls:
result.add Wall(a: w.a, b: w.b, door: w.kind == wkDoor, open: w.open)
result.add Wall(a: w.a, b: w.b, door: w.door, open: w.open)
proc ruleWall*(w: WallRec): Wall =
## The same wall as the move rules see it (they need `door`/`open` to know what blocks).
Wall(a: w.a, b: w.b, door: w.kind == wkDoor, open: w.open)
Wall(a: w.a, b: w.b, door: w.door, open: w.open)
proc ruleToken*(sc: SceneRec, t: TokenRec): moverules.Token =
moverules.Token(pos: t.pos, owner: t.owner,
+130 -6
View File
@@ -38,9 +38,9 @@ suite "migrate":
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 7
check LatestVersion == 8
let rows = appliedMigrations(db)
check rows.len == 7
check rows.len == 8
check rows[0][0] == 1
check rows[0][1] == "meta"
check rows[1][0] == 2
@@ -55,6 +55,8 @@ suite "migrate":
check rows[5][1] == "token details"
check rows[6][0] == 7
check rows[6][1] == "characters"
check rows[7][0] == 8
check rows[7][1] == "wall record"
# the steps' own DDL ran: meta and the auth tables exist and are empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0"
@@ -77,6 +79,16 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM encountered") == "0"
for col in ["character_id", "reveal_all"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('entity') WHERE name = '" & col & "'")) == "1"
# step 8 rebuilds `wall` into typed columns, drops `kind`, and creates `marker_seen`
check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall')") == "19"
check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'kind'") == "0"
for col in ["thickness", "position", "blocks_sight", "blocks_movement", "sight_dir",
"player_marker", "door", "open", "secret", "locked", "height", "label", "flags"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('wall') WHERE name = '" & col & "'")) == "1"
check db.getValue(sql"SELECT count(*) FROM marker_seen") == "0"
check db.getValue(sql"SELECT sql FROM sqlite_master WHERE name = 'marker_seen'")
.contains("FOREIGN KEY (scene_id, wall_id) REFERENCES wall(scene_id, id) ON DELETE CASCADE")
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'wall_v1'") == "0"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
@@ -165,7 +177,7 @@ suite "migrate":
check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == LatestVersion - 2 # steps 3 to 7 run
check migrate(db) == LatestVersion - 2 # steps 3 to 8 run
check schemaVersion(db) == LatestVersion
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
@@ -198,15 +210,17 @@ suite "migrate":
check schemaVersion(db) == 4
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0"
check migrate(db) == 3 # steps 5, 6 and 7 run
check migrate(db) == 4 # steps 5, 6, 7 and 8 run
check schemaVersion(db) == LatestVersion
check appliedMigrations(db).len == 7
check appliedMigrations(db).len == 8
check appliedMigrations(db)[4] == (version: 5, name: "explored")
check appliedMigrations(db)[5] == (version: 6, name: "token details")
check appliedMigrations(db)[6] == (version: 7, name: "characters")
check appliedMigrations(db)[7] == (version: 8, name: "wall record")
# step 6: the status table exists, and the old token's buckets default to empty objects
check db.getValue(sql"SELECT count(*) FROM entity_status") == "0"
check db.getValue(sql"SELECT props_public || props_owner || props_gm FROM entity") == "{}{}{}"
check db.getValue(sql"SELECT props_public || props_owner FROM entity") == "{}{}"
check db.getValue(sql"SELECT props_gm FROM entity") == """{"height":1.8}"""
# the explored store exists, with both FKs and the 512-byte chunk invariant
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
check db.getValue(sql"SELECT sql FROM sqlite_master WHERE name = 'explored_chunk'").contains("length(bits) = 512")
@@ -222,3 +236,113 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "1"
db.exec(sql"DELETE FROM player WHERE id = 2")
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
# Bring a fresh, empty DB to step `n` exactly as an older build left it.
proc applySteps(db: DbConn, n: int) =
db.exec(sql(MigrationHistoryDdl))
for m in migrations[0 ..< n]:
db.exec(sql"BEGIN")
for stmt in m.stmts: db.exec(sql(stmt))
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, 'x')",
m.version, m.name)
db.exec(sql("PRAGMA user_version = " & $m.version))
db.exec(sql"COMMIT")
suite "step 8 wall CHECKs (DESIGN 4.4)":
test "every impossible wall row is rejected by the database":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
discard migrate(db)
# A valid legacy wall (today's behaviour after the mapping) and a valid open door.
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position,
blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret,
locked, height, label, flags)
VALUES (1, 1, 0, 0, 100, 0, 0, 'center', 1, 1, 'both', 0, 0, 0, 0, 0,
NULL, NULL, '{}')""")
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position,
blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret,
locked, height, label, flags)
VALUES (1, 2, 0, 0, 100, 0, 128, 'left', 1, 1, 'left', 1, 1, 1, 0, 0,
1.8, 'railing', '{}')""")
checkpoint "a valid secret door, fixed window and height/label row also insert"
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position,
blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret,
locked, height, label, flags)
VALUES (1, 3, 0, 0, 100, 0, 0, 'center', 1, 1, 'both', 0, 1, 0, 1, 1,
NULL, NULL, '{}')""")
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position,
blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret,
locked, height, label, flags)
VALUES (1, 4, 0, 0, 100, 0, 0, 'center', 0, 1, 'both', 1, 0, 0, 0, 0,
NULL, NULL, '{}')""")
proc insert(row: string): bool =
try:
db.exec(sql("INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, " &
"blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret, locked, " &
"height, label, flags) VALUES " & row))
true
except CatchableError:
false
var id = 10
proc row(thickness = "0", position = "'center'", blocksSight = "1",
blocksMovement = "1", sightDir = "'both'", marker = "0", door = "0",
open = "0", secret = "0", locked = "0", height = "NULL",
label = "NULL"): string =
inc id
"(1, " & $id & ", 0, 0, 100, 0, " & thickness & ", " & position & ", " & blocksSight &
", " & blocksMovement & ", " & sightDir & ", " & marker & ", " & door & ", " &
open & ", " & secret & ", " & locked & ", " & height & ", " & label & ", '{}')"
check not insert(row(thickness = "-1"))
check not insert(row(thickness = "257"))
check not insert(row(position = "'north'"))
check not insert(row(blocksSight = "2"))
check not insert(row(blocksMovement = "2"))
check not insert(row(sightDir = "'north'"))
check not insert(row(marker = "2"))
check not insert(row(door = "2"))
check not insert(row(open = "2"))
check not insert(row(secret = "2"))
check not insert(row(locked = "2"))
check not insert(row(height = "0"))
check not insert(row(height = "101"))
check not insert(row(label = "''"))
check not insert(row(label = "'" & repeat('x', 65) & "'"))
check not insert(row(door = "0", open = "1")) # open non-door
check not insert(row(door = "0", secret = "1")) # secret non-door
check not insert(row(door = "1", open = "1", secret = "1")) # open secret door
check not insert(row(door = "1", secret = "1", blocksSight = "0"))
check not insert(row(door = "1", secret = "1", blocksMovement = "0"))
check not insert(row(door = "1", secret = "1", sightDir = "'left'"))
check not insert(row(door = "0", locked = "1")) # locked non-door
check not insert(row(blocksSight = "0", sightDir = "'left'")) # direction with no sight
check insert(row(door = "1", open = "1")) # an open door is legal
check db.getValue(sql"SELECT count(*) FROM wall") == "5"
test "a failing step 8 rolls back the rebuild, the history row and the version":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
applySteps(db, 7)
# A pre-existing `marker_seen` makes the last statement of step 8 fail after the wall table
# has been renamed, rebuilt, filled and dropped: the whole step must roll back.
db.exec(sql"CREATE TABLE marker_seen (x INTEGER)")
var raised = false
try:
discard migrate(db)
except MigrationError:
raised = true
check raised
check schemaVersion(db) == 7
check appliedMigrations(db).len == 7
# the legacy wall table is back: `kind` present, the typed columns absent
check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'kind'") == "1"
check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'thickness'") == "0"
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'wall_v1'") == "0"
+2 -2
View File
@@ -127,7 +127,7 @@ suite "player view (3.1: controlled always, LOS + not gm_only otherwise)":
check other.tokens[1].includeVisionRadius == false
test "a scan of every player frame finds no wall-ish or GM-only key":
let sc = sceneWith(@[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())])
let sc = sceneWith(@[defaultWall((700.0, 0.0), (700.0, 4096.0))])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0),
tok("secret", 500, 500, 0, gmOnly = true)]
var known: Known
@@ -195,7 +195,7 @@ suite "diff (6.4: only what changed)":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.scene.walls = @[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())]
ctx.scene.walls = @[defaultWall((700.0, 0.0), (700.0, 4096.0))]
refreshAll(ctx)
let frames = pass(ctx, known)
check frames[0]["t"].getStr == "vision" # the polygons shrank
+3 -1
View File
@@ -10,7 +10,9 @@ proc sceneWith(walls: seq[WallRec]): SceneRec =
extra: newJObject(), walls: walls)
proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec =
WallRec(a: (ax, ay), b: (bx, by), kind: kind, open: open, flags: newJObject())
result = defaultWall((ax, ay), (bx, by))
result.kind = kind
result.open = open
proc tok(id: string, x, y: float, owner: int, visionFlag = true, gmOnly = false): TokenRec =
TokenRec(id: id, scene: 1, kind: "pc", descriptiveName: id, actualName: id, pos: (x, y),
+33 -5
View File
@@ -13,7 +13,9 @@ proc tmpDir(): string =
createDir(result)
proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec =
WallRec(a: (ax, ay), b: (bx, by), kind: kind, open: open, flags: newJObject())
result = defaultWall((ax, ay), (bx, by))
result.kind = kind
result.open = open
proc freshScene(): tuple[db: DbConn, dir: string] =
## A migrated DB (the scene row comes from migration step 3) plus the scene loaded into memory.
@@ -136,12 +138,15 @@ suite "persistence (write-through, restart-identical)":
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id1 = addWall(conn, sc, WallRec(a: (0, 0), b: (4096, 0), kind: wkWall,
flags: %*{"note": "north"})).get
var north = defaultWall((0.0, 0.0), (4096.0, 0.0))
north.flags = %*{"note": "north"}
let id1 = addWall(conn, sc, north).get
let id2 = addWall(conn, sc, wall(100, 25, 300, 25, wkDoor)).get
check setDoor(conn, sc, id2, true) == waOk
let changed = WallRec(id: id1, a: (0, 0), b: (2000, 0), kind: wkDoor,
open: false, flags: %*{"note": "north wall"})
var changed = defaultWall((0.0, 0.0), (2000.0, 0.0))
changed.id = id1
changed.kind = wkDoor
changed.flags = %*{"note": "north wall"}
check updateWall(conn, sc, changed) == waOk
let reloaded = loadScene(conn).get
@@ -162,6 +167,29 @@ suite "persistence (write-through, restart-identical)":
check loadScene(conn).get.walls.len == 1
check loadScene(conn).get.nextWallId == 3
test "nullable height and label use SQL literals and round-trip as none, not 0 or ''":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
var withBoth = defaultWall((10.0, 10.0), (100.0, 10.0))
withBoth.height = some(2.5)
withBoth.label = some("the king's window")
let id = addWall(conn, sc, withBoth).get
let plain = addWall(conn, sc, defaultWall((10.0, 20.0), (100.0, 20.0))).get
let reloaded = loadScene(conn).get
check reloaded.walls[0].height == some(2.5)
check reloaded.walls[0].label == some("the king's window")
check reloaded.walls[1].height.isNone # NULL, never 0 (a height is > 0)
check reloaded.walls[1].label.isNone # NULL, never '' (a label is 1..64)
check conn.getValue(sql("SELECT label FROM wall WHERE id = " & $id)) == "the king's window"
check sqlLitText("the king's window") == "'the king''s window'"
check sqlLitTextOrNull(none(string)) == "NULL"
check sqlLitRealOrNull(none(float)) == "NULL"
check sqlLitRealOrNull(some(1.8)) == "1.8"
check conn.getValue(sql("SELECT count(*) FROM wall WHERE id = " & $plain & " AND height IS NULL")) == "1"
test "authoring runs with synchronous=FULL and leaves NORMAL behind (Q12)":
let (conn, d) = freshScene()
defer:
+205 -5
View File
@@ -399,8 +399,7 @@ INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, own
PRAGMA user_version = 4;
`
test('migration: a schema-4 DB (fixture) migrates under the real binary to the latest schema', async () => {
const stateDir = makeStateDir()
test('migration: a schema-4 DB (fixture) migrates under the real binary to the latest schema', async () => { const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
@@ -413,7 +412,7 @@ test('migration: a schema-4 DB (fixture) migrates under the real binary to the l
}
const s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=7 applied=3/, s.log())
assert.match(s.log(), /db_ready .*schema_version=8 applied=4/, s.log())
// The old data is served unchanged through the product surface.
const alice = { id: 2, key: 'ALIC-ALIC-ALIC-ALIC-ALIC' }
const conn = await openAs(s.origin, alice.key)
@@ -434,13 +433,16 @@ test('migration: a schema-4 DB (fixture) migrates under the real binary to the l
}
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 7)
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 8)
assert.deepEqual(db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all()
.map(r => [Number(r.version), r.name]),
[[1, 'meta'], [2, 'auth'], [3, 'world'], [4, 'tokens'], [5, 'explored'],
[6, 'token details'], [7, 'characters']])
[6, 'token details'], [7, 'characters'], [8, 'wall record']])
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM explored_chunk').get().n), 0)
assert.equal(db.prepare('SELECT name FROM player WHERE id = 2').get().name, 'Alice')
// step 8's data hook gave the schema-4 token its height
assert.deepEqual(JSON.parse(db.prepare("SELECT props_gm FROM entity WHERE id = 'tok000000001'").get().props_gm),
{ height: 1.8 })
} finally {
db.close()
}
@@ -449,3 +451,201 @@ test('migration: a schema-4 DB (fixture) migrates under the real binary to the l
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
// A DB exactly as the schema-7 build (#23) left it: every table of steps 1..7, two legacy wall
// kinds (one wall carrying a meaningless `open`, two doors with their stored state), a token with
// empty props, a linked token with a hand-set height/eye_height, and two characters, one with a
// hand-set height. Step 8 must rebuild `wall`, drop `kind`, add `marker_seen` and backfill only
// the missing heights.
const V7_DDL = `
CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT UNIQUE, role TEXT NOT NULL CHECK (role IN ('gm', 'player')), colour TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm';
CREATE TABLE player_key (player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, secret TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_seen TEXT NOT NULL);
CREATE INDEX session_player ON session(player_id);
CREATE TABLE scene (id INTEGER PRIMARY KEY, name TEXT NOT NULL, w REAL NOT NULL, h REAL NOT NULL, tile_size INTEGER NOT NULL, cell INTEGER NOT NULL, grid_size REAL NOT NULL, vision_radius_default REAL NOT NULL, token_radius_default REAL NOT NULL, art_version INTEGER NOT NULL, active INTEGER NOT NULL DEFAULT 1, next_wall_id INTEGER NOT NULL DEFAULT 1, extra TEXT NOT NULL DEFAULT '{}');
CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax REAL NOT NULL, ay REAL NOT NULL, bx REAL NOT NULL, by REAL NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id));
CREATE TABLE entity (id TEXT PRIMARY KEY, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, kind TEXT NOT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, radius REAL, owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)), vision_radius REAL, flags TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', character_id TEXT REFERENCES character(id), reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)));
CREATE TABLE explored_chunk (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy));
CREATE TABLE entity_status (entity_id TEXT NOT NULL REFERENCES entity(id) ON DELETE CASCADE, status TEXT NOT NULL CHECK (status IN ('stuck', 'squeezed')), source TEXT NOT NULL CHECK (source IN ('walls', 'GM')), PRIMARY KEY (entity_id, status, source));
CREATE TABLE character (id TEXT PRIMARY KEY, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)), props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL);
CREATE INDEX character_owner ON character(owner_player_id);
CREATE TABLE name_reveal (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, subject_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (player_id, subject_id));
CREATE TABLE encountered (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, entity_id TEXT NOT NULL, character_id TEXT, descriptive_name TEXT NOT NULL, actual_name TEXT, created_at TEXT NOT NULL, PRIMARY KEY (player_id, entity_id));
CREATE INDEX encountered_character ON encountered(character_id);
INSERT INTO schema_migration VALUES (1, 'meta', '2026-11-15T00:00:00Z'), (2, 'auth', '2026-11-15T00:00:00Z'), (3, 'world', '2026-11-15T00:00:00Z'), (4, 'tokens', '2026-11-15T00:00:00Z'), (5, 'explored', '2026-11-15T00:00:00Z'), (6, 'token details', '2026-11-15T00:00:00Z'), (7, 'characters', '2026-11-15T00:00:00Z');
INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version, active, next_wall_id, extra) VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 5, '{}');
INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#6b7280', '2026-11-15T00:00:00Z');
INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#2563eb', '2026-11-15T00:00:00Z');
INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'ALIC-ALIC-ALIC-ALIC-ALIC', '2026-11-15T00:00:00Z');
INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags) VALUES
(1, 1, 0, 0, 4096, 0, 'wall', 0, '{"note":"north"}'),
(1, 2, 10, 10, 100, 10, 'wall', 1, '{}'),
(1, 3, 100, 100, 400, 100, 'door', 1, '{"a":1}'),
(1, 4, 500, 500, 900, 500, 'door', 0, '{}');
INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, created_at, props_gm) VALUES
('char000000001', 1, 'Alice', 'Alice', '2026-11-15T00:00:00Z', '{}'),
('char000000002', 1, 'Bob', 'Bob', '2026-11-15T00:00:00Z', '{"height":1.5}');
INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, owner_player_id, flags, created_at, props_gm, character_id) VALUES
('tok000000001', 1, 'pc', 'a wanderer', 'Wanderer', 400, 400, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{}', NULL),
('tok000000002', 1, 'pc', '', '', 800, 800, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{"height":2.5,"eye_height":2.0}', 'char000000001');
PRAGMA user_version = 7;
`
const V7_WALLS = [
{ id: 1, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null,
flags: '{"note":"north"}' },
{ id: 2, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' },
{ id: 3, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 1, open: 1, secret: 0, locked: 0, height: null, label: null,
flags: '{"a":1}' },
{ id: 4, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 1, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' },
]
function readWallRows(db) {
return db.prepare(`SELECT id, thickness, position, blocks_sight, blocks_movement, sight_dir,
player_marker, door, open, secret, locked, height, label, flags
FROM wall ORDER BY id`).all()
.map(r => ({ ...r, id: Number(r.id), thickness: Number(r.thickness) }))
}
function readProps(db, table) {
return Object.fromEntries(db.prepare(`SELECT id, props_gm FROM ${table} ORDER BY id`).all()
.map(r => [r.id, JSON.parse(r.props_gm)]))
}
test('migration: a schema-7 wall/token/character fixture maps to typed storage and backfills height', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
assert.equal(Number(fixture.prepare('PRAGMA user_version').get().user_version), 7)
} finally {
fixture.close()
}
let before
let s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=8 applied=1/, s.log())
const db = new DatabaseSync(dbPath)
try {
const cols = db.prepare("SELECT name FROM pragma_table_info('wall')").all().map(r => r.name)
assert.ok(!cols.includes('kind'), 'the legacy kind column is dropped')
for (const col of ['thickness', 'position', 'blocks_sight', 'blocks_movement', 'sight_dir',
'player_marker', 'door', 'open', 'secret', 'locked', 'height', 'label',
'flags']) {
assert.ok(cols.includes(col), `wall.${col} exists`)
}
assert.deepEqual(readWallRows(db), V7_WALLS)
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM marker_seen').get().n), 0)
assert.match(db.prepare("SELECT sql FROM sqlite_master WHERE name = 'marker_seen'").get().sql,
/FOREIGN KEY \(scene_id, wall_id\) REFERENCES wall\(scene_id, id\) ON DELETE CASCADE/)
// The height backfill: missing keys get 1.8, hand-set values survive, eye_height is never written.
assert.deepEqual(readProps(db, 'entity'), {
tok000000001: { height: 1.8 },
tok000000002: { height: 2.5, eye_height: 2.0 },
})
assert.deepEqual(readProps(db, 'character'), {
char000000001: { height: 1.8 },
char000000002: { height: 1.5 },
})
before = { walls: readWallRows(db), entity: readProps(db, 'entity'),
character: readProps(db, 'character') }
} finally {
db.close()
}
// The old scene is still served through the product surface.
const conn = await openAs(s.origin, 'ALIC-ALIC-ALIC-ALIC-ALIC')
try {
const hello = await conn.ws.waitText('hello')
assert.equal(hello.role, 'player')
assert.equal(hello.me.name, 'Alice')
const tok = await conn.ws.waitFor(m => m.t === 'token' && m.id === 'tok000000001')
assert.deepEqual(tok.pos, [400, 400])
} finally {
conn.ws.close()
}
} finally {
await stopServer(s)
}
// Second start: the migration runner writes nothing and the data is byte-identical.
s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=8 applied=0/, s.log())
const db = new DatabaseSync(dbPath)
try {
assert.deepEqual(readWallRows(db), before.walls)
assert.deepEqual(readProps(db, 'entity'), before.entity)
assert.deepEqual(readProps(db, 'character'), before.character)
} finally {
db.close()
}
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('migration: a failing step 8 leaves the schema-7 DB untouched', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
// The pre-existing table makes the last statement of step 8 fail after `wall` was rebuilt.
fixture.exec('CREATE TABLE marker_seen (x INTEGER)')
} finally {
fixture.close()
}
try {
await assert.rejects(startServer({ stateDir }), /db_migrate_failed|migration 8/)
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 7)
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM schema_migration').get().n), 7)
const cols = db.prepare("SELECT name FROM pragma_table_info('wall')").all().map(r => r.name)
assert.ok(cols.includes('kind'), 'the legacy table is back')
assert.ok(!cols.includes('thickness'), 'the typed columns were rolled back')
assert.equal(Number(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'wall_v1'")
.get().n), 0)
// The data hook never ran: no height was written.
assert.deepEqual(JSON.parse(db.prepare("SELECT props_gm FROM entity WHERE id = 'tok000000001'")
.get().props_gm), {})
} finally {
db.close()
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('startup: a database from a newer server (user_version=9) is refused, not downgraded', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
fixture.exec('PRAGMA user_version = 9')
} finally {
fixture.close()
}
try {
await assert.rejects(startServer({ stateDir }), /db_migrate_failed|newer than this server/)
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 9)
assert.ok(db.prepare("SELECT name FROM pragma_table_info('wall')").all()
.some(r => r.name === 'kind'), 'the newer DB was not touched')
} finally {
db.close()
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
+4 -4
View File
@@ -49,16 +49,16 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async ()
const first = await startServer({ stateDir })
const firstLog = first.log()
await stopServer(first)
assert.match(firstLog, /db_ready .*schema_version=7 applied=7/, firstLog)
assert.match(firstLog, /db_ready .*schema_version=8 applied=8/, firstLog)
assert.ok(fs.existsSync(first.dbPath), 'state.db was not created')
const db = new DatabaseSync(first.dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 7)
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 8)
const rows = db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all()
assert.deepEqual(rows.map(r => [Number(r.version), r.name]),
[[1, 'meta'], [2, 'auth'], [3, 'world'], [4, 'tokens'], [5, 'explored'],
[6, 'token details'], [7, 'characters']])
[6, 'token details'], [7, 'characters'], [8, 'wall record']])
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM meta').get().n), 0)
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM player').get().n), 0)
// step 3 seeds the single v1 scene (Q3) with no walls and a counter at 1
@@ -87,7 +87,7 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async ()
const second = await startServer({ stateDir })
const secondLog = second.log().slice(firstLog.length)
await stopServer(second)
assert.match(secondLog, /db_ready .*schema_version=7 applied=0/, secondLog)
assert.match(secondLog, /db_ready .*schema_version=8 applied=0/, secondLog)
assert.doesNotMatch(secondLog, /applied=[1-9]/)
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })