@jskit-ai/database-runtime 0.1.261 → 0.1.263

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.
@@ -4,7 +4,8 @@ import {
4
4
  parseDatabaseUrl,
5
5
  resolveDatabaseClientFromEnvironment,
6
6
  resolveDatabaseConnectionFromEnvironment,
7
- resolveKnexConnectionFromEnvironment
7
+ resolveKnexConnectionFromEnvironment,
8
+ resolveKnexPool
8
9
  } from "../src/shared/databaseConnection.js";
9
10
 
10
11
  test("parseDatabaseUrl parses mysql url fields", () => {
@@ -103,3 +104,27 @@ test("resolveKnexConnectionFromEnvironment keeps only MySQL DATE columns as stri
103
104
  assert.equal(postgresConnection.dateStrings, undefined);
104
105
  assert.equal(postgresConnection.timezone, undefined);
105
106
  });
107
+
108
+ test("resolveKnexPool sets each PostgreSQL session to UTC before the pool hands the connection out", async () => {
109
+ assert.equal(resolveKnexPool("mysql2"), undefined);
110
+ const pool = resolveKnexPool("pg");
111
+ const statements = [];
112
+ const connection = {
113
+ query(sql, callback) {
114
+ statements.push(sql);
115
+ callback(null);
116
+ }
117
+ };
118
+ const handedOut = await new Promise((resolve, reject) => {
119
+ pool.afterCreate(connection, (error, created) => (error ? reject(error) : resolve(created)));
120
+ });
121
+ assert.equal(handedOut, connection);
122
+ assert.deepEqual(statements, ["SET TIME ZONE 'UTC'"]);
123
+
124
+ // A connection that cannot set its time zone is not handed out.
125
+ const refusal = new Error("permission denied");
126
+ const failed = await new Promise((resolve) => {
127
+ pool.afterCreate({ query: (_sql, callback) => callback(refusal) }, (error) => resolve(error));
128
+ });
129
+ assert.equal(failed, refusal);
130
+ });
@@ -9,6 +9,22 @@ test("isDuplicateEntryError matches mysql and postgres duplicate signatures", ()
9
9
  assert.equal(isDuplicateEntryError({ code: "ER_PARSE_ERROR", errno: 1064 }), false);
10
10
  });
11
11
 
