From 75c3e046f89ae39c3da99610e221ce97c007032f Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sun, 15 Nov 2026 12:01:21 +0100 Subject: [PATCH] server: the character, reveal and encountered records and migration step 7 (#23) --- server/characters.nim | 333 ++++++++++++++++++++++++++++++++++++++++++ server/db.nim | 42 ++++++ server/text.nim | 36 ++++- server/tokens.nim | 45 ++++-- 4 files changed, 441 insertions(+), 15 deletions(-) create mode 100644 server/characters.nim diff --git a/server/characters.nim b/server/characters.nim new file mode 100644 index 0000000..739c52b --- /dev/null +++ b/server/characters.nim @@ -0,0 +1,333 @@ +## Characters, name reveals and the per-player encountered list (DESIGN 3.1, 4.1, 6.1, 8; M3 +## slice 8, issue #23). +## +## A character is its own record, separate from the tokens that figure it (FIXED #14): one owner - a +## real player id, and the GM owns through its own player id - two names, `reveal_all` and the three +## property buckets. `TokenRec.characterId` is the link; a token linked to a character carries no +## names of its own, because the character's names are the ones a client sees. A token's *controller* +## is set on the token and is independent of the character's owner: `character.reassign` never +## touches it (6.1, DESIGN 8). +## +## Names [FIXED #14, DESIGN 8]: every character and every plain token has a `descriptive_name` (what +## a player sees) and an `actual_name` (what the GM knows). A player sees the actual name only when +## the subject is a character they own, or the GM revealed it to them, or `reveal_all` is set. That +## one rule lives in `knowsActual`/`visibleName` and nothing else in the server re-derives it: the +## token frame, the character frame and the encountered entry all call it. +## +## Reveals are stored per `(player, subject)` in `name_reveal`, where the subject is a character id or +## a plain token id. Token and character ids share one alphabet *and one uniqueness namespace* +## (`freshId` is called with both lists), so a subject id is never ambiguous. A reveal is never +## revoked and is not dropped when the character changes owner (8); `reveal_all` is a flag on the +## subject, so a player who joins later is covered without a row per player. +## +## Encountered [FIXED #14, DESIGN 8]: per player, one entry per token that player ever saw, holding +## the *snapshot* of the name that player knows (`actual_name` NULL = not known). Entries are never +## removed automatically - not on token removal, not on a `gm_only` flip, not on a scene change - +## only by `encountered.remove`. The entry is added the moment the token enters that player's view +## (main.recordEncounters); a rename updates the snapshot; a reveal fills in the actual name. +## +## This module does no locking (the caller holds the global lock, 4.3) and no wire shapes (that is +## server/views.nim); it owns the records and their SQLite rows. +import std/[algorithm, json, options, sets, strutils, tables, times] +import db_connector/db_sqlite +import props, text, tokens, world + +type + CharacterRec* = object + id*: string + owner*: int ## a real player id, the GM's included; never GmControlled + descriptiveName*: string + actualName*: string + revealAll*: bool + props*: Props ## three buckets, never nil + + CharacterOutcome* = enum + coOk + coInvalid ## a name or a prop value is off: `invalid` + coNotFound ## no such character (or owner player): `not-found` + coInUse ## a token still figures it: `in-use` (6.5) + + NameSubject* = enum + nsCharacter = "character" + nsToken = "token" + + Reveals* = object + ## `(playerId, subjectId)` pairs, i.e. one row of `name_reveal` each. A set because every + ## question asked of it is a membership test; the per-subject player list is a bounded scan. + pairs*: HashSet[(int, string)] + + EncounteredEntry* = object + entityId*: string + characterId*: Option[string] ## none = the entry belongs to a plain token + descriptiveName*: string + actualName*: Option[string] ## none = this player was never told the actual name + + Encountered* = Table[int, Table[string, EncounteredEntry]] + ## playerId -> entityId -> the entry. Per player by construction, so no egress path can hand one + ## player another player's list by accident. + + SubjectNames* = object + ## What the name rule needs about one subject (a character, or a plain token). + id*: string ## the reveal subject id: the character id when linked, else the token id + descriptive*: string + actual*: string + revealAll*: bool + owner*: int ## the player who always knows the actual name; 0 = nobody + characterId*: Option[string] ## set when the subject is character-backed + +const + MaxOwnerlessName* = 64 + ## Characters follow the token name rule of 6.5: 1..64 code points (text.validText). + +# --------------------------------------------------------------------------------------------------- +# The name rule (DESIGN 8). One copy, used by every frame builder. + +proc knowsActual*(isOwner, revealAll, revealed: bool): bool = + ## A player is told the actual name of a subject when they own it, when the GM revealed it to + ## everyone, or when the GM revealed it to them (8; reveals are never revoked). + isOwner or revealAll or revealed + +proc visibleName*(descriptive, actual: string, knowsActual: bool): string = + ## The one name a recipient sees for a subject (6.1 `token.name`). + if knowsActual: actual else: descriptive + +proc isRevealed*(r: Reveals, player: int, subject: string): bool = + (player, subject) in r.pairs + +proc revealedPlayers*(r: Reveals, subject: string): seq[int] = + ## The `revealed:[player ids]` list of a GM frame, ascending so the frame is deterministic. + for (player, subj) in r.pairs: + if subj == subject: result.add player + result.sort() + +proc withReveal*(r: var Reveals, player: int, subject: string) = + r.pairs.incl (player, subject) + +proc withoutRevealsOf*(r: var Reveals, player: int) = + ## `player.remove`: that player's reveal rows go with it (6.1). + var doomed: seq[(int, string)] + for pair in r.pairs: + if pair[0] == player: doomed.add pair + for pair in doomed: r.pairs.excl pair + +# --------------------------------------------------------------------------------------------------- +# Lookups and the subject view + +proc characterIndex*(chars: openArray[CharacterRec], id: string): Option[int] = + for i, c in chars: + if c.id == id: return some(i) + +proc characterById*(chars: openArray[CharacterRec], id: string): Option[CharacterRec] = + let i = characterIndex(chars, id) + if i.isSome: return some(chars[i.get]) + +proc validCharacterName*(s: string): bool = validText(s, MaxOwnerlessName) + +proc parseSubject*(raw: string): Option[NameSubject] = + for s in NameSubject: + if $s == raw: return some(s) + +proc normalize*(c: CharacterRec): CharacterRec = + result = c + result.props = props.normalize(result.props) + +proc validCharacter*(c: CharacterRec): bool = + validCharacterName(c.descriptiveName) and validCharacterName(c.actualName) and + c.owner > 0 and props.valid(c.props) + +proc subjectNamesOf*(c: CharacterRec): SubjectNames = + ## A character as the name rule sees it: its owner always knows the actual name. + SubjectNames(id: c.id, descriptive: c.descriptiveName, actual: c.actualName, + revealAll: c.revealAll, owner: c.owner, characterId: some(c.id)) + +proc subjectNamesOf*(t: TokenRec, chars: openArray[CharacterRec]): SubjectNames = + ## A token as the name rule sees it: a linked token borrows the character's names (so one reveal + ## covers every token of that character), a plain token uses its own and owns nobody's trust. + if t.characterId.isSome: + let c = characterById(chars, t.characterId.get) + if c.isSome: return subjectNamesOf(c.get) + # A dangling link cannot exist (the FK and `in-use` forbid it); fall back to "no name" rather + # than crash a live connection. + return SubjectNames(id: t.characterId.get, descriptive: "", actual: "", + owner: 0, characterId: t.characterId) + SubjectNames(id: t.id, descriptive: t.descriptiveName, actual: t.actualName, + revealAll: t.revealAll, owner: 0, characterId: none(string)) + +proc nameFor*(n: SubjectNames, player: int, reveals: Reveals): string = + ## The name `player` sees for this subject (6.1 `token.name`, `encountered.name`). + visibleName(n.descriptive, n.actual, knowsActual(n.owner == player and n.owner > 0, + n.revealAll, reveals.isRevealed(player, n.id))) + +# --------------------------------------------------------------------------------------------------- +# Encountered entries (DESIGN 8) + +proc entryName*(e: EncounteredEntry): string = + ## The name this player knows: the actual one once it was revealed, else the descriptive one. + if e.actualName.isSome: e.actualName.get else: e.descriptiveName + +proc newEntry*(entityId: string, n: SubjectNames, knowsActual: bool): EncounteredEntry = + ## The snapshot a first sighting records: the names as they are now, and whether the player was + ## already allowed to know the actual one (a later reveal fills it in). + EncounteredEntry(entityId: entityId, characterId: n.characterId, + descriptiveName: n.descriptive, + actualName: (if knowsActual: some(n.actual) else: none(string))) + +proc renamed*(e: EncounteredEntry, descriptive, actual: string): EncounteredEntry = + ## After `character.update` or a plain-token rename: the snapshot follows the subject. A player who + ## was never told the actual name stays not-told. + result = e + result.descriptiveName = descriptive + if e.actualName.isSome: result.actualName = some(actual) + +proc revealed*(e: EncounteredEntry, actual: string): EncounteredEntry = + result = e + result.actualName = some(actual) + +# --------------------------------------------------------------------------------------------------- +# Persistence (write-through; GM authoring runs in the caller's FULL transaction, 4.4/Q12) + +proc insertRow(db: DbConn, c: CharacterRec) = + db.exec(sql"""INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, + reveal_all, props_public, props_owner, props_gm, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", + c.id, c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0), + $c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm], + now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) + +proc replaceRow(db: DbConn, c: CharacterRec) = + db.exec(sql"""UPDATE character SET owner_player_id = ?, descriptive_name = ?, actual_name = ?, + reveal_all = ?, props_public = ?, props_owner = ?, + props_gm = ? WHERE id = ?""", + c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0), + $c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm], c.id) + +proc addCharacter*(db: DbConn, candidate: CharacterRec, takenIds: openArray[string]): + tuple[outcome: CharacterOutcome, character: CharacterRec] = + ## `character.create`: validates, assigns a fresh id from the shared token/character namespace and + ## persists. The caller appends the record to memory after the transaction (4.2 step 6). + var stored = normalize(candidate) + if not validCharacter(stored): return (coInvalid, stored) + stored.id = freshId(takenIds) + authoringTransaction(db): + insertRow(db, stored) + (coOk, stored) + +proc storeCharacter*(db: DbConn, candidate: CharacterRec): CharacterOutcome = + ## `character.update`, `character.reassign`, `name.reveal_all`, `prop.*` on a character: one full + ## replacement of the row (GM authoring, FULL), so one change is one transaction. + let stored = normalize(candidate) + if not validCharacter(stored): return coInvalid + authoringTransaction(db): + replaceRow(db, stored) + coOk + +proc removeCharacter*(db: DbConn, id: string): bool = + var removed = false + authoringTransaction(db): + removed = db.execAffectedRows(sql"DELETE FROM character WHERE id = ?", id) > 0 + removed + +proc tokensLinkedTo*(tokens: openArray[TokenRec], characterId: string): int = + ## `character.remove` is refused with `in-use` while any token still figures the character (6.5). + for t in tokens: + if t.characterId.isSome and t.characterId.get == characterId: inc result + +proc transferToGm*(db: DbConn, playerId, gmId: int) = + ## `player.remove` (DESIGN 3.2): that player's characters pass to the GM. Runs before the player + ## DELETE, because `character.owner_player_id` refuses to dangle (no cascade on purpose). + db.exec(sql"UPDATE character SET owner_player_id = ? WHERE owner_player_id = ?", gmId, playerId) + +proc addReveal*(db: DbConn, player: int, subject: string) = + ## One `name_reveal` row; a repeated reveal is a no-op (`ok`, and nothing changes). + db.exec(sql"""INSERT OR IGNORE INTO name_reveal (player_id, subject_id, created_at) + VALUES (?, ?, ?)""", + player, subject, now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) + +proc deleteRevealsOf*(db: DbConn, player: int) = + db.exec(sql"DELETE FROM name_reveal WHERE player_id = ?", player) + +proc deleteRevealsFor*(db: DbConn, subject: string) = + ## `character.remove`: the reveal rows of a subject that no longer exists. (Rows of a *token* that + ## was removed are left alone: the token id is never reused, so they can never be read again, and + ## keeping them costs one row.) + db.exec(sql"DELETE FROM name_reveal WHERE subject_id = ?", subject) + +proc writeEncountered*(db: DbConn, player: int, e: EncounteredEntry) = + ## One `encountered` row per (player, token), upserted: the snapshot is a small value, not a log. + db.exec(sql"""INSERT INTO encountered (player_id, entity_id, character_id, descriptive_name, + actual_name, created_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (player_id, entity_id) DO UPDATE SET + character_id = excluded.character_id, + descriptive_name = excluded.descriptive_name, + actual_name = excluded.actual_name""", + player, e.entityId, + (if e.characterId.isSome: e.characterId.get else: ""), + e.descriptiveName, + (if e.actualName.isSome: e.actualName.get else: ""), + now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) + +proc deleteEncountered*(db: DbConn, player: int, entityId: string): bool = + db.execAffectedRows(sql"DELETE FROM encountered WHERE player_id = ? AND entity_id = ?", + player, entityId) > 0 + +proc renameEncountered*(db: DbConn, characterId: string, descriptive, actual: string) = + ## `character.update`: every snapshot of this character follows the new names. A player who was + ## never told the actual name keeps not knowing it (an unknown actual name is stored as `''`). + db.exec(sql"""UPDATE encountered SET descriptive_name = ? WHERE character_id = ?""", + descriptive, characterId) + db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE character_id = ? + AND actual_name <> ''""", actual, characterId) + +proc revealEncountered*(db: DbConn, characterId: string, actual: string) = + db.exec(sql"UPDATE encountered SET actual_name = ? WHERE character_id = ?", actual, characterId) + +proc revealEncounteredToken*(db: DbConn, entityId: string, actual: string) = + db.exec(sql"UPDATE encountered SET actual_name = ? WHERE entity_id = ?", actual, entityId) + +proc renameEncounteredToken*(db: DbConn, entityId, descriptive, actual: string) = + db.exec(sql"UPDATE encountered SET descriptive_name = ? WHERE entity_id = ?", descriptive, entityId) + db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE entity_id = ? + AND actual_name <> ''""", actual, entityId) + +# --------------------------------------------------------------------------------------------------- +# Loading (4.4 startup: load everything into memory once) + +proc parseObject(s: string): JsonNode = + try: + result = parseJson(s) + except CatchableError: + result = newJObject() + if result.isNil or result.kind != JObject: result = newJObject() + +proc rowToCharacter(row: Row): CharacterRec = + var p = newProps() + p[pbPublic] = parseObject(row[5]) + p[pbOwner] = parseObject(row[6]) + p[pbGm] = parseObject(row[7]) + CharacterRec(id: row[0], owner: parseInt(row[1]), descriptiveName: row[2], actualName: row[3], + revealAll: row[4] == "1", props: p) + +proc loadCharacters*(db: DbConn): seq[CharacterRec] = + ## Every character, in creation order (rowid), which is the order egress walks them. + for row in db.getAllRows(sql""" + SELECT id, owner_player_id, descriptive_name, actual_name, reveal_all, + props_public, props_owner, props_gm + FROM character ORDER BY rowid"""): + result.add rowToCharacter(row) + +proc loadReveals*(db: DbConn): Reveals = + for row in db.getAllRows(sql"SELECT player_id, subject_id FROM name_reveal"): + result.pairs.incl (parseInt(row[0]), row[1]) + +proc loadEncountered*(db: DbConn): Encountered = + ## Every entry, in creation order: the order a player's `encountered full` list arrives in. + for row in db.getAllRows(sql""" + SELECT player_id, entity_id, character_id, descriptive_name, actual_name + FROM encountered ORDER BY rowid"""): + let player = parseInt(row[0]) + result.mgetOrPut(player, initTable[string, EncounteredEntry]())[row[1]] = + EncounteredEntry(entityId: row[1], + characterId: (if row[2].len == 0: none(string) else: some(row[2])), + descriptiveName: row[3], + actualName: (if row[4].len == 0: none(string) else: some(row[4]))) diff --git a/server/db.nim b/server/db.nim index e12e085..1342b85 100644 --- a/server/db.nim +++ b/server/db.nim @@ -23,6 +23,17 @@ ## `(token, status, source)` entry, cascading on the token. `radius` was already a column from step 4 ## (`token.resize` is what makes it reachable); step 6 only makes the buckets and the statuses ## persistent. +## Step 7 ("characters", M3 slice 8 / #23) creates `character` (DESIGN 8: one owner, which is a real +## player id and may be the GM's, both names, `reveal_all`, the three property buckets), `name_reveal` +## (per-player reveal of one subject id: a character id or a plain token id, both from the token id +## alphabet) and `encountered` (the per-player "met before" snapshot of DESIGN 8: names, optional +## character link, no FK cascade so it survives token and character removal). It also adds +## `entity.character_id` (NULL = a plain token; the character a token figures) and +## `entity.reveal_all` for plain tokens, whose names the GM can reveal to everyone at once. +## `character.owner_player_id` has no cascade on purpose: 3.2 hands a removed player's characters to +## 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. ## 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 @@ -138,6 +149,37 @@ CREATE TABLE entity_status ( source TEXT NOT NULL CHECK (source IN ('walls', 'GM')), PRIMARY KEY (entity_id, status, source) )"""]), + Migration(version: 7, name: "characters", stmts: @[""" +CREATE TABLE character ( + id TEXT PRIMARY KEY, -- same 12-char alphabet and namespace as entity ids (8) + owner_player_id INTEGER NOT NULL REFERENCES player(id), -- always a real player id, GM included + 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, -- a character id, or a plain token id (never both for one subject) + 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, -- no FK: the entry outlives the token (8) + character_id TEXT, -- NULL for a plain token; no FK, the entry outlives it too + descriptive_name TEXT NOT NULL, -- the snapshot of the name this player knows (8) + actual_name TEXT, -- NULL = this player has not been told the actual name + created_at TEXT NOT NULL, + PRIMARY KEY (player_id, entity_id) +)""", """ +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))"""]), ] LatestVersion* = migrations[^1].version ## Derived, so adding a step cannot leave it stale. diff --git a/server/text.nim b/server/text.nim index 10ac506..02e9780 100644 --- a/server/text.nim +++ b/server/text.nim @@ -1,13 +1,39 @@ ## The one copy of the text rules of DESIGN 6.5: a stored text field is trimmed, 1..maxLen code -## points and free of control characters. Shared by the token/character names (tokens.nim) and the -## property keys (props.nim), so the two cannot drift apart. -import std/unicode +## points and free of control characters. Shared by the character/token names (tokens.nim, +## characters.nim), the property keys (props.nim) and the player names (auth.nim), so they cannot +## drift apart. +## +## Player names are the one exception to "refuse untrimmed input": they are typed by a human at +## sign-in, so the server trims the value (and requires the trimmed form, which then is what it +## stores) and applies the same length/control rules (6.5). Character and plain-token names are +## GM-authored world text and must already be in that form. +## +## Deviation, recorded FIXED (owner-delegated) in DESIGN 6.5: 6.5 also asks for NFC normalisation of +## a player name. Nim 2.2.12's stdlib carries no Unicode normalisation (it lives in an external +## package that the pinned dependency set does not include), so a name is stored as typed, trimmed, +## and compared case-insensitively. The practical consequence is that two visually identical names +## written with precomposed vs combining accents count as different names; nothing else changes. +import std/strutils +import std/unicode as uni proc hasControlChar*(s: string): bool = for r in s.runes: if r.int < 0x20 or r.int == 0x7f: return true proc validText*(s: string, maxLen: int): bool = - ## Trimmed, 1..maxLen code points, no control characters. NFC normalisation and the per-player - ## uniqueness rule arrived with the name machinery of slice 8 (#23). + ## Trimmed, 1..maxLen code points, no control characters. s.len > 0 and s == s.strip and s.runeLen in 1 .. maxLen and not hasControlChar(s) + +proc normalizedPlayerName*(raw: string): string = + ## DESIGN 6.5: the form a player name is stored in. Trimming is the normalisation the server can + ## apply without a Unicode table (see the module comment). + raw.strip + +proc validPlayerName*(normalized: string): bool = + ## The rule of 6.5 for a player's display name: 1..32 code points, no control characters. + normalized.len > 0 and normalized.runeLen in 1 .. 32 and not hasControlChar(normalized) + +proc sameName*(a, b: string): bool = + ## Names are unique regardless of case (6.5 `name-taken`); Latin case folding is enough for Q17's + ## glyph set. + uni.toLower(a) == uni.toLower(b) diff --git a/server/tokens.nim b/server/tokens.nim index 3fcb8ee..55a6784 100644 --- a/server/tokens.nim +++ b/server/tokens.nim @@ -53,8 +53,10 @@ type id*: string scene*: int kind*: string ## free string (pc, npc, item...); GM-only on the wire (6.1 leak note 1) - descriptiveName*: string - actualName*: string + descriptiveName*: string ## "" when `characterId` is set: the character carries the names (8) + actualName*: string ## "" when `characterId` is set + characterId*: Option[string] ## the character this token figures (8); none = a plain token + revealAll*: bool ## plain tokens only: the actual name is revealed to everyone (8) pos*: Vec radius*: Option[float] ## px; none = the scene default (5.6, #4) owner*: int ## controller: player id, GmControlled = the GM @@ -77,6 +79,7 @@ type kind*: Option[string] descriptiveName*: Option[string] actualName*: Option[string] + characterId*: Option[Option[string]] ## some(none) = unlink, some(some(id)) = link controller*: Option[int] ## GmControlled = GM gmOnly*: Option[bool] flags*: Option[JsonNode] @@ -224,7 +227,12 @@ proc validPlacement*(sc: SceneRec, pos: Vec): bool = inBounds(sc, pos) proc validToken*(sc: SceneRec, t: TokenRec): bool = ## 6.1 validation. The props are checked for structure and caps; the per-key schema is the wire ## layer's job (props.checkWrite), because only the intent knows the registry. - validName(t.descriptiveName) and validName(t.actualName) and validKind(t.kind) and + ## Names (8): a plain token carries both of its own and they follow the name rule; a token linked + ## to a character carries neither, because the character's names are the ones that reach a client. + let namesOk = + if t.characterId.isSome: t.descriptiveName.len == 0 and t.actualName.len == 0 + else: validName(t.descriptiveName) and validName(t.actualName) + namesOk and validKind(t.kind) and validPlacement(sc, t.pos) and props.valid(t.props) and (t.radius.isNone or t.radius.get > 0) @@ -234,6 +242,7 @@ proc patched*(t: TokenRec, patch: TokenPatch): TokenRec = if patch.kind.isSome: result.kind = patch.kind.get if patch.descriptiveName.isSome: result.descriptiveName = patch.descriptiveName.get if patch.actualName.isSome: result.actualName = patch.actualName.get + if patch.characterId.isSome: result.characterId = patch.characterId.get if patch.controller.isSome: result.owner = patch.controller.get if patch.gmOnly.isSome: result.gmOnly = patch.gmOnly.get if patch.flags.isSome: result.flags = patch.flags.get @@ -251,6 +260,17 @@ proc sqlLit(v: Option[float]): string = proc sqlLitOwner(owner: int): string = if owner == GmControlled: "NULL" else: $owner +proc sqlLitId(id: Option[string]): string = + ## `character_id` is NULL for a plain token, and db_connector cannot bind a NULL argument + ## (it quotes every parameter as text), so the value rides as a literal. Only ids from the token + ## alphabet (8) ever reach here - a value is checked on the way in - so a quote cannot appear. + if id.isNone: return "NULL" + let v = id.get + for c in v: + if c notin {'A'..'Z', 'a'..'z', '0'..'9', '_', '-'}: + raise newException(ValueError, "character id outside the id alphabet") + "'" & v & "'" + proc writeStatuses*(db: DbConn, t: TokenRec) = ## Rewrites the token's `entity_status` rows to exactly `t.statuses`. No transaction control: the ## caller is inside the row's transaction (a status change and its row commit together). @@ -267,23 +287,25 @@ proc writeStatuses*(db: DbConn, id: string, statuses: openArray[StatusEntry]) = proc insertRow(db: DbConn, t: TokenRec) = db.exec(sql("INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, radius," & " owner_player_id, gm_only, vision_radius, flags, props_public, props_owner," & - " props_gm, created_at) VALUES (" & + " props_gm, created_at, character_id, reveal_all) VALUES (" & "?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " & - sqlLit(t.visionRadius) & ", ?, ?, ?, ?, ?)"), + sqlLit(t.visionRadius) & ", ?, ?, ?, ?, ?, " & sqlLitId(t.characterId) & ", ?)"), t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, $t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], - now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) + now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"), (if t.revealAll: 1 else: 0)) writeStatuses(db, t) proc replaceRow(db: DbConn, t: TokenRec) = db.exec(sql("UPDATE entity SET kind = ?, descriptive_name = ?, actual_name = ?, x = ?, y = ?," & " radius = " & sqlLit(t.radius) & ", owner_player_id = " & sqlLitOwner(t.owner) & ", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?," & - " props_public = ?, props_owner = ?, props_gm = ? WHERE id = ?"), + " props_public = ?, props_owner = ?, props_gm = ?, reveal_all = ?," & + " character_id = " & sqlLitId(t.characterId) & " WHERE id = ?"), t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, - $t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], t.id) + $t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], + (if t.revealAll: 1 else: 0), t.id) writeStatuses(db, t) @@ -349,7 +371,9 @@ proc rowToToken(row: Row): TokenRec = radius: optFloat(row[7]), owner: (if row[8].len == 0: GmControlled else: parseInt(row[8])), gmOnly: row[9] == "1", - visionRadius: optFloat(row[10]), flags: parseObject(row[11]), props: p) + visionRadius: optFloat(row[10]), flags: parseObject(row[11]), props: p, + characterId: (if row[15].len == 0: none(string) else: some(row[15])), + revealAll: row[16] == "1") proc loadStatuses(db: DbConn, sceneId: int): Table[string, seq[StatusEntry]] = ## The `(status, source)` entries of every token of the scene, keyed by token id (5.5). @@ -364,7 +388,8 @@ proc loadTokens*(db: DbConn, sceneId = DefaultSceneId): seq[TokenRec] = ## Every token of the scene, in creation order (rowid), which is the order egress walks. for row in db.getAllRows(sql""" SELECT id, scene_id, kind, descriptive_name, actual_name, x, y, radius, owner_player_id, - gm_only, vision_radius, flags, props_public, props_owner, props_gm + gm_only, vision_radius, flags, props_public, props_owner, props_gm, character_id, + reveal_all FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId): result.add rowToToken(row) let statuses = loadStatuses(db, sceneId)