@jskit-ai/resource-runtime 0.2.47 → 0.2.48

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/package.json +3 -3
  3. package/src/server/resourceHost.js +22 -2
  4. package/src/test/index.js +19 -2
  5. package/test/blobFields.test.js +1 -1
  6. package/test/callSettings.test.js +1 -1
  7. package/test/countOnlyTable.test.js +1 -1
  8. package/test/crossTableFilters.test.js +1 -1
  9. package/test/entrypoints.boundary.test.js +34 -1
  10. package/test/filterJoinSources.test.js +1 -1
  11. package/test/hiddenFields.test.js +3 -1
  12. package/test/lateRequires.test.js +1 -1
  13. package/test/lockIncludes.test.js +1 -1
  14. package/test/lockPolicy.test.js +1 -1
  15. package/test/lockWhereOrder.test.js +1 -1
  16. package/test/lostInsertRace.test.js +1 -1
  17. package/test/pagedReads.test.js +1 -1
  18. package/test/policyTransaction.test.js +1 -1
  19. package/test/queryFields.test.js +1 -1
  20. package/test/reportsAcrossOwners.test.js +1 -1
  21. package/test/requestCallOptions.test.js +1 -1
  22. package/test/resourceRuntime.test.js +16 -7
  23. package/test/storedSource.test.js +1 -1
  24. package/test/support/mysqlDatabase.js +5 -28
  25. package/test/testHelpers.test.js +26 -1
  26. package/test/transactionChecks.test.js +1 -1
  27. package/test/blobFields.mysql.test.js +0 -8
  28. package/test/countOnlyTable.mysql.test.js +0 -8
  29. package/test/crossTableFilters.mysql.test.js +0 -8
  30. package/test/filterJoinSources.mysql.test.js +0 -8
  31. package/test/lateRequires.mysql.test.js +0 -8
  32. package/test/lockIncludes.mysql.test.js +0 -8
  33. package/test/lockPolicy.mysql.test.js +0 -8
  34. package/test/lockWhereOrder.mysql.test.js +0 -8
  35. package/test/pagedReads.mysql.test.js +0 -8
  36. package/test/policyTransaction.mysql.test.js +0 -8
  37. package/test/reportsAcrossOwners.mysql.test.js +0 -8
  38. package/test/storedSource.mysql.test.js +0 -8
  39. package/test/transactionChecks.mysql.test.js +0 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.3.3 exactly (from 3.3.2): on a descending sort, rows tied on its last key come in descending id order (the id that breaks ties takes the last key's direction), so MySQL and MariaDB read a descending page from an index leading with that key instead of sorting every row, and leave out the `IS NULL` term where the server already places NULLs last; and capabilities a start could not observe (the server not up yet) are observed again on the next storage call until that succeeds.
6
+ - json-rest-api's log details reach the application's log: `createResourceHost` hands each of json-rest-api's (message, details) calls to the runtime logger as pino's (fields, message), where pino dropped what followed the message. A database version observation that fails at boot now logs its backend and error ("Database version observation failed", `backend`, `phase`, `error`), "Database capabilities detected:" its database, version and window functions, and every json-rest-api warning and error its details. A detail that is not one object is logged as `details`; a message with none stays a message alone; trace and fatal reach a logger that has them.
7
+ - `createTestResourceRuntime({ createTables: true })` and `startTestFeatures({ createTables: true })` create each owned table after the tables its belongs-to fields reference, where they followed the order the resources were owned in: on MySQL, MariaDB and PostgreSQL, which check a foreign key as its table is created, a table that references one owned after it was refused (MariaDB: `Foreign key constraint is incorrectly formed`, for workspaces-core's memberships before its invitations). `./test`'s `createPackageTestKnex` gives a `DB_CLIENT=mysql2` run a MySQL or MariaDB database per test (see database-runtime), so the package's own data tests run on MariaDB in such a run, as they run on PostgreSQL in a `pg` one; the thirteen `*.mysql.test.js` files that ran the same cases on a database of their own are gone, and three fixtures (`notes`, `visits`, `cards`) carry the workspace index `lockWhere` needs on MySQL and MariaDB.
5
8
  - Depends on json-rest-api 3.3.2 exactly (from 3.3.1): on MariaDB a locking read with a list of 1,000 values or more (`in_predicate_conversion_threshold`), of the column's type, was planned as a join with a table of the values, which could read a key's leading columns and lock every row they matched: a `lockWhere` of 1,000 records' current revisions by record and revision number held every revision of those records. Every lock (`lock`, `lockMany`, `lockWhere`, `lockPages`, `claim`, a locking `aggregate`), its link checks and a write's lock of the records it links to now send a longer list as an OR of lists below the server's threshold, and hold the rows the list names alone; a write's lock of its targets reads their primary key on MySQL and MariaDB, so on MariaDB a list naming much of the table is no longer read by scanning it, holding every owner's rows.
6
9
  - A lock's `include` reads its own rows' links through the primary key on MySQL and MariaDB (`FORCE INDEX (PRIMARY)`), in lists below MariaDB's `in_predicate_conversion_threshold`: on MariaDB a lock of 1,000 of a table's 2,400 rows with an include read its links by scanning the whole table and held every row, other owners' included, until commit, and now holds those rows alone. (MySQL 8.4 can still read a list that names a large share of a small table through the whole primary key, as json-rest-api's scoped-reads guide says.)
7
10
  - Depends on json-rest-api 3.3.1 exactly (from 3.3.0): on MySQL and MariaDB a lock's to-one link check (in `lock`, `lockMany`, `lockWhere` and `lockPages`) reads the linked table through its primary key (`FORCE INDEX (PRIMARY)`) and holds the linked rows alone, where it could read and hold, until commit, every row of the caller's range of an index that starts with the ownership columns, or, on MariaDB with a long id list, every row of the table, other owners' rows too.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.47",
3
+ "version": "0.2.48",
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.224",
19
19
  "@jskit-ai/resource-crud-core": "0.1.226",
20
- "json-rest-api": "3.3.2"
20
+ "json-rest-api": "3.3.3"
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": {
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.283",
67
+ "@jskit-ai/database-runtime": "0.1.284",
68
68
  "@jskit-ai/kernel": "0.2.33"
69
69
  }
