@jskit-ai/resource-runtime 0.2.26 → 0.2.27
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
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Depends on json-rest-api 3.1.6 exactly (from 3.1.5): within one transaction (a handle's `withTransaction`, or a write's own), json-rest-api answers a check of a row a write links to, or of a to-one link a response shows, from the transaction's own earlier check of that row in the same scope (the same ownership, row policy and filter values) under a lock at least as strong, until the transaction sends a statement that could change the answer: an insert or update of a table the check reads, an update of a column a remembered check names (such as `workspace_id`), a delete, a savepoint's rollback, or any other statement. A check that found no row is never remembered, and nothing carries from one transaction to the next. Installing one module (a form and a module, each published from a draft version, every row naming its author and publisher) in one transaction sent 55 statements and now sends 30; 32 modules in one transaction sent 1,698 and now send 836: its checks went from 1,024 to 162, the two users every row names checked twice instead of 480 times, and each module's own new rows 5 times instead of 17 (again only after a write to their table), on MariaDB 11.4 and PostgreSQL alike. `transactionChecks.test.js` (SQLite, and PostgreSQL in CI) and `transactionChecks.mysql.test.js` compare 1 and 32 modules, and show a transaction refusing a row it removed, moved out of the caller's scope or hid, another workspace's or user's row in the same transaction, a row an earlier transaction checked, and every link refused before.
|
|
5
6
|
- Depends on json-rest-api 3.1.5 exactly (from 3.1.4), from the registry with its published integrity: a read-only builder (a `scopedQuery()`, a join source, a row policy's `ownTable()`) that json-rest-api's own query compiles as a subquery keeps its joins, where 3.1.4 dropped them and the subquery matched more rows than it should (a row policy or filter narrowing with `whereExists` over a joined subquery widened), and `lockByIds`/`lockWhere` take `lockMode: 'share'`.
|
|
6
7
|
- **Security.** A row policy's calls that are not where calls (`join`, `leftJoin`, `select` and the rest) now throw a TypeError naming the feature, the policy and the table, as the policy makes them. Its calls replay inside one `where` group, where Knex compiles predicates only and dropped a join without a word, so a policy that narrowed through a join narrowed nothing and its readers saw rows it meant to hide. A policy narrows through another table with `whereExists` over `ownTable(name)` (which may join the owner's tables) or over another owner's `joinSource({ alias }, options)`. Upgrading: a policy that called `join` now fails every read of its table; rewrite it as a `whereExists`.
|
|
7
8
|
- A row policy is told the call's options as `options`, `{ context, trx }` as the caller passed them (frozen), so a policy that reads another owner's join source passes them on: `requires.members.joinSource({ alias: "tm" }, options)` reads in the caller's scope and transaction.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/resource-runtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@jskit-ai/resource-core": "0.1.212",
|
|
19
19
|
"@jskit-ai/resource-crud-core": "0.1.214",
|
|
20
|
-
"json-rest-api": "3.1.
|
|
20
|
+
"json-rest-api": "3.1.6"
|
|
21
21
|
},
|
|
22
22
|
"description": "The resource runtime: features own their tables through it and read and write them with scoped handles on json-rest-api.",
|
|
23
23
|
"jskit": {
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
3
|
+
import { USER_EIGHT, USER_SEVEN, WORKSPACE_ONE, WORKSPACE_TWO, installModule, moduleFixture } from "./transactionChecksFixture.js";
|
|
4
|
+
|
|
5
|
+
// One transaction that installs modules links every row it writes to the users who wrote it and to the rows it wrote
|
|
6
|
+
// before. json-rest-api checks each link with a scoped read of the linked row's id, as it checks each link a response
|
|
7
|
+
// shows; within one transaction it answers a check from its own earlier check of the same row in the same scope, until
|
|
8
|
+
// the transaction sends something that could change the answer. Each database's test file runs these cases on its own
|
|
9
|
+
// connection.
|
|
10
|
+
|
|
11
|
+
// A check: a read of one table's ids and nothing else (on SQLite, the id in a CASE that keeps a large one exact).
|
|
12
|
+
const CHECK = /^select (?:distinct )?([^,*]*?) from ([`"])(\w+)\2 where /iu;
|
|
13
|
+
|
|
14
|
+
function checksOf(queries) {
|
|
15
|
+
const checks = {};
|
|
16
|
+
for (const sql of queries) {
|
|
17
|
+
const [, selected, quote, table] = CHECK.exec(sql) || [];
|
|
18
|
+
if (table && selected.includes(`${quote}${table}${quote}.${quote}id${quote}`)) {
|
|
19
|
+
checks[table] = (checks[table] || 0) + 1;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return checks;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The refusal of a link to a row the caller cannot see, however the handle's errors wrap it.
|
|
26
|
+
function refusedLink(type, id) {
|
|
27
|
+
const message = `Cannot create relationship to non-existent ${type} with id ${id}`;
|
|
28
|
+
return (error) => {
|
|
29
|
+
for (let cause = error; cause; cause = cause.cause) {
|
|
30
|
+
if (cause.message === message) {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
assert.fail(`expected "${message}", got: ${error?.message}`);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
40
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
41
|
+
*/
|
|
42
|
+
function transactionChecksCases(connect) {
|
|
43
|
+
return [
|
|
44
|
+
["a transaction installing 32 modules checks the users they name once, and each module's new rows as often as one module's", async (t) => {
|
|
45
|
+
const knex = await connect(t, "tc_counts");
|
|
46
|
+
const { handles } = await moduleFixture(knex);
|
|
47
|
+
let installed = 0;
|
|
48
|
+
const install = async (modules, { transactionEach = false } = {}) => {
|
|
49
|
+
const inOne = (count) => handles.forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
50
|
+
for (let index = 0; index < count; index += 1) {
|
|
51
|
+
installed += 1;
|
|
52
|
+
await installModule(handles, tx, { name: `module ${installed}`, author: "7", publisher: "8" });
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
const { queries } = await countQueries(knex, async () => {
|
|
56
|
+
for (const count of transactionEach ? Array(modules).fill(1) : [modules]) {
|
|
57
|
+
await inOne(count);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
return { statements: queries.length, checks: checksOf(queries) };
|
|
61
|
+
};
|
|
62
|
+
const one = await install(1);
|
|
63
|
+
const many = await install(32);
|
|
64
|
+
const each = await install(32, { transactionEach: true });
|
|
65
|
+
const counts = JSON.stringify({ one, many, each });
|
|
66
|
+
// Every module names the same two users, its author and its publisher: one transaction checks each once.
|
|
67
|
+
assert.equal(one.checks.users, 2, counts);
|
|
68
|
+
assert.equal(many.checks.users, 2, counts);
|
|
69
|
+
// A transaction per module checks them in each, as every write did before.
|
|
70
|
+
assert.equal(each.checks.users, 32 * 2, counts);
|
|
71
|
+
// A module's own new rows are checked as often in a big transaction as in a small one: the checks follow the
|
|
72
|
+
// rows written, and a write to a table makes its next check read again.
|
|
73
|
+
for (const table of ["forms", "form_versions", "modules", "module_versions"]) {
|
|
74
|
+
assert.equal(many.checks[table], 32 * one.checks[table], `${table}: ${counts}`);
|
|
75
|
+
assert.equal(each.checks[table], 32 * one.checks[table], `${table}: ${counts}`);
|
|
76
|
+
}
|
|
77
|
+
assert.deepEqual(Object.keys(many.checks).sort(), ["form_versions", "forms", "module_versions", "modules", "users"], counts);
|
|
78
|
+
// So one transaction's statements are 32 modules' worth beside its BEGIN, its COMMIT and the users' two checks.
|
|
79
|
+
const fixed = 2 + 2;
|
|
80
|
+
assert.equal(many.statements - fixed, 32 * (one.statements - fixed), counts);
|
|
81
|
+
}],
|
|
82
|
+
|
|
83
|
+
["a transaction checks a row again once it removes the row, moves it out of the caller's scope or changes what hides it", async (t) => {
|
|
84
|
+
const knex = await connect(t, "tc_changes");
|
|
85
|
+
const { handles } = await moduleFixture(knex);
|
|
86
|
+
const { drafts, formVersions, forms, memberships } = handles;
|
|
87
|
+
// User 8 leaves workspace 1 after a form named them.
|
|
88
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
89
|
+
await forms.create({ name: "a", createdBy: "8" }, tx);
|
|
90
|
+
const membership = (await memberships.queryAll({}, tx)).find(({ userId }) => String(userId) === "8");
|
|
91
|
+
await memberships.delete(membership.id, tx);
|
|
92
|
+
await forms.create({ name: "b", createdBy: "8" }, tx);
|
|
93
|
+
}), refusedLink("users", "8"));
|
|
94
|
+
// The transaction moves a form to workspace 2 by a statement of its own, after a version linked it.
|
|
95
|
+
let formId;
|
|
96
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
97
|
+
formId = (await forms.create({ name: "c", createdBy: "7" }, tx)).id;
|
|
98
|
+
await formVersions.create({ formId, status: "draft", createdBy: "7" }, tx);
|
|
99
|
+
await tx.trx("forms").where({ id: formId }).update({ workspace_id: 2 });
|
|
100
|
+
await formVersions.create({ formId, status: "draft", createdBy: "7" }, tx);
|
|
101
|
+
}), (error) => refusedLink("forms", formId)(error));
|
|
102
|
+
// The transaction deletes a draft a form linked.
|
|
103
|
+
let draftId;
|
|
104
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
105
|
+
draftId = (await drafts.create({ title: "mine" }, tx)).id;
|
|
106
|
+
const form = await forms.create({ name: "d", createdBy: "7", draftId }, tx);
|
|
107
|
+
await forms.delete(form.id, tx);
|
|
108
|
+
await drafts.delete(draftId, tx);
|
|
109
|
+
await forms.create({ name: "e", createdBy: "7", draftId }, tx);
|
|
110
|
+
}), (error) => refusedLink("drafts", draftId)(error));
|
|
111
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
112
|
+
}],
|
|
113
|
+
|
|
114
|
+
["a check made for one workspace or user never answers another's in the same transaction", async (t) => {
|
|
115
|
+
const knex = await connect(t, "tc_scopes");
|
|
116
|
+
const { handles } = await moduleFixture(knex);
|
|
117
|
+
const { drafts, forms } = handles;
|
|
118
|
+
// User 7 is a member of workspace 1 only.
|
|
119
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
120
|
+
await forms.create({ name: "a", createdBy: "7" }, tx);
|
|
121
|
+
await forms.create({ name: "b", createdBy: "7" }, { context: WORKSPACE_TWO, trx: tx.trx });
|
|
122
|
+
}), refusedLink("users", "7"));
|
|
123
|
+
// A draft is its own user's.
|
|
124
|
+
const draft = await drafts.create({ title: "mine" }, { context: USER_SEVEN });
|
|
125
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
126
|
+
await forms.create({ name: "c", createdBy: "7", draftId: draft.id }, tx);
|
|
127
|
+
await forms.create({ name: "d", createdBy: "8", draftId: draft.id }, { context: USER_EIGHT, trx: tx.trx });
|
|
128
|
+
}), refusedLink("drafts", draft.id));
|
|
129
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
130
|
+
}],
|
|
131
|
+
|
|
132
|
+
["each transaction checks again what an earlier one checked, whether it rolled back or committed", async (t) => {
|
|
133
|
+
const knex = await connect(t, "tc_next");
|
|
134
|
+
const { handles } = await moduleFixture(knex);
|
|
135
|
+
const { forms } = handles;
|
|
136
|
+
const rollBack = new Error("roll back");
|
|
137
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, async (tx) => {
|
|
138
|
+
await forms.create({ name: "a", createdBy: "7" }, tx);
|
|
139
|
+
throw rollBack;
|
|
140
|
+
}), (error) => error === rollBack);
|
|
141
|
+
await forms.withTransaction({ context: WORKSPACE_ONE }, (tx) => forms.create({ name: "b", createdBy: "8" }, tx));
|
|
142
|
+
// Users 7 and 8 leave workspace 1, outside any transaction.
|
|
143
|
+
await knex("memberships").whereIn("user_id", [7, 8]).delete();
|
|
144
|
+
for (const userId of ["7", "8"]) {
|
|
145
|
+
await assert.rejects(forms.withTransaction({ context: WORKSPACE_ONE }, (tx) => forms.create({ name: "c", createdBy: userId }, tx)),
|
|
146
|
+
refusedLink("users", userId));
|
|
147
|
+
}
|
|
148
|
+
assert.deepEqual((await knex("forms").select("name")).map(({ name }) => name), ["b"]);
|
|
149
|
+
}],
|
|
150
|
+
|
|
151
|
+
["every link refused before is refused in a transaction that checked other rows of the table: another workspace's user, a missing row, another user's draft", async (t) => {
|
|
152
|
+
const knex = await connect(t, "tc_refusals");
|
|
153
|
+
const { handles } = await moduleFixture(knex);
|
|
154
|
+
const { drafts, forms } = handles;
|
|
155
|
+
const mine = await drafts.create({ title: "mine" }, { context: USER_SEVEN });
|
|
156
|
+
const theirs = await drafts.create({ title: "theirs" }, { context: USER_EIGHT });
|
|
157
|
+
for (const [data, refusal] of [
|
|
158
|
+
[{ createdBy: "9" }, refusedLink("users", "9")],
|
|
159
|
+
[{ createdBy: "999" }, refusedLink("users", "999")],
|
|
160
|
+
[{ createdBy: "7", draftId: theirs.id }, refusedLink("drafts", theirs.id)]
|
|
161
|
+
]) {
|
|
162
|
+
await assert.rejects(forms.withTransaction({ context: USER_SEVEN }, async (tx) => {
|
|
163
|
+
await forms.create({ name: "kept", createdBy: "7", draftId: mine.id }, tx);
|
|
164
|
+
await forms.create({ name: "refused", ...data }, tx);
|
|
165
|
+
}), refusal);
|
|
166
|
+
}
|
|
167
|
+
assert.deepEqual(await knex("forms").select("name"), []);
|
|
168
|
+
}]
|
|
169
|
+
];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export { transactionChecksCases };
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
2
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
3
|
+
|
|
4
|
+
// A workspace's forms and modules, each published from a draft version, every row naming the users who wrote it: the
|
|
5
|
+
// writes one transaction makes when it installs a module. Users are one table every workspace shares, which a row
|
|
6
|
+
// policy narrows to the members of the caller's workspace; a form may start from a user's own private draft; everything
|
|
7
|
+
// else is the workspace's own.
|
|
8
|
+
|
|
9
|
+
const WORKSPACE_ONE = Object.freeze({ workspace: Object.freeze({ id: "1" }), actor: Object.freeze({ id: "7" }) });
|
|
10
|
+
const WORKSPACE_TWO = Object.freeze({ workspace: Object.freeze({ id: "2" }), actor: Object.freeze({ id: "9" }) });
|
|
11
|
+
// Users 7 and 8 in workspace 1, each signed in, so each reads their own drafts only.
|
|
12
|
+
const signedIn = (userId) => Object.freeze({
|
|
13
|
+
workspace: Object.freeze({ id: "1" }),
|
|
14
|
+
actor: Object.freeze({ id: userId }),
|
|
15
|
+
visibilityContext: Object.freeze({ userId })
|
|
16
|
+
});
|
|
17
|
+
const USER_SEVEN = signedIn("7");
|
|
18
|
+
const USER_EIGHT = signedIn("8");
|
|
19
|
+
// Users 7 and 8 are members of workspace 1; user 9 only of workspace 2.
|
|
20
|
+
const USERS = Object.freeze([
|
|
21
|
+
Object.freeze({ id: 7, name: "Ada", workspaces: [1] }),
|
|
22
|
+
Object.freeze({ id: 8, name: "Grace", workspaces: [1] }),
|
|
23
|
+
Object.freeze({ id: 9, name: "Edsger", workspaces: [2] })
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
const workspaceId = { type: "id", nullable: true, storage: { column: "workspace_id" } };
|
|
27
|
+
const userLink = (as, column, extra = {}) => ({ type: "id", belongsTo: "users", as, storage: { column }, ...extra });
|
|
28
|
+
|
|
29
|
+
const userResource = defineTableResource({
|
|
30
|
+
name: "users",
|
|
31
|
+
tableName: "users",
|
|
32
|
+
ownership: "public",
|
|
33
|
+
schema: { name: { type: "string", required: true } }
|
|
34
|
+
});
|
|
35
|
+
const membershipResource = defineTableResource({
|
|
36
|
+
name: "memberships",
|
|
37
|
+
tableName: "memberships",
|
|
38
|
+
ownership: "workspace",
|
|
39
|
+
schema: { workspaceId, userId: { type: "id", required: true, storage: { column: "user_id" } } },
|
|
40
|
+
foreignKeys: [{ columns: ["userId"], referencedTableName: "users" }]
|
|
41
|
+
});
|
|
42
|
+
const draftResource = defineTableResource({
|
|
43
|
+
name: "drafts",
|
|
44
|
+
tableName: "drafts",
|
|
45
|
+
ownership: "user",
|
|
46
|
+
schema: { userId: { type: "id", storage: { column: "user_id" } }, title: { type: "string", required: true } },
|
|
47
|
+
foreignKeys: [{ columns: ["userId"], referencedTableName: "users" }]
|
|
48
|
+
});
|
|
49
|
+
const formResource = defineTableResource({
|
|
50
|
+
name: "forms",
|
|
51
|
+
tableName: "forms",
|
|
52
|
+
ownership: "workspace",
|
|
53
|
+
schema: {
|
|
54
|
+
workspaceId,
|
|
55
|
+
name: { type: "string", required: true },
|
|
56
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
57
|
+
draftId: { type: "id", nullable: true, belongsTo: "drafts", as: "draft", storage: { column: "draft_id" } },
|
|
58
|
+
currentVersionId: { type: "id", nullable: true, belongsTo: "formVersions", as: "currentVersion", storage: { column: "current_version_id" } }
|
|
59
|
+
},
|
|
60
|
+
foreignKeys: [
|
|
61
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
62
|
+
{ columns: ["draftId"], referencedTableName: "drafts" },
|
|
63
|
+
{ columns: ["currentVersionId"], referencedTableName: "form_versions" }
|
|
64
|
+
]
|
|
65
|
+
});
|
|
66
|
+
const formVersionResource = defineTableResource({
|
|
67
|
+
name: "formVersions",
|
|
68
|
+
tableName: "form_versions",
|
|
69
|
+
ownership: "workspace",
|
|
70
|
+
schema: {
|
|
71
|
+
workspaceId,
|
|
72
|
+
formId: { type: "id", required: true, belongsTo: "forms", as: "form", storage: { column: "form_id" } },
|
|
73
|
+
status: { type: "string", required: true },
|
|
74
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
75
|
+
publishedBy: userLink("publisher", "published_by", { nullable: true })
|
|
76
|
+
},
|
|
77
|
+
foreignKeys: [
|
|
78
|
+
{ columns: ["formId"], referencedTableName: "forms" },
|
|
79
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
80
|
+
{ columns: ["publishedBy"], referencedTableName: "users" }
|
|
81
|
+
]
|
|
82
|
+
});
|
|
83
|
+
const moduleResource = defineTableResource({
|
|
84
|
+
name: "modules",
|
|
85
|
+
tableName: "modules",
|
|
86
|
+
ownership: "workspace",
|
|
87
|
+
schema: {
|
|
88
|
+
workspaceId,
|
|
89
|
+
name: { type: "string", required: true },
|
|
90
|
+
formId: { type: "id", required: true, belongsTo: "forms", as: "form", storage: { column: "form_id" } },
|
|
91
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
92
|
+
currentVersionId: { type: "id", nullable: true, belongsTo: "moduleVersions", as: "currentVersion", storage: { column: "current_version_id" } }
|
|
93
|
+
},
|
|
94
|
+
foreignKeys: [
|
|
95
|
+
{ columns: ["formId"], referencedTableName: "forms" },
|
|
96
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
97
|
+
{ columns: ["currentVersionId"], referencedTableName: "module_versions" }
|
|
98
|
+
]
|
|
99
|
+
});
|
|
100
|
+
const moduleVersionResource = defineTableResource({
|
|
101
|
+
name: "moduleVersions",
|
|
102
|
+
tableName: "module_versions",
|
|
103
|
+
ownership: "workspace",
|
|
104
|
+
schema: {
|
|
105
|
+
workspaceId,
|
|
106
|
+
moduleId: { type: "id", required: true, belongsTo: "modules", as: "module", storage: { column: "module_id" } },
|
|
107
|
+
formVersionId: { type: "id", required: true, belongsTo: "formVersions", as: "formVersion", storage: { column: "form_version_id" } },
|
|
108
|
+
status: { type: "string", required: true },
|
|
109
|
+
createdBy: userLink("creator", "created_by", { required: true }),
|
|
110
|
+
publishedBy: userLink("publisher", "published_by", { nullable: true })
|
|
111
|
+
},
|
|
112
|
+
foreignKeys: [
|
|
113
|
+
{ columns: ["moduleId"], referencedTableName: "modules" },
|
|
114
|
+
{ columns: ["formVersionId"], referencedTableName: "form_versions" },
|
|
115
|
+
{ columns: ["createdBy"], referencedTableName: "users" },
|
|
116
|
+
{ columns: ["publishedBy"], referencedTableName: "users" }
|
|
117
|
+
]
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// A request sees the users who are members of its workspace; background work sees every user.
|
|
121
|
+
function workspaceMembers({ query, column, caller, context, ownTable }) {
|
|
122
|
+
if (caller.kind === "system") {
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
const workspace = context.workspace?.id ?? context.scopeValues?.workspaceId;
|
|
126
|
+
if (!workspace) {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
query.whereIn(column("id"), ownTable("memberships").select("user_id").where("workspace_id", workspace));
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Integer keys that reference another table's increments() id, which MySQL and MariaDB make unsigned.
|
|
134
|
+
const reference = (table, column, target, { nullable = false } = {}) => {
|
|
135
|
+
const definition = table.integer(column).unsigned();
|
|
136
|
+
(nullable ? definition.nullable() : definition.notNullable()).references("id").inTable(target);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
async function createTables(knex) {
|
|
140
|
+
await knex.schema.createTable("users", (table) => {
|
|
141
|
+
table.increments("id");
|
|
142
|
+
table.string("name").notNullable();
|
|
143
|
+
});
|
|
144
|
+
await knex.schema.createTable("memberships", (table) => {
|
|
145
|
+
table.increments("id");
|
|
146
|
+
table.integer("workspace_id").nullable().index();
|
|
147
|
+
reference(table, "user_id", "users");
|
|
148
|
+
});
|
|
149
|
+
await knex.schema.createTable("drafts", (table) => {
|
|
150
|
+
table.increments("id");
|
|
151
|
+
reference(table, "user_id", "users");
|
|
152
|
+
table.string("title").notNullable();
|
|
153
|
+
});
|
|
154
|
+
await knex.schema.createTable("forms", (table) => {
|
|
155
|
+
table.increments("id");
|
|
156
|
+
table.integer("workspace_id").nullable().index();
|
|
157
|
+
table.string("name").notNullable();
|
|
158
|
+
reference(table, "created_by", "users");
|
|
159
|
+
reference(table, "draft_id", "drafts", { nullable: true });
|
|
160
|
+
table.integer("current_version_id").unsigned().nullable();
|
|
161
|
+
});
|
|
162
|
+
await knex.schema.createTable("form_versions", (table) => {
|
|
163
|
+
table.increments("id");
|
|
164
|
+
table.integer("workspace_id").nullable().index();
|
|
165
|
+
reference(table, "form_id", "forms");
|
|
166
|
+
table.string("status").notNullable();
|
|
167
|
+
reference(table, "created_by", "users");
|
|
168
|
+
reference(table, "published_by", "users", { nullable: true });
|
|
169
|
+
});
|
|
170
|
+
await knex.schema.alterTable("forms", (table) => {
|
|
171
|
+
table.foreign("current_version_id").references("id").inTable("form_versions");
|
|
172
|
+
});
|
|
173
|
+
await knex.schema.createTable("modules", (table) => {
|
|
174
|
+
table.increments("id");
|
|
175
|
+
table.integer("workspace_id").nullable().index();
|
|
176
|
+
table.string("name").notNullable();
|
|
177
|
+
reference(table, "form_id", "forms");
|
|
178
|
+
reference(table, "created_by", "users");
|
|
179
|
+
table.integer("current_version_id").unsigned().nullable();
|
|
180
|
+
});
|
|
181
|
+
await knex.schema.createTable("module_versions", (table) => {
|
|
182
|
+
table.increments("id");
|
|
183
|
+
table.integer("workspace_id").nullable().index();
|
|
184
|
+
reference(table, "module_id", "modules");
|
|
185
|
+
reference(table, "form_version_id", "form_versions");
|
|
186
|
+
table.string("status").notNullable();
|
|
187
|
+
reference(table, "created_by", "users");
|
|
188
|
+
reference(table, "published_by", "users", { nullable: true });
|
|
189
|
+
});
|
|
190
|
+
await knex.schema.alterTable("modules", (table) => {
|
|
191
|
+
table.foreign("current_version_id").references("id").inTable("module_versions");
|
|
192
|
+
});
|
|
193
|
+
await knex("users").insert(USERS.map(({ id, name }) => ({ id, name })));
|
|
194
|
+
await knex("memberships").insert(USERS.flatMap(({ id, workspaces }) => workspaces.map((workspace) => ({ workspace_id: workspace, user_id: id }))));
|
|
195
|
+
// PostgreSQL's sequence does not follow ids inserted by hand.
|
|
196
|
+
if (String(knex.client.config.client).includes("pg")) {
|
|
197
|
+
await knex.raw("SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT MAX(id) FROM users))");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The tables, their users and memberships, and the handles of one feature that owns them all.
|
|
203
|
+
* @param {import("knex").Knex} knex
|
|
204
|
+
*/
|
|
205
|
+
async function moduleFixture(knex) {
|
|
206
|
+
await createTables(knex);
|
|
207
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
208
|
+
const handles = await runtime.own("modules.feature", [
|
|
209
|
+
{ resource: userResource, rowPolicy: workspaceMembers },
|
|
210
|
+
membershipResource,
|
|
211
|
+
draftResource,
|
|
212
|
+
formResource,
|
|
213
|
+
formVersionResource,
|
|
214
|
+
moduleResource,
|
|
215
|
+
moduleVersionResource
|
|
216
|
+
]);
|
|
217
|
+
const systemContext = runtime.declareSystemScope("modules.feature", "The fixture checks every workspace's rows.");
|
|
218
|
+
return { knex, handles, system: systemContext("check the fixture's rows") };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Installs one module in the caller's transaction, as a setup service does: a form with a draft version it publishes,
|
|
223
|
+
* then a module on that form with a draft version it publishes. Every row names the users who wrote it. Answers the
|
|
224
|
+
* ids it wrote.
|
|
225
|
+
* @param {Record<string, any>} handles
|
|
226
|
+
* @param {{ context: object, trx: object }} tx
|
|
227
|
+
* @param {{ name: string, author: string, publisher: string }} module
|
|
228
|
+
*/
|
|
229
|
+
async function installModule(handles, tx, { name, author, publisher }) {
|
|
230
|
+
const { forms, formVersions, modules, moduleVersions } = handles;
|
|
231
|
+
const form = await forms.create({ name: `${name} form`, createdBy: author }, tx);
|
|
232
|
+
const formVersion = await formVersions.create({ formId: form.id, status: "draft", createdBy: author }, tx);
|
|
233
|
+
await formVersions.patch(formVersion.id, { status: "published", publishedBy: publisher }, tx);
|
|
234
|
+
await forms.patch(form.id, { currentVersionId: formVersion.id }, tx);
|
|
235
|
+
await forms.get(form.id, {}, tx);
|
|
236
|
+
const module = await modules.create({ name, formId: form.id, createdBy: author }, tx);
|
|
237
|
+
const moduleVersion = await moduleVersions.create({ moduleId: module.id, formVersionId: formVersion.id, status: "draft", createdBy: author }, tx);
|
|
238
|
+
await moduleVersions.patch(moduleVersion.id, { status: "published", publishedBy: publisher }, tx);
|
|
239
|
+
await modules.patch(module.id, { currentVersionId: moduleVersion.id }, tx);
|
|
240
|
+
return Object.freeze({ formId: form.id, formVersionId: formVersion.id, moduleId: module.id, moduleVersionId: moduleVersion.id });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export { USERS, USER_EIGHT, USER_SEVEN, WORKSPACE_ONE, WORKSPACE_TWO, installModule, moduleFixture };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
|
|
3
|
+
import { transactionChecksCases } from "./support/transactionChecksCases.js";
|
|
4
|
+
|
|
5
|
+
// MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
|
|
6
|
+
for (const [name, run] of transactionChecksCases(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 { transactionChecksCases } from "./support/transactionChecksCases.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 transactionChecksCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
|
|
7
|
+
test(name, run);
|
|
8
|
+
}
|