@mailwoman/sqlite 11.0.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +2 -2
  2. package/lib/batched.ts +5 -6
  3. package/lib/client.ts +4 -7
  4. package/lib/database-schema.ts +3 -4
  5. package/lib/dialect/config.ts +3 -6
  6. package/lib/dialect.ts +2 -5
  7. package/lib/driver.ts +2 -5
  8. package/lib/index.ts +12 -9
  9. package/lib/introspection.ts +3 -3
  10. package/lib/lookup.ts +6 -6
  11. package/lib/schema-columns.ts +2 -5
  12. package/lib/sealed/build.ts +13 -9
  13. package/lib/sealed/db.ts +99 -18
  14. package/lib/sealed/digest.ts +211 -0
  15. package/lib/sealed.ts +11 -9
  16. package/out/batched.d.ts +2 -6
  17. package/out/batched.d.ts.map +1 -1
  18. package/out/batched.js +2 -8
  19. package/out/batched.js.map +1 -1
  20. package/out/client.d.ts +2 -7
  21. package/out/client.d.ts.map +1 -1
  22. package/out/client.js +3 -6
  23. package/out/client.js.map +1 -1
  24. package/out/database-schema.d.ts +0 -4
  25. package/out/database-schema.d.ts.map +1 -1
  26. package/out/database-schema.js +2 -7
  27. package/out/database-schema.js.map +1 -1
  28. package/out/dialect/config.d.ts +1 -6
  29. package/out/dialect/config.d.ts.map +1 -1
  30. package/out/dialect/config.js +2 -5
  31. package/out/dialect/config.js.map +1 -1
  32. package/out/dialect.d.ts +0 -5
  33. package/out/dialect.d.ts.map +1 -1
  34. package/out/dialect.js +2 -5
  35. package/out/dialect.js.map +1 -1
  36. package/out/driver.d.ts +0 -5
  37. package/out/driver.d.ts.map +1 -1
  38. package/out/driver.js +2 -5
  39. package/out/driver.js.map +1 -1
  40. package/out/index.d.ts +9 -9
  41. package/out/index.d.ts.map +1 -1
  42. package/out/index.js +11 -9
  43. package/out/index.js.map +1 -1
  44. package/out/introspection.d.ts +0 -3
  45. package/out/introspection.d.ts.map +1 -1
  46. package/out/introspection.js +2 -11
  47. package/out/introspection.js.map +1 -1
  48. package/out/lookup.d.ts +3 -6
  49. package/out/lookup.d.ts.map +1 -1
  50. package/out/lookup.js +2 -9
  51. package/out/lookup.js.map +1 -1
  52. package/out/schema-columns.d.ts +0 -5
  53. package/out/schema-columns.d.ts.map +1 -1
  54. package/out/schema-columns.js +2 -5
  55. package/out/schema-columns.js.map +1 -1
  56. package/out/sealed/build.d.ts +2 -7
  57. package/out/sealed/build.d.ts.map +1 -1
  58. package/out/sealed/build.js +10 -7
  59. package/out/sealed/build.js.map +1 -1
  60. package/out/sealed/db.d.ts +45 -15
  61. package/out/sealed/db.d.ts.map +1 -1
  62. package/out/sealed/db.js +50 -22
  63. package/out/sealed/db.js.map +1 -1
  64. package/out/sealed/digest.d.ts +53 -0
  65. package/out/sealed/digest.d.ts.map +1 -0
  66. package/out/sealed/digest.js +122 -0
  67. package/out/sealed/digest.js.map +1 -0
  68. package/out/sealed.d.ts +8 -9
  69. package/out/sealed.d.ts.map +1 -1
  70. package/out/sealed.js +2 -13
  71. package/out/sealed.js.map +1 -1
  72. package/out/tsconfig.test.tsbuildinfo +1 -1
  73. package/package.json +3 -3
package/README.md CHANGED
@@ -29,7 +29,7 @@ console.log(place?.name) // "Paris"
29
29
 
30
30
  `DatabaseClient` extends Kysely and owns one SQLite connection. Pass a file path
31
31
  to its constructor for a persistent database. `DatabaseClient.temp()` creates an
