@protobase/server 0.129.1 → 0.130.1
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/dist/assistant/query-runner/grants-sql.js +32 -0
- package/dist/assistant/query-runner/query-input.js +33 -0
- package/dist/assistant/query-runner/query-module.js +44 -0
- package/dist/assistant/query-runner/query-runner.d.ts +8 -11
- package/dist/assistant/query-runner/query-runner.js +15 -57
- package/dist/assistant/query-runner/read-query.js +54 -0
- package/dist/assistant/query-runner/runner-sql.js +4 -20
- package/dist/assistant/query-runner/steps/001-role.js +19 -0
- package/dist/auth-store.d.ts +2 -2
- package/dist/auth-store.js +3 -3
- package/dist/better-auth/auth-schema.d.ts +13 -4
- package/dist/better-auth/auth-schema.js +40 -32
- package/dist/better-auth/auth-settings.d.ts +59 -11
- package/dist/better-auth/auth-settings.js +57 -13
- package/dist/better-auth/auth-tables.d.ts +6 -3
- package/dist/better-auth/auth-tables.js +12 -7
- package/dist/better-auth/authenticator.js +10 -2
- package/dist/better-auth/create-auth.d.ts +62 -7
- package/dist/better-auth/create-auth.js +55 -14
- package/dist/better-auth/device-sign-in-check.js +13 -0
- package/dist/better-auth/names/declaration.d.ts +18 -5
- package/dist/better-auth/names/declaration.js +3 -1
- package/dist/better-auth/names/modules/auth.js +9 -0
- package/dist/better-auth/names/modules/index.d.ts +34 -4
- package/dist/better-auth/names/modules/organizations.js +10 -3
- package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
- package/dist/better-auth/names/modules-on.js +25 -2
- package/dist/better-auth/names/resolve-names.d.ts +9 -1
- package/dist/better-auth/names/resolve-names.js +15 -9
- package/dist/better-auth/organizations/accept-invitation.js +5 -4
- package/dist/better-auth/organizations/add-every-user.js +3 -2
- package/dist/better-auth/organizations/host-scope.d.ts +10 -0
- package/dist/better-auth/organizations/host-scope.js +15 -0
- package/dist/better-auth/organizations/host.d.ts +12 -6
- package/dist/better-auth/organizations/host.js +99 -61
- package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
- package/dist/better-auth/organizations/kept-organizations.js +62 -0
- package/dist/better-auth/organizations/member-endpoints.js +4 -3
- package/dist/better-auth/organizations/options.d.ts +15 -0
- package/dist/better-auth/organizations/options.js +19 -1
- package/dist/better-auth/organizations/people-endpoint.js +3 -2
- package/dist/better-auth/organizations/pinned-membership.js +81 -0
- package/dist/better-auth/organizations/pinned-sessions.js +46 -0
- package/dist/better-auth/organizations/session-organization.js +3 -2
- package/dist/better-auth/organizations/store.d.ts +1 -1
- package/dist/better-auth/organizations/store.js +14 -9
- package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
- package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
- package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
- package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
- package/dist/better-auth/store/adoption.js +25 -10
- package/dist/better-auth/store/drift.js +5 -4
- package/dist/better-auth/store/legacy-record.d.ts +10 -0
- package/dist/better-auth/store/legacy-record.js +56 -0
- package/dist/better-auth/store/migration-sql.js +31 -26
- package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
- package/dist/better-auth/store/offline/archive-revival.js +25 -0
- package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
- package/dist/better-auth/store/offline/baseline-store.js +15 -12
- package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
- package/dist/better-auth/store/offline/contract-gate.js +35 -0
- package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
- package/dist/better-auth/store/offline/module-archive.js +95 -0
- package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
- package/dist/better-auth/store/offline/module-delete.js +99 -0
- package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
- package/dist/better-auth/store/offline/module-switches.js +113 -0
- package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
- package/dist/better-auth/store/offline/name-changes.js +5 -2
- package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
- package/dist/better-auth/store/offline/offline-steps.js +29 -20
- package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
- package/dist/better-auth/store/offline/retired-watch.js +43 -0
- package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
- package/dist/better-auth/store/offline/settings-names.js +10 -3
- package/dist/better-auth/store/offline/store-model.d.ts +27 -1
- package/dist/better-auth/store/offline/store-model.js +22 -5
- package/dist/better-auth/store/resources-outside.js +1 -1
- package/dist/better-auth/store/step-record.d.ts +13 -0
- package/dist/better-auth/store/step-record.js +59 -0
- package/dist/better-auth/store/steps/index.js +6 -1
- package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
- package/dist/better-auth/store/steps/render.d.ts +3 -0
- package/dist/better-auth/store/steps/render.js +48 -25
- package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
- package/dist/better-auth/store/steps/step-lint.js +31 -10
- package/dist/better-auth/store/steps/step.d.ts +18 -0
- package/dist/better-auth/store/steps/step.js +7 -1
- package/dist/better-auth/store/store-db.d.ts +6 -0
- package/dist/better-auth/store/store-db.js +11 -5
- package/dist/better-auth/store/store-names.d.ts +4 -0
- package/dist/better-auth/store/store-sql.d.ts +1 -1
- package/dist/better-auth/token-standing.js +12 -7
- package/dist/better-auth/users.d.ts +7 -2
- package/dist/better-auth/users.js +25 -3
- package/dist/built-in-resources.js +1 -1
- package/dist/calls/calls-module.js +42 -0
- package/dist/calls/calls-sql.js +4 -30
- package/dist/changes/capture-names.d.ts +3 -1
- package/dist/changes/capture-names.js +5 -2
- package/dist/changes/capture-schema-sql.d.ts +10 -0
- package/dist/changes/capture-schema-sql.js +21 -0
- package/dist/changes/capture-schema.d.ts +0 -18
- package/dist/changes/capture-schema.js +1 -74
- package/dist/changes/capture-sql.js +30 -24
- package/dist/changes/changes-input.js +36 -0
- package/dist/changes/changes-module.js +44 -0
- package/dist/changes/read-capture.js +67 -0
- package/dist/changes/steps/001-outbox.js +23 -0
- package/dist/channels/sends-module.js +37 -0
- package/dist/channels/sends-schema-sql.js +5 -5
- package/dist/comments/comments-module.js +30 -0
- package/dist/comments/comments-sql.js +1 -22
- package/dist/computed/buckets-sql.d.ts +5 -1
- package/dist/computed/buckets-sql.js +39 -46
- package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
- package/dist/computed/buckets-targets.js +50 -0
- package/dist/computed/computed-input.js +65 -0
- package/dist/computed/computed-module.js +102 -0
- package/dist/computed/formula-sql.js +14 -1
- package/dist/computed/read-computed.js +100 -0
- package/dist/computed/rollup-sql.js +13 -10
- package/dist/config-exports.d.ts +2 -2
- package/dist/create-admin.js +21 -5
- package/dist/derived/derived-module.js +89 -0
- package/dist/derived/derived-sql.js +1 -47
- package/dist/functions/define-function.d.ts +10 -4
- package/dist/functions/routes.js +5 -3
- package/dist/functions/supabase-routes.js +7 -5
- package/dist/history/history-module.js +34 -0
- package/dist/index.d.ts +19 -28
- package/dist/index.js +11 -21
- package/dist/internal.d.ts +30 -10
- package/dist/internal.js +26 -8
- package/dist/jobs/functions-sql.js +7 -11
- package/dist/jobs/job-data.js +36 -0
- package/dist/jobs/job-types.d.ts +6 -3
- package/dist/jobs/jobs-module.d.ts +5 -0
- package/dist/jobs/jobs-module.js +84 -0
- package/dist/jobs/run-job.d.ts +1 -1
- package/dist/jobs/run-job.js +7 -5
- package/dist/jobs/runtime.d.ts +9 -4
- package/dist/jobs/runtime.js +11 -6
- package/dist/jobs/schema.d.ts +0 -11
- package/dist/jobs/schema.js +1 -59
- package/dist/jobs/steps/001-pg-boss-45.js +483 -0
- package/dist/live/notices-module.js +30 -0
- package/dist/live/notices-sql.js +2 -1
- package/dist/mail/feedback/feedback-schema.js +3 -30
- package/dist/mail/feedback/mail-feedback-module.js +37 -0
- package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
- package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
- package/dist/migration-record/check-record.d.ts +9 -7
- package/dist/migration-record/check-record.js +12 -11
- package/dist/migration-record/module-needs.js +30 -0
- package/dist/migration-record/read-record.js +27 -15
- package/dist/migration-record/record-model.d.ts +7 -2
- package/dist/migration-record/record-model.js +14 -6
- package/dist/migration-record/startup-decision.js +18 -7
- package/dist/migration-sql/additive-statements.d.ts +4 -0
- package/dist/migration-sql/additive-statements.js +105 -0
- package/dist/notifications/devices-module.js +61 -0
- package/dist/notifications/history-module.js +50 -0
- package/dist/notifications/notifications-targets.js +23 -0
- package/dist/notifications/read-table.js +16 -0
- package/dist/notifications/schema-sql.js +1 -22
- package/dist/notifications/schema.js +1 -101
- package/dist/notifications/table-names.js +40 -0
- package/dist/organization-scope/app-scope.js +38 -0
- package/dist/organization-scope/auth-request-organization.js +71 -0
- package/dist/organization-scope/organization-tables.js +20 -0
- package/dist/organization-scope/sign-in-organization.js +21 -0
- package/dist/package.js +1 -1
- package/dist/personal-mail/shared-sender-store.js +4 -2
- package/dist/realtime/relay/realtime-relay-module.js +37 -0
- package/dist/relation-found.js +6 -0
- package/dist/relay/read-relay.js +85 -0
- package/dist/relay/realtime-members-sql.js +51 -28
- package/dist/relay/relay-module.js +53 -0
- package/dist/relay/relay-targets.js +28 -0
- package/dist/relay/session-end.js +1 -3
- package/dist/relay/sessions-sql.js +4 -27
- package/dist/rest/table-routes.js +9 -2
- package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
- package/dist/schema-modules/feature-schemas-sql.js +51 -0
- package/dist/schema-modules/module-difference.d.ts +31 -0
- package/dist/schema-modules/module-difference.js +98 -0
- package/dist/schema-modules/modules-sql.js +13 -0
- package/dist/schema-modules/modules.d.ts +37 -0
- package/dist/schema-modules/modules.js +56 -0
- package/dist/schema-modules/needed-modules.d.ts +41 -0
- package/dist/schema-modules/needed-modules.js +61 -0
- package/dist/schema-modules/resource-difference.js +83 -0
- package/dist/schema-modules/schema-module.d.ts +112 -0
- package/dist/schema-modules/schema-module.js +8 -0
- package/dist/status/status-module.js +63 -0
- package/dist/status/status-targets.js +21 -0
- package/dist/types.d.ts +6 -1
- package/dist/user-tables/reloading-admin.d.ts +1 -0
- package/dist/user-tables/reloading-admin.js +1 -0
- package/dist/user-tables/schema-sql.js +1 -14
- package/dist/user-tables/schema.js +4 -27
- package/dist/user-tables/user-tables-module.js +38 -0
- package/dist/webhooks/table/delivery-log-module.js +36 -0
- package/dist/webhooks/table/owner-roles.js +3 -2
- package/dist/webhooks/table/schema-sql.js +27 -26
- package/dist/webhooks/table/webhooks-schema-module.js +63 -0
- package/dist/webhooks/table/webhooks-targets.js +26 -0
- package/dist/webhooks/webhooks.js +1 -1
- package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
- package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
- package/dist/workflows/custom-steps/runners-sql.js +10 -7
- package/dist/workflows/read-catalogue.js +23 -0
- package/dist/workflows/schema-sql.js +12 -9
- package/dist/workflows/status-sql.js +12 -6
- package/dist/workflows/storage/storage-module.js +39 -0
- package/dist/workflows/storage/storage-sql.js +8 -5
- package/dist/workflows/workflows-schema-module.js +49 -0
- package/dist/workflows/workflows-tables-sql.js +32 -0
- package/dist/workflows/workflows-targets.js +16 -0
- package/package.json +6 -6
- package/dist/assistant/query-runner/runner-plan.js +0 -30
- package/dist/better-auth/store/migrations-table.js +0 -27
- package/dist/better-auth/store/modules-off.js +0 -17
- package/dist/calls/calls-sql.d.ts +0 -11
- package/dist/changes/capture-plan.js +0 -79
- package/dist/channels/sends-schema.d.ts +0 -7
- package/dist/channels/sends-schema.js +0 -18
- package/dist/comments/comments-sql.d.ts +0 -14
- package/dist/computed/buckets-plan.d.ts +0 -2
- package/dist/computed/buckets-plan.js +0 -88
- package/dist/computed/buckets-schema.js +0 -39
- package/dist/computed/computed-plan.js +0 -81
- package/dist/computed/computed-schema.d.ts +0 -16
- package/dist/computed/computed-schema.js +0 -63
- package/dist/derived/derived-sql.d.ts +0 -12
- package/dist/mail/feedback/feedback-schema.d.ts +0 -7
- package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
- package/dist/notifications/schema.d.ts +0 -14
- package/dist/realtime/relay/relay-schema.d.ts +0 -7
- package/dist/realtime/relay/relay-schema.js +0 -20
- package/dist/relay/realtime-members-schema.js +0 -67
- package/dist/relay/relay-schema.d.ts +0 -14
- package/dist/relay/relay-schema.js +0 -28
- package/dist/status/schema.d.ts +0 -12
- package/dist/status/schema.js +0 -33
- package/dist/user-tables/schema.d.ts +0 -11
- package/dist/webhooks/table/schema.d.ts +0 -16
- package/dist/webhooks/table/schema.js +0 -56
- package/dist/workflows/schema.d.ts +0 -13
- package/dist/workflows/schema.js +0 -88
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { unsubscribesTable } from "./unsubscribe-store.js";
|
|
2
|
+
import { hasIndexes } from "../../has-indexes.js";
|
|
3
|
+
import { relationFound } from "../../relation-found.js";
|
|
4
|
+
import { unsubscribesIndexes, unsubscribesTableSql } from "./unsubscribe-schema.js";
|
|
5
|
+
//#region src/mail/unsubscribe/unsubscribes-module.ts
|
|
6
|
+
/** The opt-outs table as the database has it: step 1 once it is there with every index. Refuses one without them, which no step records. */
|
|
7
|
+
const readUnsubscribes = async (db) => {
|
|
8
|
+
if (!await relationFound(db, unsubscribesTable)) return;
|
|
9
|
+
if (!await hasIndexes(db, "mail", "unsubscribes", unsubscribesIndexes.map(([name]) => name))) throw new Error(`The opt-outs table ${unsubscribesTable} lacks indexes no step of this version of Protobase records: add them with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
|
|
10
|
+
return {
|
|
11
|
+
lastStep: 1,
|
|
12
|
+
replaceables: {}
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
/** The table of who unsubscribed from which topic of the bulk mail, with `unsubscribe`. Never dropped. */
|
|
16
|
+
const unsubscribesModule = {
|
|
17
|
+
label: "the opt-outs table",
|
|
18
|
+
title: "The table of who unsubscribed from which topic of the bulk mail",
|
|
19
|
+
steps: [{
|
|
20
|
+
step: 1,
|
|
21
|
+
name: "unsubscribes",
|
|
22
|
+
title: "The opt-outs table and its indexes",
|
|
23
|
+
additive: true,
|
|
24
|
+
sql: () => unsubscribesTableSql()
|
|
25
|
+
}],
|
|
26
|
+
replaceables: [],
|
|
27
|
+
resourceReplaceables: [],
|
|
28
|
+
read: readUnsubscribes
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { unsubscribesModule };
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RecordModel } from "./record-model.js";
|
|
2
|
+
import { Kysely } from "kysely";
|
|
2
3
|
//#region src/migration-record/check-record.d.ts
|
|
3
4
|
/**
|
|
4
|
-
* Refuses to go on, before the server serves, while the database's record of migrations does not match
|
|
5
|
-
* version reads (`startupRefusal`
|
|
6
|
-
*
|
|
5
|
+
* Refuses to go on, before the server serves, while the database's record of migrations does not match `runtime`, the
|
|
6
|
+
* model this version reads (`runtimeModel`), as `startupRefusal` decides. It reads the record once and nothing else;
|
|
7
|
+
* the server never migrates itself, and reads it without the app's query plugins. A runtime that reads nothing of the
|
|
8
|
+
* record reads nothing.
|
|
7
9
|
*/
|
|
8
|
-
export declare const checkMigrationRecord: (
|
|
9
|
-
/** Whether the database's record has a
|
|
10
|
-
export declare const recordsRuntimeModel: (
|
|
10
|
+
export declare const checkMigrationRecord: (db: Kysely<any>, runtime: RecordModel, running: string) => Promise<void>;
|
|
11
|
+
/** Whether the database's record has a row that holds `runtime`. */
|
|
12
|
+
export declare const recordsRuntimeModel: (db: Kysely<any>, runtime: RecordModel) => Promise<boolean>;
|
|
11
13
|
//#endregion
|
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { modelHash, runtimeModel } from "./record-model.js";
|
|
1
|
+
import { withoutAppPlugins } from "../better-auth/store/store-db.js";
|
|
3
2
|
import { readRecordState, recordHasModel } from "./read-record.js";
|
|
3
|
+
import { readsNothing } from "./record-model.js";
|
|
4
4
|
import { startupRefusal } from "./startup-decision.js";
|
|
5
5
|
//#region src/migration-record/check-record.ts
|
|
6
|
+
const plainDb = (db) => withoutAppPlugins(db, "the record of migrations belongs to no organization");
|
|
6
7
|
/**
|
|
7
|
-
* Refuses to go on, before the server serves, while the database's record of migrations does not match
|
|
8
|
-
* version reads (`startupRefusal`
|
|
9
|
-
*
|
|
8
|
+
* Refuses to go on, before the server serves, while the database's record of migrations does not match `runtime`, the
|
|
9
|
+
* model this version reads (`runtimeModel`), as `startupRefusal` decides. It reads the record once and nothing else;
|
|
10
|
+
* the server never migrates itself, and reads it without the app's query plugins. A runtime that reads nothing of the
|
|
11
|
+
* record reads nothing.
|
|
10
12
|
*/
|
|
11
|
-
const checkMigrationRecord = async (
|
|
12
|
-
if (
|
|
13
|
-
const
|
|
14
|
-
const refusal = startupRefusal(runtime, await readRecordState(plainStoreDb(auth), modelHash(runtime)), running);
|
|
13
|
+
const checkMigrationRecord = async (db, runtime, running) => {
|
|
14
|
+
if (readsNothing(runtime)) return;
|
|
15
|
+
const refusal = startupRefusal(runtime, await readRecordState(plainDb(db), runtime), running);
|
|
15
16
|
if (refusal) throw new Error(refusal);
|
|
16
17
|
};
|
|
17
|
-
/** Whether the database's record has a
|
|
18
|
-
const recordsRuntimeModel = (
|
|
18
|
+
/** Whether the database's record has a row that holds `runtime`. */
|
|
19
|
+
const recordsRuntimeModel = (db, runtime) => recordHasModel(plainDb(db), runtime);
|
|
19
20
|
//#endregion
|
|
20
21
|
export { checkMigrationRecord, recordsRuntimeModel };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { moduleNameChanges } from "../schema-modules/module-difference.js";
|
|
2
|
+
import { schemaModules } from "../schema-modules/modules.js";
|
|
3
|
+
//#region src/migration-record/module-needs.ts
|
|
4
|
+
const stepLabel = (id, step) => `step ${step} (${schemaModules[id].steps[step - 1]?.name ?? "unknown"})`;
|
|
5
|
+
const resourceNeeds = (label, had, needed) => Object.entries(needed.resources ?? {}).flatMap(([name, entries]) => Object.entries(entries).flatMap(([key, entry]) => {
|
|
6
|
+
const found = had.resources?.[name]?.[key];
|
|
7
|
+
if (!found) return [`${label} lacks its ${name} of ${key}`];
|
|
8
|
+
return found.version === entry.version && found.digest === entry.digest ? [] : [`${label} has its ${name} of ${key} otherwise than this version writes them for the config`];
|
|
9
|
+
}));
|
|
10
|
+
/** What the runtime needs of the schema modules that the database's model lacks, has older or names otherwise, one line each. */
|
|
11
|
+
const moduleNeeds = (database, runtime) => Object.entries(runtime).flatMap(([id, needed]) => {
|
|
12
|
+
const { label } = schemaModules[id];
|
|
13
|
+
const had = database?.[id];
|
|
14
|
+
if (!had) return [`the database lacks ${label}, which this version needs at ${stepLabel(id, needed.lastStep)}`];
|
|
15
|
+
const steps = had.lastStep < needed.lastStep ? [`${label} is at ${stepLabel(id, had.lastStep)}, and this version needs ${stepLabel(id, needed.lastStep)}`] : [];
|
|
16
|
+
const replaced = Object.entries(needed.replaceables).flatMap(([name, version]) => {
|
|
17
|
+
const found = had.replaceables[name];
|
|
18
|
+
if (found === void 0) return [`${label} lacks its ${name}, which this version needs at version ${version}`];
|
|
19
|
+
return found < version ? [`${label} has its ${name} at version ${found}, and this version needs version ${version}`] : [];
|
|
20
|
+
});
|
|
21
|
+
const renamed = moduleNameChanges(schemaModules[id], had.names, needed.names ?? {}, "the database");
|
|
22
|
+
return [
|
|
23
|
+
...steps,
|
|
24
|
+
...replaced,
|
|
25
|
+
...renamed,
|
|
26
|
+
...resourceNeeds(label, had, needed)
|
|
27
|
+
];
|
|
28
|
+
});
|
|
29
|
+
//#endregion
|
|
30
|
+
export { moduleNeeds };
|
|
@@ -1,14 +1,28 @@
|
|
|
1
1
|
import { recordTable } from "./record-table.js";
|
|
2
2
|
import { sql } from "kysely";
|
|
3
3
|
//#region src/migration-record/read-record.ts
|
|
4
|
+
const holdsModule = (id, module) => {
|
|
5
|
+
const { resources = {}, ...rest } = module;
|
|
6
|
+
const found = sql`(model -> 'modules' -> ${id}::text)`;
|
|
7
|
+
return sql`(${found} - 'resources' = ${JSON.stringify(rest)}::jsonb and coalesce(${found} -> 'resources', '{}'::jsonb) @> ${JSON.stringify(resources)}::jsonb)`;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Whether a row of the record holds every part of `runtime` as it is: the auth store and each schema module it reads
|
|
11
|
+
* (`holdsModule`). A part the runtime does not read, such as a module another version needs, does not count.
|
|
12
|
+
*/
|
|
13
|
+
const holdsRuntime = (runtime) => sql.join([
|
|
14
|
+
sql`true`,
|
|
15
|
+
...runtime.auth ? [sql`model -> 'auth' = ${JSON.stringify(runtime.auth)}::jsonb`] : [],
|
|
16
|
+
...Object.entries(runtime.modules ?? {}).map(([id, module]) => holdsModule(id, module))
|
|
17
|
+
], sql` and `);
|
|
18
|
+
const recordFound = async (db) => (await sql`select to_regclass(${recordTable}) is not null as found`.execute(db)).rows[0].found;
|
|
4
19
|
/**
|
|
5
|
-
* The record as the startup decides on it, for the
|
|
6
|
-
* query for the newest row, whether a row
|
|
7
|
-
* the unfinished rows.
|
|
20
|
+
* The record as the startup decides on it, for the model the runtime reads: whether the table is there, then one
|
|
21
|
+
* query for the newest row, whether a row holds that model (`holdsRuntime`), the rows not marked additive since the
|
|
22
|
+
* newest such row, and the unfinished rows.
|
|
8
23
|
*/
|
|
9
|
-
const readRecordState = async (db,
|
|
10
|
-
|
|
11
|
-
if (!found?.found) return {
|
|
24
|
+
const readRecordState = async (db, runtime) => {
|
|
25
|
+
if (!await recordFound(db)) return {
|
|
12
26
|
newest: void 0,
|
|
13
27
|
matched: false,
|
|
14
28
|
notAdditiveSince: [],
|
|
@@ -16,9 +30,9 @@ const readRecordState = async (db, hash) => {
|
|
|
16
30
|
};
|
|
17
31
|
const table = sql.raw(recordTable);
|
|
18
32
|
const [row] = (await sql`
|
|
19
|
-
with matched as (select max(applied_at) as at from ${table} where
|
|
33
|
+
with matched as (select max(applied_at) as at from ${table} where ${holdsRuntime(runtime)})
|
|
20
34
|
select
|
|
21
|
-
(select json_build_object('name', name, 'protobase_version', protobase_version, 'model', model
|
|
35
|
+
(select json_build_object('name', name, 'protobase_version', protobase_version, 'model', model) from ${table} order by applied_at desc limit 1) as newest,
|
|
22
36
|
(select at is not null from matched) as matched,
|
|
23
37
|
(select coalesce(json_agg(h.name order by h.applied_at), '[]') from ${table} h, matched where h.applied_at > matched.at and h.additive is not true) as not_additive,
|
|
24
38
|
(select coalesce(json_agg(json_build_object('name', h.name, 'after', h.physical -> 'after') order by h.applied_at), '[]') from ${table} h where h.completed_at is null) as unfinished`.execute(db)).rows;
|
|
@@ -27,19 +41,17 @@ const readRecordState = async (db, hash) => {
|
|
|
27
41
|
newest: newest ? {
|
|
28
42
|
name: newest.name,
|
|
29
43
|
version: newest.protobase_version,
|
|
30
|
-
model: newest.model
|
|
31
|
-
hash: newest.model_hash
|
|
44
|
+
model: newest.model
|
|
32
45
|
} : void 0,
|
|
33
46
|
matched: row.matched,
|
|
34
47
|
notAdditiveSince: row.not_additive,
|
|
35
48
|
unfinished: row.unfinished
|
|
36
49
|
};
|
|
37
50
|
};
|
|
38
|
-
/** Whether
|
|
39
|
-
const recordHasModel = async (db,
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const [row] = (await sql`select exists (select from ${sql.raw(recordTable)} where model_hash = ${hash}) as has`.execute(db)).rows;
|
|
51
|
+
/** Whether a row of the record holds `runtime` (`holdsRuntime`): `false` without a record. */
|
|
52
|
+
const recordHasModel = async (db, runtime) => {
|
|
53
|
+
if (!await recordFound(db)) return false;
|
|
54
|
+
const [row] = (await sql`select exists (select from ${sql.raw(recordTable)} where ${holdsRuntime(runtime)}) as has`.execute(db)).rows;
|
|
43
55
|
return row.has;
|
|
44
56
|
};
|
|
45
57
|
//#endregion
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { StoreNamesSource } from "../better-auth/store/store-names.js";
|
|
2
2
|
import { StoreModel } from "../better-auth/store/offline/store-model.js";
|
|
3
|
+
import { ModuleTargets, ModulesModel } from "../schema-modules/modules.js";
|
|
3
4
|
//#region src/migration-record/record-model.d.ts
|
|
4
5
|
export type RecordModel = {
|
|
5
6
|
auth?: StoreModel;
|
|
7
|
+
modules?: ModulesModel;
|
|
6
8
|
};
|
|
7
9
|
/** The SHA-256 of the model as JSON, the same for the snapshot, the record and the runtime. */
|
|
8
10
|
export declare const modelHash: (model: RecordModel) => string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The model this version of Protobase reads with the app's auth and the schema modules it needs: the store and each
|
|
13
|
+
* module at every step and replaceable this version ships, with the names and resources the app gives it.
|
|
14
|
+
*/
|
|
15
|
+
export declare const runtimeModel: (auth: StoreNamesSource | undefined, modules: ModuleTargets) => RecordModel;
|
|
11
16
|
//#endregion
|
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import { storeNames } from "../better-auth/store/store-names.js";
|
|
2
2
|
import { latestSteps, storeModel } from "../better-auth/store/offline/store-model.js";
|
|
3
|
+
import { latestModules, targetIds } from "../schema-modules/modules.js";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
4
5
|
//#region src/migration-record/record-model.ts
|
|
5
6
|
/** The SHA-256 of the model as JSON, the same for the snapshot, the record and the runtime. */
|
|
6
7
|
const modelHash = (model) => createHash("sha256").update(JSON.stringify(model)).digest("hex");
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
/**
|
|
9
|
+
* The model this version of Protobase reads with the app's auth and the schema modules it needs: the store and each
|
|
10
|
+
* module at every step and replaceable this version ships, with the names and resources the app gives it.
|
|
11
|
+
*/
|
|
12
|
+
const runtimeModel = (auth, modules) => {
|
|
13
|
+
const names = auth && storeNames(auth);
|
|
14
|
+
return {
|
|
15
|
+
...names && { auth: storeModel(names, latestSteps(names.names.modules)) },
|
|
16
|
+
...targetIds(modules).length > 0 && { modules: latestModules(modules) }
|
|
17
|
+
};
|
|
12
18
|
};
|
|
19
|
+
/** Whether the runtime reads nothing of the record: sign-in off and no schema module needed. */
|
|
20
|
+
const readsNothing = (model) => !model.auth && !model.modules;
|
|
13
21
|
//#endregion
|
|
14
|
-
export { modelHash, runtimeModel };
|
|
22
|
+
export { modelHash, readsNothing, runtimeModel };
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { moduleSteps } from "../better-auth/store/steps/index.js";
|
|
2
|
-
import { modelHash } from "./record-model.js";
|
|
3
2
|
import { recordTable } from "./record-table.js";
|
|
3
|
+
import { schemaModules } from "../schema-modules/modules.js";
|
|
4
|
+
import { readsNothing } from "./record-model.js";
|
|
4
5
|
import { nameChanges } from "../better-auth/store/offline/name-changes.js";
|
|
6
|
+
import { moduleNeeds } from "./module-needs.js";
|
|
5
7
|
//#region src/migration-record/startup-decision.ts
|
|
6
8
|
const stepLabel = (module, step) => `step ${step} (${moduleSteps[module][step - 1]?.name ?? "unknown"})`;
|
|
7
9
|
/** What the runtime needs of the auth store that the database's lacks or has older, one line each. */
|
|
8
10
|
const authNeeds = (database, runtime) => {
|
|
11
|
+
if (!runtime) return [];
|
|
9
12
|
if (!database) return ["the auth store is not recorded"];
|
|
10
13
|
return [...Object.entries(runtime.modules).flatMap(([module, entry]) => {
|
|
11
14
|
const had = database.modules[module]?.lastStep;
|
|
@@ -20,21 +23,29 @@ const unfinishedRefusals = (unfinished) => unfinished.flatMap(({ name, after })
|
|
|
20
23
|
return after.filter(({ unique }) => unique).map(({ index }) => `${name} has not finished building the unique index ${index}`);
|
|
21
24
|
});
|
|
22
25
|
const waysOut = (matches, running) => `To bring the database up to ${running}, run \`protobase migrate --plan\` to see the migrations it will apply, then \`protobase migrate\`. Or run Protobase ${matches}, the version the database matches.`;
|
|
26
|
+
const neededParts = (runtime) => {
|
|
27
|
+
const modules = Object.keys(runtime.modules ?? {});
|
|
28
|
+
const parts = [...runtime.auth ? ["the auth store"] : [], ...modules.map((id) => schemaModules[id].label)];
|
|
29
|
+
const already = [...runtime.auth ? ["with `protobase auth migration` for a store whose tables are there already"] : [], ...modules.length > 0 ? ["with `protobase migration baseline` for a schema a migration of an earlier version made"] : []];
|
|
30
|
+
return `this version of Protobase needs ${parts.join(" and ")}. Write the migration that makes and records ${parts.length > 1 ? "them" : "it"} with \`protobase migration\`, or ${already.join(", or ")}`;
|
|
31
|
+
};
|
|
23
32
|
/**
|
|
24
33
|
* Why the server must not start on the database `state` describes, running `running` with the model `runtime`;
|
|
25
|
-
* `undefined` when it starts.
|
|
34
|
+
* `undefined` when it starts. Each part the runtime reads is compared on its own, and a part of the record it does
|
|
35
|
+
* not read, such as a module another version needs, does not count. A runtime that reads nothing of the record, sign-in
|
|
36
|
+
* off and no schema module needed, always starts.
|
|
26
37
|
*/
|
|
27
38
|
const startupRefusal = (runtime, state, running) => {
|
|
28
|
-
if (
|
|
39
|
+
if (readsNothing(runtime)) return;
|
|
29
40
|
const unfinished = unfinishedRefusals(state.unfinished);
|
|
30
41
|
if (unfinished.length > 0) return `The database's migrations have not finished, so the server will not start: ${unfinished.join("; ")}. Run \`protobase migrate\` to finish them.`;
|
|
31
42
|
const { newest } = state;
|
|
32
|
-
if (!newest) return `The database has no migration recorded in ${recordTable}, so the server will not start:
|
|
33
|
-
if (newest.hash === modelHash(runtime)) return;
|
|
43
|
+
if (!newest) return `The database has no migration recorded in ${recordTable}, so the server will not start: ${neededParts(runtime)}, run \`protobase migrate --plan\` to see it, then \`protobase migrate\`.`;
|
|
34
44
|
if (state.matched && state.notAdditiveSince.length === 0) return;
|
|
35
|
-
const needs = authNeeds(newest.model.auth, runtime.auth);
|
|
45
|
+
const needs = [...authNeeds(newest.model.auth, runtime.auth), ...moduleNeeds(newest.model.modules, runtime.modules ?? {})];
|
|
36
46
|
if (needs.length > 0) return `The database is behind Protobase ${running}, so the server will not start: ${needs.join("; ")}. ${waysOut(newest.version, running)}`;
|
|
37
|
-
return `The database is ahead of Protobase ${running}, so the server will not start:
|
|
47
|
+
if (state.matched) return `The database is ahead of Protobase ${running}, so the server will not start: it has migrations that break older code since the one this version reads: ${state.notAdditiveSince.join(", ")}. Rolling back to this version is blocked once they are applied: run Protobase ${newest.version}, the version the database matches, or a later one.`;
|
|
48
|
+
return `The database is ahead of Protobase ${running}, so the server will not start: its newest migration, ${newest.name}, records a model no migration of this version's records. ${waysOut(newest.version, running)}`;
|
|
38
49
|
};
|
|
39
50
|
//#endregion
|
|
40
51
|
export { startupRefusal };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
//#region src/migration-sql/additive-statements.ts
|
|
2
|
+
const relationKey = ({ schemaname, relname }) => `${schemaname ?? ""}.${relname}`;
|
|
3
|
+
const names = (items) => (items ?? []).map((item) => item.String?.sval).join(".");
|
|
4
|
+
/** Statements that only add whatever they act on. */
|
|
5
|
+
const plainKinds = /* @__PURE__ */ new Set([
|
|
6
|
+
"CreateSchemaStmt",
|
|
7
|
+
"CreateStmt",
|
|
8
|
+
"CreateExtensionStmt",
|
|
9
|
+
"CreateSeqStmt",
|
|
10
|
+
"CreateEnumStmt",
|
|
11
|
+
"CreateFunctionStmt",
|
|
12
|
+
"CreateTrigStmt",
|
|
13
|
+
"ViewStmt",
|
|
14
|
+
"CommentStmt",
|
|
15
|
+
"VariableSetStmt",
|
|
16
|
+
"GrantStmt",
|
|
17
|
+
"CreatePolicyStmt"
|
|
18
|
+
]);
|
|
19
|
+
const looseConstraints = /* @__PURE__ */ new Set([
|
|
20
|
+
"CONSTR_NULL",
|
|
21
|
+
"CONSTR_DEFAULT",
|
|
22
|
+
"CONSTR_GENERATED",
|
|
23
|
+
"CONSTR_IDENTITY"
|
|
24
|
+
]);
|
|
25
|
+
const alterLabels = {
|
|
26
|
+
AT_DropColumn: "drops a column",
|
|
27
|
+
AT_AlterColumnType: "changes a column's type",
|
|
28
|
+
AT_SetNotNull: "makes a column not null",
|
|
29
|
+
AT_DropConstraint: "drops a constraint"
|
|
30
|
+
};
|
|
31
|
+
const kindLabels = {
|
|
32
|
+
RenameStmt: "renames a table, column or other object",
|
|
33
|
+
AlterObjectSchemaStmt: "moves an object to another schema",
|
|
34
|
+
DeleteStmt: "deletes rows",
|
|
35
|
+
TruncateStmt: "empties a table"
|
|
36
|
+
};
|
|
37
|
+
const alterFinding = (cmd, made) => {
|
|
38
|
+
switch (cmd.subtype) {
|
|
39
|
+
case "AT_DropNotNull": return;
|
|
40
|
+
case "AT_ColumnDefault": return cmd.def ? void 0 : "drops a column's default";
|
|
41
|
+
case "AT_AddConstraint": return made ? void 0 : `adds a constraint to a table there already, which rows written by older code may break`;
|
|
42
|
+
case "AT_AddColumn": {
|
|
43
|
+
if (made) return;
|
|
44
|
+
const constraints = (cmd.def.ColumnDef.constraints ?? []).filter((item) => !(item.Constraint.contype === "CONSTR_DEFAULT" && item.Constraint.raw_expr?.A_Const?.isnull)).map((item) => item.Constraint.contype);
|
|
45
|
+
if (constraints.includes("CONSTR_NOTNULL") && !constraints.includes("CONSTR_DEFAULT")) return `adds the required column ${cmd.def.ColumnDef.colname} without a default`;
|
|
46
|
+
return constraints.filter((contype) => !looseConstraints.has(contype) && contype !== "CONSTR_NOTNULL").length > 0 ? `adds the column ${cmd.def.ColumnDef.colname} with a constraint older code's rows may break` : void 0;
|
|
47
|
+
}
|
|
48
|
+
default: return alterLabels[cmd.subtype] ?? `${cmd.subtype.replace(/^AT_/, "")}, which the lint cannot tell only adds`;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const droppedTriggers = (statement) => (statement.objects ?? []).map((object) => names(object?.List?.items));
|
|
52
|
+
const createdTrigger = (node) => `${node.relation.schemaname ? `${node.relation.schemaname}.` : ""}${node.relation.relname}.${node.trigname}`;
|
|
53
|
+
const modifyingCtes = (node) => [...node.withClause?.ctes ?? [], ...node.selectStmt?.SelectStmt?.withClause?.ctes ?? []].flatMap((cte) => Object.keys(cte.CommonTableExpr?.ctequery ?? {})).filter((kind) => kind !== "SelectStmt");
|
|
54
|
+
const droppedNames = (statement) => (statement.objects ?? []).map((object) => names(object?.List?.items ?? object?.ObjectWithArgs?.objname ?? (object?.String ? [object] : []))).join(", ");
|
|
55
|
+
/**
|
|
56
|
+
* What in `statements`, as Postgres's parser reads them in order, takes something from older code, one line each:
|
|
57
|
+
* none when every statement only adds. A table the same statements make, without `if not exists`, takes any change;
|
|
58
|
+
* a trigger dropped without `cascade` and made again on its table by a later statement is replaced.
|
|
59
|
+
*/
|
|
60
|
+
const contractingStatements = (statements) => {
|
|
61
|
+
const made = new Set(statements.filter(({ kind, node }) => kind === "CreateStmt" && !node.if_not_exists).map(({ node }) => relationKey(node.relation)));
|
|
62
|
+
const triggersMade = statements.flatMap(({ kind, node }, index) => kind === "CreateTrigStmt" ? [{
|
|
63
|
+
key: createdTrigger(node),
|
|
64
|
+
index
|
|
65
|
+
}] : []);
|
|
66
|
+
return statements.flatMap(({ kind, node }, index) => {
|
|
67
|
+
if (plainKinds.has(kind)) return [];
|
|
68
|
+
if (kind === "InsertStmt" || kind === "UpdateStmt") return modifyingCtes(node).map((cte) => kindLabels[cte] ?? `${cte.replace(/Stmt$/, "")} in a with clause, which the lint cannot tell only adds`);
|
|
69
|
+
if (kind === "AlterEnumStmt") return node.oldVal ? ["renames a value of an enum type"] : [];
|
|
70
|
+
if (kind === "IndexStmt") return node.unique && !made.has(relationKey(node.relation)) ? ["adds a unique index to a table there already, which rows written by older code may break"] : [];
|
|
71
|
+
if (kind === "AlterTableStmt" && node.objtype === "OBJECT_TABLE") return node.cmds.flatMap(({ AlterTableCmd: cmd }) => {
|
|
72
|
+
const finding = alterFinding(cmd, made.has(relationKey(node.relation)));
|
|
73
|
+
return finding ? [finding] : [];
|
|
74
|
+
});
|
|
75
|
+
if (kind === "DropStmt" && (node.removeType === "OBJECT_INDEX" || node.removeType === "OBJECT_POLICY")) return [];
|
|
76
|
+
if (kind === "DropStmt" && node.behavior === "DROP_CASCADE") return ["drops with cascade"];
|
|
77
|
+
if (kind === "DropStmt" && node.removeType === "OBJECT_TRIGGER") return droppedTriggers(node).filter((key) => !triggersMade.some((made) => made.key === key && made.index > index)).map((key) => `drops trigger ${key} without making it again`);
|
|
78
|
+
if (kind === "DropStmt") {
|
|
79
|
+
const what = node.removeType.replace(/^OBJECT_/, "").toLowerCase().replaceAll("_", " ");
|
|
80
|
+
const replace = node.removeType === "OBJECT_VIEW" || node.removeType === "OBJECT_FUNCTION" ? `, which \`create or replace\` keeps for older code` : "";
|
|
81
|
+
return [`drops ${what} ${droppedNames(node)}${replace}`];
|
|
82
|
+
}
|
|
83
|
+
return [kindLabels[kind] ?? `${kind.replace(/Stmt$/, "")}, which the lint cannot tell only adds`];
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
/** What in `sql` takes something from older code, read with libpg-query, Postgres's parser; a parse error is one line. */
|
|
87
|
+
const contractingSql = async (sql) => {
|
|
88
|
+
const { parse, SqlError } = await import("libpg-query");
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = await parse(sql);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (!(error instanceof SqlError)) throw error;
|
|
94
|
+
return ["SQL the parser cannot read"];
|
|
95
|
+
}
|
|
96
|
+
return contractingStatements((parsed.stmts ?? []).map(({ stmt }) => {
|
|
97
|
+
const [kind, node] = Object.entries(stmt ?? {})[0];
|
|
98
|
+
return {
|
|
99
|
+
kind,
|
|
100
|
+
node
|
|
101
|
+
};
|
|
102
|
+
}));
|
|
103
|
+
};
|
|
104
|
+
//#endregion
|
|
105
|
+
export { contractingSql, contractingStatements };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { deviceColumns } from "./options.js";
|
|
2
|
+
import { devicesTableSql, qualified } from "./schema-sql.js";
|
|
3
|
+
import { legacyKindChecks } from "./legacy-kind-checks.js";
|
|
4
|
+
import { cascadesFrom, columnNumbers, uniqueOn } from "./read-table.js";
|
|
5
|
+
import { regclass } from "./schema.js";
|
|
6
|
+
import { tableNames } from "./table-names.js";
|
|
7
|
+
import { sql } from "kysely";
|
|
8
|
+
//#region src/notifications/devices-module.ts
|
|
9
|
+
const upgradeFirst = "with `protobase migration` and `protobase migrate` of Protobase 0.14.2 first, then run this command again";
|
|
10
|
+
const kindChecksWithoutRelay = async (db, oid, names) => {
|
|
11
|
+
const { rows } = await sql`select c.conname as name, pg_get_constraintdef(c.oid) as def from pg_constraint c
|
|
12
|
+
join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey)
|
|
13
|
+
where c.conrelid = ${oid} and c.contype = 'c' and a.attname = ${names.columns.kind} order by c.conname`.execute(db);
|
|
14
|
+
return legacyKindChecks(rows, names.columns);
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The devices table as the database has it, made by a migration or the app's own: step 1 once it has each column under
|
|
18
|
+
* its configured name, a unique index on the token alone, which moving a device relies on, and with sign-in a foreign
|
|
19
|
+
* key from the user column that deletes a user's devices with the user. Refuses one written before devices kept their
|
|
20
|
+
* session or could be relay devices, which no step records, and one without what the server relies on, naming it.
|
|
21
|
+
*/
|
|
22
|
+
const readDevices = async (db, input) => {
|
|
23
|
+
const { table: names, users } = tableNames(input.names, deviceColumns);
|
|
24
|
+
const devices = qualified(names);
|
|
25
|
+
const oid = await regclass(db, devices);
|
|
26
|
+
if (oid === null) return;
|
|
27
|
+
const numbers = await columnNumbers(db, oid, names);
|
|
28
|
+
if (numbers.session_id === void 0 || (await kindChecksWithoutRelay(db, oid, names)).length > 0) throw new Error(`The devices table ${devices} was written before devices kept their session and could be relay devices, which no step of this version of Protobase records: bring it there ${upgradeFirst}`);
|
|
29
|
+
const missing = deviceColumns.find((column) => numbers[column] === void 0);
|
|
30
|
+
if (missing !== void 0) throw new Error(`The devices table ${devices} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { devices: { columns: { ${missing}: ... } } } in protobase.config.ts`);
|
|
31
|
+
if (!await uniqueOn(db, oid, numbers.token)) throw new Error(`The devices table ${devices} needs a unique index on its token column "${names.columns.token}" alone, which moving a device to the user who registers it relies on`);
|
|
32
|
+
if (users && !await cascadesFrom(db, oid, numbers.user_id, users)) throw new Error(`The devices table ${devices} needs a foreign key from "${names.columns.user_id}" to ${users} with on delete cascade, so a deleted user's devices go with them`);
|
|
33
|
+
return {
|
|
34
|
+
lastStep: 1,
|
|
35
|
+
replaceables: {},
|
|
36
|
+
names: input.names
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The devices table notifications push to, unless a store of the app's own keeps them, under the names the config gives
|
|
41
|
+
* it (`moduleNames`): its user column points at the auth store's users with sign-in. Never dropped.
|
|
42
|
+
*/
|
|
43
|
+
const notificationDevicesModule = {
|
|
44
|
+
label: "the devices table of notifications",
|
|
45
|
+
title: "The devices table of notifications",
|
|
46
|
+
steps: [{
|
|
47
|
+
step: 1,
|
|
48
|
+
name: "devices",
|
|
49
|
+
title: "The devices table and its indexes",
|
|
50
|
+
additive: true,
|
|
51
|
+
sql: (moduleNames) => {
|
|
52
|
+
const { table, user } = tableNames(moduleNames, deviceColumns);
|
|
53
|
+
return `${devicesTableSql(table, user).join(";\n")};`;
|
|
54
|
+
}
|
|
55
|
+
}],
|
|
56
|
+
replaceables: [],
|
|
57
|
+
resourceReplaceables: [],
|
|
58
|
+
read: readDevices
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { notificationDevicesModule };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { historyColumns } from "./options.js";
|
|
2
|
+
import { qualified } from "./schema-sql.js";
|
|
3
|
+
import { cascadesFrom, columnNumbers } from "./read-table.js";
|
|
4
|
+
import { regclass } from "./schema.js";
|
|
5
|
+
import { tableNames } from "./table-names.js";
|
|
6
|
+
import { historyTableSql } from "./history-sql.js";
|
|
7
|
+
//#region src/notifications/history-module.ts
|
|
8
|
+
/**
|
|
9
|
+
* The history table as the database has it, made by a migration or the app's own: step 1 once it has each column under
|
|
10
|
+
* its configured name and, with sign-in, the foreign key that deletes a user's history with the user. Refuses one
|
|
11
|
+
* without them, naming what it lacks.
|
|
12
|
+
*/
|
|
13
|
+
const readHistory = async (db, input) => {
|
|
14
|
+
const { table: names, users } = tableNames(input.names, historyColumns);
|
|
15
|
+
const history = qualified(names);
|
|
16
|
+
const oid = await regclass(db, history);
|
|
17
|
+
if (oid === null) return;
|
|
18
|
+
const numbers = await columnNumbers(db, oid, names);
|
|
19
|
+
const missing = historyColumns.find((column) => numbers[column] === void 0);
|
|
20
|
+
if (missing !== void 0) throw new Error(`The history table ${history} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { history: { columns: { ${missing}: ... } } } in protobase.config.ts`);
|
|
21
|
+
if (users && !await cascadesFrom(db, oid, numbers.user_id, users)) throw new Error(`The history table ${history} needs a foreign key from "${names.columns.user_id}" to ${users} with on delete cascade, so a deleted user's history goes with them`);
|
|
22
|
+
return {
|
|
23
|
+
lastStep: 1,
|
|
24
|
+
replaceables: {},
|
|
25
|
+
names: input.names
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Each user's notification history, unless a store of the app's own keeps it, under the names the config gives it
|
|
30
|
+
* (`moduleNames`): its user column points at the auth store's users with sign-in. Never dropped.
|
|
31
|
+
*/
|
|
32
|
+
const notificationHistoryModule = {
|
|
33
|
+
label: "the history table of notifications",
|
|
34
|
+
title: "The table of each user's notification history",
|
|
35
|
+
steps: [{
|
|
36
|
+
step: 1,
|
|
37
|
+
name: "history",
|
|
38
|
+
title: "The history table and its indexes",
|
|
39
|
+
additive: true,
|
|
40
|
+
sql: (moduleNames) => {
|
|
41
|
+
const { table, user } = tableNames(moduleNames, historyColumns);
|
|
42
|
+
return `${historyTableSql(table, user).join(";\n")};`;
|
|
43
|
+
}
|
|
44
|
+
}],
|
|
45
|
+
replaceables: [],
|
|
46
|
+
resourceReplaceables: [],
|
|
47
|
+
read: readHistory
|
|
48
|
+
};
|
|
49
|
+
//#endregion
|
|
50
|
+
export { notificationHistoryModule };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { historyNames, notificationsNames } from "./options.js";
|
|
2
|
+
import { moduleNames, usersTarget } from "./table-names.js";
|
|
3
|
+
//#region src/notifications/notifications-targets.ts
|
|
4
|
+
/**
|
|
5
|
+
* The schema modules `notifications` needs, under the names its options give them: the devices table unless a store of
|
|
6
|
+
* the app's own keeps the devices, and the history table unless one keeps the history, each pointing at the users of
|
|
7
|
+
* the auth store `store` names, none without sign-in.
|
|
8
|
+
*/
|
|
9
|
+
const notificationsTargets = (options, store) => {
|
|
10
|
+
const users = usersTarget(store);
|
|
11
|
+
return {
|
|
12
|
+
...!options.store && { notification_devices: {
|
|
13
|
+
names: moduleNames(notificationsNames(options), users),
|
|
14
|
+
resources: {}
|
|
15
|
+
} },
|
|
16
|
+
...!options.historyStore && { notification_history: {
|
|
17
|
+
names: moduleNames(historyNames(options), users),
|
|
18
|
+
resources: {}
|
|
19
|
+
} }
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { notificationsTargets };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
//#region src/notifications/read-table.ts
|
|
3
|
+
const columnsOf = async (db, oid) => (await sql`select attname as name, attnum as num from pg_attribute where attrelid = ${oid} and attnum > 0 and not attisdropped`.execute(db)).rows;
|
|
4
|
+
/** Each column of `names` by its number in the table, `undefined` for one the table lacks. */
|
|
5
|
+
const columnNumbers = async (db, oid, names) => {
|
|
6
|
+
const found = await columnsOf(db, oid);
|
|
7
|
+
return Object.fromEntries(Object.entries(names.columns).map(([column, name]) => [column, found.find((row) => row.name === name)?.num]));
|
|
8
|
+
};
|
|
9
|
+
/** Whether a valid unique index without a condition holds exactly the column: one an interrupted concurrent build left does not. */
|
|
10
|
+
const uniqueOn = async (db, oid, num) => (await sql`select exists (select from pg_index where indrelid = ${oid} and indisunique and indisvalid and indpred is null and indexprs is null and indnatts = 1 and indkey[0] = ${num}) as found`.execute(db)).rows[0].found;
|
|
11
|
+
/** Whether a foreign key from exactly the column points at the users table's `id` and deletes with it. */
|
|
12
|
+
const cascadesFrom = async (db, oid, num, users) => (await sql`select exists (select from pg_constraint where conrelid = ${oid} and contype = 'f' and confdeltype = 'c'
|
|
13
|
+
and conkey = array[${num}]::int2[] and confrelid = to_regclass(${users})
|
|
14
|
+
and confkey = array[(select attnum from pg_attribute where attrelid = to_regclass(${users}) and attname = 'id' and not attisdropped)]::int2[]) as found`.execute(db)).rows[0].found;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { cascadesFrom, columnNumbers, uniqueOn };
|
|
@@ -2,11 +2,6 @@ import { quoteIdent } from "../changes/capture-sql.js";
|
|
|
2
2
|
//#region src/notifications/schema-sql.ts
|
|
3
3
|
/** A table by its schema, when one is named, and its name, quoted. */
|
|
4
4
|
const qualified = ({ schema, table }) => schema ? `${quoteIdent(schema)}.${quoteIdent(table)}` : quoteIdent(table);
|
|
5
|
-
/** The session column, added to a devices table written before devices kept the session they were registered in. */
|
|
6
|
-
const deviceSessionColumnSql = ({ schema, table, columns }) => `alter table ${qualified({
|
|
7
|
-
schema,
|
|
8
|
-
table
|
|
9
|
-
})} add column ${quoteIdent(columns.session_id)} text`;
|
|
10
5
|
const quotedColumns = (columns) => Object.fromEntries(Object.entries(columns).map(([name, value]) => [name, quoteIdent(value)]));
|
|
11
6
|
const kindCheck = (c) => `check (${c.kind} in ('web', 'apns', 'fcm', 'relay'))`;
|
|
12
7
|
const fieldsCheck = (c) => `check (
|
|
@@ -16,22 +11,6 @@ const fieldsCheck = (c) => `check (
|
|
|
16
11
|
or (${c.kind} = 'relay' and ${c.p256dh} is null and ${c.auth} is null and ${c.environment} is null and ${c.app_id} is null)
|
|
17
12
|
)`;
|
|
18
13
|
/**
|
|
19
|
-
* The kind checks, replacing `constraints`, those of a devices table written before devices could be relay devices,
|
|
20
|
-
* in one statement.
|
|
21
|
-
*/
|
|
22
|
-
const deviceKindChecksSql = ({ schema, table, columns }, constraints) => {
|
|
23
|
-
const c = quotedColumns(columns);
|
|
24
|
-
const drops = constraints.map((name) => `drop constraint ${quoteIdent(name)}`);
|
|
25
|
-
return `alter table ${qualified({
|
|
26
|
-
schema,
|
|
27
|
-
table
|
|
28
|
-
})} ${[
|
|
29
|
-
...drops,
|
|
30
|
-
`add ${kindCheck(c)}`,
|
|
31
|
-
`add ${fieldsCheck(c)}`
|
|
32
|
-
].join(", ")}`;
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
14
|
* The devices table: the token unique, so registering one moves it; with auth, its user column points at auth's users
|
|
36
15
|
* table and goes with the user. A field that does not apply to the kind must be NULL, and nothing has a default.
|
|
37
16
|
*/
|
|
@@ -63,4 +42,4 @@ const devicesTableSql = ({ schema, table, columns }, user) => {
|
|
|
63
42
|
];
|
|
64
43
|
};
|
|
65
44
|
//#endregion
|
|
66
|
-
export {
|
|
45
|
+
export { devicesTableSql, qualified };
|