@jskit-ai/resource-runtime 0.2.18 → 0.2.19
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 +4 -0
- package/package.json +2 -2
- package/src/server/filterJoinSources.js +177 -0
- package/src/server/handleEveryRow.js +59 -3
- package/src/server/handleLocks.js +162 -35
- package/src/server/handleRecords.js +14 -2
- package/src/server/resourceHandle.js +6 -4
- package/src/server/resourceRuntime.js +23 -2
- package/test/filterJoinSources.mysql.test.js +8 -0
- package/test/filterJoinSources.test.js +8 -0
- package/test/lockIncludes.mysql.test.js +8 -0
- package/test/lockIncludes.test.js +8 -0
- package/test/lockedReads.mysql.test.js +72 -10
- package/test/resourceRuntime.test.js +19 -11
- package/test/support/filterJoinSourcesCases.js +256 -0
- package/test/support/lockIncludesCases.js +158 -0
- package/test/support/pagedReadsCases.js +40 -0
- package/test/support/reportsAcrossOwnersCases.js +47 -0
|
@@ -7,6 +7,7 @@ import { checkBlobReads, checkBlobValues, namedBlobs, refuseBlobsInJson } from "
|
|
|
7
7
|
import { createEveryRowReads } from "./handleEveryRow.js";
|
|
8
8
|
import { createHiddenFieldReads, createJoinSource, markHandleFunctions } from "./handleHidden.js";
|
|
9
9
|
import { createLockReads, lockModeOf } from "./handleLocks.js";
|
|
10
|
+
import { withCallOptions } from "./filterJoinSources.js";
|
|
10
11
|
import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
|
|
11
12
|
import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
|
|
12
13
|
import { valueOnlyRaw } from "./rawExpression.js";
|
|
@@ -143,8 +144,9 @@ function write(options, run) {
|
|
|
143
144
|
* @param {{ requestRowLimit: number, serverPageSize: number }} dependencies.settings
|
|
144
145
|
* @param {(name: string) => (import("@jskit-ai/resource-core/shared/tableResource").TableResource | null)} dependencies.resourceNamed
|
|
145
146
|
* The application's table resources by name, which shape included records.
|
|
147
|
+
* @param {(name: string) => ({ lockMany: Function } | null)} dependencies.handleNamed Owned tables' handles, for a lock's include.
|
|
146
148
|
*/
|
|
147
|
-
function createResourceHandle({ api, resource, hooks, settings, resourceNamed }) {
|
|
149
|
+
function createResourceHandle({ api, resource, hooks, settings, resourceNamed, handleNamed }) {
|
|
148
150
|
const name = resource.name;
|
|
149
151
|
const lockVersionField = resource.lockVersionField || "";
|
|
150
152
|
const quiet = { list: quietCollections(resource, "hydrateOnList"), view: quietCollections(resource, "hydrateOnView") };
|
|
@@ -153,11 +155,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
|
|
|
153
155
|
return api.resources[name];
|
|
154
156
|
}
|
|
155
157
|
|
|
156
|
-
/** @param {{ context?: object | null }} options */
|
|
158
|
+
/** @param {{ context?: object | null, trx?: object | null }} options The call's, which its join sources are built in. */
|
|
157
159
|
function contextOf(options) {
|
|
158
160
|
requireHandleTransaction(name, options);
|
|
159
161
|
requireOwners(name, resource.ownership, options.context);
|
|
160
|
-
return createJsonRestContext(options.context);
|
|
162
|
+
return withCallOptions(createJsonRestContext(options.context), options);
|
|
161
163
|
}
|
|
162
164
|
|
|
163
165
|
// The fields a list or a one-record read names (see requestedFields).
|
|
@@ -167,7 +169,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
|
|
|
167
169
|
// The table as a join source, with its visible columns only (see handleHidden.js).
|
|
168
170
|
const joinSource = createJoinSource({ api, resource, jsonRest, scopedQuery, column });
|
|
169
171
|
// lock, lockMany, lockWhere and claim (see handleLocks.js).
|
|
170
|
-
const { lock, lockMany, lockWhere, claim } = createLockReads({ name, resource, jsonRest, readFields, contextOf, hiddenFields });
|
|
172
|
+
const { lock, lockMany, lockWhere, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed });
|
|
171
173
|
|
|
172
174
|
/**
|
|
173
175
|
* Runs work in the caller's transaction (`options.trx`), or in one it opens,
|
|
@@ -4,6 +4,7 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
|
|
|
4
4
|
import { isTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
5
5
|
import { callerOf, createSystemContext } from "./contexts.js";
|
|
6
6
|
import { DuplicateOwnerError } from "./errors.js";
|
|
7
|
+
import { filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
|
|
7
8
|
import { createResourceHandle } from "./resourceHandle.js";
|
|
8
9
|
import { resourceScopeOptions } from "./resourceHost.js";
|
|
9
10
|
|
|
@@ -110,6 +111,8 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
|
|
|
110
111
|
const ownedByName = new Map();
|
|
111
112
|
/** @type {Map<string, string>} */
|
|
112
113
|
const ownerByTable = new Map();
|
|
114
|
+
/** @type {Map<string, object>} Each owned table's handle, by resource name: a lock's include locks through it. */
|
|
115
|
+
const handleByName = new Map();
|
|
113
116
|
// Cross-table filters whose target table no feature owns yet: they are checked when its owner owns it.
|
|
114
117
|
const pendingCrossTableFilters = [];
|
|
115
118
|
/** @type {Map<string, string>} The system scope each feature declared. */
|
|
@@ -134,6 +137,14 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
|
|
|
134
137
|
return ownedByName.get(name)?.resource ?? null;
|
|
135
138
|
}
|
|
136
139
|
|
|
140
|
+
/**
|
|
141
|
+
* The handle of the table a feature owns under `name`, or null: a lock's include locks related records through it.
|
|
142
|
+
* @param {string} name
|
|
143
|
+
*/
|
|
144
|
+
function handleNamed(name) {
|
|
145
|
+
return handleByName.get(name) ?? null;
|
|
146
|
+
}
|
|
147
|
+
|
|
137
148
|
// A SELECT-only builder over one of the feature's own tables, for a row policy's subqueries.
|
|
138
149
|
function ownTableReader(featureId, db) {
|
|
139
150
|
return function ownTable(name) {
|
|
@@ -257,15 +268,24 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
|
|
|
257
268
|
claim(featureId, resource);
|
|
258
269
|
}
|
|
259
270
|
const contributions = entries.map(() => []);
|
|
271
|
+
// Filters that read other tables through their owners' join sources (see filterJoinSources.js).
|
|
272
|
+
const searches = entries.map((entry) => filterJoinSources(featureId, entry.resource, entry.searchSchema));
|
|
260
273
|
const scopes = entries.map((entry, index) => resourceScopeOptions(entry.resource, {
|
|
261
274
|
writeSerializers: WRITE_SERIALIZERS,
|
|
262
275
|
normalizeId: entry.normalizeId,
|
|
263
276
|
rowPolicy: composedRowPolicy(featureId, entry, contributions[index], requires),
|
|
264
|
-
searchSchema:
|
|
277
|
+
searchSchema: searches[index].searchSchema,
|
|
265
278
|
queryFields: entry.queryFields
|
|
266
279
|
}));
|
|
267
280
|
checkCrossTableFilters(entries, scopes);
|
|
268
281
|
const handles = {};
|
|
282
|
+
// A join source's picker gets the feature's dependencies and its own handles, built below before any read.
|
|
283
|
+
const ownerOf = (pick) => pick({ requires, owned: handles });
|
|
284
|
+
for (const [index, { declared }] of searches.entries()) {
|
|
285
|
+
if (declared.length > 0) {
|
|
286
|
+
scopes[index].hooks = joinSourceHooks({ resourceName: entries[index].resource.name, declared, ownerOf });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
269
289
|
for (const [index, entry] of entries.entries()) {
|
|
270
290
|
const { resource } = entry;
|
|
271
291
|
ownedByName.set(resource.name, {
|
|
@@ -276,7 +296,8 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
|
|
|
276
296
|
});
|
|
277
297
|
ownerByTable.set(resource.tableName, featureId);
|
|
278
298
|
await api.addResource(resource.name, scopes[index]);
|
|
279
|
-
handles[resource.name] = createResourceHandle({ api, resource, hooks: entry.hooks, settings, resourceNamed: tableResource });
|
|
299
|
+
handles[resource.name] = createResourceHandle({ api, resource, hooks: entry.hooks, settings, resourceNamed: tableResource, handleNamed });
|
|
300
|
+
handleByName.set(resource.name, handles[resource.name]);
|
|
280
301
|
}
|
|
281
302
|
Object.defineProperty(handles, "contributeRowPolicy", {
|
|
282
303
|
value: (name, policy) => contributeRowPolicy(featureId, name, policy),
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { filterJoinSourcesCases } from "./support/filterJoinSourcesCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of filterJoinSourcesCases(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 { filterJoinSourcesCases } from "./support/filterJoinSourcesCases.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 filterJoinSourcesCases((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 { lockIncludesCases } from "./support/lockIncludesCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of lockIncludesCases(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 { lockIncludesCases } from "./support/lockIncludesCases.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 lockIncludesCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|
|
@@ -4,10 +4,10 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
|
|
|
4
4
|
import { createTestResourceRuntime } from "../src/test/index.js";
|
|
5
5
|
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
6
6
|
|
|
7
|
-
// What a lock's caller reads after the lock on MySQL and MariaDB, under InnoDB's REPEATABLE READ. A
|
|
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
|
|
7
|
+
// What a lock's caller reads after the lock on MySQL and MariaDB, under InnoDB's REPEATABLE READ. A plain read inside a
|
|
9
8
|
// 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.
|
|
9
|
+
// lock's previous holder committed, one that read before its lock does not. A lock and the records its include names
|
|
10
|
+
// are locking reads, so they read what was committed whatever that snapshot holds.
|
|
11
11
|
|
|
12
12
|
const WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
|
|
13
13
|
|
|
@@ -20,6 +20,15 @@ const seatResource = defineTableResource({
|
|
|
20
20
|
code: { type: "string", required: true }
|
|
21
21
|
}
|
|
22
22
|
});
|
|
23
|
+
const ticketResource = defineTableResource({
|
|
24
|
+
name: "tickets",
|
|
25
|
+
tableName: "tickets",
|
|
26
|
+
ownership: "workspace",
|
|
27
|
+
schema: {
|
|
28
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
29
|
+
number: { type: "string", required: true }
|
|
30
|
+
}
|
|
31
|
+
});
|
|
23
32
|
const bookingResource = defineTableResource({
|
|
24
33
|
name: "bookings",
|
|
25
34
|
tableName: "bookings",
|
|
@@ -28,6 +37,7 @@ const bookingResource = defineTableResource({
|
|
|
28
37
|
schema: {
|
|
29
38
|
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
30
39
|
seatId: { type: "id", required: true, storage: { column: "seat_id" } },
|
|
40
|
+
ticketId: { type: "id", nullable: true, belongsTo: "tickets", as: "ticket", storage: { column: "ticket_id" } },
|
|
31
41
|
guest: { type: "string", required: true }
|
|
32
42
|
}
|
|
33
43
|
});
|
|
@@ -39,14 +49,22 @@ async function database(t, suffix) {
|
|
|
39
49
|
table.integer("workspace_id").nullable();
|
|
40
50
|
table.string("code").notNullable();
|
|
41
51
|
});
|
|
52
|
+
await knex.schema.createTable("tickets", (table) => {
|
|
53
|
+
table.increments("id");
|
|
54
|
+
table.integer("workspace_id").nullable();
|
|
55
|
+
table.string("number").notNullable();
|
|
56
|
+
});
|
|
42
57
|
await knex.schema.createTable("bookings", (table) => {
|
|
43
58
|
table.increments("id");
|
|
44
59
|
table.integer("workspace_id").nullable();
|
|
45
60
|
table.integer("seat_id").notNullable().index();
|
|
61
|
+
table.integer("ticket_id").nullable();
|
|
46
62
|
table.string("guest").notNullable();
|
|
63
|
+
// lockWhere on MySQL reads through an index that starts with the ownership column.
|
|
64
|
+
table.index(["workspace_id", "seat_id"]);
|
|
47
65
|
});
|
|
48
66
|
const runtime = await createTestResourceRuntime({ knex });
|
|
49
|
-
return runtime.own("seats.feature", [seatResource, bookingResource]);
|
|
67
|
+
return runtime.own("seats.feature", [seatResource, ticketResource, bookingResource]);
|
|
50
68
|
}
|
|
51
69
|
|
|
52
70
|
/**
|
|
@@ -74,12 +92,17 @@ async function readAfterLock(t, suffix, { readFirst }) {
|
|
|
74
92
|
});
|
|
75
93
|
await held;
|
|
76
94
|
const reader = seats.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
95
|
+
try {
|
|
96
|
+
await assert.rejects(seats.lock(seatId, { ...tx, include: ["bookings"] }), /seats\.lock\(\) includes "bookings", which is no belongs-to relationship of seats/u);
|
|
97
|
+
const before = readFirst ? await guestsOf(tx) : null;
|
|
98
|
+
// The holder commits only once the reader has made its plain read, or is about to lock.
|
|
99
|
+
commit();
|
|
100
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
101
|
+
return { before, after: await guestsOf(tx) };
|
|
102
|
+
} finally {
|
|
103
|
+
// A failed step still lets the holder finish, so the test fails rather than waits.
|
|
104
|
+
commit();
|
|
105
|
+
}
|
|
83
106
|
});
|
|
84
107
|
const [, read] = await Promise.all([holder, reader]);
|
|
85
108
|
return { before: read.before?.map(({ guest }) => guest) ?? null, after: read.after.map(({ guest }) => guest) };
|
|
@@ -92,3 +115,42 @@ test("a transaction that locks first reads, after its lock, the rows the lock's
|
|
|
92
115
|
test("a transaction that made a plain read before its lock still reads that read's snapshot after the lock", async (t) => {
|
|
93
116
|
assert.deepEqual(await readAfterLock(t, "da_lr_read", { readFirst: true }), { before: [], after: [] });
|
|
94
117
|
});
|
|
118
|
+
|
|
119
|
+
test("a lock's include reads the records committed after the transaction's snapshot, which a plain read after the lock misses", async (t) => {
|
|
120
|
+
const { seats, tickets, bookings } = await database(t, "da_lr_include");
|
|
121
|
+
const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
|
|
122
|
+
let commit;
|
|
123
|
+
const committing = new Promise((resolve) => {
|
|
124
|
+
commit = resolve;
|
|
125
|
+
});
|
|
126
|
+
let holding;
|
|
127
|
+
const held = new Promise((resolve) => {
|
|
128
|
+
holding = resolve;
|
|
129
|
+
});
|
|
130
|
+
// The holder locks the seat, then adds a ticket and a booking that names it.
|
|
131
|
+
const holder = seats.withTransaction(WORKSPACE, async (tx) => {
|
|
132
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
133
|
+
const ticket = await tickets.create({ number: "T1" }, { ...tx, returning: "id" });
|
|
134
|
+
await bookings.create({ seatId, ticketId: ticket, guest: "first" }, { ...tx, returning: "none" });
|
|
135
|
+
holding();
|
|
136
|
+
await committing;
|
|
137
|
+
});
|
|
138
|
+
await held;
|
|
139
|
+
// The reader's plain read takes its snapshot before the holder commits; its lock waits for the commit.
|
|
140
|
+
const reader = seats.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
|
|
141
|
+
try {
|
|
142
|
+
const before = await bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"], include: ["ticket"] }, tx);
|
|
143
|
+
commit();
|
|
144
|
+
await seats.lock(seatId, { ...tx, fields: ["code"] });
|
|
145
|
+
const locked = await bookings.lockWhere({ seatIds: [seatId] }, { ...tx, fields: ["guest"], include: ["ticket"] });
|
|
146
|
+
const after = await bookings.queryAll({ filters: { seatIds: [seatId] }, fields: ["guest"], include: ["ticket"] }, tx);
|
|
147
|
+
return { before, locked, after };
|
|
148
|
+
} finally {
|
|
149
|
+
commit();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
const [, read] = await Promise.all([holder, reader]);
|
|
153
|
+
assert.deepEqual(read.before, []);
|
|
154
|
+
assert.deepEqual(read.locked.map(({ guest, ticketId, ticket }) => [guest, ticketId !== null && ticketId === ticket?.id, ticket?.number ?? null]), [["first", true, "T1"]]);
|
|
155
|
+
assert.deepEqual(read.after, []);
|
|
156
|
+
});
|
|
@@ -838,7 +838,7 @@ test("locks need a transaction and take only the caller's rows", async (t) => {
|
|
|
838
838
|
assert.deepEqual((await notes.lockMany([a.id, other.id], { ...txOptions, missing: "skip" })).map(({ title }) => title), ["a"]);
|
|
839
839
|
assert.deepEqual((await notes.lockWhere({ status: "queued" }, txOptions)).map(({ title }) => title), ["b"]);
|
|
840
840
|
assert.deepEqual((await notes.claim({ filters: { status: "queued" }, take: 5 }, txOptions)).map(({ id }) => String(id)), [String(b.id)]);
|
|
841
|
-
await assert.rejects(notes.claim({ status: "queued" }, { limit: 5 }, txOptions), /takes \(\{ filters, sort, take \}, options\)/u);
|
|
841
|
+
await assert.rejects(notes.claim({ status: "queued" }, { limit: 5 }, txOptions), /takes \(\{ filters, sort, take, include \}, options\)/u);
|
|
842
842
|
});
|
|
843
843
|
await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, (txOptions) => notes.lock(other.id, txOptions)), notFound);
|
|
844
844
|
});
|
|
@@ -1814,27 +1814,35 @@ test("lock, lockMany, lockWhere and claim read only the fields they name, so a r
|
|
|
1814
1814
|
assert.deepEqual(locked, [{ id: ids[0], stage: "new", vetId: "1" }]);
|
|
1815
1815
|
});
|
|
1816
1816
|
|
|
1817
|
-
test("a lock
|
|
1817
|
+
test("a lock includes its rows' related records as a read does, each locked after the rows; a collection is refused before any statement", async (t) => {
|
|
1818
1818
|
const { visits, options, ids, selects } = await createVisitFixture(t);
|
|
1819
1819
|
const refused = (method) => ({
|
|
1820
1820
|
name: "TypeError",
|
|
1821
|
-
message: new RegExp(`^visits\\.${method}\\(\\)
|
|
1821
|
+
message: new RegExp(`^visits\\.${method}\\(\\) includes "notes", which is no belongs-to relationship of visits: a lock includes only the records its rows name`, "u")
|
|
1822
1822
|
});
|
|
1823
1823
|
const statements = await selects(() => visits.withTransaction(options, async (tx) => {
|
|
1824
|
-
const including = { ...tx, include: ["customer"] };
|
|
1824
|
+
const including = { ...tx, include: ["customer", "notes"] };
|
|
1825
1825
|
await assert.rejects(visits.lock(ids[0], including), refused("lock"));
|
|
1826
1826
|
await assert.rejects(visits.lockMany(ids, including), refused("lockMany"));
|
|
1827
1827
|
await assert.rejects(visits.lockWhere({ id: ids }, including), refused("lockWhere"));
|
|
1828
1828
|
await assert.rejects(visits.claim({ filters: { id: ids } }, including), refused("claim"));
|
|
1829
|
-
await assert.rejects(visits.claim({ filters: { id: ids }, include: ["
|
|
1829
|
+
await assert.rejects(visits.claim({ filters: { id: ids }, include: ["notes"] }, tx), refused("claim"));
|
|
1830
1830
|
}));
|
|
1831
1831
|
assert.deepEqual(statements, []);
|
|
1832
|
-
//
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1832
|
+
// A lock's include answers what a read's include answers: the records left out by default stay out, the related
|
|
1833
|
+
// records nest under their relationships, and each included table is read once, after the lock's own rows.
|
|
1834
|
+
for (const include of [["customer"], ["customer", "vet"], "vet"]) {
|
|
1835
|
+
const read = await visits.queryAll({ filters: { id: ids }, include }, options);
|
|
1836
|
+
let locked;
|
|
1837
|
+
const tables = await selects(() => visits.withTransaction(options, async (tx) => {
|
|
1838
|
+
locked = await visits.lockMany(ids, { ...tx, include });
|
|
1839
|
+
}));
|
|
1840
|
+
assert.deepEqual(locked, read, JSON.stringify(include));
|
|
1841
|
+
assert.equal(tables[0], "visits", JSON.stringify(include));
|
|
1842
|
+
for (const table of ["customers", "vets"]) {
|
|
1843
|
+
assert.ok(tables.filter((name) => name === table).length <= 1, `${JSON.stringify(include)}: ${tables.join(", ")}`);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1838
1846
|
});
|
|
1839
1847
|
|
|
1840
1848
|
test("a patch that compares a lock version or onlyIf locks only the version, and compares onlyIf in SQL, hidden fields too", async (t) => {
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
3
|
+
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
5
|
+
|
|
6
|
+
// Search filters that read other tables through their owners' join sources, on every database the runtime supports:
|
|
7
|
+
// a plain read (query, queryAll, aggregate) asks which of its rows have, or lack, another owner's rows, or whether any
|
|
8
|
+
// of its own rows match, in its one statement, the other table's ownership, row policy and hidden fields deciding what
|
|
9
|
+
// the filter sees. Each database's test file runs these cases on its own connection.
|
|
10
|
+
|
|
11
|
+
const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
|
|
12
|
+
// A request hides what only background work may see.
|
|
13
|
+
const inRequest = (caller) => caller.kind === "user" || caller.kind === "anonymous";
|
|
14
|
+
|
|
15
|
+
const projectResource = defineTableResource({
|
|
16
|
+
name: "projects",
|
|
17
|
+
tableName: "projects",
|
|
18
|
+
ownership: "workspace",
|
|
19
|
+
schema: {
|
|
20
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
21
|
+
name: { type: "string", required: true }
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const taskResource = defineTableResource({
|
|
26
|
+
name: "tasks",
|
|
27
|
+
tableName: "tasks",
|
|
28
|
+
ownership: "workspace",
|
|
29
|
+
schema: {
|
|
30
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
31
|
+
projectId: { type: "id", required: true, storage: { column: "project_id" } },
|
|
32
|
+
status: { type: "string", required: true },
|
|
33
|
+
confidential: { type: "boolean", defaultTo: false },
|
|
34
|
+
reviewNote: { type: "string", nullable: true, hidden: true, storage: { column: "review_note" } }
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// The tasks' owner's join source, which the projects' feature requires as `tasks`.
|
|
39
|
+
const tasksSource = ({ requires }) => requires.tasks;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The projects owner's search filters, each reading the tasks through their owner's join source, or the projects
|
|
43
|
+
* themselves through the feature's own handle.
|
|
44
|
+
*/
|
|
45
|
+
const projectSearch = Object.freeze({
|
|
46
|
+
// Projects with a task in this status.
|
|
47
|
+
taskStatus: {
|
|
48
|
+
type: "string",
|
|
49
|
+
joinSources: { k: tasksSource },
|
|
50
|
+
applyFilter(query, status, { column, joinSource }) {
|
|
51
|
+
const task = joinSource("k");
|
|
52
|
+
query.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("status"), status));
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
// Projects with no task the caller sees (true), or with one (false).
|
|
56
|
+
idle: {
|
|
57
|
+
type: "boolean",
|
|
58
|
+
joinSources: { k: tasksSource },
|
|
59
|
+
applyFilter(query, idle, { column, joinSource }) {
|
|
60
|
+
const task = joinSource("k");
|
|
61
|
+
const tasks = task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id"));
|
|
62
|
+
if (idle) {
|
|
63
|
+
query.whereNotExists(tasks);
|
|
64
|
+
} else {
|
|
65
|
+
query.whereExists(tasks);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
// Projects named like the term; when no project the caller sees is, those with a task in the term's status.
|
|
70
|
+
named: {
|
|
71
|
+
type: "string",
|
|
72
|
+
joinSources: { k: tasksSource, other: ({ owned }) => owned.projects },
|
|
73
|
+
applyFilter(query, term, { column, joinSource }) {
|
|
74
|
+
const other = joinSource("other");
|
|
75
|
+
const task = joinSource("k");
|
|
76
|
+
query.where((match) => match
|
|
77
|
+
.where(column("name"), "like", `%${term}%`)
|
|
78
|
+
.orWhere((fallback) => fallback
|
|
79
|
+
.whereNotExists(other.query.select(other.column("id")).where(other.column("name"), "like", `%${term}%`))
|
|
80
|
+
.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("status"), term))));
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
// A filter on a column the tasks' join source does not carry.
|
|
84
|
+
reviewed: {
|
|
85
|
+
type: "string",
|
|
86
|
+
joinSources: { k: tasksSource },
|
|
87
|
+
applyFilter(query, note, { column, joinSource }) {
|
|
88
|
+
const task = joinSource("k");
|
|
89
|
+
query.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("reviewNote"), note));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Workspace 1's projects Alpha (an open and a done task), Beta (a done task, and an open task of workspace 2's that
|
|
96
|
+
* names it) and Gamma (a confidential open task, which only background work sees); workspace 2's Delta (an open task).
|
|
97
|
+
*/
|
|
98
|
+
async function projectsAndTasks(knex) {
|
|
99
|
+
await knex.schema.createTable("projects", (table) => {
|
|
100
|
+
table.increments("id");
|
|
101
|
+
table.integer("workspace_id").nullable().index();
|
|
102
|
+
table.string("name").notNullable();
|
|
103
|
+
});
|
|
104
|
+
await knex.schema.createTable("tasks", (table) => {
|
|
105
|
+
table.increments("id");
|
|
106
|
+
table.integer("workspace_id").nullable();
|
|
107
|
+
table.integer("project_id").notNullable().index();
|
|
108
|
+
table.string("status").notNullable();
|
|
109
|
+
table.boolean("confidential").notNullable().defaultTo(false);
|
|
110
|
+
table.string("review_note").nullable();
|
|
111
|
+
});
|
|
112
|
+
await knex("projects").insert([
|
|
113
|
+
{ workspace_id: 1, name: "Alpha" },
|
|
114
|
+
{ workspace_id: 1, name: "Beta" },
|
|
115
|
+
{ workspace_id: 1, name: "Gamma" },
|
|
116
|
+
{ workspace_id: 2, name: "Delta" }
|
|
117
|
+
]);
|
|
118
|
+
await knex("tasks").insert([
|
|
119
|
+
{ workspace_id: 1, project_id: 1, status: "open", confidential: false, review_note: "ok" },
|
|
120
|
+
{ workspace_id: 1, project_id: 1, status: "done", confidential: false },
|
|
121
|
+
{ workspace_id: 1, project_id: 2, status: "done", confidential: false },
|
|
122
|
+
{ workspace_id: 1, project_id: 3, status: "open", confidential: true },
|
|
123
|
+
{ workspace_id: 2, project_id: 4, status: "open", confidential: false },
|
|
124
|
+
{ workspace_id: 2, project_id: 2, status: "open", confidential: false }
|
|
125
|
+
]);
|
|
126
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
127
|
+
const { tasks } = await runtime.own("tasks.feature", [{
|
|
128
|
+
resource: taskResource,
|
|
129
|
+
rowPolicy: ({ query, column, caller }) => {
|
|
130
|
+
if (inRequest(caller)) query.where(column("confidential"), false);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
}]);
|
|
134
|
+
const { projects } = await runtime.own("projects.feature", [{ resource: projectResource, searchSchema: projectSearch }], { requires: { tasks } });
|
|
135
|
+
const job = runtime.declareSystemScope("projects.feature", "review every workspace's projects")("review").forWorkspace("1");
|
|
136
|
+
return { runtime, projects, tasks, job: { context: job } };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const names = (rows) => rows.map(({ name }) => name);
|
|
140
|
+
const sorted = { sort: ["id"] };
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
144
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
145
|
+
*/
|
|
146
|
+
function filterJoinSourcesCases(connect) {
|
|
147
|
+
return [
|
|
148
|
+
["a search filter asks, in a plain read's one statement, which of its rows have or lack another owner's rows, through that owner's join source and row policy", async (t) => {
|
|
149
|
+
const knex = await connect(t, "da_fjs_exists");
|
|
150
|
+
const { projects, job } = await projectsAndTasks(knex);
|
|
151
|
+
const request = { context: WORKSPACE_A };
|
|
152
|
+
|
|
153
|
+
const open = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { taskStatus: "open" } }, request));
|
|
154
|
+
// Beta's open task is workspace 2's, and Gamma's is confidential.
|
|
155
|
+
assert.deepEqual([names(open.result), open.count], [["Alpha"], 1]);
|
|
156
|
+
assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { taskStatus: "open" } }, job)), ["Alpha", "Gamma"]);
|
|
157
|
+
assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { taskStatus: "done" } }, request)), ["Alpha", "Beta"]);
|
|
158
|
+
|
|
159
|
+
const idle = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { idle: true } }, request));
|
|
160
|
+
assert.deepEqual([names(idle.result), idle.count], [["Gamma"], 1]);
|
|
161
|
+
assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: true } }, job)), []);
|
|
162
|
+
assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: false } }, request)), ["Alpha", "Beta"]);
|
|
163
|
+
|
|
164
|
+
// A page, an aggregate and a join source take the filter as they take any other.
|
|
165
|
+
const page = await countQueries(knex, () => projects.query({ ...sorted, filters: { idle: false }, page: { size: 1 } }, request));
|
|
166
|
+
assert.deepEqual([names(page.result.records), page.result.page.hasMore, page.count], [["Alpha"], true, 1]);
|
|
167
|
+
const counted = await countQueries(knex, () => projects.aggregate({ measures: { projects: { count: "*" } }, filters: { taskStatus: "done" } }, request));
|
|
168
|
+
assert.deepEqual([counted.result, counted.count], [[{ projects: 2 }], 1]);
|
|
169
|
+
const source = await projects.joinSource({ alias: "p", filters: { idle: true } }, request);
|
|
170
|
+
assert.deepEqual(names(await source.query.select({ name: source.column("name") })), ["Gamma"]);
|
|
171
|
+
const pages = [];
|
|
172
|
+
for await (const records of projects.queryPages({ filters: { taskStatus: "done" } }, request)) {
|
|
173
|
+
pages.push(names(records));
|
|
174
|
+
}
|
|
175
|
+
assert.deepEqual(pages, [["Alpha", "Beta"]]);
|
|
176
|
+
}],
|
|
177
|
+
|
|
178
|
+
["a search filter asks whether any of the caller's own rows match, through the feature's own handle, and falls back on another owner's rows", async (t) => {
|
|
179
|
+
const knex = await connect(t, "da_fjs_own");
|
|
180
|
+
const { projects } = await projectsAndTasks(knex);
|
|
181
|
+
const request = { context: WORKSPACE_A };
|
|
182
|
+
const read = async (term) => {
|
|
183
|
+
const { result, count } = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { named: term } }, request));
|
|
184
|
+
return [names(result), count];
|
|
185
|
+
};
|
|
186
|
+
assert.deepEqual(await read("lph"), [["Alpha"], 1]);
|
|
187
|
+
// No project the caller sees is named like "done" (workspace 2's Delta is not either), so the tasks decide.
|
|
188
|
+
assert.deepEqual(await read("done"), [["Alpha", "Beta"], 1]);
|
|
189
|
+
// Delta matches "elt", but it is workspace 2's, so workspace 1's projects fall back on their tasks, of which none
|
|
190
|
+
// is in the status "elt".
|
|
191
|
+
assert.deepEqual(await read("elt"), [[], 1]);
|
|
192
|
+
}],
|
|
193
|
+
|
|
194
|
+
["a join source in a filter carries no hidden column but the ownership fields, as a report's does", async (t) => {
|
|
195
|
+
const knex = await connect(t, "da_fjs_hidden");
|
|
196
|
+
const { projects, job } = await projectsAndTasks(knex);
|
|
197
|
+
for (const options of [{ context: WORKSPACE_A }, job]) {
|
|
198
|
+
await assert.rejects(projects.queryAll({ filters: { reviewed: "ok" } }, options),
|
|
199
|
+
/tasks\.joinSource\(\) carries no hidden field but its ownership fields, so it has no column for "reviewNote"/u);
|
|
200
|
+
}
|
|
201
|
+
}],
|
|
202
|
+
|
|
203
|
+
["own() refuses, at startup, join sources it cannot use: no alias map, a name that is no alias, an owner that is no function, a filter with no applyFilter", async (t) => {
|
|
204
|
+
const knex = await connect(t, "da_fjs_startup");
|
|
205
|
+
await knex.schema.createTable("things", (table) => {
|
|
206
|
+
table.increments("id");
|
|
207
|
+
table.integer("workspace_id").nullable();
|
|
208
|
+
table.string("name").notNullable();
|
|
209
|
+
});
|
|
210
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
211
|
+
const thing = defineTableResource({
|
|
212
|
+
name: "things",
|
|
213
|
+
tableName: "things",
|
|
214
|
+
ownership: "workspace",
|
|
215
|
+
schema: { workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } }, name: { type: "string" } }
|
|
216
|
+
});
|
|
217
|
+
const owning = (entry) => runtime.own("things.feature", [{ resource: thing, searchSchema: { linked: { type: "string", ...entry } } }]);
|
|
218
|
+
const applyFilter = () => {};
|
|
219
|
+
await assert.rejects(owning({ joinSources: {}, applyFilter }), /filter "linked" of "things" joinSources must name each join source by its alias/u);
|
|
220
|
+
await assert.rejects(owning({ joinSources: { "1k": () => null }, applyFilter }), /names the join source "1k", which is no alias/u);
|
|
221
|
+
await assert.rejects(owning({ joinSources: { k: "tasks" }, applyFilter }), /join source "k" must be a function answering its owner/u);
|
|
222
|
+
await assert.rejects(owning({ joinSources: { k: () => null } }), /reads join sources, so it takes an applyFilter\(query, value, \{ column, joinSource \}\) and no oneOf/u);
|
|
223
|
+
// The table resource's own search names no feature to answer its join sources.
|
|
224
|
+
const sharedSearch = defineTableResource({ ...thing, searchSchema: { linked: { type: "string", joinSources: { k: () => null }, applyFilter } } });
|
|
225
|
+
await assert.rejects(runtime.own("things.feature", [sharedSearch]),
|
|
226
|
+
/filter "linked" of "things" names joinSources in the table resource, which names no feature to answer them; give the filter in the owns entry's searchSchema/u);
|
|
227
|
+
// Nothing was owned by the refused calls, so a correct declaration owns the table.
|
|
228
|
+
const { things } = await owning({ joinSources: { k: () => null }, applyFilter });
|
|
229
|
+
await assert.rejects(things.queryAll({ filters: { linked: "x" } }, { context: WORKSPACE_A }), /things filter "linked" join source "k" names no owner with joinSource\(\{ alias \}, options\)/u);
|
|
230
|
+
}],
|
|
231
|
+
|
|
232
|
+
["a write or a lock that chooses its rows by a join-source filter is refused on MySQL and MariaDB, which read the source from the snapshot; elsewhere it chooses the rows the filter matches", async (t) => {
|
|
233
|
+
const knex = await connect(t, "da_fjs_writes");
|
|
234
|
+
const { projects } = await projectsAndTasks(knex);
|
|
235
|
+
const request = { context: WORKSPACE_A };
|
|
236
|
+
const mysql = knex.client.config.client === "mysql2";
|
|
237
|
+
if (mysql) {
|
|
238
|
+
// A write answers json-rest-api's RestApiWriteError, whose cause is the refusal, as for a filter on another table's field.
|
|
239
|
+
const refused = (method) => (error) => {
|
|
240
|
+
const refusal = error.name === "RestApiWriteError" ? error.cause : error;
|
|
241
|
+
return refusal.name === "RestApiValidationError" &&
|
|
242
|
+
new RegExp(`${method} on 'projects' filters "idle" through another table's join source, which MySQL and MariaDB read from the transaction snapshot`, "u").test(refusal.message);
|
|
243
|
+
};
|
|
244
|
+
await assert.rejects(projects.patchWhere({ idle: true }, { name: "Quiet" }, request), refused("patchWhere"));
|
|
245
|
+
await assert.rejects(projects.withTransaction(request, (tx) => projects.lockWhere({ idle: true }, tx)), refused("lockWhere"));
|
|
246
|
+
assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: true } }, request)), ["Gamma"]);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
assert.deepEqual(names(await projects.withTransaction(request, (tx) => projects.lockWhere({ idle: true }, { ...tx, fields: ["name"] }))), ["Gamma"]);
|
|
250
|
+
assert.deepEqual(await projects.patchWhere({ idle: true }, { name: "Quiet" }, { ...request, returning: "ids" }), ["3"]);
|
|
251
|
+
assert.deepEqual(names(await projects.queryAll(sorted, request)), ["Alpha", "Beta", "Quiet"]);
|
|
252
|
+
}]
|
|
253
|
+
];
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export { filterJoinSourcesCases };
|