32
- in-memory database. The package requires Node.js `^24.22.1 || >=26.12.1`.
32
+ in-memory database. The package requires Node.js `^24.22.3 || >=26.13.1`.
33
33
 
34
34
  ## Open a built artifact
35
35
 
@@ -44,7 +44,7 @@ const places = await db.selectFrom("places").selectAll().execute()
44
44
 
45
45
  `openBuiltClient` opens read-only by default. Its `{ write: true }` option checks
46
46
  the file's write permissions before opening it and rejects a sealed file with
47
- `SealedArtifactError`. A read-only open does not require that the file has
47
+ `SealedArtifactError`. A read-only open doesn't require that the file has
48
48
  already been sealed.
49
49
 
50
50
  Use `using` even when the factory is asynchronous. The connection's
package/lib/batched.ts CHANGED
@@ -1,10 +1,9 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Batched bulk-write transactions — the `commit`/`begin` cadence every streaming ingest repeats around its
7
- * raw prepared-statement loop.
5
+ * Batched bulk-write transactions — the `commit`/`begin` cadence every streaming
6
+ * ingest repeats around its raw prepared-statement loop.
8
7
  */
9
8
 
10
9
  /**
package/lib/client.ts CHANGED
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import {
8
5
  DatabaseSync,
@@ -21,7 +18,7 @@ import { SqliteDialect } from "#dialect"
21
18
  import type { SqliteDialectConfig } from "#dialect/config"
22
19
 
23
20
  /**
24
- * A connection's non-Kysely surface: the statements Kysely does not model, plus ending the connection.
21
+ * A connection's non-Kysely surface: the statements Kysely doesn't model, plus ending the connection.
25
22
  *
26
23
  * Schema-agnostic because Kysely is invariant in `DB`: a parameter typed
27
24
  * `DatabaseClient` would reject every real client.
@@ -84,7 +81,7 @@ export class DatabaseClient<DB = Database> extends Kysely<DB> implements Disposa
84
81
  }
85
82
 
86
83
  /**
87
- * Run a statement Kysely does not model: `pragma`, `vacuum`, `analyze`, `attach`, FTS5 virtual-table DDL.
84
+ * Run a statement Kysely doesn't model: `pragma`, `vacuum`, `analyze`, `attach`, FTS5 virtual-table DDL.
88
85
  */
