@jskit-ai/users-core 0.2.16 → 0.2.17

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `users.profiles.listByIds(ids, options)` answers every profile of a list of ids in one call, however many, sorted by id. An id named twice answers its profile once, and an id naming no profile the caller can see, or that is no id, is left out. It reads 1,000 distinct ids per statement, each joining the caller's transaction and seeing what `query` sees for the caller's context. Code that names people by id read them in `query` pages of at most 100, walked by hand, once a group passed 100 people. Its tests run on MariaDB/MySQL (`listByIds.mysql.test.js`) and PostgreSQL (`listByIds.postgres.test.js`, in CI's PostgreSQL job).
6
+ - `users.settings.listByUserIds(userIds, options)` answers the settings of a list of users in one call, the same way: sorted by user id, each user once, users without settings left out, and each locale canonical as `findByUserId` reads it. Code that showed many people's settings read them with one `findByUserId` per person.
7
+
8
+ - user_settings declares its foreign key, user_id to users (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database. workspaces-core's `repositories.integration.test.js` proves it matches the migrations, with the users table, which has none.
5
9
  - The `users/user-administration-server` pattern's `workspaceMembersOnly` reads the workspace's members with only the list's context and transaction (`passedOn(options)`): the list's own settings, such as `format: "jsonapi"`, no longer reach `workspaces.memberships`.
6
10
  - The user settings table's fields with a default (theme, locale, time zone, date and number formats, currency, avatar size, and the password and notification flags) are no longer `required`, which `defineTableResource` now refuses beside `defaultTo`: a create that leaves one out gets its default where it failed REQUIRED. The CRUD and API contracts keep their own body and output schemas, so requests are unchanged.
7
11
  - `@jskit-ai/database-runtime` and `@jskit-ai/resource-runtime` are peer dependencies, required and at the same versions, where they were dependencies: its user settings are a table resource and its profiles live in the database, and the app holds one copy of the table runtime that every package shares, as it does the kernel. npm installs a required peer as it installed the dependency, so an app installs the same packages and versions; a release whose versions disagree now fails the install with ERESOLVE instead of nesting a second copy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/users-core",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -18,10 +18,10 @@
18
18
  "./locales/en.json": "./locales/en.json"
19
19
  },
20
20
  "dependencies": {
21
- "@jskit-ai/resource-core": "0.1.205",
22
- "@jskit-ai/resource-crud-core": "0.1.205",
23
- "@jskit-ai/storage-runtime": "0.1.260",
24
- "@jskit-ai/uploads-runtime": "0.2.14",
21
+ "@jskit-ai/resource-core": "0.1.206",
22
+ "@jskit-ai/resource-crud-core": "0.1.206",
23
+ "@jskit-ai/storage-runtime": "0.1.261",
24
+ "@jskit-ai/uploads-runtime": "0.2.15",
25
25
  "json-rest-schema": "^1.0.17"
26
26
  },
27
27
  "description": "Users/account runtime plus HTTP routes for account features.",
@@ -196,10 +196,10 @@
196
196
  }
197
197
  },
198
198
  "peerDependencies": {
199
- "@jskit-ai/auth-core": "0.2.14",
200
- "@jskit-ai/database-runtime": "0.1.263",
201
- "@jskit-ai/http-runtime": "0.2.14",
202
- "@jskit-ai/kernel": "0.2.14",
203
- "@jskit-ai/resource-runtime": "0.2.12"
199
+ "@jskit-ai/auth-core": "0.2.15",
200
+ "@jskit-ai/database-runtime": "0.1.264",
201
+ "@jskit-ai/http-runtime": "0.2.15",
202
+ "@jskit-ai/kernel": "0.2.15",
203
+ "@jskit-ai/resource-runtime": "0.2.13"
204
204
  }
205
205
  }
@@ -60,14 +60,18 @@ hook, a job) requires their owners' capabilities, never the `users` or
60
60
  `user_settings` tables:
61
61
 
62
62
  - `users.profiles`: `findById`, `findByEmail`, `findByIdentity`,
