feat(db): typed wall storage, marker_seen and height backfill (#53)
This commit is contained in:
+205
-5
@@ -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 })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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 })
|
||||
|
||||
Reference in New Issue
Block a user