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,