63
- `listByEmails(emails, options)` (one read), `upsert`,
63
+ `listByEmails(emails, options)` (one read),
64
+ `listByIds(ids, options)` (every profile of the ids, sorted by id, one read
65
+ per 1,000 ids), `upsert`,
64
66
  `createWithSettings({ profile, settings }, options)` (the profile and its
65
67
  settings in one transaction; settings start from the defaults),
66
68
  `createWithId(profile, options)` (a profile keeping an earlier table's id),
67
69
  `createManyIgnoringExisting(profiles, options)` (a re-runnable bulk import,
68
70
  system context only), `changeUsername(userId, username, options)` and
69
71
  `countUsers({ excludeIds, createdSince, authProvider }, options)`.
70
- - `users.settings`: `findByUserId`, `ensureForUserId` and the settings updates.
72
+ - `users.settings`: `findByUserId`, `listByUserIds(userIds, options)` (the
73
+ settings of every listed user who has them, sorted by user id, one read per
74
+ 1,000 ids), `ensureForUserId` and the settings updates.
71
75
 
72
76
  Their types are `UsersProfiles` and `UsersSettings` in
73
77
  `@jskit-ai/users-core/server/types`. Every method takes `options` last and
@@ -10,9 +10,9 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.15",
14
- "@jskit-ai/resource-crud-core": "0.1.205",
15
- "@jskit-ai/users-core": "0.2.16"
13
+ "@jskit-ai/crud-core": "0.2.16",
14
+ "@jskit-ai/resource-crud-core": "0.1.206",
15
+ "@jskit-ai/users-core": "0.2.17"
16
16
  },
17
17
  "jskit": {
18
18
  "kind": "runtime",
@@ -10,14 +10,14 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.15",
14
- "@jskit-ai/resource-crud-core": "0.1.205",
15
- "@jskit-ai/users-core": "0.2.16",
16
- "@jskit-ai/workspaces-core": "0.2.16"
13
+ "@jskit-ai/crud-core": "0.2.16",
14
+ "@jskit-ai/resource-crud-core": "0.1.206",
15
+ "@jskit-ai/users-core": "0.2.17",
16
+ "@jskit-ai/workspaces-core": "0.2.17"
17
17
  },
18
18
  "peerDependencies": {
19
- "@jskit-ai/kernel": "0.2.14",
20
- "@jskit-ai/resource-runtime": "0.2.12"
19
+ "@jskit-ai/kernel": "0.2.15",
20
+ "@jskit-ai/resource-runtime": "0.2.13"
21
21
  },