70
70
  }
@@ -639,13 +639,33 @@ async function returnBadRequestWhenJsonRestFieldsetInvalid(run) {
639
639
  }
640
640
  }
641
641
 
642
+ const JSON_REST_LOG_LEVELS = Object.freeze(["trace", "debug", "info", "warn", "error", "fatal"]);
643
+
644
+ /**
645
+ * json-rest-api writes (message, ...details), console's order. The runtime logger takes pino's (fields, message),
646
+ * and pino drops what follows a message with no %-placeholder: a starter booted against an unreachable database
647
+ * logged "Database version observation failed" with neither its backend nor its error. So each json-rest-api
648
+ * detail reaches the runtime logger first, as its fields: one object as it is, anything else as `details`.
649
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
650
+ */
651
+ function jsonRestApiLogger(logger) {
652
+ return Object.fromEntries(JSON_REST_LOG_LEVELS.map((level) => [
653
+ level,
654
+ // readable-check: allow optional-call - input validation: the runtime logger has debug, info, warn and error; trace and fatal are pino's own
655
+ (message, ...details) => (details.length === 0
656
+ ? logger[level]?.(message)
657
+ : logger[level]?.(details.length === 1 && isRecord(details[0]) ? details[0] : { details }, message))
658
+ ]));
659
+ }
660
+
642
661
  /**
643
662
  * The json-rest-api instance behind the resource runtime: its REST, query
644
663
  * projection, Knex, row policy and autofilter plugins, with JSKIT's ownership
645
664
  * presets and the resolvers that read a context's workspace and user.
646
665
  * @param {object} dependencies
647
666
  * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
648
- * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger Receives json-rest-api's log calls.
667
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger Receives json-rest-api's log
668
+ * calls, each detail first, as its fields (jsonRestApiLogger).
649
669
  */
