@jskit-ai/resource-runtime 0.2.17 → 0.2.18
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/CHANGELOG.md +10 -0
- package/locales/en.json +3 -1
- package/package.json +5 -5
- package/src/server/errors.js +29 -5
- package/src/server/handleBlobs.js +139 -0
- package/src/server/handleEveryRow.js +132 -0
- package/src/server/handleHidden.js +46 -4
- package/src/server/handleLocks.js +29 -2
- package/src/server/handleRecords.js +2 -1
- package/src/server/index.js +1 -0
- package/src/server/manyRowChannel.js +44 -0
- package/src/server/resourceHandle.js +58 -48
- package/src/server/resourceHost.js +5 -5
- package/src/server/resourceRuntime.js +44 -18
- package/src/server/types.js +5 -0
- package/src/test/expectFlatQueries.js +23 -11
- package/src/test/index.js +2 -2
- package/test/blobFields.mysql.test.js +8 -0
- package/test/blobFields.test.js +8 -0
- package/test/crossTableFilters.mysql.test.js +8 -0
- package/test/crossTableFilters.test.js +8 -0
- package/test/hiddenFields.test.js +41 -0
- package/test/lockedReads.mysql.test.js +94 -0
- package/test/pagedReads.mysql.test.js +8 -0
- package/test/pagedReads.test.js +8 -0
- package/test/reportsAcrossOwners.mysql.test.js +8 -0
- package/test/reportsAcrossOwners.test.js +8 -0
- package/test/resourceRuntime.test.js +46 -1
- package/test/support/blobFieldsCases.js +226 -0
- package/test/support/crossTableFiltersCases.js +180 -0
- package/test/support/mysqlDatabase.js +35 -0
- package/test/support/pagedReadsCases.js +128 -0
- package/test/support/reportsAcrossOwnersCases.js +154 -0
- package/test/testHelpers.test.js +128 -3
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { createTestResourceRuntime } from "../src/test/index.js";
|
|
5
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
6
|
+
|
|
7
|
+
// What a lock's caller reads after the lock on MySQL and MariaDB, under InnoDB's REPEATABLE READ. A lock answers only
|
|
8
|
+
// the rows it locks and refuses include, so the related rows come from a plain read after it, and a plain read inside a
|
|
9
|
+
// transaction sees the snapshot of the transaction's first plain read: a transaction that locks first reads what the
|
|
10
|
+
// lock's previous holder committed, one that read before its lock does not.
|
|
11
|
+
|
|
12
|
+
const WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
|
|
13
|
+
|
|
14
|
+
const seatResource = defineTableResource({
|
|
15
|
+
name: "seats",
|
|
16
|
+
tableName: "seats",
|
|
17
|
+
ownership: "workspace",
|
|
18
|
+
schema: {
|
|
19
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
20
|
+
code: { type: "string", required: true }
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
const bookingResource = defineTableResource({
|
|
24
|
+
name: "bookings",
|
|
25
|
+
tableName: "bookings",
|
|
26
|
+
ownership: "workspace",
|
|
27
|
+
searchSchema: { seatIds: { type: "array", actualField: "seatId", filterOperator: "in" } },
|
|
28
|
+
schema: {
|
|
29
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
30
|
+
seatId: { type: "id", required: true, storage: { column: "seat_id" } },
|
|
31
|
+
guest: { type: "string", required: true }
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
async function database(t, suffix) {
|
|
36
|
+
const knex = await ownMysqlDatabase(t, suffix);
|
|
37
|
+
await knex.schema.createTable("seats", (table) => {
|
|
38
|
+
table.increments("id");
|
|
39
|
+
table.integer("workspace_id").nullable();
|
|
40
|
+
table.string("code").notNullable();
|
|
41
|
+
});
|
|
42
|
+
await knex.schema.createTable("bookings", (table) => {
|
|
43
|
+
table.increments("id");
|
|
44
|
+
table.integer("workspace_id").nullable();
|
|
45
|
+
table.integer("seat_id").notNullable().index();
|
|
46
|
+
table.string("guest").notNullable();
|
|
47
|
+
});
|
|
48
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
49
|
+
return runtime.own("seats.feature", [seatResource, bookingResource]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* One transaction holds a seat's lock and adds a booking for it; a second, the reader, locks the seat (waiting for
|
|
54
|
+
* the holder's commit) and then reads the seat's bookings. With `readFirst` the reader makes a plain read before the
|
|
55
|
+
* holder commits. Answers the reader's bookings before (readFirst only) and after its lock.
|
|
56
|
+
*/
|
|
57
|
+
async function readAfterLock(t, suffix, { readFirst }) {
|
|
58
|
+
const { seats, bookings } = await database(t, suffix);
|
|
59
|
+
const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
|
|
60
|
+
const guestsOf = (tx) => bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"] }, tx);
|
|
61
|
+
let commit;
|
|
62
|
+
const committing = new Promise((resolve) => {
|
|
63
|
+
commit = resolve;
|
|
64
|
+
});
|
|
65
|
+
let holding;
|
|
66
|
+
const held = new Promise((resolve) => {
|
|
67
|
+
holding = resolve;
|
|
68
|
+
});
|
|
69
|
+
const holder = seats.withTransaction(WORKSPACE, async (tx) => {
|
|
70
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
71
|
+
await bookings.create({ seatId, guest: "first" }, { ...tx, returning: "none" });
|
|
72
|
+
holding();
|
|
73
|
+
await committing;
|
|
74
|
+
});
|
|
75
|
+
await held;
|
|
76
|
+
const reader = seats.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
77
|
+
await assert.rejects(seats.lock(seatId, { ...tx, include: ["bookings"] }), /seats\.lock\(\) locks only its own rows .* takes no include/u);
|
|
78
|
+
const before = readFirst ? await guestsOf(tx) : null;
|
|
79
|
+
// The holder commits only once the reader has made its plain read, or is about to lock.
|
|
80
|
+
commit();
|
|
81
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
82
|
+
return { before, after: await guestsOf(tx) };
|
|
83
|
+
});
|
|
84
|
+
const [, read] = await Promise.all([holder, reader]);
|
|
85
|
+
return { before: read.before?.map(({ guest }) => guest) ?? null, after: read.after.map(({ guest }) => guest) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
test("a transaction that locks first reads, after its lock, the rows the lock's previous holder committed", async (t) => {
|
|
89
|
+
assert.deepEqual(await readAfterLock(t, "da_lr_lock", { readFirst: false }), { before: null, after: ["first"] });
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("a transaction that made a plain read before its lock still reads that read's snapshot after the lock", async (t) => {
|
|
93
|
+
assert.deepEqual(await readAfterLock(t, "da_lr_read", { readFirst: true }), { before: [], after: [] });
|
|
94
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { pagedReadsCases } from "./support/pagedReadsCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of pagedReadsCases(ownMysqlDatabase)) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { createPackageTestKnex } from "../src/test/index.js";
|
|
3
|
+
import { pagedReadsCases } from "./support/pagedReadsCases.js";
|
|
4
|
+
|
|
5
|
+
// SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
|
|
6
|
+
for (const [name, run] of pagedReadsCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { reportsAcrossOwnersCases } from "./support/reportsAcrossOwnersCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of reportsAcrossOwnersCases(ownMysqlDatabase)) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { createPackageTestKnex } from "../src/test/index.js";
|
|
3
|
+
import { reportsAcrossOwnersCases } from "./support/reportsAcrossOwnersCases.js";
|
|
4
|
+
|
|
5
|
+
// SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
|
|
6
|
+
for (const [name, run] of reportsAcrossOwnersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -196,7 +196,7 @@ test("query() pages with page.size and page.after, and refuses an unpaged or ove
|
|
|
196
196
|
assert.deepEqual(second.records.map(({ title }) => title), ["n2", "n3"]);
|
|
197
197
|
const filtered = await notes.query({ filters: { title: "n4" }, page: { size: 2 } }, { context: WORKSPACE_A });
|
|
198
198
|
assert.deepEqual(filtered.records.map(({ title }) => title), ["n4"]);
|
|
199
|
-
assert.deepEqual(notes.pageLimits(), { request: 20, server: 1000 });
|
|
199
|
+
assert.deepEqual(notes.pageLimits(), { request: 20, server: 1000, requestRows: 10000 });
|
|
200
200
|
});
|
|
201
201
|
|
|
202
202
|
test("query() serves a numbered page in one statement, with no count, and refuses page.number with page.after", async (t) => {
|
|
@@ -330,6 +330,28 @@ test("many-row writes run per chunk in the caller's workspace, and answer nothin
|
|
|
330
330
|
assert.deepEqual(await knex("notes").pluck("title"), ["other"]);
|
|
331
331
|
});
|
|
332
332
|
|
|
333
|
+
test("a many-row write refuses a chunk of fewer than 100 rows before any statement, and takes 100 or more", async (t) => {
|
|
334
|
+
const { notes, knex } = await createFixture(t);
|
|
335
|
+
const options = { context: WORKSPACE_A };
|
|
336
|
+
const [id] = await notes.createMany([{ title: "a" }], { ...options, returning: "ids" });
|
|
337
|
+
for (const chunkSize of [1, 99, 0, 150.5, -100, "200", null]) {
|
|
338
|
+
for (const [operation, call] of [
|
|
339
|
+
["createMany", () => notes.createMany([{ title: "b" }], { ...options, chunkSize })],
|
|
340
|
+
["patchMany", () => notes.patchMany([{ id, title: "b" }], { ...options, chunkSize })],
|
|
341
|
+
["patchWhere", () => notes.patchWhere({ id }, { title: "b" }, { ...options, chunkSize })],
|
|
342
|
+
["deleteWhere", () => notes.deleteWhere({ id }, { ...options, chunkSize })]
|
|
343
|
+
]) {
|
|
344
|
+
const refused = new RegExp(`^TypeError: notes\\.${operation}\\(\\) chunkSize is a whole number of at least 100 rows \\(500 when left out\\)`, "u");
|
|
345
|
+
const { count } = await countQueries(knex, () => assert.rejects(call(), refused, `${operation} with chunkSize ${chunkSize}`));
|
|
346
|
+
assert.equal(count, 0, `${operation} with chunkSize ${chunkSize} sends nothing`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
assert.deepEqual(await knex("notes").pluck("title"), ["a"]);
|
|
350
|
+
const { count } = await countQueries(knex, () => notes.createMany(Array.from({ length: 250 }, (_, index) => ({ title: `c${index}` })), { ...options, chunkSize: 100 }));
|
|
351
|
+
assert.ok(count >= 3, `250 rows in chunks of 100 are 3 inserts, in ${count} statements`);
|
|
352
|
+
assert.equal((await knex("notes").pluck("id")).length, 251);
|
|
353
|
+
});
|
|
354
|
+
|
|
333
355
|
test("a table keyed by a uuid or a string takes its ids as text without its own normalizeId", async (t) => {
|
|
334
356
|
const tokens = defineTableResource({
|
|
335
357
|
name: "tokens",
|
|
@@ -1792,6 +1814,29 @@ test("lock, lockMany, lockWhere and claim read only the fields they name, so a r
|
|
|
1792
1814
|
assert.deepEqual(locked, [{ id: ids[0], stage: "new", vetId: "1" }]);
|
|
1793
1815
|
});
|
|
1794
1816
|
|
|
1817
|
+
test("a lock refuses include before any statement; its rows' related records come from a read after the lock, in its transaction", async (t) => {
|
|
1818
|
+
const { visits, options, ids, selects } = await createVisitFixture(t);
|
|
1819
|
+
const refused = (method) => ({
|
|
1820
|
+
name: "TypeError",
|
|
1821
|
+
message: new RegExp(`^visits\\.${method}\\(\\) locks only its own rows and reads no included records, so it takes no include\\. Read the related records after the lock`, "u")
|
|
1822
|
+
});
|
|
1823
|
+
const statements = await selects(() => visits.withTransaction(options, async (tx) => {
|
|
1824
|
+
const including = { ...tx, include: ["customer"] };
|
|
1825
|
+
await assert.rejects(visits.lock(ids[0], including), refused("lock"));
|
|
1826
|
+
await assert.rejects(visits.lockMany(ids, including), refused("lockMany"));
|
|
1827
|
+
await assert.rejects(visits.lockWhere({ id: ids }, including), refused("lockWhere"));
|
|
1828
|
+
await assert.rejects(visits.claim({ filters: { id: ids } }, including), refused("claim"));
|
|
1829
|
+
await assert.rejects(visits.claim({ filters: { id: ids }, include: ["customer"] }, tx), refused("claim"));
|
|
1830
|
+
}));
|
|
1831
|
+
assert.deepEqual(statements, []);
|
|
1832
|
+
// What the refusal says: the lock first, then one read of the locked rows with their related records.
|
|
1833
|
+
const read = await visits.withTransaction(options, async (tx) => {
|
|
1834
|
+
const locked = await visits.lockMany(ids, { ...tx, fields: ["stage"] });
|
|
1835
|
+
return visits.queryAll({ filters: { id: locked.map(({ id }) => id) }, include: ["customer"] }, tx);
|
|
1836
|
+
});
|
|
1837
|
+
assert.deepEqual(read.map(({ id, stage, customerId, customer }) => [id, stage, customerId, customer.name]), ids.map((id) => [id, "new", "1", "Ada"]));
|
|
1838
|
+
});
|
|
1839
|
+
|
|
1795
1840
|
test("a patch that compares a lock version or onlyIf locks only the version, and compares onlyIf in SQL, hidden fields too", async (t) => {
|
|
1796
1841
|
const { visits, options, ids, selects } = await createVisitFixture(t);
|
|
1797
1842
|
// The patch's own locking read checks no relation: the customer it writes unchanged is checked by the write alone.
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { Buffer } from "node:buffer";
|
|
3
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
4
|
+
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
5
|
+
import { createTestResourceRuntime, expectFlatQueries } from "../../src/test/index.js";
|
|
6
|
+
|
|
7
|
+
// A blob field on every database the runtime supports: writes take bytes within maxBytes, checked before any
|
|
8
|
+
// statement; reads answer it only when their fields name it, never as JSON, never an included table's, and never more
|
|
9
|
+
// than 16 MiB of it but one record's, so queryPages() shrinks its pages to fit. Each database's test file runs these
|
|
10
|
+
// cases on its own connection.
|
|
11
|
+
|
|
12
|
+
const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
|
|
13
|
+
// expectFlatQueries() runs only against a test database, which TEST_DB_NAME names.
|
|
14
|
+
const TEST_ENVIRONMENT = Object.freeze({ TEST_DB_NAME: "blob_test" });
|
|
15
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
16
|
+
|
|
17
|
+
const avatarResource = defineTableResource({
|
|
18
|
+
name: "avatars",
|
|
19
|
+
tableName: "avatars",
|
|
20
|
+
ownership: "workspace",
|
|
21
|
+
lockVersionField: "lockVersion",
|
|
22
|
+
schema: {
|
|
23
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
24
|
+
albumId: { type: "id", nullable: true, belongsTo: "albums", as: "album", storage: { column: "album_id" } },
|
|
25
|
+
label: { type: "string", required: true, search: true },
|
|
26
|
+
image: { type: "blob", maxBytes: MAX_BYTES, nullable: true },
|
|
27
|
+
lockVersion: { type: "integer", defaultTo: 0, storage: { column: "lock_version" } }
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const albumResource = defineTableResource({
|
|
32
|
+
name: "albums",
|
|
33
|
+
tableName: "albums",
|
|
34
|
+
ownership: "workspace",
|
|
35
|
+
relationships: { avatars: { type: "hasMany", target: "avatars", foreignKey: "albumId" } },
|
|
36
|
+
schema: {
|
|
37
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
38
|
+
title: { type: "string", required: true }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {import("knex").Knex} knex
|
|
44
|
+
* @param {{ afterWrite?: Function }} [hooks] The avatars' hooks.
|
|
45
|
+
*/
|
|
46
|
+
async function createAvatars(knex, hooks) {
|
|
47
|
+
await knex.schema.createTable("albums", (table) => {
|
|
48
|
+
table.increments("id");
|
|
49
|
+
table.integer("workspace_id").nullable();
|
|
50
|
+
table.string("title").notNullable();
|
|
51
|
+
});
|
|
52
|
+
await knex.schema.createTable("avatars", (table) => {
|
|
53
|
+
table.increments("id");
|
|
54
|
+
table.integer("workspace_id").nullable();
|
|
55
|
+
table.integer("album_id").nullable().index();
|
|
56
|
+
table.string("label").notNullable();
|
|
57
|
+
// MySQL's BLOB holds 64 KiB; a column holds the field's maxBytes.
|
|
58
|
+
if (knex.client.config.client === "mysql2") {
|
|
59
|
+
table.specificType("image", "MEDIUMBLOB").nullable();
|
|
60
|
+
} else {
|
|
61
|
+
table.binary("image").nullable();
|
|
62
|
+
}
|
|
63
|
+
table.integer("lock_version").notNullable().defaultTo(0);
|
|
64
|
+
});
|
|
65
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
66
|
+
const { avatars, albums } = await runtime.own("avatars.feature", [hooks ? { resource: avatarResource, hooks } : avatarResource, albumResource]);
|
|
67
|
+
const system = runtime.declareSystemScope("avatars.feature", "resize every workspace's avatars")("resize");
|
|
68
|
+
return { avatars, albums, system, job: { context: system.forWorkspace("1") } };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function pagesOf(pages) {
|
|
72
|
+
const read = [];
|
|
73
|
+
for await (const records of pages) {
|
|
74
|
+
read.push(records);
|
|
75
|
+
}
|
|
76
|
+
return read;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const validation = (rule) => (error) => error.code === "REST_API_VALIDATION" && error.details.violations[0].field === "image" &&
|
|
80
|
+
error.details.violations[0].rule === rule;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
84
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
85
|
+
*/
|
|
86
|
+
function blobFieldsCases(connect) {
|
|
87
|
+
return [
|
|
88
|
+
["a blob field takes bytes within maxBytes, refusing anything else before any statement, and a read answers it only when its fields name it", async (t) => {
|
|
89
|
+
const knex = await connect(t, "da_bl_values");
|
|
90
|
+
const { avatars } = await createAvatars(knex);
|
|
91
|
+
const options = { context: WORKSPACE_A };
|
|
92
|
+
const bytes = Buffer.from([0, 1, 2, 255]);
|
|
93
|
+
|
|
94
|
+
const created = await avatars.create({ label: "plain", image: bytes }, options);
|
|
95
|
+
assert.equal(Object.hasOwn(created, "image"), false);
|
|
96
|
+
const read = await avatars.get(created.id, { fields: ["label", "image"] }, options);
|
|
97
|
+
assert.equal(Buffer.isBuffer(read.image), true);
|
|
98
|
+
assert.deepEqual([...read.image], [0, 1, 2, 255]);
|
|
99
|
+
assert.equal(Object.hasOwn(await avatars.get(created.id, {}, options), "image"), false);
|
|
100
|
+
|
|
101
|
+
const viewed = await avatars.create({ label: "view", image: new Uint8Array([7, 8, 9]).subarray(1) }, { ...options, returning: "id" });
|
|
102
|
+
assert.deepEqual([...(await avatars.get(viewed, { fields: ["image"] }, options)).image], [8, 9]);
|
|
103
|
+
|
|
104
|
+
for (const [value, rule] of [["text", "blob"], [[1, 2], "blob"], [{ data: [1] }, "blob"], [Buffer.alloc(MAX_BYTES + 1), "max_bytes"]]) {
|
|
105
|
+
const refused = await countQueries(knex, () => assert.rejects(avatars.create({ label: "bad", image: value }, options), validation(rule)));
|
|
106
|
+
assert.equal(refused.count, 0);
|
|
107
|
+
}
|
|
108
|
+
await assert.rejects(avatars.createMany([{ label: "ok", image: bytes }, { label: "bad", image: "text" }], options), validation("blob"));
|
|
109
|
+
await assert.rejects(avatars.patchMany([{ id: created.id, image: Buffer.alloc(MAX_BYTES + 1) }], options), validation("max_bytes"));
|
|
110
|
+
await assert.rejects(avatars.patchWhere({ id: [created.id] }, { image: 5 }, options), validation("blob"));
|
|
111
|
+
await avatars.patch(created.id, { image: Buffer.alloc(MAX_BYTES) }, { ...options, returning: "none" });
|
|
112
|
+
assert.equal((await avatars.get(created.id, { fields: ["image"] }, options)).image.byteLength, MAX_BYTES);
|
|
113
|
+
await avatars.patch(created.id, { image: null }, { ...options, returning: "none" });
|
|
114
|
+
assert.equal((await avatars.get(created.id, { fields: ["image"] }, options)).image, null);
|
|
115
|
+
|
|
116
|
+
// One page names it; a read of every row at once, a JSON:API read and a filter lock do not.
|
|
117
|
+
const page = await avatars.query({ filters: { label: "view" }, fields: ["label", "image"], page: { size: 4 } }, options);
|
|
118
|
+
assert.deepEqual([...page.records[0].image], [8, 9]);
|
|
119
|
+
await assert.rejects(avatars.queryAll({ fields: ["label", "image"] }, options),
|
|
120
|
+
/avatars\.queryAll\(\) reads every matching row at once, so it reads no blob \(avatars\.image\): read blobs a page at a time with queryPages\(\)/u);
|
|
121
|
+
await assert.rejects(avatars.query({ fields: { avatars: "label,image" }, page: { size: 10 } }, { ...options, format: "jsonapi" }),
|
|
122
|
+
(error) => error.status === 400 && error.code === "JSON_API_FIELDSET_INVALID" && error.messageCode === "resource.blobFields" &&
|
|
123
|
+
error.messageParams.fields === "avatars.image" && /JSON holds no binary, so their fields name no blob \(avatars\.image\)/u.test(error.message));
|
|
124
|
+
await assert.rejects(avatars.get(viewed, { fields: { avatars: "image" } }, { ...options, format: "jsonapi" }), /JSON holds no binary/u);
|
|
125
|
+
const locked = await avatars.withTransaction(options, async (tx) => {
|
|
126
|
+
await assert.rejects(avatars.lockWhere({ label: "view" }, { ...tx, fields: ["image"] }), /avatars\.lockWhere\(\) reads every matching row at once, so it reads no blob/u);
|
|
127
|
+
assert.equal(Object.hasOwn(await avatars.lock(viewed, tx), "image"), false);
|
|
128
|
+
return avatars.lockMany([viewed], { ...tx, fields: ["image"] });
|
|
129
|
+
});
|
|
130
|
+
assert.deepEqual([...locked[0].image], [8, 9]);
|
|
131
|
+
}],
|
|
132
|
+
|
|
133
|
+
["queryPages() reads named blobs in pages that hold at most 16 MiB of them, and every row a page without them", async (t) => {
|
|
134
|
+
const knex = await connect(t, "da_bl_pages");
|
|
135
|
+
const { avatars, system, job } = await createAvatars(knex);
|
|
136
|
+
await avatars.createMany(Array.from({ length: 9 }, (_, index) => ({ label: `a${index}`, image: Buffer.from([index]) })), { ...job, returning: "none" });
|
|
137
|
+
const sizes = async (params) => (await pagesOf(avatars.queryPages(params, job))).map((records) => records.length);
|
|
138
|
+
// A 4 MiB blob: 4 rows a page.
|
|
139
|
+
assert.deepEqual(await sizes({ fields: ["label", "image"] }), [4, 4, 1]);
|
|
140
|
+
assert.deepEqual(await sizes({ fields: ["label"] }), [9]);
|
|
141
|
+
const last = [];
|
|
142
|
+
for await (const records of avatars.queryPages({ filters: { label: "a8" }, fields: ["image"] }, job)) {
|
|
143
|
+
last.push(...records.map(({ image }) => [...image]));
|
|
144
|
+
}
|
|
145
|
+
assert.deepEqual(last, [[8]]);
|
|
146
|
+
|
|
147
|
+
// Each later page's own statement is allowed, as a many-row write's later chunks are, so the paged read is flat.
|
|
148
|
+
let workspace = 1;
|
|
149
|
+
const seed = async (size) => {
|
|
150
|
+
workspace += 1;
|
|
151
|
+
const options = { context: system.forWorkspace(String(workspace)), returning: "none" };
|
|
152
|
+
await avatars.createMany(Array.from({ length: size }, (_, index) => ({ label: `w${index}`, image: Buffer.from([index]) })), options);
|
|
153
|
+
return String(workspace);
|
|
154
|
+
};
|
|
155
|
+
const run = async (seeded) => (await pagesOf(avatars.queryPages({ fields: ["image"] }, { context: system.forWorkspace(seeded) }))).flat().length;
|
|
156
|
+
assert.deepEqual(await expectFlatQueries({ knex, environment: TEST_ENVIRONMENT, sizes: [5, 20], seed, run }),
|
|
157
|
+
[{ size: 5, count: 2, chunkStatements: 1 }, { size: 20, count: 5, chunkStatements: 4 }]);
|
|
158
|
+
}],
|
|
159
|
+
|
|
160
|
+
["a write whose blob is wrong sends no statement, not a lock or a BEGIN, whatever the patch's conditions or the table's hooks", async (t) => {
|
|
161
|
+
const knex = await connect(t, "da_bl_first");
|
|
162
|
+
const written = [];
|
|
163
|
+
const { avatars } = await createAvatars(knex, { afterWrite: ({ operation }) => { written.push(operation); } });
|
|
164
|
+
const options = { context: WORKSPACE_A };
|
|
165
|
+
const { id, lockVersion } = await avatars.create({ label: "framed", image: Buffer.from([1]) }, options);
|
|
166
|
+
const oversize = Buffer.alloc(MAX_BYTES + 1);
|
|
167
|
+
const writes = [
|
|
168
|
+
() => avatars.patch(id, { image: oversize }, { ...options, lockVersion }),
|
|
169
|
+
() => avatars.patch(id, { image: oversize }, { ...options, onlyIf: { label: "framed" } }),
|
|
170
|
+
() => avatars.patch(id, { image: oversize }, options),
|
|
171
|
+
() => avatars.create({ label: "big", image: oversize }, options),
|
|
172
|
+
() => avatars.createMany([{ label: "big", image: oversize }], options),
|
|
173
|
+
() => avatars.patchMany([{ id, image: oversize }], options),
|
|
174
|
+
() => avatars.patchWhere({ id: [id] }, { image: oversize }, options),
|
|
175
|
+
() => avatars.findOrCreate({ id: "999", label: "big", image: oversize }, options),
|
|
176
|
+
() => avatars.lockOrCreate({ id: "999", label: "big", image: oversize }, options, () => null)
|
|
177
|
+
];
|
|
178
|
+
for (const write of writes) {
|
|
179
|
+
const refused = await countQueries(knex, () => assert.rejects(write(), validation("max_bytes")));
|
|
180
|
+
assert.equal(refused.count, 0);
|
|
181
|
+
}
|
|
182
|
+
assert.deepEqual(written, ["create"]);
|
|
183
|
+
}],
|
|
184
|
+
|
|
185
|
+
["a read holds at most 16 MiB of blobs, or one record's, and no included table's: a query page, a lockMany() list, an include and a join source", async (t) => {
|
|
186
|
+
const knex = await connect(t, "da_bl_bound");
|
|
187
|
+
const { avatars, albums, job } = await createAvatars(knex);
|
|
188
|
+
const options = { context: WORKSPACE_A };
|
|
189
|
+
const ids = await avatars.createMany(Array.from({ length: 5 }, (_, index) => ({ label: `b${index}`, image: Buffer.from([index]) })), { ...options, returning: "ids" });
|
|
190
|
+
const albumId = await albums.create({ title: "Faces" }, { ...options, returning: "id" });
|
|
191
|
+
|
|
192
|
+
// A 4 MiB blob: 4 records hold 16 MiB.
|
|
193
|
+
assert.equal((await avatars.query({ fields: ["image"], page: { size: 4 } }, options)).records.length, 4);
|
|
194
|
+
const page = await countQueries(knex, () => assert.rejects(avatars.query({ fields: ["image"], page: { size: 5 } }, options),
|
|
195
|
+
/avatars\.query\(\) reads up to 5 records, and 4 of them already hold 16 MiB of avatars\.image: read at most 4 at a time/u));
|
|
196
|
+
assert.equal(page.count, 0);
|
|
197
|
+
await avatars.withTransaction(options, async (tx) => {
|
|
198
|
+
await assert.rejects(avatars.lockMany(ids, { ...tx, fields: ["image"] }), /avatars\.lockMany\(\) reads up to 5 records/u);
|
|
199
|
+
assert.equal((await avatars.lockMany(ids.slice(0, 4), { ...tx, fields: ["image"] })).length, 4);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// An include holds any number of records, so no read names an included table's blob.
|
|
203
|
+
const faces = { include: ["avatars"], fields: { albums: "title", avatars: "label,image" } };
|
|
204
|
+
const included = /albums\.(get|query|queryPages|queryAll)\(\) fields name avatars\.image, a blob of an included table/u;
|
|
205
|
+
const reads = [
|
|
206
|
+
() => albums.get(albumId, faces, options),
|
|
207
|
+
() => albums.query({ ...faces, page: { size: 10 } }, options),
|
|
208
|
+
() => albums.queryAll(faces, options),
|
|
209
|
+
() => pagesOf(albums.queryPages(faces, job))
|
|
210
|
+
];
|
|
211
|
+
for (const read of reads) {
|
|
212
|
+
const refused = await countQueries(knex, () => assert.rejects(read(), included));
|
|
213
|
+
assert.equal(refused.count, 0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// A join source carries no blob, so a report's select of every column reads none.
|
|
217
|
+
const source = await avatars.joinSource({ alias: "a" }, options);
|
|
218
|
+
const [row] = await source.query.select("a.*").orderBy("a.id").limit(1);
|
|
219
|
+
assert.equal(Object.hasOwn(row, "image"), false);
|
|
220
|
+
assert.equal(row.label, "b0");
|
|
221
|
+
assert.throws(() => source.column("image"), /avatars\.joinSource\(\) carries no blob, so it has no column for "image"/u);
|
|
222
|
+
}]
|
|
223
|
+
];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export { blobFieldsCases };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
3
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
4
|
+
|
|
5
|
+
// A search filter that reads another owner's table, on every database the runtime supports: json-rest-api joins that
|
|
6
|
+
// table as the table's own read in the caller's scope, so its ownership, its owner's row policy and the policies
|
|
7
|
+
// contributed to it decide which of its rows a filter can match; own() refuses a filter into a system table or onto a
|
|
8
|
+
// hidden field. Each database's test file runs these cases on its own connection.
|
|
9
|
+
|
|
10
|
+
const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
|
|
11
|
+
// A request hides what only background work may see.
|
|
12
|
+
const inRequest = (caller) => caller.kind === "user" || caller.kind === "anonymous";
|
|
13
|
+
|
|
14
|
+
const supplierResource = defineTableResource({
|
|
15
|
+
name: "suppliers",
|
|
16
|
+
tableName: "suppliers",
|
|
17
|
+
ownership: "workspace",
|
|
18
|
+
searchSchema: { itemName: { type: "string", actualField: "items.name" } },
|
|
19
|
+
relationships: { items: { type: "hasMany", target: "items", foreignKey: "supplierId" } },
|
|
20
|
+
schema: {
|
|
21
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
22
|
+
name: { type: "string", required: true, indexed: true },
|
|
23
|
+
archived: { type: "boolean", defaultTo: false },
|
|
24
|
+
blocked: { type: "boolean", defaultTo: false },
|
|
25
|
+
token: { type: "string", nullable: true, hidden: true, indexed: true }
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const itemResource = (searchSchema = { supplierName: { type: "string", actualField: "suppliers.name" } }, schema = {}) => defineTableResource({
|
|
30
|
+
name: "items",
|
|
31
|
+
tableName: "items",
|
|
32
|
+
ownership: "workspace",
|
|
33
|
+
searchSchema,
|
|
34
|
+
schema: {
|
|
35
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
36
|
+
name: { type: "string", required: true, indexed: true },
|
|
37
|
+
supplierId: { type: "id", nullable: true, belongsTo: "suppliers", as: "supplier", storage: { column: "supplier_id" } },
|
|
38
|
+
...schema
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const vaultResource = defineTableResource({
|
|
43
|
+
name: "vaults",
|
|
44
|
+
tableName: "vaults",
|
|
45
|
+
ownership: "system",
|
|
46
|
+
schema: { code: { type: "string", required: true, indexed: true } }
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Suppliers in workspace 1: Acme, Bolt (archived, which only background work sees) and Crate (blocked by the items
|
|
51
|
+
* feature's contributed policy, for everyone); and an Acme in workspace 2. Workspace 1's items: Hammer twice and
|
|
52
|
+
* Recalled (which only background work sees) from Acme, Nails from Bolt, Box from Crate and Saw from workspace 2's Acme.
|
|
53
|
+
*/
|
|
54
|
+
async function suppliersAndItems(knex) {
|
|
55
|
+
await knex.schema.createTable("suppliers", (table) => {
|
|
56
|
+
table.increments("id");
|
|
57
|
+
table.integer("workspace_id").nullable();
|
|
58
|
+
table.string("name").notNullable().index();
|
|
59
|
+
table.boolean("archived").notNullable().defaultTo(false);
|
|
60
|
+
table.boolean("blocked").notNullable().defaultTo(false);
|
|
61
|
+
table.string("token").nullable();
|
|
62
|
+
});
|
|
63
|
+
await knex.schema.createTable("items", (table) => {
|
|
64
|
+
table.increments("id");
|
|
65
|
+
table.integer("workspace_id").nullable();
|
|
66
|
+
table.string("name").notNullable().index();
|
|
67
|
+
table.integer("supplier_id").nullable().index();
|
|
68
|
+
});
|
|
69
|
+
await knex("suppliers").insert([
|
|
70
|
+
{ workspace_id: 1, name: "Acme", archived: false, blocked: false },
|
|
71
|
+
{ workspace_id: 1, name: "Bolt", archived: true, blocked: false },
|
|
72
|
+
{ workspace_id: 2, name: "Acme", archived: false, blocked: false },
|
|
73
|
+
{ workspace_id: 1, name: "Crate", archived: false, blocked: true }
|
|
74
|
+
]);
|
|
75
|
+
await knex("items").insert([
|
|
76
|
+
{ workspace_id: 1, name: "Hammer", supplier_id: 1 },
|
|
77
|
+
{ workspace_id: 1, name: "Nails", supplier_id: 2 },
|
|
78
|
+
{ workspace_id: 1, name: "Saw", supplier_id: 3 },
|
|
79
|
+
{ workspace_id: 1, name: "Box", supplier_id: 4 },
|
|
80
|
+
{ workspace_id: 1, name: "Hammer", supplier_id: 1 },
|
|
81
|
+
{ workspace_id: 1, name: "Recalled", supplier_id: 1 },
|
|
82
|
+
{ workspace_id: 2, name: "Drill", supplier_id: 3 }
|
|
83
|
+
]);
|
|
84
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
85
|
+
const { suppliers } = await runtime.own("suppliers.feature", [{
|
|
86
|
+
resource: supplierResource,
|
|
87
|
+
acceptsContributions: true,
|
|
88
|
+
rowPolicy: ({ query, column, caller }) => {
|
|
89
|
+
if (inRequest(caller)) query.where(column("archived"), false);
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
}]);
|
|
93
|
+
const owned = await runtime.own("items.feature", [{
|
|
94
|
+
resource: itemResource(),
|
|
95
|
+
rowPolicy: ({ query, column, caller }) => {
|
|
96
|
+
if (inRequest(caller)) query.whereNot(column("name"), "Recalled");
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
}]);
|
|
100
|
+
owned.contributeRowPolicy("suppliers", ({ query, column }) => {
|
|
101
|
+
query.where(column("blocked"), false);
|
|
102
|
+
return true;
|
|
103
|
+
});
|
|
104
|
+
const job = runtime.declareSystemScope("items.feature", "restock every workspace")("restock").forWorkspace("1");
|
|
105
|
+
return { suppliers, items: owned.items, job: { context: job } };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const names = (records) => records.map(({ name }) => name);
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
112
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
113
|
+
*/
|
|
114
|
+
function crossTableFiltersCases(connect) {
|
|
115
|
+
return [
|
|
116
|
+
["a filter on another owner's table matches only the rows the caller's scope reads there: its ownership, its owner's row policy and the policies contributed to it", async (t) => {
|
|
117
|
+
const knex = await connect(t, "da_xt_scope");
|
|
118
|
+
const { suppliers, items, job } = await suppliersAndItems(knex);
|
|
119
|
+
const request = { context: WORKSPACE_A };
|
|
120
|
+
const itemsOf = async (supplierName, options) => names(await items.queryAll({ filters: { supplierName } }, options));
|
|
121
|
+
|
|
122
|
+
// Workspace 2's Acme is not the caller's, so Saw, which names it, matches no Acme of the caller's.
|
|
123
|
+
assert.deepEqual(await itemsOf("Acme", request), ["Hammer", "Hammer"]);
|
|
124
|
+
assert.deepEqual(await itemsOf("Acme", job), ["Hammer", "Hammer", "Recalled"]);
|
|
125
|
+
// The suppliers' owner shows an archived supplier to background work only.
|
|
126
|
+
assert.deepEqual(await itemsOf("Bolt", request), []);
|
|
127
|
+
assert.deepEqual(await itemsOf("Bolt", job), ["Nails"]);
|
|
128
|
+
// The contributed policy hides a blocked supplier from everyone.
|
|
129
|
+
assert.deepEqual(await itemsOf("Crate", request), []);
|
|
130
|
+
assert.deepEqual(await itemsOf("Crate", job), []);
|
|
131
|
+
// An aggregate filters the same way, counting each item once.
|
|
132
|
+
assert.deepEqual(await items.aggregate({ measures: { items: { count: "*" } }, filters: { supplierName: "Acme" } }, request), [{ items: 2 }]);
|
|
133
|
+
const page = await items.query({ filters: { supplierName: "Acme" }, page: { size: 1 } }, request);
|
|
134
|
+
assert.deepEqual([names(page.records), page.page.hasMore], [["Hammer"], true]);
|
|
135
|
+
|
|
136
|
+
// The other way, a supplier filtered by its items' names: each supplier once, through the items' own scope.
|
|
137
|
+
assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Hammer" } }, request)), ["Acme"]);
|
|
138
|
+
assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Recalled" } }, request)), []);
|
|
139
|
+
assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Recalled" } }, job)), ["Acme"]);
|
|
140
|
+
assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Drill" } }, request)), []);
|
|
141
|
+
}],
|
|
142
|
+
|
|
143
|
+
["own() refuses a filter that reads a system table from a table that is not one, or a field its owner hides, saying what to do instead", async (t) => {
|
|
144
|
+
const knex = await connect(t, "da_xt_refuse");
|
|
145
|
+
const owning = async (...features) => {
|
|
146
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
147
|
+
for (const [featureId, owns] of features) {
|
|
148
|
+
await runtime.own(featureId, owns);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
const vaultCode = itemResource({ vaultCode: { type: "string", actualField: "vaults.code" } }, {
|
|
152
|
+
vaultId: { type: "id", nullable: true, belongsTo: "vaults", as: "vault", storage: { column: "vault_id" } }
|
|
153
|
+
});
|
|
154
|
+
await assert.rejects(owning(["vaults.feature", [vaultResource]], ["suppliers.feature", [supplierResource]], ["items.feature", [vaultCode]]), {
|
|
155
|
+
name: "TypeError",
|
|
156
|
+
message: 'Table resource "items" filters "vaultCode" on vaults.code, which reads "vaults", a system table: only its ' +
|
|
157
|
+
"owner's system context reads it, and the filter would read it in the caller's scope, a request's too. Make " +
|
|
158
|
+
'"vaults" a table the caller\'s scope guards, or filter on a field of "items", or have the owner of "vaults" ' +
|
|
159
|
+
"answer the ids it matches (an owner API) and filter by them."
|
|
160
|
+
});
|
|
161
|
+
// The filtering table owned first: the check waits for the table it reads.
|
|
162
|
+
await assert.rejects(owning(["items.feature", [vaultCode]], ["suppliers.feature", [supplierResource]], ["vaults.feature", [vaultResource]]),
|
|
163
|
+
/filters "vaultCode" on vaults\.code, which reads "vaults", a system table/u);
|
|
164
|
+
const supplierToken = itemResource({ supplierToken: { type: "string", actualField: "suppliers.token" } });
|
|
165
|
+
await assert.rejects(owning(["vaults.feature", [vaultResource]], ["suppliers.feature", [supplierResource]], ["items.feature", [supplierToken]]),
|
|
166
|
+
/Table resource "items" filters "supplierToken" on suppliers\.token, a field "suppliers" hides: a filter on it would tell a caller who may not read it which rows hold a value\. Filter on a field "suppliers" shows, or filter on a field of "items"/u);
|
|
167
|
+
// A system table may filter on another: its reads already need a system context.
|
|
168
|
+
const ledgerResource = defineTableResource({
|
|
169
|
+
name: "ledgers",
|
|
170
|
+
tableName: "ledgers",
|
|
171
|
+
ownership: "system",
|
|
172
|
+
searchSchema: { vaultCode: { type: "string", actualField: "vaults.code" } },
|
|
173
|
+
schema: { vaultId: { type: "id", nullable: true, belongsTo: "vaults", as: "vault", storage: { column: "vault_id" } } }
|
|
174
|
+
});
|
|
175
|
+
await owning(["vaults.feature", [vaultResource, ledgerResource]]);
|
|
176
|
+
}]
|
|
177
|
+
];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export { crossTableFiltersCases };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import knexLib from "knex";
|
|
2
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
3
|
+
|
|
4
|
+
// The connection settings the runtime gives mysql2 (BIGINT as text, DATE as text, UTC).
|
|
5
|
+
const RUNTIME_MYSQL = Object.freeze({ supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" });
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A MariaDB/MySQL database of the test's own beside TEST_DB_NAME, dropped after the test. Every connection runs with
|
|
9
|
+
* MariaDB's innodb_snapshot_isolation off, the MariaDB 11.4 default (11.6 turns it on), so a test reads InnoDB's
|
|
10
|
+
* REPEATABLE READ as every supported server does by default; a server without the setting (MySQL) needs nothing.
|
|
11
|
+
* @param {import("node:test").TestContext} context
|
|
12
|
+
* @param {string} suffix The database's name after TEST_DB_NAME's.
|
|
13
|
+
*/
|
|
14
|
+
async function ownMysqlDatabase(context, suffix) {
|
|
15
|
+
const name = `${requireTestDatabase(process.env)}_${suffix}`;
|
|
16
|
+
const server = { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
|
|
17
|
+
const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
|
|
18
|
+
const [variables] = await admin.raw("SHOW VARIABLES LIKE 'innodb_snapshot_isolation'");
|
|
19
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
20
|
+
await admin.raw("CREATE DATABASE ??", [name]);
|
|
21
|
+
const setting = variables.length === 0 ? null : "SET SESSION innodb_snapshot_isolation = OFF";
|
|
22
|
+
const knex = knexLib({
|
|
23
|
+
client: "mysql2",
|
|
24
|
+
connection: { ...server, database: name, ...RUNTIME_MYSQL },
|
|
25
|
+
pool: { min: 0, max: 6, ...(setting ? { afterCreate: (connection, done) => connection.query(setting, (error) => done(error, connection)) } : {}) }
|
|
26
|
+
});
|
|
27
|
+
context.after(async () => {
|
|
28
|
+
await knex.destroy();
|
|
29
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
30
|
+
await admin.destroy();
|
|
31
|
+
});
|
|
32
|
+
return knex;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { ownMysqlDatabase };
|