22
22
  "jskit": {
23
23
  "kind": "runtime",
@@ -0,0 +1,38 @@
1
+ import { normalizeDbRecordId } from "@jskit-ai/database-runtime/shared";
2
+ import { passedOn } from "@jskit-ai/resource-runtime/server";
3
+
4
+ // The ids one read binds: far under PostgreSQL's 65,535 parameters, and one page of the runtime's every-row reads
5
+ // (1,000 rows), so each read is one statement.
6
+ const IDS_PER_READ = 1000;
7
+
8
+ // Canonical ids (digits, no leading zero) in numeric order: shorter first, then by their digits.
9
+ function byNumericId(left, right) {
10
+ return left.length - right.length || (left < right ? -1 : left > right ? 1 : 0);
11
+ }
12
+
13
+ /**
14
+ * The records of a users table keyed by user id with these ids, all of them however many, sorted by id: one read per
15
+ * 1,000 distinct ids, each joining the caller's transaction and seeing what `query` sees for the caller's context. An
16
+ * id named twice answers its record once; an id naming no record the caller can see, or that is no id, is left out.
17
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
18
+ * @param {string} method The caller's name, for its error.
19
+ * @param {readonly unknown[]} userIds
20
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
21
+ * @returns {Promise<Record<string, unknown>[]>}
22
+ */
23
+ async function queryAllByIds(handle, method, userIds, options) {
24
+ if (!Array.isArray(userIds)) {
25
+ throw new TypeError(`${method} takes an array of user ids.`);
26
+ }
27
+ const ids = [...new Set(userIds.map((id) => normalizeDbRecordId(id, { fallback: null })).filter(Boolean))].sort(byNumericId);
28
+ const records = [];
29
+ for (let start = 0; start < ids.length; start += IDS_PER_READ) {
30
+ records.push(...await handle.queryAll(
31
+ { filters: { id: ids.slice(start, start + IDS_PER_READ) }, sort: ["id"] },
32
+ passedOn(options)
33
+ ));
34
+ }
35
+ return records;
36
+ }
37
+
38
+ export { queryAllByIds };
@@ -7,6 +7,7 @@ import {
7
7
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
8
8
  import { isSystemContext } from "@jskit-ai/resource-runtime/server";
9
9
  import { normalizeIdentity } from "../support/identity.js";
10
+ import { queryAllByIds } from "./recordsByIds.js";
10
11
  import { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername } from "../../../shared/resources/userProfileValues.js";
11
12
 
12
13
  function normalizeProfileRecord(payload = null) {
@@ -70,7 +71,6 @@ function usernameBaseFromEmail(email) {
70
71
 
71
72
  // The base, then base-2 to base-1000.
72
73
  const USERNAME_CANDIDATE_LIMIT = 1000;
73
-
74
74
  function buildUsernameCandidate(baseUsername, suffix) {
75
75
  const normalizedBase = normalizeUsername(baseUsername) || "user";
76
76
  if (suffix < 1) {
@@ -390,6 +390,19 @@ function createRepository({ userProfiles, userSettings }) {
390
390
  return rows.map(normalizeProfileRecord);
391
391
  }
392
392
 
393
+ /**
394
+ * The profiles with these ids, all of them in one call however many, sorted
395
+ * by id: one read per 1,000 distinct ids, each joining the caller's
396
+ * transaction and seeing what `query` sees for the caller's context. An id
397
+ * named twice answers its profile once; an id naming no profile the caller
398
+ * can see, or that is no id, is left out.
399
+ * @param {readonly unknown[]} userIds
400
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
401
+ */
402
+ async function listByIds(userIds, options = {}) {
403
+ return (await queryAllByIds(userProfiles, "listByIds", userIds, options)).map(normalizeProfileRecord);
404
+ }
405
+
393
406
  /**
394
407
  * Creates the profiles whose identity (authProvider and authProviderUserSid)
395
408
  * has none yet, in one INSERT per chunk, and leaves those that have one as
@@ -488,6 +501,7 @@ function createRepository({ userProfiles, userSettings }) {
488
501
  createWithId,
489
502
  createManyIgnoringExisting,
490
503
  listByEmails,
504
+ listByIds,
491
505
  changeUsername,
492
506
  countUsers,
493
507
  // The CRUD surface's reads (a CRUD feature serving the users table names this repository as its ownerRepository).
@@ -1,6 +1,7 @@
1
1
  import { isLostDuplicateInsertRace } from "@jskit-ai/database-runtime/shared";
2
2
  import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
3
3
  import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../../../shared/settings.js";
4
+ import { queryAllByIds } from "./recordsByIds.js";
4
5
 
5
6
  const USER_SETTINGS_PATCH_FIELDS = Object.freeze([
6
7
  "theme",
@@ -29,6 +30,11 @@ function pickPatchFields(source = {}) {
29
30
  return patch;
30
31
  }
31
32
 
33
+ // Rows saved before locales were canonical hold lowercased tags ("en-us").
34
+ function withCanonicalLocale(row) {
35
+ return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
36
+ }
37
+
32
38
  function buildDefaultUserSettingsCreatePayload(userId) {
33
39
  return {
34
40
  id: userId,
@@ -61,9 +67,19 @@ function createRepository({ userSettings }) {
61
67
  }
62
68
 
63
69
  const { records } = await userSettings.query({ filters: { id: normalizedUserId }, page: { size: 1 } }, options);
64
- const row = records[0] || null;
65
- // Rows saved before locales were canonical hold lowercased tags ("en-us").
66
- return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
70
+ return withCanonicalLocale(records[0] || null);
71
+ }
72
+
73
+ /**
74
+ * The settings of these users, all of them in one call however many, sorted
75
+ * by user id: one read per 1,000 distinct ids, each joining the caller's
76
+ * transaction. A user named twice answers once; a user without settings,
77
+ * or a value that is no id, is left out.
78
+ * @param {readonly unknown[]} userIds
79
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
80
+ */
81
+ async function listByUserIds(userIds, options = {}) {
82
+ return (await queryAllByIds(userSettings, "listByUserIds", userIds, options)).map(withCanonicalLocale);
67
83
  }
68
84
 
69
85
  async function ensureForUserId(userId, options = {}) {
@@ -143,6 +159,7 @@ function createRepository({ userSettings }) {
143
159
  return Object.freeze({
144
160
  withTransaction: userSettings.withTransaction,
145
161
  findByUserId,
162
+ listByUserIds,
146
163
  ensureForUserId,
147
164
  patchUserSettings,
148
165
  updatePreferences,
@@ -285,6 +285,7 @@ const userSettingsTableResource = defineTableResource({
285
285
  name: "userSettings",
286
286
  tableName: "user_settings",
287
287
  ownership: "public",
288
+ foreignKeys: [{ columns: ["id"], referencedTableName: "users" }],
288
289
  idProperty: "user_id",
289
290
  schema: {
290
291
  id: {
@@ -0,0 +1,5 @@
1
+ import { listByIdsCases } from "./support/listByIdsCases.js";
2
+ import { usersDatabase } from "./support/usersDatabases.js";
3
+
4
+ // users.profiles.listByIds on MariaDB/MySQL.
5
+ listByIdsCases(usersDatabase("users_ids"));
@@ -0,0 +1,6 @@
1
+ import { listByIdsCases } from "./support/listByIdsCases.js";
2
+ import { POSTGRES_ELSEWHERE, postgresUsersDatabase } from "./support/usersDatabases.js";
3
+
4
+ // users.profiles.listByIds on PostgreSQL: run with TEST_DB_NAME (and the usual DB_HOST, DB_PORT, DB_USER and
5
+ // DB_PASSWORD) naming a PostgreSQL database, and DB_CLIENT unset or pg.
6
+ listByIdsCases(postgresUsersDatabase("users_ids"), { skip: POSTGRES_ELSEWHERE });
@@ -5,7 +5,7 @@ import { findDuplicateEntryError } from "@jskit-ai/database-runtime/shared";
5
5
  import { createRepository as createUserProfilesRepository } from "../src/server/common/repositories/userProfilesRepository.js";
6
6
  import { createRepository as createUserSettingsRepository } from "../src/server/common/repositories/userSettingsRepository.js";
7
7
  import { DEFAULT_USER_SETTINGS } from "../src/shared/settings.js";
8
- import { usersDatabase } from "./support/mysqlUsers.js";
8
+ import { usersDatabase } from "./support/usersDatabases.js";
9
9
 
10
10
  // users.profiles and users.settings on MariaDB/MySQL, on the users and user_settings table handles: the records
11
11
  // they answer, the username a new profile gets, transactions, and a standalone insert that loses a race.
@@ -0,0 +1,115 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { countQueries, requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
+
5
+ // users.profiles.listByIds and users.settings.listByUserIds on a database of the test file's own (usersDatabases.js),
6
+ // run on MariaDB/MySQL and on PostgreSQL alike: more ids than one page of query in one call, an id named twice, and
7
+ // ids the caller cannot see.
8
+
9
+ const identityOf = (tag, extra = {}) => ({
10
+ authProvider: "local",
11
+ authProviderUserSid: `identity-${tag}`,
12
+ email: `${tag}@example.test`,
13
+ displayName: tag,
14
+ username: tag,
15
+ ...extra
16
+ });
17
+
18
+ // Ids in numeric order, as the users table sorts them.
19
+ const numerically = (left, right) => (BigInt(left) < BigInt(right) ? -1 : BigInt(left) > BigInt(right) ? 1 : 0);
20
+
21
+ /**
22
+ * Registers the listByIds and listByUserIds tests on `database`.
23
+ * @param {{ open: () => Promise<any> }} database
24
+ * @param {{ skip?: string | false }} [options]
25
+ */
26
+ function listByIdsCases(database, { skip = false } = {}) {
27
+ test("listByIds answers every profile of 1,205 ids in one call, sorted by id, in one statement per 1,000 ids", { skip }, async () => {
28
+ requireTestDatabase(process.env);
29
+ const db = await database.open();
30
+ const ids = await db.profiles.createManyIgnoringExisting(
31
+ Array.from({ length: 1205 }, (_, index) => identityOf(`many-${index}`)),
32
+ { context: db.systemContext }
33
+ );
34
+ assert.equal(ids.length, 1205);
35
+
36
+ const { result, count } = await countQueries(db.knex, () => db.profiles.listByIds([...ids].reverse()));
37
+ assert.deepEqual(result.map(({ id }) => id), [...ids].sort(numerically));
38
+ assert.equal(count, 2, "1,205 ids are read in two statements, never one per page of 100 or per id");
39
+ assert.deepEqual(result[0], await db.profiles.findById(result[0].id), "each profile reads as findById answers it");
40
+ });
41
+
42
+ test("listByIds answers a profile named twice once, and leaves out ids naming no profile and values that are no id", { skip }, async () => {
43
+ requireTestDatabase(process.env);
44
+ const db = await database.open();
45
+ const one = await db.profiles.upsert(identityOf("ids-one"));
46
+ const two = await db.profiles.upsert(identityOf("ids-two"));
47
+ const { result, count } = await countQueries(db.knex, () => db.profiles.listByIds([
48
+ two.id, ` ${one.id} `, Number(two.id), one.id, "999999999", "not-an-id", `0${one.id}`, 0, -1, null, undefined
49
+ ]));
50
+ assert.deepEqual(result.map(({ id }) => id), [one.id, two.id]);
51
+ assert.deepEqual(result, [await db.profiles.findById(one.id), await db.profiles.findById(two.id)]);
52
+ assert.equal(count, 1);
53
+
54
+ assert.deepEqual(await countQueries(db.knex, () => db.profiles.listByIds([])), { result: [], count: 0, queries: [] });
55
+ assert.deepEqual(await db.profiles.listByIds(["999999999", "not-an-id"]), []);
56
+ await assert.rejects(db.profiles.listByIds(one.id), /listByIds takes an array of user ids/u);
57
+ });
58
+
59
+ test("listByIds sees what query sees for the caller, and joins the caller's transaction", { skip }, async () => {
60
+ requireTestDatabase(process.env);
61
+ const db = await database.open();
62
+ const shown = await db.profiles.upsert(identityOf("ids-shown"));
63
+ const hidden = await db.profiles.upsert(identityOf("ids-hidden"));
64
+ const ids = [hidden.id, shown.id];
65
+ // The users table owned again, with a row policy that hides one profile from every caller but background work.
66
+ const narrowed = await db.ownedWith({
67
+ rowPolicy: ({ query, column, caller }) => {
68
+ if (caller.kind !== "system") query.whereNot(column("username"), hidden.username);
69
+ return true;
70
+ }
71
+ });
72
+
73
+ const { records } = await narrowed.profiles.query({ filters: { id: ids }, page: { size: 10 } }, {});
74
+ assert.deepEqual(records.map(({ id }) => id), [shown.id]);
75
+ assert.deepEqual((await narrowed.profiles.listByIds(ids)).map(({ id }) => id), [shown.id]);
76
+ assert.deepEqual(
77
+ (await narrowed.profiles.listByIds(ids, { context: narrowed.systemContext })).map(({ id }) => id),
78
+ [shown.id, hidden.id].sort(numerically)
79
+ );
80
+
81
+ // A profile created in the caller's transaction is listed inside it, and is gone once the transaction rolls back.
82
+ const abort = new Error("Abort");
83
+ let created = null;
84
+ await assert.rejects(db.profiles.withTransaction({}, async (txOptions) => {
85
+ created = await db.profiles.upsert(identityOf("ids-uncommitted"), txOptions);
86
+ assert.deepEqual((await db.profiles.listByIds([created.id, shown.id], txOptions)).map(({ id }) => id), [shown.id, created.id]);
87
+ throw abort;
88
+ }), (error) => error === abort);
89
+ assert.deepEqual((await db.profiles.listByIds([created.id, shown.id])).map(({ id }) => id), [shown.id]);
90
+ });
91
+
92
+ test("settings.listByUserIds answers each listed user's settings once, sorted by user id, as findByUserId reads them", { skip }, async () => {
93
+ requireTestDatabase(process.env);
94
+ const db = await database.open();
95
+ const one = await db.profiles.upsert(identityOf("settings-one"));
96
+ const two = await db.profiles.upsert(identityOf("settings-two"));
97
+ const unset = await db.profiles.upsert(identityOf("settings-unset"));
98
+ await db.settings.ensureForUserId(one.id);
99
+ await db.settings.ensureForUserId(two.id);
100
+ // A row saved before locales were canonical.
101
+ await db.knex("user_settings").where({ user_id: two.id }).update({ locale: "en-us" });
102
+
103
+ const { result, count } = await countQueries(db.knex, () => db.settings.listByUserIds([
104
+ two.id, unset.id, ` ${one.id} `, two.id, "not-an-id", null
105
+ ]));
106
+ assert.deepEqual(result, [await db.settings.findByUserId(one.id), await db.settings.findByUserId(two.id)]);
107
+ assert.equal(result[1].locale, "en-US");
108
+ assert.equal(count, 1, "one statement, never one per user");
109
+
110
+ assert.deepEqual(await countQueries(db.knex, () => db.settings.listByUserIds([])), { result: [], count: 0, queries: [] });
111
+ await assert.rejects(db.settings.listByUserIds(one.id), /listByUserIds takes an array of user ids/u);
112
+ });
113
+ }
114
+
115
+ export { listByIdsCases };
@@ -11,11 +11,39 @@ import { createUsersIdentity } from "../../src/server/usersIdentity.js";
11
11
  import { userProfileTableResource } from "../../src/shared/resources/userProfileResource.js";
12
12
  import { userSettingsTableResource } from "../../src/shared/resources/userSettingsResource.js";
13
13
 
14
- // The migrated users tables in a MariaDB/MySQL database of the test file's own, named after TEST_DB_NAME with the
15
- // file's suffix, made on first use and dropped when the file ends. Each test keeps to its own users.
14
+ // The migrated users tables in a database of the test file's own, made on first use and dropped when the file ends:
15
+ // on MariaDB/MySQL a database named after TEST_DB_NAME with the file's suffix, on PostgreSQL a schema of that name in
16
+ // TEST_DB_NAME. Each test keeps to its own users.
16
17
  const MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt];
17
18
 
18
- async function openDatabase(suffix, cleanups) {
19
+ // A PostgreSQL test on a run for another database, such as CI's MariaDB run, is left to the PostgreSQL run.
20
+ const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "pg"
21
+ ? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
22
+ : false;
23
+
24
+ /**
25
+ * users.profiles, users.settings and the projector on `knex`'s users tables, owned as UsersIdentityProvider owns
26
+ * them; `rowPolicy` narrows the users table as an owner's row policy would.
27
+ * @param {import("knex").Knex} knex
28
+ * @param {{ rowPolicy?: Function }} [options]
29
+ */
30
+ async function ownUsers(knex, { rowPolicy } = {}) {
31
+ const runtime = await createTestResourceRuntime({ knex, logger: silentLogger });
32
+ const profilesEntry = rowPolicy ? { resource: userProfileTableResource, rowPolicy } : userProfileTableResource;
33
+ const resources = await runtime.own("users.identity", [profilesEntry, userSettingsTableResource]);
34
+ const identity = createUsersIdentity({ resources, extensions: createUsersExtensions() });
35
+ // Background work's context, as a feature declaring a systemScope receives it.
36
+ const systemContext = runtime.declareSystemScope("users.identity", "import users")("users test import");
37
+ return Object.freeze({ knex, resources, systemContext, ...identity });
38
+ }
39
+
40
+ async function migratedUsers(knex) {
41
+ for (const migration of MIGRATIONS) await migration.up(knex);
42
+ const owned = await ownUsers(knex);
43
+ return Object.freeze({ ...owned, ownedWith: (options) => ownUsers(knex, options) });
44
+ }
45
+
46
+ async function openMysqlDatabase(suffix, cleanups) {
19
47
  const name = `${requireTestDatabase(process.env)}_${suffix}`;
20
48
  if (name.length > 64) throw new Error(`Test database name ${name} is longer than MySQL's 64 characters.`);
21
49
  const server = {
@@ -41,22 +69,36 @@ async function openDatabase(suffix, cleanups) {
41
69
  });
42
70
  await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
43
71
  await admin.raw("CREATE DATABASE ??", [name]);
44
- for (const migration of MIGRATIONS) await migration.up(knex);
45
- // The users tables, owned as UsersIdentityProvider owns them.
46
- const runtime = await createTestResourceRuntime({ knex, logger: silentLogger });
47
- const resources = await runtime.own("users.identity", [userProfileTableResource, userSettingsTableResource]);
48
- const identity = createUsersIdentity({ resources, extensions: createUsersExtensions() });
49
- // Background work's context, as a feature declaring a systemScope receives it.
50
- const systemContext = runtime.declareSystemScope("users.identity", "import users")("users test import");
51
- return Object.freeze({ knex, resources, systemContext, ...identity });
72
+ return migratedUsers(knex);
52
73
  }
53
74
 
54
- /**
55
- * The file's database: call it at the file's top level, then `await open()` in each test after
56
- * requireTestDatabase(). The database is made by the first test that opens it and dropped after the file's tests.
57
- * @param {string} suffix A short name unique to the test file, such as "users_repos".
58
- */
59
- function usersDatabase(suffix) {
75
+ async function openPostgresSchema(suffix, cleanups) {
76
+ const database = requireTestDatabase(process.env);
77
+ const schema = `${database}_${suffix}_${process.pid}`;
78
+ if (schema.length > 63) throw new Error(`Test schema name ${schema} is longer than PostgreSQL's 63 characters.`);
79
+ const connection = {
80
+ host: process.env.DB_HOST,
81
+ port: Number(process.env.DB_PORT) || 5432,
82
+ user: process.env.DB_USER,
83
+ password: process.env.DB_PASSWORD,
84
+ database
85
+ };
86
+ const admin = knexLib({ client: "pg", connection, pool: { min: 0, max: 1 } });
87
+ const knex = knexLib({ client: "pg", connection, searchPath: [schema], pool: { min: 0, max: 6 } });
88
+ cleanups.push(async () => {
89
+ try {
90
+ await knex.destroy();
91
+ await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
92
+ } finally {
93
+ await admin.destroy();
94
+ }
95
+ });
96
+ await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
97
+ await admin.raw("CREATE SCHEMA ??", [schema]);
98
+ return migratedUsers(knex);
99
+ }
100
+
101
+ function fileDatabase(openDatabase, suffix) {
60
102
  const cleanups = [];
61
103
  let opening = null;
62
104
  after(async () => {
@@ -71,4 +113,23 @@ function usersDatabase(suffix) {
71
113
  });
72
114
  }
73
115
 
74
- export { usersDatabase };
116
+ /**
117
+ * The file's MariaDB/MySQL database: call it at the file's top level, then `await open()` in each test after
118
+ * requireTestDatabase(). The database is made by the first test that opens it and dropped after the file's tests.
119
+ * Its `ownedWith({ rowPolicy })` owns the same tables again, narrowed.
120
+ * @param {string} suffix A short name unique to the test file, such as "users_repos".
121
+ */
122
+ function usersDatabase(suffix) {
123
+ return fileDatabase(openMysqlDatabase, suffix);
124
+ }
125
+
126
+ /**
127
+ * The file's PostgreSQL schema in TEST_DB_NAME, used as usersDatabase() is. Its tests skip with
128
+ * POSTGRES_ELSEWHERE on a run for another database.
129
+ * @param {string} suffix A short name unique to the test file.
130
+ */
131
+ function postgresUsersDatabase(suffix) {
132
+ return fileDatabase(openPostgresSchema, suffix);
133
+ }
134
+
135
+ export { POSTGRES_ELSEWHERE, postgresUsersDatabase, usersDatabase };