BlueGit

timfa questward

Add SQLite world and state databases with revisioned authored chunks.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
cc1b0d3e523d8694b0c0019ae8ed68c8b2a66943
Parent
87e2f6b7
4 files changed +428 −9
docs/FEATURES.md +9 −9
@@ -39,21 +39,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
39 39
40 40 ## Authored world and runtime state persistence
41 41
42 **Status:** not implemented
43 **Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Chunks persist on unload.
44 **Code:** —
42 **Status:** full
43 **Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
44 **Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
45 45
46 46 ## World revisions and pending editor saves
47 47
48 **Status:** not implemented
49 **Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until restart or an explicit apply.
50 **Code:** —
48 **Status:** partial
49 **Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until an admin **Apply now** (in-process reload). Midnight restart/Git deploy is not implemented yet.
50 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
51 51
52 52 ## World settings
53 53
54 **Status:** not implemented
55 **Spec:** Global cadence and timers (walk speed, tick rate, deletion delay, and similar) live in authored world settings, edited from a modal.
56 **Code:** —
54 **Status:** partial
55 **Spec:** Global cadence and timers live in authored `world_settings` per revision, with design defaults. Walk speed and tick rate can be saved from the editor. Other timers are stored but not all are consumed yet.
56 **Code:** `server/src/persistence/worldDb.js`, `shared/protocol/constants.js` (`DEFAULT_WORLD_SETTINGS`)
57 57
58 58 ## Baked lighting
59 59
@@ -39,21 +39,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
39
39
40## Authored world and runtime state persistence
40## Authored world and runtime state persistence
41
41
42**Status:** not implemented
42**Status:** full
43**Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Chunks persist on unload.
43**Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
44**Code:** —
44**Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
45
45
46## World revisions and pending editor saves
46## World revisions and pending editor saves
47
47
48**Status:** not implemented
48**Status:** partial
49**Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until restart or an explicit apply.
49**Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until an admin **Apply now** (in-process reload). Midnight restart/Git deploy is not implemented yet.
50**Code:** —
50**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
51
51
52## World settings
52## World settings
53
53
54**Status:** not implemented
54**Status:** partial
55**Spec:** Global cadence and timers (walk speed, tick rate, deletion delay, and similar) live in authored world settings, edited from a modal.
55**Spec:** Global cadence and timers live in authored `world_settings` per revision, with design defaults. Walk speed and tick rate can be saved from the editor. Other timers are stored but not all are consumed yet.
56**Code:** —
56**Code:** `server/src/persistence/worldDb.js`, `shared/protocol/constants.js` (`DEFAULT_WORLD_SETTINGS`)
57
57
58## Baked lighting
58## Baked lighting
59
59
server/src/persistence/database.js added +28 −0
@@ -0,0 +1,28 @@
1 import { DatabaseSync } from "node:sqlite";
2 import { mkdirSync } from "node:fs";
3 import { dirname } from "node:path";
4
5 export function openDatabase (filePath)
6 {
7 mkdirSync(dirname(filePath), { recursive: true });
8 const database = new DatabaseSync(filePath);
9 database.exec("PRAGMA journal_mode = WAL");
10 database.exec("PRAGMA foreign_keys = ON");
11 return database;
12 }
13
14 export function withTransaction (database, fn)
15 {
16 database.exec("BEGIN");
17 try
18 {
19 const result = fn();
20 database.exec("COMMIT");
21 return result;
22 }
23 catch (error)
24 {
25 database.exec("ROLLBACK");
26 throw error;
27 }
28 }
@@ -0,0 +1,28 @@
1import { DatabaseSync } from "node:sqlite";
2import { mkdirSync } from "node:fs";
3import { dirname } from "node:path";
4
5export function openDatabase (filePath)
6{
7 mkdirSync(dirname(filePath), { recursive: true });
8 const database = new DatabaseSync(filePath);
9 database.exec("PRAGMA journal_mode = WAL");
10 database.exec("PRAGMA foreign_keys = ON");
11 return database;
12}
13
14export function withTransaction (database, fn)
15{
16 database.exec("BEGIN");
17 try
18 {
19 const result = fn();
20 database.exec("COMMIT");
21 return result;
22 }
23 catch (error)
24 {
25 database.exec("ROLLBACK");
26 throw error;
27 }
28}
server/src/persistence/stateDb.js added +182 −0
@@ -0,0 +1,182 @@
1 import { openDatabase } from "./database.js";
2
3 const STATE_SCHEMA = `
4 CREATE TABLE IF NOT EXISTS accounts (
5 account_id INTEGER PRIMARY KEY AUTOINCREMENT,
6 auth_subject TEXT NOT NULL UNIQUE,
7 email TEXT,
8 is_admin INTEGER NOT NULL DEFAULT 0
9 );
10
11 CREATE TABLE IF NOT EXISTS surname_claims (
12 surname_normalized TEXT PRIMARY KEY,
13 account_id INTEGER NOT NULL
14 );
15
16 CREATE TABLE IF NOT EXISTS characters (
17 character_id INTEGER PRIMARY KEY AUTOINCREMENT,
18 account_id INTEGER NOT NULL,
19 first_name TEXT NOT NULL,
20 last_name TEXT NOT NULL,
21 first_normalized TEXT NOT NULL,
22 last_normalized TEXT NOT NULL,
23 sex TEXT NOT NULL,
24 tile_x INTEGER NOT NULL DEFAULT 8,
25 tile_y INTEGER NOT NULL DEFAULT 8,
26 gait TEXT NOT NULL DEFAULT 'walk',
27 deletion_scheduled_at INTEGER
28 );
29 `;
30
31 export class StateDatabase
32 {
33 constructor (filePath)
34 {
35 this.db = openDatabase(filePath);
36 this.db.exec(STATE_SCHEMA);
37 }
38
39 getAccountBySubject (authSubject)
40 {
41 return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;
42 }
43
44 createAccount (authSubject, isAdmin, email = null)
45 {
46 this.db.prepare("INSERT INTO accounts (auth_subject, email, is_admin) VALUES (?, ?, ?)").run(
47 authSubject,
48 email,
49 isAdmin ? 1 : 0
50 );
51 return this.getAccountBySubject(authSubject);
52 }
53
54 ensureAccount (authSubject, isAdmin, email = null)
55 {
56 const existing = this.getAccountBySubject(authSubject);
57 if (existing)
58 { return existing; }
59
60 return this.createAccount(authSubject, isAdmin, email);
61 }
62
63 listCharacters (accountId)
64 {
65 return this.db.prepare(`
66 SELECT * FROM characters
67 WHERE account_id = ?
68 ORDER BY character_id ASC
69 `).all(accountId);
70 }
71
72 getCharacter (characterId)
73 {
74 return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;
75 }
76
77 findSurnameClaim (surnameNormalized)
78 {
79 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
80 }
81
82 createCharacter (accountId, firstName, lastName, sex, tileX, tileY)
83 {
84 const firstNormalized = normalizeName(firstName);
85 const lastNormalized = normalizeName(lastName);
86 this.db.exec("BEGIN");
87 try
88 {
89 this.db.prepare(`
90 INSERT INTO characters (
91 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y
92 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
93 `).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY);
94 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
95
96 const claim = this.findSurnameClaim(lastNormalized);
97 if (!claim)
98 {
99 this.db.prepare("INSERT INTO surname_claims (surname_normalized, account_id) VALUES (?, ?)").run(
100 lastNormalized,
101 accountId
102 );
103 }
104
105 this.db.exec("COMMIT");
106 return this.getCharacter(characterId);
107 }
108 catch (error)
109 {
110 this.db.exec("ROLLBACK");
111 throw error;
112 }
113 }
114
115 scheduleDeletion (characterId, at)
116 {
117 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
118 }
119
120 cancelDeletion (characterId)
121 {
122 this.db.prepare("UPDATE characters SET deletion_scheduled_at = NULL WHERE character_id = ?").run(characterId);
123 }
124
125 deleteCharacter (characterId)
126 {
127 const character = this.getCharacter(characterId);
128 if (!character)
129 { return; }
130
131 this.db.exec("BEGIN");
132 try
133 {
134 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
135 const remaining = this.db.prepare(`
136 SELECT COUNT(*) AS count FROM characters
137 WHERE account_id = ? AND last_normalized = ?
138 `).get(character.account_id, character.last_normalized);
139 if (!remaining.count)
140 {
141 this.db.prepare("DELETE FROM surname_claims WHERE surname_normalized = ? AND account_id = ?").run(
142 character.last_normalized,
143 character.account_id
144 );
145 }
146 this.db.exec("COMMIT");
147 }
148 catch (error)
149 {
150 this.db.exec("ROLLBACK");
151 throw error;
152 }
153 }
154
155 saveCharacterPosition (characterId, tileX, tileY, gait)
156 {
157 this.db.prepare("UPDATE characters SET tile_x = ?, tile_y = ?, gait = ? WHERE character_id = ?").run(
158 tileX,
159 tileY,
160 gait,
161 characterId
162 );
163 }
164
165 listDueDeletions (now)
166 {
167 return this.db.prepare(`
168 SELECT * FROM characters
169 WHERE deletion_scheduled_at IS NOT NULL AND deletion_scheduled_at <= ?
170 `).all(now);
171 }
172
173 close ()
174 {
175 this.db.close();
176 }
177 }
178
179 export function normalizeName (value)
180 {
181 return String(value ?? "").trim().toLocaleLowerCase();
182 }
@@ -0,0 +1,182 @@
1import { openDatabase } from "./database.js";
2
3const STATE_SCHEMA = `
4CREATE TABLE IF NOT EXISTS accounts (
5 account_id INTEGER PRIMARY KEY AUTOINCREMENT,
6 auth_subject TEXT NOT NULL UNIQUE,
7 email TEXT,
8 is_admin INTEGER NOT NULL DEFAULT 0
9);
10
11CREATE TABLE IF NOT EXISTS surname_claims (
12 surname_normalized TEXT PRIMARY KEY,
13 account_id INTEGER NOT NULL
14);
15
16CREATE TABLE IF NOT EXISTS characters (
17 character_id INTEGER PRIMARY KEY AUTOINCREMENT,
18 account_id INTEGER NOT NULL,
19 first_name TEXT NOT NULL,
20 last_name TEXT NOT NULL,
21 first_normalized TEXT NOT NULL,
22 last_normalized TEXT NOT NULL,
23 sex TEXT NOT NULL,
24 tile_x INTEGER NOT NULL DEFAULT 8,
25 tile_y INTEGER NOT NULL DEFAULT 8,
26 gait TEXT NOT NULL DEFAULT 'walk',
27 deletion_scheduled_at INTEGER
28);
29`;
30
31export class StateDatabase
32{
33 constructor (filePath)
34 {
35 this.db = openDatabase(filePath);
36 this.db.exec(STATE_SCHEMA);
37 }
38
39 getAccountBySubject (authSubject)
40 {
41 return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;
42 }
43
44 createAccount (authSubject, isAdmin, email = null)
45 {
46 this.db.prepare("INSERT INTO accounts (auth_subject, email, is_admin) VALUES (?, ?, ?)").run(
47 authSubject,
48 email,
49 isAdmin ? 1 : 0
50 );
51 return this.getAccountBySubject(authSubject);
52 }
53
54 ensureAccount (authSubject, isAdmin, email = null)
55 {
56 const existing = this.getAccountBySubject(authSubject);
57 if (existing)
58 { return existing; }
59
60 return this.createAccount(authSubject, isAdmin, email);
61 }
62
63 listCharacters (accountId)
64 {
65 return this.db.prepare(`
66 SELECT * FROM characters
67 WHERE account_id = ?
68 ORDER BY character_id ASC
69 `).all(accountId);
70 }
71
72 getCharacter (characterId)
73 {
74 return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;
75 }
76
77 findSurnameClaim (surnameNormalized)
78 {
79 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
80 }
81
82 createCharacter (accountId, firstName, lastName, sex, tileX, tileY)
83 {
84 const firstNormalized = normalizeName(firstName);
85 const lastNormalized = normalizeName(lastName);
86 this.db.exec("BEGIN");
87 try
88 {
89 this.db.prepare(`
90 INSERT INTO characters (
91 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y
92 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
93 `).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY);
94 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
95
96 const claim = this.findSurnameClaim(lastNormalized);
97 if (!claim)
98 {
99 this.db.prepare("INSERT INTO surname_claims (surname_normalized, account_id) VALUES (?, ?)").run(
100 lastNormalized,
101 accountId
102 );
103 }
104
105 this.db.exec("COMMIT");
106 return this.getCharacter(characterId);
107 }
108 catch (error)
109 {
110 this.db.exec("ROLLBACK");
111 throw error;
112 }
113 }
114
115 scheduleDeletion (characterId, at)
116 {
117 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
118 }
119
120 cancelDeletion (characterId)
121 {
122 this.db.prepare("UPDATE characters SET deletion_scheduled_at = NULL WHERE character_id = ?").run(characterId);
123 }
124
125 deleteCharacter (characterId)
126 {
127 const character = this.getCharacter(characterId);
128 if (!character)
129 { return; }
130
131 this.db.exec("BEGIN");
132 try
133 {
134 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
135 const remaining = this.db.prepare(`
136 SELECT COUNT(*) AS count FROM characters
137 WHERE account_id = ? AND last_normalized = ?
138 `).get(character.account_id, character.last_normalized);
139 if (!remaining.count)
140 {
141 this.db.prepare("DELETE FROM surname_claims WHERE surname_normalized = ? AND account_id = ?").run(
142 character.last_normalized,
143 character.account_id
144 );
145 }
146 this.db.exec("COMMIT");
147 }
148 catch (error)
149 {
150 this.db.exec("ROLLBACK");
151 throw error;
152 }
153 }
154
155 saveCharacterPosition (characterId, tileX, tileY, gait)
156 {
157 this.db.prepare("UPDATE characters SET tile_x = ?, tile_y = ?, gait = ? WHERE character_id = ?").run(
158 tileX,
159 tileY,
160 gait,
161 characterId
162 );
163 }
164
165 listDueDeletions (now)
166 {
167 return this.db.prepare(`
168 SELECT * FROM characters
169 WHERE deletion_scheduled_at IS NOT NULL AND deletion_scheduled_at <= ?
170 `).all(now);
171 }
172
173 close ()
174 {
175 this.db.close();
176 }
177}
178
179export function normalizeName (value)
180{
181 return String(value ?? "").trim().toLocaleLowerCase();
182}
server/src/persistence/worldDb.js added +209 −0
@@ -0,0 +1,209 @@
1 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 import { openDatabase, withTransaction } from "./database.js";
3
4 const WORLD_SCHEMA = `
5 CREATE TABLE IF NOT EXISTS world_revisions (
6 revision_id INTEGER PRIMARY KEY AUTOINCREMENT,
7 created_at INTEGER NOT NULL,
8 created_by TEXT NOT NULL,
9 status TEXT NOT NULL
10 );
11
12 CREATE TABLE IF NOT EXISTS world_chunk_versions (
13 chunk_x INTEGER NOT NULL,
14 chunk_y INTEGER NOT NULL,
15 revision_id INTEGER NOT NULL,
16 open INTEGER NOT NULL,
17 data_blob TEXT NOT NULL,
18 PRIMARY KEY (chunk_x, chunk_y, revision_id)
19 );
20
21 CREATE TABLE IF NOT EXISTS world_meta (
22 key TEXT PRIMARY KEY,
23 value INTEGER
24 );
25
26 CREATE TABLE IF NOT EXISTS world_settings (
27 revision_id INTEGER PRIMARY KEY,
28 settings_blob TEXT NOT NULL
29 );
30
31 CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
32 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
33 chunk_x INTEGER NOT NULL,
34 chunk_y INTEGER NOT NULL,
35 revision_id INTEGER NOT NULL,
36 editor_admin_id TEXT NOT NULL,
37 edited_at INTEGER NOT NULL,
38 diff_entries TEXT NOT NULL
39 );
40 `;
41
42 export class WorldDatabase
43 {
44 constructor (filePath)
45 {
46 this.db = openDatabase(filePath);
47 this.db.exec(WORLD_SCHEMA);
48 this.#ensureInitialRevision();
49 }
50
51 #ensureInitialRevision ()
52 {
53 const meta = this.db.prepare("SELECT key, value FROM world_meta").all();
54 if (meta.length > 0)
55 { return; }
56
57 withTransaction(this.db, () =>
58 {
59 this.db.prepare(
60 "INSERT INTO world_revisions (created_at, created_by, status) VALUES (?, ?, ?)"
61 ).run(Date.now(), "system", "active");
62 const revisionId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
63 this.db.prepare("INSERT INTO world_meta (key, value) VALUES ('active_revision', ?)").run(revisionId);
64 this.db.exec("INSERT INTO world_meta (key, value) VALUES ('pending_revision', NULL)");
65 this.db.prepare("INSERT INTO world_settings (revision_id, settings_blob) VALUES (?, ?)").run(
66 revisionId,
67 JSON.stringify(DEFAULT_WORLD_SETTINGS)
68 );
69 });
70 }
71
72 getActiveRevisionId ()
73 {
74 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'active_revision'").get()?.value ?? null;
75 }
76
77 getPendingRevisionId ()
78 {
79 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'pending_revision'").get()?.value ?? null;
80 }
81
82 getEditorRevisionId ()
83 {
84 return this.getPendingRevisionId() ?? this.getActiveRevisionId();
85 }
86
87 getSettings (revisionId)
88 {
89 const row = this.db.prepare("SELECT settings_blob FROM world_settings WHERE revision_id = ?").get(revisionId);
90 if (row)
91 { return { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }; }
92
93 const fallback = this.db.prepare(
94 "SELECT settings_blob FROM world_settings WHERE revision_id <= ? ORDER BY revision_id DESC LIMIT 1"
95 ).get(revisionId);
96 return fallback
97 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(fallback.settings_blob) }
98 : { ...DEFAULT_WORLD_SETTINGS };
99 }
100
101 getChunkVersion (chunkX, chunkY, revisionId)
102 {
103 return this.db.prepare(`
104 SELECT chunk_x, chunk_y, revision_id, open, data_blob
105 FROM world_chunk_versions
106 WHERE chunk_x = ? AND chunk_y = ? AND revision_id <= ?
107 ORDER BY revision_id DESC
108 LIMIT 1
109 `).get(chunkX, chunkY, revisionId) ?? null;
110 }
111
112 listChunkCoords (revisionId)
113 {
114 return this.db.prepare(`
115 SELECT chunk_x, chunk_y, MAX(revision_id) AS revision_id
116 FROM world_chunk_versions
117 WHERE revision_id <= ?
118 GROUP BY chunk_x, chunk_y
119 `).all(revisionId);
120 }
121
122 ensurePendingRevision (createdBy)
123 {
124 const existing = this.getPendingRevisionId();
125 if (existing)
126 { return existing; }
127
128 return withTransaction(this.db, () =>
129 {
130 const activeId = this.getActiveRevisionId();
131 this.db.prepare(
132 "INSERT INTO world_revisions (created_at, created_by, status) VALUES (?, ?, ?)"
133 ).run(Date.now(), createdBy, "pending");
134 const revisionId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
135 this.db.prepare("UPDATE world_meta SET value = ? WHERE key = 'pending_revision'").run(revisionId);
136
137 const settings = this.getSettings(activeId);
138 this.db.prepare("INSERT INTO world_settings (revision_id, settings_blob) VALUES (?, ?)").run(
139 revisionId,
140 JSON.stringify(settings)
141 );
142 return revisionId;
143 });
144 }
145
146 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob)
147 {
148 this.db.prepare(`
149 INSERT INTO world_chunk_versions (chunk_x, chunk_y, revision_id, open, data_blob)
150 VALUES (?, ?, ?, ?, ?)
151 ON CONFLICT(chunk_x, chunk_y, revision_id) DO UPDATE SET
152 open = excluded.open,
153 data_blob = excluded.data_blob
154 `).run(chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
155 }
156
157 saveSettings (revisionId, settings)
158 {
159 this.db.prepare(`
160 INSERT INTO world_settings (revision_id, settings_blob)
161 VALUES (?, ?)
162 ON CONFLICT(revision_id) DO UPDATE SET settings_blob = excluded.settings_blob
163 `).run(revisionId, JSON.stringify(settings));
164 }
165
166 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries)
167 {
168 this.db.prepare(`
169 INSERT INTO world_chunk_edit_log
170 (chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
171 VALUES (?, ?, ?, ?, ?, ?)
172 `).run(chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
173 }
174
175 listChangelog (chunkX, chunkY)
176 {
177 return this.db.prepare(`
178 SELECT log_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
179 FROM world_chunk_edit_log
180 WHERE chunk_x = ? AND chunk_y = ?
181 ORDER BY edited_at ASC, log_id ASC
182 `).all(chunkX, chunkY).map((row) => ({
183 ...row,
184 diffEntries: JSON.parse(row.diff_entries)
185 }));
186 }
187
188 promotePendingRevision ()
189 {
190 const pendingId = this.getPendingRevisionId();
191 if (!pendingId)
192 { return this.getActiveRevisionId(); }
193
194 return withTransaction(this.db, () =>
195 {
196 const activeId = this.getActiveRevisionId();
197 this.db.prepare("UPDATE world_revisions SET status = 'superseded' WHERE revision_id = ?").run(activeId);
198 this.db.prepare("UPDATE world_revisions SET status = 'active' WHERE revision_id = ?").run(pendingId);
199 this.db.prepare("UPDATE world_meta SET value = ? WHERE key = 'active_revision'").run(pendingId);
200 this.db.exec("UPDATE world_meta SET value = NULL WHERE key = 'pending_revision'");
201 return pendingId;
202 });
203 }
204
205 close ()
206 {
207 this.db.close();
208 }
209 }
@@ -0,0 +1,209 @@
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { openDatabase, withTransaction } from "./database.js";
3
4const WORLD_SCHEMA = `
5CREATE TABLE IF NOT EXISTS world_revisions (
6 revision_id INTEGER PRIMARY KEY AUTOINCREMENT,
7 created_at INTEGER NOT NULL,
8 created_by TEXT NOT NULL,
9 status TEXT NOT NULL
10);
11
12CREATE TABLE IF NOT EXISTS world_chunk_versions (
13 chunk_x INTEGER NOT NULL,
14 chunk_y INTEGER NOT NULL,
15 revision_id INTEGER NOT NULL,
16 open INTEGER NOT NULL,
17 data_blob TEXT NOT NULL,
18 PRIMARY KEY (chunk_x, chunk_y, revision_id)
19);
20
21CREATE TABLE IF NOT EXISTS world_meta (
22 key TEXT PRIMARY KEY,
23 value INTEGER
24);
25
26CREATE TABLE IF NOT EXISTS world_settings (
27 revision_id INTEGER PRIMARY KEY,
28 settings_blob TEXT NOT NULL
29);
30
31CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
32 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
33 chunk_x INTEGER NOT NULL,
34 chunk_y INTEGER NOT NULL,
35 revision_id INTEGER NOT NULL,
36 editor_admin_id TEXT NOT NULL,
37 edited_at INTEGER NOT NULL,
38 diff_entries TEXT NOT NULL
39);
40`;
41
42export class WorldDatabase
43{
44 constructor (filePath)
45 {
46 this.db = openDatabase(filePath);
47 this.db.exec(WORLD_SCHEMA);
48 this.#ensureInitialRevision();
49 }
50
51 #ensureInitialRevision ()
52 {
53 const meta = this.db.prepare("SELECT key, value FROM world_meta").all();
54 if (meta.length > 0)
55 { return; }
56
57 withTransaction(this.db, () =>
58 {
59 this.db.prepare(
60 "INSERT INTO world_revisions (created_at, created_by, status) VALUES (?, ?, ?)"
61 ).run(Date.now(), "system", "active");
62 const revisionId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
63 this.db.prepare("INSERT INTO world_meta (key, value) VALUES ('active_revision', ?)").run(revisionId);
64 this.db.exec("INSERT INTO world_meta (key, value) VALUES ('pending_revision', NULL)");
65 this.db.prepare("INSERT INTO world_settings (revision_id, settings_blob) VALUES (?, ?)").run(
66 revisionId,
67 JSON.stringify(DEFAULT_WORLD_SETTINGS)
68 );
69 });
70 }
71
72 getActiveRevisionId ()
73 {
74 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'active_revision'").get()?.value ?? null;
75 }
76
77 getPendingRevisionId ()
78 {
79 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'pending_revision'").get()?.value ?? null;
80 }
81
82 getEditorRevisionId ()
83 {
84 return this.getPendingRevisionId() ?? this.getActiveRevisionId();
85 }
86
87 getSettings (revisionId)
88 {
89 const row = this.db.prepare("SELECT settings_blob FROM world_settings WHERE revision_id = ?").get(revisionId);
90 if (row)
91 { return { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }; }
92
93 const fallback = this.db.prepare(
94 "SELECT settings_blob FROM world_settings WHERE revision_id <= ? ORDER BY revision_id DESC LIMIT 1"
95 ).get(revisionId);
96 return fallback
97 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(fallback.settings_blob) }
98 : { ...DEFAULT_WORLD_SETTINGS };
99 }
100
101 getChunkVersion (chunkX, chunkY, revisionId)
102 {
103 return this.db.prepare(`
104 SELECT chunk_x, chunk_y, revision_id, open, data_blob
105 FROM world_chunk_versions
106 WHERE chunk_x = ? AND chunk_y = ? AND revision_id <= ?
107 ORDER BY revision_id DESC
108 LIMIT 1
109 `).get(chunkX, chunkY, revisionId) ?? null;
110 }
111
112 listChunkCoords (revisionId)
113 {
114 return this.db.prepare(`
115 SELECT chunk_x, chunk_y, MAX(revision_id) AS revision_id
116 FROM world_chunk_versions
117 WHERE revision_id <= ?
118 GROUP BY chunk_x, chunk_y
119 `).all(revisionId);
120 }
121
122 ensurePendingRevision (createdBy)
123 {
124 const existing = this.getPendingRevisionId();
125 if (existing)
126 { return existing; }
127
128 return withTransaction(this.db, () =>
129 {
130 const activeId = this.getActiveRevisionId();
131 this.db.prepare(
132 "INSERT INTO world_revisions (created_at, created_by, status) VALUES (?, ?, ?)"
133 ).run(Date.now(), createdBy, "pending");
134 const revisionId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
135 this.db.prepare("UPDATE world_meta SET value = ? WHERE key = 'pending_revision'").run(revisionId);
136
137 const settings = this.getSettings(activeId);
138 this.db.prepare("INSERT INTO world_settings (revision_id, settings_blob) VALUES (?, ?)").run(
139 revisionId,
140 JSON.stringify(settings)
141 );
142 return revisionId;
143 });
144 }
145
146 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob)
147 {
148 this.db.prepare(`
149 INSERT INTO world_chunk_versions (chunk_x, chunk_y, revision_id, open, data_blob)
150 VALUES (?, ?, ?, ?, ?)
151 ON CONFLICT(chunk_x, chunk_y, revision_id) DO UPDATE SET
152 open = excluded.open,
153 data_blob = excluded.data_blob
154 `).run(chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
155 }
156
157 saveSettings (revisionId, settings)
158 {
159 this.db.prepare(`
160 INSERT INTO world_settings (revision_id, settings_blob)
161 VALUES (?, ?)
162 ON CONFLICT(revision_id) DO UPDATE SET settings_blob = excluded.settings_blob
163 `).run(revisionId, JSON.stringify(settings));
164 }
165
166 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries)
167 {
168 this.db.prepare(`
169 INSERT INTO world_chunk_edit_log
170 (chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
171 VALUES (?, ?, ?, ?, ?, ?)
172 `).run(chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
173 }
174
175 listChangelog (chunkX, chunkY)
176 {
177 return this.db.prepare(`
178 SELECT log_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
179 FROM world_chunk_edit_log
180 WHERE chunk_x = ? AND chunk_y = ?
181 ORDER BY edited_at ASC, log_id ASC
182 `).all(chunkX, chunkY).map((row) => ({
183 ...row,
184 diffEntries: JSON.parse(row.diff_entries)
185 }));
186 }
187
188 promotePendingRevision ()
189 {
190 const pendingId = this.getPendingRevisionId();
191 if (!pendingId)
192 { return this.getActiveRevisionId(); }
193
194 return withTransaction(this.db, () =>
195 {
196 const activeId = this.getActiveRevisionId();
197 this.db.prepare("UPDATE world_revisions SET status = 'superseded' WHERE revision_id = ?").run(activeId);
198 this.db.prepare("UPDATE world_revisions SET status = 'active' WHERE revision_id = ?").run(pendingId);
199 this.db.prepare("UPDATE world_meta SET value = ? WHERE key = 'active_revision'").run(pendingId);
200 this.db.exec("UPDATE world_meta SET value = NULL WHERE key = 'pending_revision'");
201 return pendingId;
202 });
203 }
204
205 close ()
206 {
207 this.db.close();
208 }
209}