@aria-framework/db-worker 0.13.0 → 0.15.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.
- package/README.md +52 -0
- package/database.js +71 -0
- package/dialect.js +55 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -229,8 +229,60 @@ Postgres sibling does nothing to an already-migrated SQLite database.
|
|
|
229
229
|
This is selection, not a portable DDL layer. An app still writes its own schema per engine —
|
|
230
230
|
the framework guarantees only which files ran and the transaction around each.
|
|
231
231
|
|
|
232
|
+
### A baseline that covers earlier migrations (0.14.0)
|
|
233
|
+
|
|
234
|
+
A baseline written for a second engine already CONTAINS everything the earlier migrations did.
|
|
235
|
+
It says so:
|
|
236
|
+
|
|
237
|
+
```sql
|
|
238
|
+
-- aria:covers-through 035
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
The runner then LEDGERS every file numbered at or below 035 instead of executing it. Without
|
|
242
|
+
that, a fresh Postgres database runs `001_baseline.postgres.sql`, builds the whole schema, and
|
|
243
|
+
then hits `002_customer_team.sql` — SQLite DDL — and fails having already changed the database.
|
|
244
|
+
|
|
245
|
+
A NUMBER, not a list: a list would have to be maintained in step with the directory, and the
|
|
246
|
+
one thing worse than no marker is one that names files which have moved.
|
|
247
|
+
|
|
248
|
+
The marker is parsed BEFORE the file is applied, so a malformed one fails with the migration
|
|
249
|
+
untouched. Like `aria:no-transaction` it is read from the HEADER only — a comment further down,
|
|
250
|
+
or inside a multi-line string literal, is not a declaration about the file — and a near miss
|
|
251
|
+
(`aria: covers-through`, `aria:covers_through`) is refused rather than ignored.
|
|
252
|
+
|
|
253
|
+
### Date helpers on the dialect (0.15.0)
|
|
254
|
+
|
|
255
|
+
An app should say WHAT it wants from a date, not how one engine spells it.
|
|
256
|
+
|
|
257
|
+
| | sqlite | postgres |
|
|
258
|
+
|---|---|---|
|
|
259
|
+
| now() | datetime(now) | to_char(NOW() AT TIME ZONE UTC, …) |
|
|
260
|
+
| nowMinusDays(n) | a retention cut | the same, as an INTERVAL |
|
|
261
|
+
| nowPlusMinutes(n) | an expiry window; the SIGN comes from the number | INTERVAL |
|
|
262
|
+
| startOf(month/year) | start of month | date_trunc on the UTC value |
|
|
263
|
+
| dateGroup(col, month/week) | strftime | to_char |
|
|
264
|
+
| daysBetween(a, b) | julianday difference | EXTRACT(EPOCH …) / 86400 |
|
|
265
|
+
|
|
266
|
+
daysBetween is RAW and unrounded on purpose: callers wrap it in AVG or SUM and multiply to the
|
|
267
|
+
unit they want. A helper that rounded would not compose with either.
|
|
268
|
+
|
|
269
|
+
dateGroup and daysBetween cast to ::timestamp on Postgres — those columns are TEXT on both
|
|
270
|
+
engines by SQLite heritage, and Postgres refuses date arithmetic on text.
|
|
271
|
+
|
|
272
|
+
ONE DIVERGENCE, ACCEPTED RATHER THAN HIDDEN: SQLite %W counts weeks from the first Monday,
|
|
273
|
+
Postgres IW is the ISO week. They can disagree by one at a year boundary. The value is a GROUP BY
|
|
274
|
+
key on a chart axis, and an ISO week is the more defensible thing to show a person.
|
|
275
|
+
|
|
232
276
|
## Changelog
|
|
233
277
|
|
|
278
|
+
- **0.15.0** — nowPlusMinutes, startOf, dateGroup, daysBetween (above).
|
|
279
|
+
|
|
280
|
+
- **0.14.0** — `-- aria:covers-through NNN` (above).
|
|
281
|
+
- **0.13.0** — the Postgres driver had the sibling savepoint defect too. Two nested transactions
|
|
282
|
+
started together on one client destroyed each other, and the failed RELEASE aborted the
|
|
283
|
+
transaction — so the outer COMMIT became a silent ROLLBACK and the caller was told it had
|
|
284
|
+
succeeded having written nothing. Fixed the same way as SQLite: one API per nesting level,
|
|
285
|
+
each owning its children's queue.
|
|
234
286
|
- **0.12.0** — dialect-selected migration files (above).
|
|
235
287
|
|
|
236
288
|
- **0.11.0** — the tenant-context contract above: `runWithTenant()` / `currentTenant()`,
|
package/database.js
CHANGED
|
@@ -261,6 +261,54 @@ function selectForDialect(files, kind) {
|
|
|
261
261
|
return files.filter((f) => !foreign.has(f) && !specific.has(f));
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
+
// A migration may declare that it already CONTAINS everything the earlier ones did:
|
|
265
|
+
//
|
|
266
|
+
// -- aria:covers-through 035
|
|
267
|
+
//
|
|
268
|
+
// Written for a second engine, a baseline is the whole schema as of some point in the chain.
|
|
269
|
+
// The files it supersedes must be LEDGERED rather than executed — running 002_customer_team.sql
|
|
270
|
+
// (SQLite DDL) against Postgres fails, and fails having already built the schema, so the next
|
|
271
|
+
// boot re-runs a baseline over live tables.
|
|
272
|
+
//
|
|
273
|
+
// Deliberately a number rather than a list: a list would have to be maintained in step with the
|
|
274
|
+
// directory, and the one thing worse than no marker is one that names files that moved.
|
|
275
|
+
const COVERS_MARKER = /^[ \t]*--[ \t]*aria:covers-through[ \t]+(\d+)[ \t]*$/;
|
|
276
|
+
// A near miss must FAIL rather than be ignored, for the same reason the no-transaction marker
|
|
277
|
+
// has one: an author looking at a file that visibly carries the marker, while the runner did
|
|
278
|
+
// not act on it, is the worst outcome available.
|
|
279
|
+
const COVERS_NEARMISS = /^[ \t]*--[ \t]*aria:[ \t]*covers[-_ ]?through\b/i;
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* The migration number this file declares it covers, or null.
|
|
283
|
+
*
|
|
284
|
+
* Header only, like the no-transaction marker — a marker inside a string literal or a seeded
|
|
285
|
+
* row is not a declaration about the file.
|
|
286
|
+
*/
|
|
287
|
+
function coversThrough(sql, file) {
|
|
288
|
+
for (const raw of String(sql).split(/\r?\n/)) {
|
|
289
|
+
const line = raw.replace(/\uFEFF/g, '');
|
|
290
|
+
if (/^[ \t]*$/.test(line)) continue;
|
|
291
|
+
if (!/^[ \t]*--/.test(line)) return null; // first real SQL ends the header
|
|
292
|
+
const m = COVERS_MARKER.exec(line);
|
|
293
|
+
if (m) return Number(m[1]);
|
|
294
|
+
if (COVERS_NEARMISS.test(line)) {
|
|
295
|
+
throw new Error(
|
|
296
|
+
`Migration ${file || ''} has a line that looks like the covers-through marker but is not ` +
|
|
297
|
+
`exactly it: ${line.trim()}. The form is: -- aria:covers-through 035`
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The files a covers-through declaration supersedes: numbered at or below it, and not itself. */
|
|
305
|
+
function coveredBy(file, through, files) {
|
|
306
|
+
return files.filter((f) => {
|
|
307
|
+
if (f === file) return false;
|
|
308
|
+
const n = /^(\d+)/.exec(f);
|
|
309
|
+
return n && Number(n[1]) <= through;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
264
312
|
/**
|
|
265
313
|
* Apply pending numbered migrations, in filename order, each in its own transaction — unless
|
|
266
314
|
* the file opts out with `-- aria:no-transaction` (see the marker notes above).
|
|
@@ -305,6 +353,9 @@ function runMigrations(migrationsDir) {
|
|
|
305
353
|
for (const file of files) {
|
|
306
354
|
if (applied.has(file)) continue;
|
|
307
355
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
356
|
+
// Parsed BEFORE anything is applied: a malformed marker must fail with the file
|
|
357
|
+
// untouched, not after it has already changed the schema.
|
|
358
|
+
const through = coversThrough(sql, file);
|
|
308
359
|
if (wantsNoTransaction(sql, file)) {
|
|
309
360
|
// Announced, not silent: an operator reading boot output should see which file gave up
|
|
310
361
|
// atomicity, because that is the file to inspect if the boot dies mid-migration.
|
|
@@ -324,6 +375,15 @@ function runMigrations(migrationsDir) {
|
|
|
324
375
|
}
|
|
325
376
|
count++;
|
|
326
377
|
_logger.info(`Migration applied: ${file}`);
|
|
378
|
+
|
|
379
|
+
if (through !== null) {
|
|
380
|
+
for (const covered of coveredBy(file, through, files)) {
|
|
381
|
+
if (applied.has(covered)) continue;
|
|
382
|
+
db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(covered);
|
|
383
|
+
applied.add(covered);
|
|
384
|
+
}
|
|
385
|
+
_logger.info(`Migration ${file} covers everything through ${through} — ledgered, not run`);
|
|
386
|
+
}
|
|
327
387
|
}
|
|
328
388
|
_logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
|
|
329
389
|
return Promise.resolve({ applied: count });
|
|
@@ -336,6 +396,9 @@ function runMigrations(migrationsDir) {
|
|
|
336
396
|
for (const file of files) {
|
|
337
397
|
if (applied.has(file)) continue;
|
|
338
398
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
399
|
+
// Parsed BEFORE anything is applied: a malformed marker must fail with the file
|
|
400
|
+
// untouched, not after it has already changed the schema.
|
|
401
|
+
const through = coversThrough(sql, file);
|
|
339
402
|
if (wantsNoTransaction(sql, file)) {
|
|
340
403
|
_logger.warn(noTxWarning(file));
|
|
341
404
|
try {
|
|
@@ -368,6 +431,14 @@ function runMigrations(migrationsDir) {
|
|
|
368
431
|
await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
|
|
369
432
|
});
|
|
370
433
|
}
|
|
434
|
+
if (through !== null) {
|
|
435
|
+
for (const covered of coveredBy(file, through, files)) {
|
|
436
|
+
if (applied.has(covered)) continue;
|
|
437
|
+
await d.run('INSERT INTO migrations (filename) VALUES (?)', [covered]);
|
|
438
|
+
applied.add(covered);
|
|
439
|
+
}
|
|
440
|
+
_logger.info(`Migration ${file} covers everything through ${through} — ledgered, not run`);
|
|
441
|
+
}
|
|
371
442
|
count++;
|
|
372
443
|
_logger.info(`Migration applied: ${file}`);
|
|
373
444
|
}
|
package/dialect.js
CHANGED
|
@@ -32,8 +32,41 @@ const sqlite = {
|
|
|
32
32
|
now: () => "datetime('now')",
|
|
33
33
|
/** N whole days before now — used by retention cuts. */
|
|
34
34
|
nowMinusDays: (n) => `datetime('now', '-${Number(n)} days')`,
|
|
35
|
+
/**
|
|
36
|
+
* N minutes AFTER now — an expiry window.
|
|
37
|
+
*
|
|
38
|
+
* Rendered rather than bound. A caller passing the modifier as a parameter
|
|
39
|
+
* (`datetime('now', ?)` with '+15 minutes') is putting SQLite's own grammar into its data,
|
|
40
|
+
* which is unreadable to any other engine. The number stays the caller's; only the spelling
|
|
41
|
+
* belongs here.
|
|
42
|
+
*/
|
|
43
|
+
// The sign comes from the NUMBER, not from a literal '+'. datetime('now', '+-15 minutes') is
|
|
44
|
+
// not valid SQLite, and a negative offset is how an expiry test reaches a moment already past.
|
|
45
|
+
nowPlusMinutes: (n) => `datetime('now', '${Number(n) >= 0 ? '+' : ''}${Number(n)} minutes')`,
|
|
46
|
+
/** The first instant of the current month or year. */
|
|
47
|
+
startOf: (unit) => {
|
|
48
|
+
if (unit !== 'month' && unit !== 'year') throw new Error(`startOf: expected 'month' or 'year', got ${JSON.stringify(unit)}`);
|
|
49
|
+
return `datetime('now', 'start of ${unit}')`;
|
|
50
|
+
},
|
|
35
51
|
/** Native timestamp type. SQLite has none, so this is the same text value. */
|
|
36
52
|
nowTz: () => "datetime('now')",
|
|
53
|
+
/**
|
|
54
|
+
* The period a timestamp column falls in: 'month' gives 2026-09, 'week' gives 2026-W36.
|
|
55
|
+
* Used as a GROUP BY key on a report axis, so it only has to be stable and sortable.
|
|
56
|
+
*/
|
|
57
|
+
dateGroup: (col, unit) => {
|
|
58
|
+
if (unit === 'month') return `strftime('%Y-%m', ${col})`;
|
|
59
|
+
if (unit === 'week') return `strftime('%Y-W%W', ${col})`;
|
|
60
|
+
throw new Error(`dateGroup: expected 'month' or 'week', got ${JSON.stringify(unit)}`);
|
|
61
|
+
},
|
|
62
|
+
/**
|
|
63
|
+
* The FRACTIONAL difference in days between two timestamp expressions.
|
|
64
|
+
*
|
|
65
|
+
* Raw and unrounded on purpose: every caller wraps it in AVG or SUM and multiplies to the
|
|
66
|
+
* unit it wants (x24 for hours, x1440 for minutes). A helper that rounded would not compose.
|
|
67
|
+
* Either side may be the literal 'now', which both engines understand.
|
|
68
|
+
*/
|
|
69
|
+
daysBetween: (from, to) => `(julianday(${to}) - julianday(${from}))`,
|
|
37
70
|
/** Read a JSON path out of a column: jsonPath('detail', '$.model'). */
|
|
38
71
|
jsonPath: (col, path) => `json_extract(${col}, '${String(path).replace(/'/g, "''")}')`,
|
|
39
72
|
/** Case-insensitive LIKE. SQLite's LIKE is already case-insensitive for ASCII. */
|
|
@@ -60,6 +93,28 @@ const postgres = {
|
|
|
60
93
|
// for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
|
|
61
94
|
now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
|
|
62
95
|
nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
96
|
+
nowPlusMinutes: (n) => `to_char((NOW() + INTERVAL '${Number(n)} minutes') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
|
|
97
|
+
// date_trunc on the UTC value, not on NOW(): truncating a timestamptz uses the SESSION time
|
|
98
|
+
// zone, so 'start of month' would land on a different instant depending on where the server
|
|
99
|
+
// thinks it is. Every other timestamp here is UTC text; this has to agree with them.
|
|
100
|
+
startOf: (unit) => {
|
|
101
|
+
if (unit !== 'month' && unit !== 'year') throw new Error(`startOf: expected 'month' or 'year', got ${JSON.stringify(unit)}`);
|
|
102
|
+
return `to_char(date_trunc('${unit}', NOW() AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS')`;
|
|
103
|
+
},
|
|
104
|
+
// ::timestamp on both, because these columns are TEXT on both engines by SQLite heritage and
|
|
105
|
+
// Postgres refuses date arithmetic on text ("operator does not exist: text - text").
|
|
106
|
+
//
|
|
107
|
+
// A NOTE ON WEEKS. SQLite's %W counts weeks from the first Monday, 00-53; Postgres IW is the
|
|
108
|
+
// ISO week, 01-53, paired with the ISO year IYYY. They can disagree by one at a year boundary.
|
|
109
|
+
// That is accepted rather than papered over: the value is a GROUP BY key on a chart axis, and
|
|
110
|
+
// an ISO week is the more defensible of the two to show a person.
|
|
111
|
+
dateGroup: (col, unit) => {
|
|
112
|
+
if (unit === 'month') return `to_char(${col}::timestamp, 'YYYY-MM')`;
|
|
113
|
+
if (unit === 'week') return `to_char(${col}::timestamp, 'IYYY-"W"IW')`;
|
|
114
|
+
throw new Error(`dateGroup: expected 'month' or 'week', got ${JSON.stringify(unit)}`);
|
|
115
|
+
},
|
|
116
|
+
daysBetween: (from, to) =>
|
|
117
|
+
`(EXTRACT(EPOCH FROM (${to}::timestamp - ${from}::timestamp)) / 86400)`,
|
|
63
118
|
/** Native timestamptz, for an app that declares real timestamp columns. */
|
|
64
119
|
nowTz: () => 'NOW()',
|
|
65
120
|
// The ::jsonb cast is load-bearing: `->>` is not defined on TEXT, and the framework's JSON
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/db-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"pg": "^8.23.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
|
-
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/smoke.js && node test/tier2.js"
|
|
41
|
+
"test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenantRls.pg.js && node test/smoke.js && node test/tier2.js"
|
|
42
42
|
}
|
|
43
43
|
}
|