650
670
  async function createResourceHost({ knex, logger }) {
651
671
  // readable-check: allow method-probe - input validation: the application passes its own Knex instance
@@ -660,7 +680,7 @@ async function createResourceHost({ knex, logger }) {
660
680
  /** @type {import("json-rest-api").JsonRestApi<Record<string, import("./types.js").JsonRestResource>>} */
661
681
  const api = new JsonRestApi({
662
682
  name: "jskit-internal-json-rest-api",
663
- logger
683
+ logger: jsonRestApiLogger(logger)
664
684
  });
665
685
 
666
686
  // A numbered page is one statement: json-rest-api counts no rows for it.
package/src/test/index.js CHANGED
@@ -12,11 +12,28 @@ import { expectScoped } from "./expectScoped.js";
12
12
  // Tables every migrated database has that no feature owns: the migration ledger.
13
13
  const MIGRATION_TABLES = Object.freeze(["knex_migrations", "knex_migrations_lock"]);
14
14
 
15
+ // The owned resources' names, each after the ones its belongsTo fields name among them, so MySQL, MariaDB and
16
+ // PostgreSQL, which check a foreign key as its table is created, find the table it references. A cycle keeps the
17
+ // order the resources were owned in.
18
+ function inCreationOrder(resources) {
19
+ const pending = new Map(resources.map((resource) => [resource.name, resource]));
20
+ const waits = (resource) => Object.values(resource.schema)
21
+ .some(({ belongsTo }) => belongsTo !== resource.name && pending.has(belongsTo));
22
+ const ordered = [];
23
+ while (pending.size > 0) {
24
+ const next = [...pending.values()].find((resource) => !waits(resource)) ?? pending.values().next().value;
25
+ pending.delete(next.name);
26
+ ordered.push(next.name);
27
+ }
28
+ return ordered;
29
+ }
30
+
15
31
  /**
16
32
  * A resource runtime on the test's own Knex, for a package test that owns
17
33
  * tables without booting a server: `runtime.own(featureId, owns)` answers handles.
18
34
  * With `createTables`, own() also creates each owned table from its resource's
19
- * schema, for a SQLite test whose shipped migrations are written for another database.
35
+ * schema, each after the tables its belongs-to fields reference, for a test whose
36
+ * shipped migrations it does not run (on SQLite, they are written for another database).
20
37
  * `hostHooks` are json-rest-api hooks the test installs on the runtime's host,
21
38
  * such as an afterCommit that fails on request.
22
39
  * @param {object} options
@@ -40,7 +57,7 @@ async function createTestResourceRuntime({ knex, logger = silentLogger, requestR
40
57
  ...runtime,
41
58
  async own(featureId, owns, options) {
42
59
  const handles = await runtime.own(featureId, owns, options);
43
- for (const name of Object.keys(handles)) {
60
+ for (const name of inCreationOrder(Object.keys(handles).map((owned) => runtime.tableResource(owned)))) {
44
61
  await api.resources[name].createKnexTable();
45
62
  }
46
63
  return handles;
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { blobFieldsCases } from "./support/blobFieldsCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of blobFieldsCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -4,7 +4,7 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
4
4
  import { passedOn } from "../src/server/index.js";
5
5
  import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
6
6
 
7
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
7
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
8
8
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
9
9
 
10
10
  // A call's settings (returning, missing, format, lockVersion...) are for that one call. What it hands on, to the work
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { countOnlyTableCases } from "./support/countOnlyTableCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of countOnlyTableCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { crossTableFiltersCases } from "./support/crossTableFiltersCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of crossTableFiltersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -184,12 +184,45 @@ test("createResourceHost uses the v2 runtime and the logger it is given", async
184
184
  assert.equal(api.vars.returning, "full");
185
185
  assert.equal(api.options.logging, undefined);
186
186
  api.log.error("failure", { code: "example" });
187
- assert.deepEqual(messages, [["failure", { code: "example" }]]);
187
+ assert.deepEqual(messages, [[{ code: "example" }, "failure"]]);
188
188
 
189
189
  const provided = await ResourceRuntimeProvider.setup({ database: { knex: fakeKnex }, logger: silentLogger });
190
190
  assert.deepEqual(Object.keys(provided), ["resources"]);
191
191
  });
192
192
 
193
+ test("createResourceHost hands each json-rest-api detail to the runtime logger as its fields, before the message", async () => {
194
+ // The runtime logger is pino's, (fields, message): pino drops what follows a message with no %-placeholder, where
195
+ // json-rest-api puts its details, so a starter booted against an unreachable database logged "Database version
196
+ // observation failed" with neither its backend nor its error.
197
+ const refused = Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:9"), { code: "ECONNREFUSED" });
198
+ const unreachableKnex = Object.assign(() => {}, {
199
+ client: { config: { client: "mysql2" } },
200
+ raw: (sql) => sql,
201
+ async first() {
202
+ throw refused;
203
+ },
204
+ transaction() {}
205
+ });
206
+ const calls = [];
207
+ const record = (level) => (...args) => calls.push({ level, args });
208
+
209
+ await createResourceHost({ knex: unreachableKnex, logger: { ...silentLogger, info: record("info"), warn: record("warn") } });
210
+
211
+ const logged = (message) => calls.find(({ args }) => args.includes(message));
212
+ const observation = logged("Database version observation failed");
213
+ assert.equal(observation?.level, "warn", JSON.stringify(calls));
214
+ const [fields, message] = observation.args;
215
+ assert.equal(message, "Database version observation failed");
216
+ assert.equal(fields.backend, "mysql2");
217
+ assert.equal(fields.phase, "version-observation");
218
+ assert.match(JSON.stringify(fields.error), /connect ECONNREFUSED 127\.0\.0\.1:9/);
219
+ assert.deepEqual(logged("Database capabilities detected:").args,
220
+ [{ database: "MySQL", version: "unknown", windowFunctions: false }, "Database capabilities detected:"]);
221
+ // A message with no details stays a message alone.
222
+ assert.deepEqual(logged("RestApiKnexPlugin installed - basic CRUD operations ready").args,
223
+ ["RestApiKnexPlugin installed - basic CRUD operations ready"]);
224
+ });
225
+
193
226
  test("createResourceHost installs row policies before resources are added", async () => {
194
227
  const fakeKnex = Object.assign(() => {}, {
195
228
  client: {
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { filterJoinSourcesCases } from "./support/filterJoinSourcesCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of filterJoinSourcesCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -6,7 +6,7 @@ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
6
6
  import { withoutHiddenFields } from "../src/server/index.js";
7
7
  import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
8
8
 
9
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
9
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
10
10
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
11
11
 
12
12
  const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
@@ -23,6 +23,8 @@ async function createCardFixture(t) {
23
23
  table.boolean("sent");
24
24
  table.integer("views");
25
25
  table.dateTime("issued_at");
26
+ // An index that reads a workspace's rows in id order, which lockWhere and lockPages need on MySQL and MariaDB.
27
+ table.index(["workspace_id"], "cards_workspace");
26
28
  });
27
29
  await knex("cards").insert([
28
30
  { workspace_id: 1, title: "Rex", public_token: "t1", sent: 1, views: 3 },
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { lateRequiresCases } from "./support/lateRequiresCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of lateRequiresCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { lockIncludesCases } from "./support/lockIncludesCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of lockIncludesCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { lockPolicyCases } from "./support/lockPolicyCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of lockPolicyCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { lockWhereOrderCases } from "./support/lockWhereOrderCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of lockWhereOrderCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -4,7 +4,7 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
4
4
  import { isDuplicateEntryError, retryLostInsertRace } from "@jskit-ai/database-runtime/shared";
5
5
  import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
6
6
 
7
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
7
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
8
8
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
9
9
 
10
10
  const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { pagedReadsCases } from "./support/pagedReadsCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of pagedReadsCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { policyTransactionCases } from "./support/policyTransactionCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of policyTransactionCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -3,7 +3,7 @@ import test from "node:test";
3
3
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
4
  import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
5
5
 
6
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
7
7
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
8
8
 
9
9
  const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { reportsAcrossOwnersCases } from "./support/reportsAcrossOwnersCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of reportsAcrossOwnersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -112,7 +112,7 @@ function fastifyStub() {
112
112
  }
113
113
 
114
114
  test("a hand route's callOptions() scope user, workspace and workspace_user tables as the same request's action", async (t) => {
115
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
115
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
116
116
  const knex = await createPackageTestKnex(t, { environment: process.env });
117
117
  for (const [table, columns] of [["bookmarks", ["user_id"]], ["notes", ["workspace_id"]], ["pins", ["workspace_id", "user_id"]]]) {
118
118
  await knex.schema.createTable(table, (builder) => {
@@ -21,7 +21,7 @@ import { isLostDuplicateInsertRace } from "@jskit-ai/database-runtime/shared";
21
21
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
22
22
  import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
23
23
 
24
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
24
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
25
25
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
26
26
 
27
27
  const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
@@ -56,6 +56,8 @@ async function createFixture(t, { requestRowLimit, owns = [noteResource()] } = {
56
56
  table.string("title").notNullable();
57
57
  table.string("status").notNullable().defaultTo("open");
58
58
  table.integer("lock_version").notNullable().defaultTo(0);
59
+ // An index that reads a workspace's rows in id order, which lockWhere and lockPages need on MySQL and MariaDB.
60
+ table.index(["workspace_id"], "notes_workspace");
59
61
  });
60
62
  const runtime = await createTestResourceRuntime({ knex, requestRowLimit });
61
63
  const resources = await runtime.own("notes.feature", owns);
@@ -1961,6 +1963,8 @@ async function createVisitFixture(t) {
1961
1963
  table.string("internal_code");
1962
1964
  table.string("reviewer");
1963
1965
  table.integer("lock_version").notNullable().defaultTo(0);
1966
+ // An index that reads a workspace's rows in id order, which lockWhere and lockPages need on MySQL and MariaDB.
1967
+ table.index(["workspace_id"], "visits_workspace");
1964
1968
  });
1965
1969
  await knex("customers").insert({ workspace_id: 1, name: "Ada" });
1966
1970
  await knex("vets").insert({ name: "Grace" });
@@ -1994,11 +1998,13 @@ async function createVisitFixture(t) {
1994
1998
  { customerId: "1", vetId: "1", stage: "new", internalCode: "k1", reviewer: "lee" },
1995
1999
  { customerId: "1", vetId: "1", stage: "new", internalCode: "k2" }
1996
2000
  ], { ...options, returning: "ids" });
1997
- // The tables each SELECT reads, in order.
2001
+ // The tables each SELECT reads, in order. On MySQL and MariaDB json-rest-api first reads the connection's schema
2002
+ // name and the table's indexes (select database(), information_schema), once, which reads no row of a table here.
1998
2003
  const selects = async (work) => (await countQueries(knex, work)).queries
1999
- .filter((sql) => /^select/iu.test(sql))
2004
+ .filter((sql) => /^select/iu.test(sql) && !/^select database\(\)|\binformation_schema\./iu.test(sql))
2000
2005
  .map((sql) => [...sql.matchAll(/from [`"](\w+)[`"]/gu)].map(([, table]) => table)[0]);
2001
- return { visits: handles.visits, options, ids: created, selects, postgres: knex.client.config.client === "pg" };
2006
+ const client = knex.client.config.client;
2007
+ return { visits: handles.visits, options, ids: created, selects, postgres: client === "pg", mysql: client === "mysql2" };
2002
2008
  }
2003
2009
 
2004
2010
  test("a read whose list filter is an empty list answers nothing without a statement, as a read that matches no row does", async (t) => {
@@ -2047,10 +2053,13 @@ test("a read whose list filter is an empty list answers nothing without a statem
2047
2053
  });
2048
2054
 
2049
2055
  test("lock, lockMany, lockWhere and claim read only the fields they name, so a relation left out costs no visibility check", async (t) => {
2050
- const { visits, options, ids, selects, postgres } = await createVisitFixture(t);
2056
+ const { visits, options, ids, selects, postgres, mysql } = await createVisitFixture(t);
2051
2057
  let locked;
2052
2058
  // PostgreSQL's lockWhere reads once more under the locks it took, for rows that started to match while it waited.
2053
2059
  const lockWhereReads = postgres ? ["visits", "visits"] : ["visits"];
2060
+ // MySQL's and MariaDB's claim reads the candidates' ids in order without a lock, then locks the first it can (SKIP
2061
+ // LOCKED) and reads its fields under that lock, since a locking read there holds every row it examines.
2062
+ const claimReads = mysql ? ["visits", "visits", "visits"] : ["visits"];
2054
2063
  // Every field: the locking read, then one visibility check per related type.
2055
2064
  assert.deepEqual(await selects(() => visits.withTransaction(options, (tx) => visits.lock(ids[0], tx))), ["visits", "customers", "vets"]);
2056
2065
  assert.deepEqual(await selects(() => visits.withTransaction(options, async (tx) => {
@@ -2066,10 +2075,10 @@ test("lock, lockMany, lockWhere and claim read only the fields they name, so a r
2066
2075
  locked = await visits.lockWhere({ id: ids }, { ...tx, fields: ["stage"] });
2067
2076
  })), lockWhereReads);
2068
2077
  assert.deepEqual(locked, ids.map((id) => ({ id, stage: "new" })));
2069
- assert.deepEqual(await selects(() => visits.withTransaction(options, (tx) => visits.claim({ filters: { id: ids } }, tx))), ["visits", "customers", "vets"]);
2078
+ assert.deepEqual(await selects(() => visits.withTransaction(options, (tx) => visits.claim({ filters: { id: ids } }, tx))), [...claimReads, "customers", "vets"]);
2070
2079
  assert.deepEqual(await selects(() => visits.withTransaction(options, async (tx) => {
2071
2080
  locked = await visits.claim({ filters: { id: ids }, take: 1 }, { ...tx, fields: ["stage", "vetId"] });
2072
- })), ["visits", "vets"]);
2081
+ })), [...claimReads, "vets"]);
2073
2082
  assert.deepEqual(locked, [{ id: ids[0], stage: "new", vetId: "1" }]);
2074
2083
  });
2075
2084
 
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { storedSourceCases } from "./support/storedSourceCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of storedSourceCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -1,35 +1,12 @@
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" });
1
+ import { createPackageTestKnex } from "@jskit-ai/database-runtime/server/testDatabases";
6
2
 
7
3
  /**
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.
4
+ * A MariaDB/MySQL database of the test's own beside TEST_DB_NAME, dropped after the test: createPackageTestKnex() on
5
+ * a mysql2 run, whatever the run's DB_CLIENT.
11
6
  * @param {import("node:test").TestContext} context
12
- * @param {string} suffix The database's name after TEST_DB_NAME's.
13
7
  */
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;
8
+ function ownMysqlDatabase(context) {
9
+ return createPackageTestKnex(context, { environment: { ...process.env, DB_CLIENT: "mysql2" } });
33
10
  }
34
11
 
35
12
  export { ownMysqlDatabase };
@@ -4,9 +4,10 @@ import knexFactory from "knex";
4
4
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
5
5
  import { defineFeature } from "@jskit-ai/kernel/server/features";
6
6
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
7
8
  import { createPackageTestKnex, createTestResourceRuntime, expectEveryTableOwned, expectFlatQueries, expectScoped, startTestFeatures, TestDatabaseMissingError } from "../src/test/index.js";
8
9
 
9
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
10
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
10
11
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
11
12
 
12
13
  const environment = Object.freeze({ TEST_DB_NAME: "catalogue_test" });
@@ -266,6 +267,30 @@ test("expectScoped() reads back only the other owner's rows, so a table past que
266
267
  assert.deepEqual(result.map(({ title }) => title).sort(), ["a", "b"]);
267
268
  });
268
269
 
270
+ test("createTables creates each owned table after the tables its belongs-to fields reference, as a foreign key needs", async (t) => {
271
+ const knex = await testKnex(t);
272
+ const runtime = await createTestResourceRuntime({ knex, createTables: true });
273
+ const visits = defineTableResource({
274
+ name: "visits",
275
+ tableName: "visits",
276
+ ownership: "public",
277
+ schema: {
278
+ id: { type: "id", primary: true },
279
+ petId: { type: "id", belongsTo: "pets", as: "pet", storage: { column: "pet_id" } }
280
+ }
281
+ });
282
+ const pets = defineTableResource({
283
+ name: "pets",
284
+ tableName: "pets",
285
+ ownership: "public",
286
+ schema: { id: { type: "id", primary: true }, ownerId: { type: "id", belongsTo: "owners", as: "owner", storage: { column: "owner_id" } } }
287
+ });
288
+ const owners = defineTableResource({ name: "owners", tableName: "owners", ownership: "public", schema: { id: { type: "id", primary: true } } });
289
+ const { queries } = await countQueries(knex, () => runtime.own("clinic.feature", [visits, pets, owners]));
290
+ const created = queries.map((sql) => /^create table [`"]?(\w+)/iu.exec(sql)?.[1]).filter(Boolean);
291
+ assert.deepEqual(created, ["owners", "pets", "visits"]);
292
+ });
293
+
269
294
  test("expectEveryTableOwned() names each table no feature owns", async (t) => {
270
295
  const { knex, runtime } = await createShelfFixture(t);
271
296
  await expectEveryTableOwned({ knex, runtime, environment });
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import { createPackageTestKnex } from "../src/test/index.js";
3
3
  import { transactionChecksCases } from "./support/transactionChecksCases.js";
4
4
 
5
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
5
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
6
6
  for (const [name, run] of transactionChecksCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
7
  test(name, run);
8
8
  }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { blobFieldsCases } from "./support/blobFieldsCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of blobFieldsCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { countOnlyTableCases } from "./support/countOnlyTableCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of countOnlyTableCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { crossTableFiltersCases } from "./support/crossTableFiltersCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of crossTableFiltersCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
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
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { lateRequiresCases } from "./support/lateRequiresCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of lateRequiresCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
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
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { lockPolicyCases } from "./support/lockPolicyCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of lockPolicyCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { lockWhereOrderCases } from "./support/lockWhereOrderCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of lockWhereOrderCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
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
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { policyTransactionCases } from "./support/policyTransactionCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of policyTransactionCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
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
- }
@@ -1,8 +0,0 @@
1
- import test from "node:test";
2
- import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
- import { storedSourceCases } from "./support/storedSourceCases.js";
4
-
5
- // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
- for (const [name, run] of storedSourceCases(ownMysqlDatabase)) {
7
- test(name, run);
8
- }
@@ -1,8 +0,0 @@
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
- }