12
+ test("isDuplicateEntryError matches SQLite's unique and primary key violations, and no other constraint", () => {
13
+ const unique = Object.assign(new Error("UNIQUE constraint failed: users.email"), { code: "SQLITE_CONSTRAINT_UNIQUE" });
14
+ const primaryKey = Object.assign(new Error("UNIQUE constraint failed: users.id"), { code: "SQLITE_CONSTRAINT_PRIMARYKEY" });
15
+ assert.equal(isDuplicateEntryError(unique), true);
16
+ assert.equal(isDuplicateEntryError(primaryKey), true);
17
+ assert.equal(isDuplicateEntryError(new Error("Write failed", { cause: unique })), true);
18
+ assert.equal(isDuplicateEntryError(unique, { dialect: "sqlite" }), true);
19
+ assert.equal(isDuplicateEntryError(unique, { client: { client: { config: { client: "better-sqlite3" } } } }), true);
20
+ assert.equal(isDuplicateEntryError(unique, { dialect: "mysql" }), false);
21
+ assert.equal(isDuplicateEntryError({ code: "ER_DUP_ENTRY" }, { dialect: "sqlite" }), false);
22
+ for (const code of ["SQLITE_CONSTRAINT_NOTNULL", "SQLITE_CONSTRAINT_FOREIGNKEY", "SQLITE_CONSTRAINT_CHECK", "SQLITE_BUSY"]) {
23
+ assert.equal(isDuplicateEntryError({ code }), false, code);
24
+ }
25
+ assert.equal(isLostDuplicateInsertRace({ transactionOutcome: "rolledBack", cause: unique }, {}), true);
26
+ });
27
+
12
28
  test("duplicate classification follows causes and retains the database error", () => {
13
29
  const databaseError = Object.freeze({ code: "23505", message: "users_email_unique" });
14
30
  const failure = new Error("Write failed", { cause: new Error("Storage failed", { cause: databaseError }) });
@@ -26,13 +26,29 @@ test("server provider module exports one declarative provider", () => {
26
26
  });
27
27
 
28
28
  test("shared entrypoint exports shared database utilities only", () => {
29
- assert.equal(typeof sharedApi.createWithTransaction, "function");
30
29
  assert.equal(typeof sharedApi.isDuplicateEntryError, "function");
31
30
  assert.equal(typeof sharedApi.isDeadlockError, "function");
32
31
  assert.equal(typeof sharedApi.retryDeadlocks, "function");
32
+ assert.equal(typeof sharedApi.retryLostInsertRace, "function");
33
33
  assert.equal(typeof sharedApi.toDatabaseDateTimeUtc, "function");
34
34
  assert.equal(typeof sharedApi.DatabaseProvider, "undefined");
35
- for (const removed of ["normalizeText", "retentionTestables", "createTransactionManager", "createRepositoryScope", "BaseRepository"]) {
35
+ for (const removed of [
36
+ "normalizeText",
37
+ "retentionTestables",
38
+ "createTransactionManager",
39
+ "createRepositoryScope",
40
+ "BaseRepository",
41
+ "runInTransaction",
42
+ "resolveTransaction",
43
+ "resolveQueryOptions",
44
+ "resolveRepoClient",
45
+ "applyForUpdate",
46
+ "createWithTransaction",
47
+ "joinOrOpenTransaction",
48
+ "lockScopedRecordId",
49
+ "applyVisibility",
50
+ "applyVisibilityOwners"
51
+ ]) {
36
52
  assert.equal(typeof sharedApi[removed], "undefined", removed);
37
53
  }
38
54
  });
@@ -26,10 +26,41 @@ test("createKnexMigrationConfig fixes MySQL without requiring DB_CLIENT", () =>
26
26
 
27
27
  assert.equal(config.client, "mysql2");
28
28
  assert.equal(config.connection.port, 3306);
29
- assert.deepEqual(config.migrations.directory, [
30
- "/srv/catalogue/migrations",
31
- "/srv/catalogue/migrations/constraints"
32
- ]);
29
+ assert.equal(config.pool, undefined);
30
+ assert.deepEqual(config.migrations.directory, ["/srv/catalogue/migrations"]);
31
+ });
32
+
33
+ test("an application without migrations/constraints/ migrates, and its constraints run once the directory exists", async (context) => {
34
+ const appRoot = await mkdtemp(path.join(os.tmpdir(), "jskit-app-constraints-"));
35
+ context.after(() => rm(appRoot, { recursive: true, force: true }));
36
+ await mkdir(path.join(appRoot, "migrations"), { recursive: true });
37
+ await writeFile(path.join(appRoot, "package.json"), JSON.stringify({ dependencies: {} }));
38
+ await writeFile(path.join(appRoot, "migrations", "20260101000000_books.cjs"),
39
+ "exports.up = (knex) => knex.schema.createTable(\"books\", (table) => table.increments(\"id\"));\nexports.down = () => {};\n");
40
+
41
+ const migrate = async () => {
42
+ const { migrations } = await createKnexMigrationConfigFromApp({ client: "pg", environment: connectionEnvironment, appRoot });
43
+ const knex = knexFactory({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, migrations });
44
+ try {
45
+ await knex.migrate.latest();
46
+ return { directories: migrations.directory, ran: await knex("knex_migrations").orderBy("id").pluck("name") };
47
+ } finally {
48
+ await knex.destroy();
49
+ }
50
+ };
51
+
52
+ assert.deepEqual(await migrate(), {
53
+ directories: [path.join(appRoot, "migrations")],
54
+ ran: ["20260101000000_books.cjs"]
55
+ });
56
+
57
+ await mkdir(path.join(appRoot, "migrations", "constraints"));
58
+ await writeFile(path.join(appRoot, "migrations", "constraints", "20260101000001_books_index.cjs"),
59
+ "exports.up = (knex) => knex.schema.alterTable(\"books\", (table) => table.index([\"id\"]));\nexports.down = () => {};\n");
60
+ assert.deepEqual(await migrate(), {
61
+ directories: [path.join(appRoot, "migrations"), path.join(appRoot, "migrations", "constraints")],
62
+ ran: ["20260101000000_books.cjs", "20260101000001_books_index.cjs"]
63
+ });
33
64
  });
34
65
 
35
66
  test("createKnexMigrationConfig fixes PostgreSQL without requiring DB_CLIENT", () => {
@@ -41,6 +72,8 @@ test("createKnexMigrationConfig fixes PostgreSQL without requiring DB_CLIENT", (
41
72
 
42
73
  assert.equal(config.client, "pg");
43
74
  assert.equal(config.connection.port, 5432);
75
+ // Migrations write in a UTC session too.
76
+ assert.equal(typeof config.pool.afterCreate, "function");
44
77
  });
45
78
 
46
79
  test("createKnexMigrationConfig requires the application's environment instead of reading DB_* from nothing", () => {
@@ -83,8 +116,7 @@ test("installed package migrations run from their owning packages without copied
83
116
  assert.deepEqual(config.migrations.directory, [
84
117
  path.join(packageRoot, "migrations"),
85
118
  path.join(appRoot, "migrations"),
86
- path.join(packageRoot, "migrations", "constraints"),
87
- path.join(appRoot, "migrations", "constraints")
119
+ path.join(packageRoot, "migrations", "constraints")
88
120
  ]);
89
121
  });
90
122
 
@@ -265,8 +297,7 @@ test("a package's migrations and constraints run after those of the packages its
265
297
  ...packageDirectories,
266
298
  path.join(appRoot, "migrations"),
267
299
  path.join(directoryOf["@example/units-core:migrations"], "constraints"),
268
- path.join(directoryOf["@example/assets-core:migrations"], "constraints"),
269
- path.join(appRoot, "migrations", "constraints")
300
+ path.join(directoryOf["@example/assets-core:migrations"], "constraints")
270
301
  ]);
271
302
  });
272
303
 
@@ -119,8 +119,8 @@ test("DatabaseProvider exposes one cohesive database capability", async () => {
119
119
  dateStrings: ["DATE"],
120
120
  timezone: "Z"
121
121
  });
122
- assert.equal(typeof database.transactionManager.inTransaction, "function");
123
- assert.deepEqual(Object.keys(database).sort(), ["driver", "knex", "transactionManager"]);
122
+ // One way to open a transaction: a table's handle. The database runtime offers none of its own.
123
+ assert.deepEqual(Object.keys(database).sort(), ["driver", "knex"]);
124
124
 
125
125
  await runtime.shutdown();
126
126
  assert.equal(database.knex.destroyCalls, 1);
@@ -2,12 +2,11 @@ import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import {
4
4
  isDeadlockError,
5
- joinOrOpenTransaction,
6
- lockScopedRecordId,
7
5
  normalizeDbRecordId,
8
6
  parseJsonValue,
9
7
  resolveInsertedRecordId,
10
- runInTransaction
8
+ retryDeadlocks,
9
+ retryLostInsertRace
11
10
  } from "../src/shared/repositoryOptions.js";
12
11
 
13
12
  function deadlock() {
@@ -17,26 +16,6 @@ function deadlock() {
17
16
  });
18
17
  }
19
18
 
20
- function fakeKnex({ isTransaction = false } = {}) {
21
- return Object.assign(() => {}, { isTransaction, transaction: async (callback) => callback("trx") });
22
- }
23
-
24
- function fakeLockTransaction(row = null) {
25
- const calls = [];
26
- const query = {
27
- select(value) { calls.push(["select", value]); return this; },
28
- where(key, value) { calls.push(["where", key, value]); return this; },
29
- andWhere(key, value) { calls.push(["andWhere", key, value]); return this; },
30
- forUpdate() { calls.push(["forUpdate"]); return this; },
31
- async first() { calls.push(["first"]); return row; }
32
- };
33
- const trx = (table) => {
34
- calls.push(["table", table]);
35
- return query;
36
- };
37
- return { calls, trx };
38
- }
39
-
40
19
  test("normalizeDbRecordId preserves canonical DB ids and rejects unsafe JS numbers", () => {
41
20
  const unsafeNumericId = Number(9007199254740993n);
42
21
  assert.equal(normalizeDbRecordId("9007199254740993"), "9007199254740993");
@@ -62,40 +41,15 @@ test("parseJsonValue parses stored JSON and falls back for empty, null or invali
62
41
  assert.deepEqual(parseJsonValue(undefined, null, { fallback: [] }), []);
63
42
  });
64
43
 
65
- test("lockScopedRecordId locks an exact record inside its owner scope", async () => {
66
- const { calls, trx } = fakeLockTransaction({ id: "42" });
67
- assert.equal(await lockScopedRecordId({
68
- trx,
69
- tableName: "daycare_events",
70
- recordId: 42,
71
- scopeId: 7
72
- }), "42");
73
- assert.deepEqual(calls, [
74
- ["table", "daycare_events"],
75
- ["select", "id"],
76
- ["where", "id", "42"],
77
- ["andWhere", "workspace_id", "7"],
78
- ["forUpdate"],
79
- ["first"]
80
- ]);
81
- });
82
-
83
- test("lockScopedRecordId rejects missing transactions and unsafe identifiers", async () => {
84
- await assert.rejects(
85
- () => lockScopedRecordId({ tableName: "records", recordId: 1, scopeId: 1 }),
86
- /requires a transaction/u
87
- );
88
- const { trx } = fakeLockTransaction();
89
- await assert.rejects(
90
- () => lockScopedRecordId({ trx, tableName: "records; drop table", recordId: 1, scopeId: 1 }),
91
- /safe SQL identifier/u
92
- );
93
- });
94
-
95
44
  test("isDeadlockError recognizes deadlock victims through causes, never a committed write", () => {
96
45
  assert.equal(isDeadlockError(deadlock()), true);
97
46
  assert.equal(isDeadlockError({ errno: 1213 }), true);
98
47
  assert.equal(isDeadlockError({ code: "40P01" }), true);
48
+ assert.equal(isDeadlockError({ code: "SQLITE_BUSY", transactionOutcome: "rolledBack" }), true);
49
+ // MariaDB's snapshot isolation: a locking read of a row changed since the transaction's snapshot.
50
+ assert.equal(isDeadlockError({ code: "ER_CHECKREAD", errno: 1020 }), true);
51
+ assert.equal(isDeadlockError({ errno: 1020 }), true);
52
+ assert.equal(isDeadlockError(new Error("Write failed", { cause: { code: "ER_CHECKREAD", errno: 1020 } })), true);
99
53
  assert.equal(isDeadlockError(new Error("Write failed", { cause: deadlock() })), true);
100
54
  assert.equal(isDeadlockError({ code: "ER_LOCK_WAIT_TIMEOUT", errno: 1205 }), false);
101
55
  assert.equal(isDeadlockError({ code: "ER_DUP_ENTRY", errno: 1062 }), false);
@@ -107,46 +61,97 @@ test("isDeadlockError recognizes deadlock victims through causes, never a commit
107
61
  }
108
62
  });
109
63
 
110
- test("runInTransaction runs a deadlock victim again and returns the clean run", async () => {
64
+ test("retryDeadlocks runs again a transaction that read a row changed since its snapshot", async () => {
111
65
  let attempts = 0;
112
- const result = await runInTransaction(fakeKnex(), async (trx) => {
66
+ const result = await retryDeadlocks(async () => {
67
+ attempts += 1;
68
+ if (attempts === 1) {
69
+ throw new Error("Write failed", { cause: Object.assign(new Error("Record has changed since last read"), { code: "ER_CHECKREAD", errno: 1020 }) });
70
+ }
71
+ return "clean";
72
+ });
73
+ assert.deepEqual([result, attempts], ["clean", 2]);
74
+ });
75
+
76
+ test("retryDeadlocks runs a deadlock victim again and returns the clean run", async () => {
77
+ let attempts = 0;
78
+ const result = await retryDeadlocks(async () => {
113
79
  attempts += 1;
114
80
  if (attempts < 3) {
115
81
  throw deadlock();
116
82
  }
117
- return trx;
83
+ return "clean";
118
84
  });
119
- assert.equal(result, "trx");
85
+ assert.equal(result, "clean");
120
86
  assert.equal(attempts, 3);
121
87
  });
122
88
 
123
- test("runInTransaction retries only deadlocks of the outermost transaction, a few times", async () => {
124
- async function attemptsUntilRejected(knex, error, options) {
89
+ test("retryDeadlocks runs again only deadlock victims, a few times", async () => {
90
+ async function attemptsUntilRejected(error, options) {
125
91
  let attempts = 0;
126
- await assert.rejects(runInTransaction(knex, async () => {
92
+ await assert.rejects(retryDeadlocks(async () => {
127
93
  attempts += 1;
128
94
  throw error;
129
95
  }, options), error);
130
96
  return attempts;
131
97
  }
132
- const failure = new Error("Validation failed");
133
- assert.equal(await attemptsUntilRejected(fakeKnex(), failure), 1);
98
+ assert.equal(await attemptsUntilRejected(new Error("Validation failed")), 1);
99
+ // A lock wait that timed out is not a deadlock: the database may have rolled back only the statement, so the
100
+ // transaction's earlier work could run twice. MySQL and MariaDB, then PostgreSQL's lock_timeout and NOWAIT.
101
+ for (const timeout of [
102
+ Object.assign(new Error("Lock wait timeout exceeded"), { code: "ER_LOCK_WAIT_TIMEOUT", errno: 1205 }),
103
+ Object.assign(new Error("canceling statement due to lock timeout"), { code: "55P03" }),
104
+ new Error("Write failed", { cause: Object.assign(new Error("Lock wait timeout exceeded"), { errno: 1205 }) })
105
+ ]) {
106
+ assert.equal(isDeadlockError(timeout), false, timeout.message);
107
+ assert.equal(await attemptsUntilRejected(timeout), 1, timeout.message);
108
+ }
134
109
  const victim = deadlock();
135
- assert.equal(await attemptsUntilRejected(fakeKnex(), victim), 4);
136
- assert.equal(await attemptsUntilRejected(fakeKnex(), victim, { retries: 0 }), 1);
137
- assert.equal(await attemptsUntilRejected(fakeKnex({ isTransaction: true }), victim), 1, "A savepoint leaves the retry to its outermost transaction");
110
+ assert.equal(await attemptsUntilRejected(victim), 4);
111
+ assert.equal(await attemptsUntilRejected(victim, { retries: 0 }), 1);
112
+ });
113
+
114
+ // What a handle's withTransaction rethrows when its insert lost to a committed one: the duplicate, rolled back in full.
115
+ function lostInsertRace() {
116
+ const duplicate = Object.assign(new Error("Duplicate entry 'k' for key 'requests_key_unique'"), { code: "ER_DUP_ENTRY", errno: 1062 });
117
+ return Object.assign(new Error("Write failed", { cause: duplicate }), { transactionOutcome: "rolledBack" });
118
+ }
119
+
120
+ test("retryLostInsertRace runs a transaction once more when its insert lost a unique race, and answers the second run", async () => {
121
+ let runs = 0;
122
+ const result = await retryLostInsertRace({ context: {} }, async () => {
123
+ runs += 1;
124
+ if (runs === 1) {
125
+ throw lostInsertRace();
126
+ }
127
+ return "the winner's record";
128
+ });
129
+ assert.deepEqual([result, runs], ["the winner's record", 2]);
138
130
  });
139
131
 
140
- test("joinOrOpenTransaction runs work in the caller's transaction, else in one it opens", async () => {
141
- const opened = [];
142
- const withTransaction = async (work) => {
143
- opened.push("opened");
144
- return work("new-trx");
145
- };
146
- const work = async (trx) => `ran in ${trx}`;
132
+ test("retryLostInsertRace runs again only a lost race outside a caller's transaction, and only once", async () => {
133
+ async function runsUntilRejected(options, error) {
134
+ let runs = 0;
135
+ await assert.rejects(retryLostInsertRace(options, async () => {
136
+ runs += 1;
137
+ throw error;
138
+ }), (thrown) => thrown === error);
139
+ return runs;
140
+ }
141
+ // A second duplicate is final.
142
+ assert.equal(await runsUntilRejected({}, lostInsertRace()), 2);
143
+ // Inside the caller's transaction the failed insert failed that transaction: the caller gets the error.
144
+ assert.equal(await runsUntilRejected({ trx: {} }, lostInsertRace()), 1);
145
+ // Not a duplicate, or a duplicate whose transaction did not roll back in full.
146
+ assert.equal(await runsUntilRejected({}, Object.assign(new Error("Validation failed"), { transactionOutcome: "rolledBack" })), 1);
147
+ assert.equal(await runsUntilRejected({}, Object.assign(lostInsertRace(), { transactionOutcome: "pending" })), 1);
148
+ assert.equal(await runsUntilRejected({}, lostInsertRace().cause), 1);
149
+ });
147
150
 
148
- assert.equal(await joinOrOpenTransaction({ trx: "caller-trx" }, withTransaction, work), "ran in caller-trx");
149
- assert.deepEqual(opened, []);
150
- assert.equal(await joinOrOpenTransaction({}, withTransaction, work), "ran in new-trx");
151
- assert.deepEqual(opened, ["opened"]);
151
+ test("retryLostInsertRace takes (options, run)", async () => {
152
+ const run = async () => "ran";
153
+ for (const call of [() => retryLostInsertRace(run), () => retryLostInsertRace(undefined, run), () => retryLostInsertRace({}, run, {})]) {
154
+ await assert.rejects(call(), /retryLostInsertRace\(\) takes \(options, run\)/u);
155
+ }
156
+ assert.equal(await retryLostInsertRace({}, run), "ran");
152
157
  });
@@ -6,8 +6,11 @@ import test from "node:test";
6
6
  import knexFactory from "knex";
7
7
  import { createKnexMigrationConfig } from "../src/server/knexMigrationConfig.js";
8
8
  import {
9
+ TestDatabaseMissingError,
9
10
  countQueries,
10
11
  requireDisposableDatabase,
12
+ requireTestDatabase,
13
+ tableNames,
11
14
  testDatabaseNames,
12
15
  testDatabaseRun,
13
16
  testDatabaseSnapshotKey
@@ -156,3 +159,37 @@ test("countQueries() records each statement a piece of work sends, so a read per
156
159
  await knex.destroy();
157
160
  }
158
161
  });
162
+
163
+ test("a data test without a test database fails instead of skipping", () => {
164
+ for (const environment of [{}, { TEST_DB_NAME: " " }]) {
165
+ assert.throws(() => requireTestDatabase(environment), (error) =>
166
+ error instanceof TestDatabaseMissingError && error.message === "TEST_DB_NAME is not set; data tests never skip.");
167
+ }
168
+ assert.equal(requireTestDatabase({ TEST_DB_NAME: " catalogue_test " }), "catalogue_test");
169
+ });
170
+
171
+ test("tableNames() reads PostgreSQL's tables under each name Knex gives its client", async () => {
172
+ for (const client of ["pg", "postgres", "postgresql"]) {
173
+ const statements = [];
174
+ const knex = {
175
+ client: { config: { client } },
176
+ async raw(sql) {
177
+ statements.push(sql);
178
+ return { rows: [{ name: "shelves" }, { name: "books" }] };
179
+ }
180
+ };
181
+ assert.deepEqual(await tableNames(knex), ["books", "shelves"], client);
182
+ assert.match(statements[0], /information_schema\.tables WHERE table_schema = current_schema\(\)/u, client);
183
+ }
184
+ });
185
+
186
+ test("tableNames() lists a database's own tables, sorted, without SQLite's internal ones", async () => {
187
+ const knex = knexFactory({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
188
+ try {
189
+ await knex.schema.createTable("shelves", (table) => table.increments("id"));
190
+ await knex.schema.createTable("books", (table) => table.increments("id"));
191
+ assert.deepEqual(await tableNames(knex), ["books", "shelves"]);
192
+ } finally {
193
+ await knex.destroy();
194
+ }
195
+ });
@@ -1,31 +0,0 @@
1
- import { retryDeadlocks } from "./repositoryOptions.js";
2
-
3
- /**
4
- * Runs work in a transaction of the database's Knex instance, retrying deadlocks,
5
- * or in the transaction the caller already holds.
6
- * @param {object} dependencies
7
- * @param {import("../server/types.js").RuntimeKnex} dependencies.knex
8
- */
9
- function createTransactionManager({ knex }) {
10
- /**
11
- * @template T
12
- * @param {(trx: import("../server/types.js").RuntimeKnexTransaction) => Promise<T>} work
13
- * @param {{ trx?: import("../server/types.js").RuntimeKnexTransaction | null }} [options] A transaction to run in instead of a new one.
14
- */
15
- async function inTransaction(work, { trx = null } = {}) {
16
- // readable-check: allow method-probe - input validation: the caller hands over the work to run
17
- if (typeof work !== "function") {
18
- throw new TypeError("inTransaction requires a callback function.");
19
- }
20
-
21
- if (trx) {
22
- return work(trx);
23
- }
24
-
25
- return retryDeadlocks(() => knex.transaction((nextTrx) => work(nextTrx)));
26
- }
27
-
28
- return Object.freeze({ inTransaction });
29
- }
30
-
31
- export { createTransactionManager };
@@ -1,73 +0,0 @@
1
- import { normalizeVisibilityContext } from "@jskit-ai/kernel/shared/support/visibility";
2
-
3
- const ALWAYS_FALSE_SQL = "1 = 0";
4
- const DEFAULT_VISIBILITY_COLUMNS = Object.freeze({
5
- scopeOwnerId: "workspace_id",
6
- userId: "user_id"
7
- });
8
-
9
- function applyVisibility(queryBuilder, visibilityContext = {}) {
10
- const context = normalizeVisibilityContext(visibilityContext);
11
- const workspaceColumn = DEFAULT_VISIBILITY_COLUMNS.scopeOwnerId;
12
- const userColumn = DEFAULT_VISIBILITY_COLUMNS.userId;
13
-
14
- if (context.visibility === "public") {
15
- return queryBuilder;
16
- }
17
-
18
- if (context.visibility === "workspace") {
19
- if (!context.scopeOwnerId) {
20
- return queryBuilder.whereRaw(ALWAYS_FALSE_SQL);
21
- }
22
- return queryBuilder.where(workspaceColumn, context.scopeOwnerId);
23
- }
24
-
25
- if (context.visibility === "user") {
26
- if (!context.userId) {
27
- return queryBuilder.whereRaw(ALWAYS_FALSE_SQL);
28
- }
29
- return queryBuilder.where(userColumn, context.userId);
30
- }
31
-
32
- if (!context.scopeOwnerId || !context.userId) {
33
- return queryBuilder.whereRaw(ALWAYS_FALSE_SQL);
34
- }
35
-
36
- return queryBuilder.where(workspaceColumn, context.scopeOwnerId).where(userColumn, context.userId);
37
- }
38
-
39
- function applyVisibilityOwners(payload = {}, visibilityContext = {}) {
40
- const source = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
41
- const context = normalizeVisibilityContext(visibilityContext);
42
-
43
- if (context.visibility === "public") {
44
- return {
45
- ...source
46
- };
47
- }
48
-
49
- if (context.visibility === "workspace" && !context.scopeOwnerId) {
50
- throw new Error("Visibility context requires scopeOwnerId.");
51
- }
52
- if (context.visibility === "user" && !context.userId) {
53
- throw new Error("Visibility context requires userId.");
54
- }
55
- if (context.visibility === "workspace_user" && (!context.scopeOwnerId || !context.userId)) {
56
- throw new Error("Visibility context requires scopeOwnerId and userId.");
57
- }
58
-
59
- const ownedPayload = {
60
- ...source
61
- };
62
-
63
- if (context.scopeOwnerId) {
64
- ownedPayload[DEFAULT_VISIBILITY_COLUMNS.scopeOwnerId] = context.scopeOwnerId;
65
- }
66
- if (context.userId) {
67
- ownedPayload[DEFAULT_VISIBILITY_COLUMNS.userId] = context.userId;
68
- }
69
-
70
- return ownedPayload;
71
- }
72
-
73
- export { DEFAULT_VISIBILITY_COLUMNS, applyVisibility, applyVisibilityOwners };
@@ -1,51 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import test from "node:test";
3
-
4
- import { createWithTransaction } from "../src/shared/index.js";
5
- import { createTransactionManager } from "../src/shared/transactionManager.js";
6
-
7
- function createKnexStub() {
8
- return {
9
- async transaction(callback) {
10
- return callback({ trxId: "trx-1" });
11
- }
12
- };
13
- }
14
-
15
- test("transaction manager wraps callback in knex transaction", async () => {
16
- const manager = createTransactionManager({ knex: createKnexStub() });
17
- const result = await manager.inTransaction(async (trx) => ({ ok: true, trx }));
18
- assert.equal(result.ok, true);
19
- assert.equal(result.trx.trxId, "trx-1");
20
- });
21
-
22
- test("transaction manager runs a deadlocked transaction again but never a borrowed one", async () => {
23
- const manager = createTransactionManager({ knex: createKnexStub() });
24
- const deadlock = Object.assign(new Error("Deadlock found when trying to get lock"), { code: "ER_LOCK_DEADLOCK" });
25
- let attempts = 0;
26
- const result = await manager.inTransaction(async (trx) => {
27
- attempts += 1;
28
- if (attempts === 1) {
29
- throw deadlock;
30
- }
31
- return trx.trxId;
32
- });
33
- assert.equal(result, "trx-1");
34
- assert.equal(attempts, 2);
35
-
36
- attempts = 0;
37
- await assert.rejects(manager.inTransaction(async () => {
38
- attempts += 1;
39
- throw deadlock;
40
- }, { trx: { trxId: "outer" } }), deadlock);
41
- assert.equal(attempts, 1);
42
- });
43
-
44
- test("createWithTransaction creates a reusable withTransaction function", async () => {
45
- const knex = Object.assign(() => {
46
- throw new Error("query execution not expected");
47
- }, createKnexStub());
48
- const withTransaction = createWithTransaction(knex);
49
- const result = await withTransaction(async (trx) => ({ id: trx.trxId }));
50
- assert.deepEqual(result, { id: "trx-1" });
51
- });