89
86
  exec(sql: string): void {
90
87
  this.#database.exec(sql)
@@ -1,8 +1,7 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * Default schema type for {@link DatabaseClient}; consumers supply their own table schema.
7
6
  */
8
7
 
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { DatabaseSync } from "node:sqlite"
8
5
 
@@ -24,7 +21,7 @@ export interface SqliteDialectConfig {
24
21
  /**
25
22
  * Called once when the first query is executed.
26
23
  *
27
- * This is a Kysely specific feature and does not come from the `node:sqlite` module.
24
+ * This is a Kysely specific feature and doesn't come from the `node:sqlite` module.
28
25
  */
29
26
  onCreateConnection?: (connection: DatabaseConnection) => Promise<void>
30
27
  }
package/lib/dialect.ts CHANGED
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import {
8
5
  SqliteAdapter,
package/lib/driver.ts CHANGED
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { DatabaseSync, StatementSync } from "node:sqlite"
8
5
 
package/lib/index.ts CHANGED
@@ -1,16 +1,19 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * The one way a Mailwoman SQLite connection comes into being.
7
6
  *
8
- * `DatabaseClient` opens the file; `openBuiltClient` opens a built artifact with the seal check. A caller specifies which
9
- * file and schema. It never constructs the connection, so one database has one schema, one owner and a
10
- * lifetime `using` can end. `new DatabaseSync` appears once in this package and nowhere else in the repository.
7
+ * `DatabaseClient` opens the file; `openBuiltClient` opens a built artifact with the seal check.
8
+ * A caller specifies which file and schema.
9
+ *
10
+ * It never constructs the connection, so one database has one schema, one owner
11
+ * and a lifetime `using` can end.
12
+ * `new DatabaseSync` appears once in this package and nowhere else in the repository.
11
13
  *
12
- * It lives outside `@mailwoman/core` because it needs none of core's 11 MB of parser reference data. Its whole
13
- * dependency set is `kysely`. That is what lets the leaf lookups use it.
14
+ * It lives outside `@mailwoman/core` because it needs none of core's 11 MB of parser reference data.
15
+ * Its whole dependency set is `kysely`.
16
+ * That's what lets the leaf lookups use it.
14
17
  */
15
18
 
16
19
  export * from "#batched"
@@ -1,7 +1,7 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
5
  * @file Questions asked of `sqlite_master`.
6
6
  *
7
7
  * its own subpath on purpose — do not fold this into the package barrel. `@mailwoman/sqlite`'s root export
package/lib/lookup.ts CHANGED
@@ -1,11 +1,11 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * The shared shape of a reader over one SQLite artifact.
7
- * A lookup either opens the file it is given or adopts a connection already held by the caller.
8
- * and it closes on disposal only what it opened.
6
+ *
7
+ * A lookup either opens the file it is given or adopts a connection already held
8
+ * by the caller. and it closes on disposal only what it opened.
9
9
  */
10
10
 
11
11
  import type { PathBuilderLike } from "path-ts"
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { CreateTableBuilder, Kysely } from "kysely"
8
5
 
@@ -1,14 +1,11 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
- import { removePathIfPresent } from "@mailwoman/core/fs/writers"
8
- import type { PathBuilderLike } from "path-ts"
4
+ import { makeDirectories, removePathIfPresent } from "@mailwoman/core/fs/writers"
5
+ import { dirname, type PathBuilderLike } from "path-ts"
9
6
 
10
7
  import { DatabaseClient } from "#client"
11
- import { sealDatabase, swapDatabaseIntoPlace } from "#sealed/db"
8
+ import { recoverInterruptedBuilds, sealDatabase, swapDatabaseIntoPlace } from "#sealed/db"
12
9
 
13
10
  export interface BuildSealedArtifactOptions<DB, Streamed, Result> {
14
11
  /**
@@ -27,7 +24,7 @@ export interface BuildSealedArtifactOptions<DB, Streamed, Result> {
27
24
  ingest: (database: DatabaseClient<DB>) => Promise<Streamed | null>
28
25
  /**
29
26
  * The bounded child-process ingest, run while the parent holds no handle: each child opens the
30
- * temp file and appends one chunk at a time, so there is exactly one writer at every instant.
27
+ * temp file and appends one chunk at a time, so there's exactly one writer at every instant.
31
28
  */
32
29
  batched?: (tmpPath: string) => Promise<Streamed>
33
30
  /**
@@ -47,6 +44,13 @@ export async function buildSealedArtifact<DB, Streamed, Result>(
47
44
  ): Promise<Result> {
48
45
  const tmpPath = `${options.out}.tmp-${process.pid}`
49
46
 
47
+ // SQLite creates the temp file but not its directory, and a new artifact's directory may not exist yet.
48
+ await makeDirectories(dirname(options.out.toString()))
49
+
50
+ // A killed earlier build's temp file is removed before this one writes its own, and a version
51
+ // it set aside moves back into an empty slot so readers keep a database while this build runs.
52
+ await recoverInterruptedBuilds(options.out)
53
+
50
54
  let streamed: Streamed | null
51
55
 
52
56
  {
package/lib/sealed/db.ts CHANGED
@@ -1,27 +1,32 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * The sealed-artifact invariant: every SQLite DB a build produces is a read-only asset. `sealDatabase`
7
- * is the last step of every builder — checkpoint, freeze the journal, chmod 0444. `openBuiltClient`
8
- * (`@mailwoman/sqlite/sealed`) is how anything opens a data artifact. a write-mode open of a sealed
9
- * file throws a descriptive error pointing at the rebuild command instead of a cryptic SQLITE_READONLY.
10
- * A caller can restore write permission only with manual `chmod u+w`; the program never changes permissions.
5
+ * The sealed-artifact invariant: every SQLite DB a build produces is a read-only asset.
6
+ *
7
+ * `sealDatabase` is the last step of every builder — checkpoint, freeze the journal, chmod 0444.
8
+ * `openBuiltClient` (`@mailwoman/sqlite/sealed`) is how anything opens a data
9
+ * artifact. a write-mode open of a sealed file throws a descriptive error pointing
10
+ * at the rebuild command instead of a cryptic SQLITE_READONLY.
11
+ *
12
+ * A caller can restore write permission only with manual `chmod u+w`;
13
+ * the program never changes permissions.
11
14
  * Rebuild the artifact to make changes.
12
15
  *
13
- * `swapDatabaseIntoPlace` is the atomic publish step agents.md
14
- * specifies in prose ("build it successfully. Move the previous version to a temp directory.
15
- * Move the new version into place."). It lives here because this module already owns the
16
- * built-artifact lifecycle. A rule stated in project prose and implemented by several builders belongs in a
17
- * shared function.
16
+ * `swapDatabaseIntoPlace` is the atomic publish step agents.md specifies in prose
17
+ * ("build it successfully. Move the previous version to a temp directory. Move the new version into place.").
18
+ * It lives here because this module already owns the built-artifact lifecycle.
19
+ *
20
+ * A rule stated in project prose and implemented by several builders belongs in a shared function.
18
21
  */
19
22
 
20
23
  import type { DatabaseSync } from "node:sqlite"
21
24
 
25
+ import { processExists } from "@mailwoman/core/fs/lock"
26
+ import { sortedGlob } from "@mailwoman/core/fs/readers"
22
27
  import { pathExists, statPath } from "@mailwoman/core/fs/readers/stat"
23
28
  import { changeMode, movePath, removePath, removePathIfPresent } from "@mailwoman/core/fs/writers"
24
- import { basename, type PathBuilderLike } from "path-ts"
29
+ import { basename, dirname, type PathBuilderLike } from "path-ts"
25
30
 
26
31
  /**
27
32
  * The one capability {@link assertDatabaseIntegrity} needs.
@@ -104,7 +109,7 @@ export async function sealDatabase(path: PathBuilderLike): Promise<void> {
104
109
  }
105
110
 
106
111
  /**
107
- * Verify a freshly-built database is not corrupt, immediately before it is sealed and published.
112
+ * Verify a freshly-built database isn't corrupt, immediately before it is sealed and published.
108
113
  *
109
114
  * Belongs beside {@link sealDatabase} for the same reason `swapDatabaseIntoPlace` does.
110
115
  * The check is part of the built-artifact lifecycle.
@@ -174,8 +179,7 @@ export async function swapDatabaseIntoPlace(tmpPath: PathBuilderLike, finalPath:
174
179
  await movePath(tmpPathString, finalPathString)
175
180
  } catch (error) {
176
181
  // The prior version is already aside at this point.
177
- // A failed forward rename must not leave the slot empty while a restorable
178
- // artifact sits one rename away.
182
+ // A failed forward rename mustn't leave the slot empty while a restorable artifact sits one rename away.
179
183
  if ((await pathExists(aside)) && !(await pathExists(finalPathString))) {
180
184
  await movePath(aside, finalPathString)
181
185
  }
@@ -188,4 +192,81 @@ export async function swapDatabaseIntoPlace(tmpPath: PathBuilderLike, finalPath:
188
192
  }
189
193
 
190
194
  await removePathIfPresent(aside)
195
+ await recoverInterruptedBuilds(finalPath)
196
+ }
197
+
198
+ /**
199
+ * The suffixes a writer gives the two siblings of a published path, each followed by `-<pid>`.
200
+ */
201
+ export interface BuildSiblingSuffixes {
202
+ /**
203
+ * The sibling a writer fills before the swap, such as `tmp` or `staging`.
204
+ */
205
+ building: string
206
+ /**
207
+ * The sibling the swap moves the published version to, such as `old` or `replaced`.
208
+ */
209
+ setAside: string
210
+ }
211
+
212
+ const SEALED_BUILD_SUFFIXES: BuildSiblingSuffixes = { building: "tmp", setAside: "old" }
213
+
214
+ /**
215
+ * Restores or removes what an interrupted write of `finalPath` left beside it.
216
+ *
217
+ * A sealed build writes `<final>.tmp-<pid>` and, during its swap, moves the
218
+ * published file to `<final>.old-<pid>`.
219
+ * A process killed in between leaves those files on disk under a pid no later build shares.
220
+ *
221
+ * Another writer that follows the same pattern under other names passes its `suffixes`.
222
+ * A sibling may be a file or a directory, and a file's `-wal` and `-shm` sidecars count with it.
223
+ *
224
+ * When the published slot is empty, the newest set-aside sibling of an exited process
225
+ * is the last published version, and it moves back into the slot.
226
+ * Every other sibling of an exited process is removed.
227
+ *
228
+ * A sibling whose process still runs belongs to a write in progress and stays.
229
+ */
230
+ export async function recoverInterruptedBuilds(
231
+ finalPath: PathBuilderLike,
232
+ suffixes: BuildSiblingSuffixes = SEALED_BUILD_SUFFIXES
233
+ ): Promise<void> {
234
+ const finalPathString = finalPath.toString()
235
+ const directory = dirname(finalPathString).toString()
236
+
237
+ if (!(await pathExists(directory))) return
238
+
239
+ const name = basename(finalPathString).toString()
240
+
241
+ const siblingPattern = new RegExp(
242
+ `\\.(${RegExp.escape(suffixes.building)}|${RegExp.escape(suffixes.setAside)})-(\\d+)(-wal|-shm)?$`,
243
+ "u"
244
+ )
245
+
246
+ const siblings = [
247
+ ...(await sortedGlob(directory, `${name}.${suffixes.building}-*`, { onlyFiles: false })),
248
+ ...(await sortedGlob(directory, `${name}.${suffixes.setAside}-*`, { onlyFiles: false })),
249
+ ].flatMap((path) => {
250
+ const match = siblingPattern.exec(path)
251
+
252
+ return match && !processExists(Number(match[2])) ? [{ path, kind: match[1], sidecar: match[3] ?? null }] : []
253
+ })
254
+
255
+ if (!(await pathExists(finalPathString))) {
256
+ const stranded = siblings.filter((sibling) => sibling.kind === suffixes.setAside && !sibling.sidecar)
257
+
258
+ const newest = (
259
+ await Promise.all(
260
+ stranded.map(async (sibling) => ({ ...sibling, mtimeMs: (await statPath(sibling.path)).mtimeMs }))
261
+ )
262
+ ).toSorted((a, b) => b.mtimeMs - a.mtimeMs)[0]
263
+
264
+ if (newest) {
265
+ await movePath(newest.path, finalPathString)
266
+ }
267
+ }
268
+
269
+ for (const sibling of siblings) {
270
+ await removePathIfPresent(sibling.path)
271
+ }
191
272
  }
@@ -0,0 +1,211 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file A digest of a database's table contents, equal for two databases that hold the same rows.
6
+ *
7
+ * A file's md5 differs between two builds of the same rows, because page layout, free pages and a
8
+ * build timestamp all reach the bytes. This digest reads rows in key order instead, so a cached
9
+ * build and a build from scratch compare equal exactly when every table holds the same rows.
10
+ *
11
+ * `@mailwoman/core` depends on this package, so hashing comes from `node:crypto` here, the module
12
+ * core's hash helpers wrap.
13
+ */
14
+
15
+ import { createHash, type Hash } from "node:crypto"
16
+
17
+ import type { DatabaseClient } from "#client"
18
+ import { listTables } from "#introspection"
19
+
20
+ /**
21
+ * The columns a build writes from its own clock or checkout, left out of every digest by default.
22
+ */
23
+ export const BUILD_STAMP_COLUMNS: Readonly<Record<string, readonly string[]>> = {
24
+ layer_manifest: ["created_at", "build_sha"],
25
+ }
26
+
27
+ /**
28
+ * What a content digest leaves out, and how it splits a table by country.
29
+ */
30
+ export interface ContentDigestSpec {
31
+ /**
32
+ * Tables left out by name, beside the `sqlite_*` tables and every virtual table's shadow tables.
33
+ */
34
+ excludeTables?: readonly string[]
35
+ /**
36
+ * Columns left out per table.
37
+ * Defaults to {@linkcode BUILD_STAMP_COLUMNS}.
38
+ */
39
+ excludeColumns?: Readonly<Record<string, readonly string[]>>
40
+ /**
41
+ * A column whose value also splits each table that has it into one digest per value,
42
+ * so a change can be traced to the countries it touched.
43
+ */
44
+ countryColumn?: string
45
+ }
46
+
47
+ /**
48
+ * One table's digest.
49
+ */
50
+ export interface TableContentDigest {
51
+ rows: number
52
+ digest: string
53
+ /**
54
+ * One digest per value of the spec's country column, when the table has that column.
55
+ */
56
+ byCountry?: Record<string, string>
57
+ }
58
+
59
+ /**
60
+ * A database's content digest: one digest per table and a root digest over them all.
61
+ */
62
+ export interface DatabaseContentDigest {
63
+ root: string
64
+ tables: Record<string, TableContentDigest>
65
+ }
66
+
67
+ interface ColumnInfo {
68
+ name: string
69
+ pk: number
70
+ }
71
+
72
+ /**
73
+ * Separates the fields of one row in the hash input.
74
+ */
75
+ const FIELD_SEPARATOR = "\u0000"
76
+
77
+ /**
78
+ * Ends one row in the hash input.
79
+ */
80
+ const ROW_SEPARATOR = "\u0001"
81
+
82
+ /**
83
+ * The digest of every table's rows, read in primary-key order, or in the order of all columns
84
+ * for a table without a primary key, so insertion order and page layout leave it unchanged.
85
+ *
86
+ * A virtual table is read through its own rows, in rowid order, and its shadow
87
+ * tables (`<name>_data`, `<name>_node` and the rest) are left out, because they
88
+ * store an index layout that depends on insertion order.
89
+ * Each value is tagged with its storage type, so the integer `1` and the real `1.0` digest differently.
90
+ */
91
+ export function databaseContentDigest<DB>(db: DatabaseClient<DB>, spec: ContentDigestSpec = {}): DatabaseContentDigest {
92
+ const excludeColumns = spec.excludeColumns ?? BUILD_STAMP_COLUMNS
93
+ const excludeTables = new Set(spec.excludeTables)
94
+
95
+ const virtualTables = (
96
+ db
97
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'")
98
+ .all() as Array<{
99
+ name: string
100
+ }>
101
+ ).map((row) => row.name)
102
+
103
+ const isShadow = (table: string) => virtualTables.some((name) => table.startsWith(`${name}_`))
104
+ const tables: Record<string, TableContentDigest> = {}
105
+
106
+ for (const table of listTables(db)) {
107
+ if (table.startsWith("sqlite_") || excludeTables.has(table) || isShadow(table)) continue
108
+
109
+ tables[table] = digestTable(db, table, {
110
+ virtual: virtualTables.includes(table),
111
+ excluded: new Set(excludeColumns[table]),
112
+ countryColumn: spec.countryColumn,
113
+ })
114
+ }
115
+
116
+ const root = createHash("sha256")
117
+
118
+ for (const [table, { digest }] of Object.entries(tables)) {
119
+ root.update(`${table}${FIELD_SEPARATOR}${digest}${ROW_SEPARATOR}`)
120
+ }
121
+
122
+ return { root: root.digest("hex"), tables }
123
+ }
124
+
125
+ /**
126
+ * The digest of one table, with its per-country split.
127
+ */
128
+ function digestTable<DB>(
129
+ db: DatabaseClient<DB>,
130
+ table: string,
131
+ options: { virtual: boolean; excluded: ReadonlySet<string>; countryColumn: string | undefined }
132
+ ): TableContentDigest {
133
+ const columnInfo: ColumnInfo[] = db
134
+ .prepare(`PRAGMA table_info("${table}")`)
135
+ .all()
136
+ .map((row) => ({ name: String(row["name"]), pk: Number(row["pk"]) }))
137
+
138
+ const columns = columnInfo.map((column) => column.name).filter((name) => !options.excluded.has(name))
139
+
140
+ const keyColumns = columnInfo
141
+ .filter((column) => column.pk > 0)
142
+ .toSorted((a, b) => a.pk - b.pk)
143
+ .map((column) => column.name)
144
+
145
+ const quoted = (name: string) => `"${name.replaceAll('"', '""')}"`
146
+
147
+ const selected = (options.virtual ? ["rowid", ...columns] : columns).flatMap((name) => [
148
+ `typeof(${quoted(name)})`,
149
+ quoted(name),
150
+ ])
151
+
152
+ const order = options.virtual ? ["rowid"] : keyColumns.length ? keyColumns : columns
153
+ const countryIndex = options.countryColumn ? columns.indexOf(options.countryColumn) : -1
154
+ const offset = options.virtual ? 1 : 0
155
+
156
+ const statement = db.prepare(
157
+ `SELECT ${selected.join(", ")} FROM ${quoted(table)} ORDER BY ${order.map(quoted).join(", ")}`
158
+ )
159
+
160
+ // A 64-bit id past 2^53 loses precision as a JavaScript number.
161
+ statement.setReadBigInts(true)
162
+ statement.setReturnArrays(true)
163
+
164
+ const hash = createHash("sha256")
165
+ const byCountry = new Map<string, Hash>()
166
+ let rows = 0
167
+
168
+ for (const row of statement.iterate() as Iterable<unknown[]>) {
169
+ const encoded = encodeRow(row)
170
+
171
+ hash.update(encoded)
172
+
173
+ rows++
174
+
175
+ if (countryIndex >= 0) {
176
+ const country = String(row[2 * (countryIndex + offset) + 1] ?? "")
177
+ const countryHash = byCountry.get(country) ?? createHash("sha256")
178
+
179
+ countryHash.update(encoded)
180
+ byCountry.set(country, countryHash)
181
+ }
182
+ }
183
+
184
+ return {
185
+ rows,
186
+ digest: hash.digest("hex"),
187
+ ...(countryIndex >= 0
188
+ ? {
189
+ byCountry: Object.fromEntries(
190
+ [...byCountry].toSorted(([a], [b]) => a.localeCompare(b)).map(([country, h]) => [country, h.digest("hex")])
191
+ ),
192
+ }
193
+ : {}),
194
+ }
195
+ }
196
+
197
+ /**
198
+ * One row as hash input: each value after its SQLite storage type, with blobs in hex.
199
+ */
200
+ function encodeRow(row: readonly unknown[]): string {
201
+ const fields: string[] = []
202
+
203
+ for (let index = 0; index < row.length; index += 2) {
204
+ const type = String(row[index])
205
+ const value = row[index + 1]
206
+
207
+ fields.push(`${type}:${value instanceof Uint8Array ? Buffer.from(value).toString("hex") : String(value)}`)
208
+ }
209
+
210
+ return `${fields.join(FIELD_SEPARATOR)}${ROW_SEPARATOR}`
211
+ }
package/lib/sealed.ts CHANGED
@@ -1,15 +1,17 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * Open a built data artifact.
7
6
  *
8
- * This is the other half of the sealed-artifact invariant in `../utils/sealed-db.ts`: that module owns the
9
- * filesystem side (seal, unseal-refusal, atomic swap) and stays free of a static `node:sqlite` import, because it
10
- * flows through the `@mailwoman/core/utils` barrel into consumers that cannot resolve one. The open lives here, where
11
- * `DatabaseClient` is already imported and the cost is paid. The open is asynchronous: the write branch awaits the
12
- * seal check against the filesystem before the handle is constructed.
7
+ * This is the other half of the sealed-artifact invariant in `../utils/sealed-db.ts`:
8
+ * that module owns the filesystem side (seal, unseal-refusal, atomic swap)
9
+ * and stays free of a static `node:sqlite` import, because it flows through the
10
+ * `@mailwoman/core/utils` barrel into consumers that cannot resolve one.
11
+ * The open lives here, where `DatabaseClient` is already imported and the cost is paid.
12
+ *
13
+ * The open is asynchronous: the write branch awaits the seal check against the
14
+ * filesystem before the handle is constructed.
13
15
  */
14
16
 
15
17
  import type { PathBuilderLike } from "path-ts"
package/out/batched.d.ts CHANGED
@@ -1,10 +1,6 @@
1
1
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Batched bulk-write transactions — the `commit`/`begin` cadence every streaming ingest repeats around its
7
- * raw prepared-statement loop.
2
+ * Batched bulk-write transactions — the `commit`/`begin` cadence every streaming
3
+ * ingest repeats around its raw prepared-statement loop.
8
4
  */
9
5
  /**
10
6
  * One open batched transaction over a connection.
@@ -1 +1 @@
1
- {"version":3,"file":"batched.d.ts","sourceRoot":"","sources":["../lib/batched.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAClC;;;OAGG;IACH,UAAU,IAAI,OAAO,CAAA;IACrB,MAAM,IAAI,IAAI,CAAA;IACd;;;OAGG;IACH,eAAe,IAAI,IAAI,CAAA;CACvB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE;IAAE,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EACrC,OAAO,EAAE;IAAE,aAAa,EAAE,MAAM,CAAA;CAAE,GAChC,kBAAkB,CA6BpB"}
1
+ {"version":3,"file":"batched.d.ts","sourceRoot":"","sources":["../lib/batched.ts"],"names":[],"mappings":"AAGA;;;GAGG;AAEH;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAClC;;;OAGG;IACH,UAAU,IAAI,OAAO,CAAA;IACrB,MAAM,IAAI,IAAI,CAAA;IACd;;;OAGG;IACH,eAAe,IAAI,IAAI,CAAA;CACvB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE;IAAE,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EACrC,OAAO,EAAE;IAAE,aAAa,EAAE,MAAM,CAAA;CAAE,GAChC,kBAAkB,CA6BpB"}
package/out/batched.js CHANGED
@@ -1,11 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Batched bulk-write transactions — the `commit`/`begin` cadence every streaming ingest repeats around its
7
- * raw prepared-statement loop.
8
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
9
3
  /**
10
4
  * Open a transaction that commits and reopens itself every `rowsPerCommit` written rows,
11
5
  * with the batch size left to the caller.
@@ -1 +1 @@
1
- {"version":3,"file":"batched.js","sourceRoot":"","sources":["../lib/batched.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAmBH;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC3B,QAAqC,EACrC,OAAkC;IAElC,IAAI,OAAO,GAAG,CAAC,CAAA;IAEf,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAEtB,OAAO;QACN,UAAU;YACT,OAAO,EAAE,CAAA;YAET,IAAI,OAAO,GAAG,OAAO,CAAC,aAAa;gBAAE,OAAO,KAAK,CAAA;YAEjD,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACvB,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAEtB,OAAO,GAAG,CAAC,CAAA;YAEX,OAAO,IAAI,CAAA;QACZ,CAAC;QACD,MAAM;YACL,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACxB,CAAC;QACD,eAAe;YACd,IAAI,CAAC;gBACJ,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YAC1B,CAAC;YAAC,MAAM,CAAC;gBACR,6CAA6C;YAC9C,CAAC;QACF,CAAC;KACD,CAAA;AACF,CAAC"}
1
+ {"version":3,"file":"batched.js","sourceRoot":"","sources":["../lib/batched.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,kEAAkE;AAwBlE;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC3B,QAAqC,EACrC,OAAkC;IAElC,IAAI,OAAO,GAAG,CAAC,CAAA;IAEf,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAEtB,OAAO;QACN,UAAU;YACT,OAAO,EAAE,CAAA;YAET,IAAI,OAAO,GAAG,OAAO,CAAC,aAAa;gBAAE,OAAO,KAAK,CAAA;YAEjD,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACvB,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAEtB,OAAO,GAAG,CAAC,CAAA;YAEX,OAAO,IAAI,CAAA;QACZ,CAAC;QACD,MAAM;YACL,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACxB,CAAC;QACD,eAAe;YACd,IAAI,CAAC;gBACJ,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YAC1B,CAAC;YAAC,MAAM,CAAC;gBACR,6CAA6C;YAC9C,CAAC;QACF,CAAC;KACD,CAAA;AACF,CAAC"}