@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,65 @@
|
|
|
1
|
+
import { quoteIdent } from "../changes/capture-sql.js";
|
|
2
|
+
import { columnType } from "./column-sql.js";
|
|
3
|
+
import { bucketModels, bucketsTarget, hasBuckets } from "./buckets-targets.js";
|
|
4
|
+
import { formulaFields, formulaSql } from "./formula-sql.js";
|
|
5
|
+
import { rollupTargets } from "./rollup-targets.js";
|
|
6
|
+
//#region src/computed/computed-input.ts
|
|
7
|
+
/** Whether a resource has rollup or formula fields. */
|
|
8
|
+
const hasComputed = (model) => Object.values(model.fields).some((field) => field.rollup || field.formula !== void 0);
|
|
9
|
+
/** Whether the computed module serves a resource: it has rollups or formulas, or is a time rollup. */
|
|
10
|
+
const computedOn = (model) => hasComputed(model) || hasBuckets(model);
|
|
11
|
+
/** A table as SQL names it to Protobase's own functions: qualified, in `public` when the resource names no schema. */
|
|
12
|
+
const qualifiedTable = (table) => `${quoteIdent(table.schema ?? "public")}.${quoteIdent(table.name)}`;
|
|
13
|
+
const tableOf = ({ table }) => ({
|
|
14
|
+
...table.schema !== void 0 && { schema: table.schema },
|
|
15
|
+
name: table.name
|
|
16
|
+
});
|
|
17
|
+
const modelTable = (model) => qualifiedTable(model.table);
|
|
18
|
+
const fieldKey = (model, field) => `${model.name}.${field.name}`;
|
|
19
|
+
const columnInput = (model, field, input) => ({
|
|
20
|
+
table: tableOf(model),
|
|
21
|
+
column: field.column,
|
|
22
|
+
input
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* What the computed module takes from the app's resources, by resource replaceable: each rollup's column and the
|
|
26
|
+
* function and trigger that keep it, each formula's column, and each time rollup's table and refresh function. A table
|
|
27
|
+
* the resource names without a schema is in `public`. Refuses a rollup whose resource, relation or field is not there.
|
|
28
|
+
*/
|
|
29
|
+
const computedInput = (models) => {
|
|
30
|
+
const rollups = rollupTargets(models, modelTable);
|
|
31
|
+
const formulas = models.flatMap((model) => Object.values(model.fields).filter((field) => field.formula !== void 0).map((field) => ({
|
|
32
|
+
model,
|
|
33
|
+
field
|
|
34
|
+
})));
|
|
35
|
+
const readFormula = ({ from, field }) => {
|
|
36
|
+
const read = field.rollup.field === void 0 ? void 0 : from.fields[field.rollup.field];
|
|
37
|
+
return read?.formula === void 0 ? void 0 : formulaSql(from, read);
|
|
38
|
+
};
|
|
39
|
+
const readRollups = (model, field) => Object.values(model.fields).filter((other) => other.rollup && formulaFields(field.formula).has(other.name)).map((other) => `${quoteIdent(other.column)} ${columnType(other)}`);
|
|
40
|
+
return {
|
|
41
|
+
names: {},
|
|
42
|
+
resources: {
|
|
43
|
+
rollup_columns: Object.fromEntries(rollups.map((target) => [fieldKey(target.model, target.field), columnInput(target.model, target.field, target)])),
|
|
44
|
+
formulas: Object.fromEntries(formulas.map(({ model, field }) => [fieldKey(model, field), columnInput(model, field, {
|
|
45
|
+
table: modelTable(model),
|
|
46
|
+
model,
|
|
47
|
+
field,
|
|
48
|
+
readsRollups: readRollups(model, field)
|
|
49
|
+
})])),
|
|
50
|
+
rollups: Object.fromEntries(rollups.map((target) => {
|
|
51
|
+
const formula = readFormula(target);
|
|
52
|
+
return [fieldKey(target.model, target.field), columnInput(target.model, target.field, {
|
|
53
|
+
...target,
|
|
54
|
+
...formula !== void 0 && { readsFormula: formula }
|
|
55
|
+
})];
|
|
56
|
+
})),
|
|
57
|
+
time_rollups: Object.fromEntries(bucketModels(models).map(({ model, from }) => [model.name, {
|
|
58
|
+
table: tableOf(model),
|
|
59
|
+
input: bucketsTarget(model, from, modelTable)
|
|
60
|
+
}]))
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
//#endregion
|
|
65
|
+
export { computedInput, computedOn, hasComputed, qualifiedTable };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { quoteIdent } from "../changes/capture-sql.js";
|
|
2
|
+
import { columnType } from "./column-sql.js";
|
|
3
|
+
import { addRollupColumnSql, backfillSql, dropRollupSql, rollupFunctionSql, rollupTriggerSql, rollupsSchema } from "./rollup-sql.js";
|
|
4
|
+
import { bucketsFillSql, createBucketsSql, dropBucketsTableSql } from "./buckets-sql.js";
|
|
5
|
+
import { addFormulaSql } from "./formula-sql.js";
|
|
6
|
+
import { qualifiedTable } from "./computed-input.js";
|
|
7
|
+
import { readComputed } from "./read-computed.js";
|
|
8
|
+
//#region src/computed/computed-module.ts
|
|
9
|
+
const statements = (list) => list.map((statement) => `${statement};`).join("\n");
|
|
10
|
+
const dropColumn = (table, column) => `-- Any index on the column goes with it, and has to be created again.\nalter table ${qualifiedTable(table)} drop column ${quoteIdent(column)};`;
|
|
11
|
+
/** Each rollup's column, which its function keeps; its rows are empty until the rollup's values are set. */
|
|
12
|
+
const rollupColumns = {
|
|
13
|
+
name: "rollup_columns",
|
|
14
|
+
title: "The column of a rollup field",
|
|
15
|
+
version: 1,
|
|
16
|
+
compatibleFrom: 1,
|
|
17
|
+
sql: (_names, input) => statements([addRollupColumnSql(input)]),
|
|
18
|
+
replace: (_names, table, column) => dropColumn(table, column),
|
|
19
|
+
keptWhileOthers: false
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Each formula's generated column, marked with its expression. Its statements name the rollup columns it reads, so a
|
|
23
|
+
* rollup column made again takes the formula with it: dropped before it, the last replaceable's removals first, and
|
|
24
|
+
* added after it.
|
|
25
|
+
*/
|
|
26
|
+
const formulas = {
|
|
27
|
+
name: "formulas",
|
|
28
|
+
title: "The generated column of a formula field",
|
|
29
|
+
version: 1,
|
|
30
|
+
compatibleFrom: 1,
|
|
31
|
+
sql: (_names, input) => {
|
|
32
|
+
const { table, model, field, readsRollups } = input;
|
|
33
|
+
return `${readsRollups.length === 0 ? "" : `-- It reads the rollup columns ${readsRollups.join(", ")}.\n`}${statements(addFormulaSql(table, model, field))}`;
|
|
34
|
+
},
|
|
35
|
+
replace: (_names, table, column) => dropColumn(table, column),
|
|
36
|
+
keptWhileOthers: false
|
|
37
|
+
};
|
|
38
|
+
const keeps = (target) => `-- It keeps ${target.table}.${quoteIdent(target.field.column)}, ${columnType(target.field)}${target.readsFormula === void 0 ? "" : `, from the formula ${target.readsFormula}`}.`;
|
|
39
|
+
/**
|
|
40
|
+
* The function and trigger that keep each rollup, made again by dropping the function, which takes its trigger with
|
|
41
|
+
* it, and gone with the rollup; its values are set from the records once the transaction commits.
|
|
42
|
+
*/
|
|
43
|
+
const rollups = {
|
|
44
|
+
name: "rollups",
|
|
45
|
+
title: "The function and trigger that keep a rollup",
|
|
46
|
+
version: 1,
|
|
47
|
+
compatibleFrom: 1,
|
|
48
|
+
sql: (_names, input) => {
|
|
49
|
+
const target = input;
|
|
50
|
+
return `${keeps(target)}\n${statements([rollupFunctionSql(target), rollupTriggerSql(target)])}`;
|
|
51
|
+
},
|
|
52
|
+
replace: (_names, table, column) => `${dropRollupSql(table, column)};`,
|
|
53
|
+
drop: (_names, table, column) => `${dropRollupSql(table, column)};`,
|
|
54
|
+
after: (_names, input) => statements([backfillSql(input)]),
|
|
55
|
+
keptWhileOthers: false
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Each time rollup's table, its indexes and refresh function, made again by dropping the table; filled once the
|
|
59
|
+
* transaction commits.
|
|
60
|
+
*/
|
|
61
|
+
const timeRollups = {
|
|
62
|
+
name: "time_rollups",
|
|
63
|
+
title: "The table and refresh function of a time rollup",
|
|
64
|
+
version: 1,
|
|
65
|
+
compatibleFrom: 1,
|
|
66
|
+
sql: (_names, input) => statements(createBucketsSql(input)),
|
|
67
|
+
replace: (_names, table) => `${dropBucketsTableSql(qualifiedTable(table))};`,
|
|
68
|
+
after: (_names, input) => statements([bucketsFillSql(input)]),
|
|
69
|
+
keptWhileOthers: false
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* The rollup and formula fields' columns, the functions and triggers that keep the rollups, and the time rollups'
|
|
73
|
+
* tables and refresh functions, per resource. A column, table or refresh function the config no longer has stays, for
|
|
74
|
+
* a migration of the project's own to drop a deploy after the one that stops reading it; a rollup's function and
|
|
75
|
+
* trigger go with it.
|
|
76
|
+
*/
|
|
77
|
+
const computedModule = {
|
|
78
|
+
label: "the rollups and formulas",
|
|
79
|
+
title: "The columns of the resources' rollup and formula fields, the triggers that keep the rollups, and the tables and refresh functions of their time rollups",
|
|
80
|
+
steps: [{
|
|
81
|
+
step: 1,
|
|
82
|
+
name: "rollups",
|
|
83
|
+
title: "The schema of the functions that keep rollups and refresh time rollups",
|
|
84
|
+
additive: true,
|
|
85
|
+
sql: () => `create schema if not exists ${quoteIdent(rollupsSchema)};`
|
|
86
|
+
}],
|
|
87
|
+
replaceables: [],
|
|
88
|
+
resourceReplaceables: [
|
|
89
|
+
rollupColumns,
|
|
90
|
+
formulas,
|
|
91
|
+
rollups,
|
|
92
|
+
timeRollups
|
|
93
|
+
],
|
|
94
|
+
read: (db, input) => readComputed(db, input, [
|
|
95
|
+
rollupColumns,
|
|
96
|
+
formulas,
|
|
97
|
+
rollups,
|
|
98
|
+
timeRollups
|
|
99
|
+
])
|
|
100
|
+
};
|
|
101
|
+
//#endregion
|
|
102
|
+
export { computedModule };
|
|
@@ -10,6 +10,19 @@ const expressionSql = (node, model) => {
|
|
|
10
10
|
if (node.kind === "coalesce") return `coalesce(${node.args.map((arg) => expressionSql(arg, model)).join(", ")})`;
|
|
11
11
|
return `round(${expressionSql(node.value, model)}${node.digits === void 0 ? "" : `, ${node.digits}`})`;
|
|
12
12
|
};
|
|
13
|
+
/** The fields a formula reads, by name. */
|
|
14
|
+
const formulaFields = (formula) => {
|
|
15
|
+
const names = /* @__PURE__ */ new Set();
|
|
16
|
+
const visit = (node) => {
|
|
17
|
+
if (node.kind === "field") names.add(node.name);
|
|
18
|
+
if (node.kind === "negate") visit(node.operand);
|
|
19
|
+
if (node.kind === "binary") [node.left, node.right].forEach(visit);
|
|
20
|
+
if (node.kind === "coalesce") node.args.forEach(visit);
|
|
21
|
+
if (node.kind === "round") visit(node.value);
|
|
22
|
+
};
|
|
23
|
+
visit(parseFormula(formula));
|
|
24
|
+
return names;
|
|
25
|
+
};
|
|
13
26
|
/** A formula field's generation expression, cast to its column's type. */
|
|
14
27
|
const formulaSql = (model, field) => `(${expressionSql(parseFormula(field.formula), model)})::${columnType(field)}`;
|
|
15
28
|
/** The comment that marks a formula's column as Protobase's, with the expression it was generated from. */
|
|
@@ -19,4 +32,4 @@ const isFormulaComment = (comment) => comment?.startsWith("protobase formula: ")
|
|
|
19
32
|
/** The statements that add a formula's generated column to `table` and mark it. */
|
|
20
33
|
const addFormulaSql = (table, model, field) => [`alter table ${table} add column ${quoteIdent(field.column)} ${columnType(field)} generated always as (${formulaSql(model, field)}) stored`, `comment on column ${table}.${quoteIdent(field.column)} is '${formulaComment(model, field).replaceAll("'", "''")}'`];
|
|
21
34
|
//#endregion
|
|
22
|
-
export { addFormulaSql, formulaComment, formulaSql, isFormulaComment };
|
|
35
|
+
export { addFormulaSql, formulaComment, formulaFields, formulaSql, isFormulaComment };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { quoteIdent } from "../changes/capture-sql.js";
|
|
2
|
+
import { columnType } from "./column-sql.js";
|
|
3
|
+
import { rollupBody, rollupFunctionName, rollupTriggerName, rollupsSchema } from "./rollup-sql.js";
|
|
4
|
+
import { bucketsBody, bucketsComment, bucketsFunctionName } from "./buckets-sql.js";
|
|
5
|
+
import { formulaComment, isFormulaComment } from "./formula-sql.js";
|
|
6
|
+
import { qualifiedTable } from "./computed-input.js";
|
|
7
|
+
import { resourceEntry } from "../schema-modules/resource-difference.js";
|
|
8
|
+
import { sql } from "kysely";
|
|
9
|
+
//#region src/computed/read-computed.ts
|
|
10
|
+
const rowsOf = async (db, query) => (await query.execute(db)).rows;
|
|
11
|
+
const placeKey = (table, column) => JSON.stringify([table, column]);
|
|
12
|
+
const readTables = async (db, tables) => rowsOf(db, sql`select t.name as "table", format('%I.%I', n.nspname, c.relname) as catalogue, obj_description(c.oid, 'pg_class') as comment
|
|
13
|
+
from unnest(${tables}::text[]) as t(name) join pg_class c on c.oid = to_regclass(t.name) join pg_namespace n on n.oid = c.relnamespace`);
|
|
14
|
+
const readColumns = async (db, places) => rowsOf(db, sql`select p.table, p.column, a.attgenerated <> '' as generated, format_type(a.atttypid, a.atttypmod) as type, col_description(a.attrelid, a.attnum) as comment
|
|
15
|
+
from unnest(${places.map(({ table }) => table)}::text[], ${places.map(({ column }) => column)}::text[]) as p("table", "column")
|
|
16
|
+
join pg_attribute a on a.attrelid = to_regclass(p.table) and a.attname = p.column
|
|
17
|
+
where a.attnum > 0 and not a.attisdropped`);
|
|
18
|
+
const readFunctions = async (db) => rowsOf(db, sql`select p.proname as name, p.prosrc as source, p.prosecdef as definer,
|
|
19
|
+
coalesce((select json_agg(json_build_object('table', format('%I.%I', ns.nspname, c.relname), 'name', t.tgname, 'enabled', t.tgenabled)) from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace ns on ns.oid = c.relnamespace where t.tgfoid = p.oid and not t.tgisinternal), '[]') as triggers
|
|
20
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${rollupsSchema}`);
|
|
21
|
+
const fieldName = ({ model, field }) => `${model.name}.${field.name}`;
|
|
22
|
+
/**
|
|
23
|
+
* The rollups and formulas as the database has them for `input`: step 1 once the rollups schema is there, and each
|
|
24
|
+
* resource's objects found, at the digest of its input when they are what this version or an earlier one made of it,
|
|
25
|
+
* else at none, so they are made again. Refuses a column or table of the project's own where the config declares one,
|
|
26
|
+
* and a rollup's column of another type. `undefined` when it has none of them.
|
|
27
|
+
*/
|
|
28
|
+
const readComputed = async (db, input, replaceables) => {
|
|
29
|
+
const given = (name) => Object.entries(input.resources[name] ?? {});
|
|
30
|
+
const targets = [...given("rollups"), ...given("time_rollups")].map(([, { input: target }]) => target);
|
|
31
|
+
const tables = new Map((await readTables(db, [...new Set(targets.flatMap((target) => [target.table, target.fromTable]))])).map((found) => [found.table, found]));
|
|
32
|
+
const columnPlaces = [...given("rollup_columns"), ...given("formulas")].map(([, entry]) => ({
|
|
33
|
+
table: qualifiedTable(entry.table),
|
|
34
|
+
column: entry.column
|
|
35
|
+
}));
|
|
36
|
+
const columns = new Map((await readColumns(db, columnPlaces)).map((found) => [placeKey(found.table, found.column), found]));
|
|
37
|
+
const [schema] = await rowsOf(db, sql`select exists (select from pg_namespace where nspname = ${rollupsSchema}) as found`);
|
|
38
|
+
const functions = schema.found ? await readFunctions(db) : [];
|
|
39
|
+
const entries = {};
|
|
40
|
+
const record = (replaceable, key, given, current) => {
|
|
41
|
+
const entry = resourceEntry(replaceable, input.names, given);
|
|
42
|
+
entries[replaceable.name] = {
|
|
43
|
+
...entries[replaceable.name],
|
|
44
|
+
[key]: current ? entry : {
|
|
45
|
+
...entry,
|
|
46
|
+
digest: ""
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
const [rollupColumns, formulas, rollups, timeRollups] = replaceables;
|
|
51
|
+
for (const [key, entry] of given("rollup_columns")) {
|
|
52
|
+
const target = entry.input;
|
|
53
|
+
const found = columns.get(placeKey(qualifiedTable(entry.table), entry.column));
|
|
54
|
+
if (!found) continue;
|
|
55
|
+
const name = `${target.table}.${quoteIdent(entry.column)}`;
|
|
56
|
+
if (found.generated) throw new Error(`Column ${name} of rollup field "${fieldName(target)}" is a generated column; drop it in a migration, then write the rollup's with \`protobase migration\``);
|
|
57
|
+
if (found.type !== columnType(target.field)) throw new Error(`Column ${name} of rollup field "${fieldName(target)}" is ${found.type}, not ${columnType(target.field)} as the field declares; change one of them`);
|
|
58
|
+
record(rollupColumns, key, entry, true);
|
|
59
|
+
}
|
|
60
|
+
for (const [key, entry] of given("formulas")) {
|
|
61
|
+
const target = entry.input;
|
|
62
|
+
const found = columns.get(placeKey(qualifiedTable(entry.table), entry.column));
|
|
63
|
+
if (!found) continue;
|
|
64
|
+
const name = `${target.table}.${quoteIdent(entry.column)}`;
|
|
65
|
+
if (!found.generated) throw new Error(`Column ${name} of formula field "${fieldName(target)}" is a plain column; drop or rename it in a migration, then write the formula's with \`protobase migration\``);
|
|
66
|
+
if (!isFormulaComment(found.comment)) throw new Error(`Column ${name} of formula field "${fieldName(target)}" is a generated column of the project's own; drop it in a migration, or remove .formula()`);
|
|
67
|
+
record(formulas, key, entry, found.comment === formulaComment(target.model, target.field) && found.type === columnType(target.field));
|
|
68
|
+
}
|
|
69
|
+
const catalogued = (target) => ({
|
|
70
|
+
...target,
|
|
71
|
+
table: tables.get(target.table)?.catalogue ?? target.table,
|
|
72
|
+
fromTable: tables.get(target.fromTable)?.catalogue ?? target.fromTable
|
|
73
|
+
});
|
|
74
|
+
for (const [key, entry] of given("rollups")) {
|
|
75
|
+
const target = entry.input;
|
|
76
|
+
const fn = functions.find((found) => found.name === rollupFunctionName(entry.table, entry.column));
|
|
77
|
+
if (!fn) continue;
|
|
78
|
+
const from = tables.get(target.fromTable)?.catalogue;
|
|
79
|
+
const body = fn.source === rollupBody(target) || fn.source === rollupBody(catalogued(target));
|
|
80
|
+
const [trigger] = fn.triggers;
|
|
81
|
+
const triggered = fn.triggers.length === 1 && trigger.name === rollupTriggerName(target) && trigger.table === from && ["O", "A"].includes(trigger.enabled);
|
|
82
|
+
record(rollups, key, entry, fn.definer && body && triggered);
|
|
83
|
+
}
|
|
84
|
+
for (const [key, entry] of given("time_rollups")) {
|
|
85
|
+
const target = entry.input;
|
|
86
|
+
const found = tables.get(target.table);
|
|
87
|
+
if (!found) continue;
|
|
88
|
+
if (!found.comment?.startsWith("protobase time rollup: ")) throw new Error(`Table ${target.table} of time rollup "${target.model.name}" is a table of the project's own; drop or rename it in a migration, or name another table`);
|
|
89
|
+
const fn = functions.find((candidate) => candidate.name === bucketsFunctionName(target));
|
|
90
|
+
record(timeRollups, key, entry, found.comment === bucketsComment(target) && fn?.source === bucketsBody(target));
|
|
91
|
+
}
|
|
92
|
+
if (!schema.found && Object.keys(entries).length === 0) return;
|
|
93
|
+
return {
|
|
94
|
+
lastStep: schema.found ? 1 : 0,
|
|
95
|
+
replaceables: {},
|
|
96
|
+
...Object.keys(entries).length > 0 && { resources: entries }
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
//#endregion
|
|
100
|
+
export { readComputed };
|
|
@@ -3,15 +3,18 @@ import { columnType } from "./column-sql.js";
|
|
|
3
3
|
//#region src/computed/rollup-sql.ts
|
|
4
4
|
/** The schema of the functions that keep rollups. */
|
|
5
5
|
const rollupsSchema = "rollups";
|
|
6
|
-
/** The function that keeps one rollup, named for its resource's table and column. */
|
|
7
|
-
const rollupFunctionName = (
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
/** The function that keeps one rollup, named for its resource's table, as the resource names it, and column. */
|
|
7
|
+
const rollupFunctionName = (table, column) => identifier([
|
|
8
|
+
table.schema,
|
|
9
|
+
table.name,
|
|
10
|
+
column
|
|
11
11
|
].filter(Boolean).join("_"));
|
|
12
|
+
const targetFunctionName = ({ model, field }) => rollupFunctionName(model.table, field.column);
|
|
12
13
|
/** The trigger on `from`'s table that calls it. */
|
|
13
|
-
const rollupTriggerName = (target) => identifier(`${
|
|
14
|
-
|
|
14
|
+
const rollupTriggerName = (target) => identifier(`${targetFunctionName(target)}_rollup`);
|
|
15
|
+
/** The function that keeps the rollup of `table`'s `column`, qualified. */
|
|
16
|
+
const rollupFunctionSqlName = (table, column) => `${quoteIdent(rollupsSchema)}.${quoteIdent(rollupFunctionName(table, column))}`;
|
|
17
|
+
const functionSql = (target) => rollupFunctionSqlName(target.model.table, target.field.column);
|
|
15
18
|
const viaColumn = ({ from, field }) => quoteIdent(from.fields[field.rollup.via].column);
|
|
16
19
|
const keyColumn = ({ model }) => quoteIdent(model.fields[model.primaryKey[0]].column);
|
|
17
20
|
const aggregateSql = ({ from, field }) => {
|
|
@@ -54,11 +57,11 @@ const readColumns = ({ from, field }) => [
|
|
|
54
57
|
].filter((name) => name !== void 0).map((name) => quoteIdent(from.fields[name].column));
|
|
55
58
|
/** A rollup's trigger: after inserts, deletes and updates of the columns it reads, for each row. */
|
|
56
59
|
const rollupTriggerSql = (target) => `create trigger ${quoteIdent(rollupTriggerName(target))} after insert or delete or update of ${readColumns(target).join(", ")} on ${target.fromTable} for each row execute function ${functionSql(target)}()`;
|
|
57
|
-
|
|
58
|
-
const
|
|
60
|
+
/** Drops the function that keeps the rollup of `table`'s `column`, and with it the trigger that calls it. */
|
|
61
|
+
const dropRollupSql = (table, column) => `drop function if exists ${rollupFunctionSqlName(table, column)}() cascade`;
|
|
59
62
|
/** Sets every record's rollup from what `from` has now. */
|
|
60
63
|
const backfillSql = (target) => refreshSql(target, "true");
|
|
61
64
|
/** The statement that adds the rollup's column, empty until the backfill sets it. */
|
|
62
65
|
const addRollupColumnSql = ({ table, field }) => `alter table ${table} add column ${quoteIdent(field.column)} ${columnType(field)}`;
|
|
63
66
|
//#endregion
|
|
64
|
-
export { addRollupColumnSql, backfillSql,
|
|
67
|
+
export { addRollupColumnSql, backfillSql, dropRollupSql, rollupBody, rollupFunctionName, rollupFunctionSql, rollupFunctionSqlName, rollupTriggerName, rollupTriggerSql, rollupsSchema };
|
package/dist/config-exports.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { webhooksModule } from "./webhooks/table/webhooks-module.js";
|
|
2
|
+
import { workflowsModule } from "./workflows/workflows-module.js";
|
|
1
3
|
import { ownedTableNames } from "./user-tables/owned-definitions.js";
|
|
2
4
|
import { definitionsSchema, userTablesSchema } from "./user-tables/names.js";
|
|
3
5
|
import { CheckedDefinition } from "./user-tables/check-definition.js";
|
|
@@ -5,6 +7,4 @@ import { maxTextLength } from "./user-tables/definition-resource.js";
|
|
|
5
7
|
import { userTableResources } from "./user-tables/user-table-resources.js";
|
|
6
8
|
import { configExports } from "./resource-source.js";
|
|
7
9
|
import { builtInResources } from "./built-in-resources.js";
|
|
8
|
-
import { webhooksModule } from "./webhooks/table/webhooks-module.js";
|
|
9
|
-
import { workflowsModule } from "./workflows/workflows-module.js";
|
|
10
10
|
export { type CheckedDefinition, builtInResources, configExports, definitionsSchema, maxTextLength, ownedTableNames, userTableResources, userTablesSchema, webhooksModule, workflowsModule };
|
package/dist/create-admin.js
CHANGED
|
@@ -26,17 +26,17 @@ import { startRealtimePrune } from "./realtime/realtime-prune.js";
|
|
|
26
26
|
import { restRoutes } from "./rest/rest-routes.js";
|
|
27
27
|
import { storageRoutes } from "./storage/storage-routes.js";
|
|
28
28
|
import { shownAppName } from "./app-name.js";
|
|
29
|
+
import { authStoreTables } from "./better-auth/auth-tables.js";
|
|
29
30
|
import { realtimePath, restPath, storagePath, supabaseFunctionsPath, supabasePath } from "./supabase-paths.js";
|
|
30
31
|
import { goTruePath } from "./gotrue/keys.js";
|
|
31
32
|
import { acceptedTags, requestLocale } from "./locale/request-locale.js";
|
|
32
33
|
import { authBasePath } from "./better-auth/auth-base-path.js";
|
|
34
|
+
import { answerInOrganization, sessionActiveOrganization } from "./organization-scope/auth-request-organization.js";
|
|
33
35
|
import { mcpDiscovery } from "./better-auth/mcp/discovery-routes.js";
|
|
34
36
|
import { mcpApprovals } from "./mcp/mcp-approval-store.js";
|
|
35
37
|
import { checkMcpWrites, rolesWithoutApproval } from "./mcp/mcp-writes.js";
|
|
36
38
|
import { mcpAuthenticator } from "./mcp/mcp-authenticator.js";
|
|
37
39
|
import { visitorsBrowse, withAnonymous } from "./anonymous.js";
|
|
38
|
-
import { checkLiveReads } from "./check-live-reads.js";
|
|
39
|
-
import { changesSchema } from "./changes/events-options.js";
|
|
40
40
|
import { mcpToolContext } from "./mcp/mcp-context.js";
|
|
41
41
|
import { mcpHandler } from "./mcp/mcp-handler.js";
|
|
42
42
|
import { closedMcpRoutes, mcpRoutes } from "./mcp/mcp-routes.js";
|
|
@@ -51,6 +51,7 @@ import { betterAuthSessionToken } from "./better-auth/session-token.js";
|
|
|
51
51
|
import { goTrueTokens } from "./gotrue/access-tokens.js";
|
|
52
52
|
import { goTrueRoutes } from "./gotrue/routes.js";
|
|
53
53
|
import { createDerived } from "./derived/derived-values.js";
|
|
54
|
+
import { changesSchema } from "./changes/events-options.js";
|
|
54
55
|
import { appOrigin } from "./comments/app-origin.js";
|
|
55
56
|
import { betterAuthActorNames } from "./history/actor-names.js";
|
|
56
57
|
import { betterAuthCommentUsers } from "./comments/comment-users.js";
|
|
@@ -58,7 +59,7 @@ import { mentionJob } from "./comments/mention-job.js";
|
|
|
58
59
|
import { historyDays } from "./history/options.js";
|
|
59
60
|
import { pruneHistoryJob } from "./history/prune-history.js";
|
|
60
61
|
import { bucketsRefreshJob } from "./computed/buckets-job.js";
|
|
61
|
-
import { hasBuckets } from "./computed/buckets-
|
|
62
|
+
import { hasBuckets } from "./computed/buckets-targets.js";
|
|
62
63
|
import { callerRecords } from "./functions/records.js";
|
|
63
64
|
import { toApiFunction } from "./functions/define-function.js";
|
|
64
65
|
import { createWebhooks } from "./webhooks/webhooks.js";
|
|
@@ -77,6 +78,7 @@ import { upgradeAuthenticator } from "./functions/upgrade-caller.js";
|
|
|
77
78
|
import { guestRoutes } from "./calls/guest-routes.js";
|
|
78
79
|
import { organizationGuestsRoute } from "./calls/organization-guests-route.js";
|
|
79
80
|
import { organizationRole } from "./better-auth/organizations/organization-role.js";
|
|
81
|
+
import { appScope } from "./organization-scope/app-scope.js";
|
|
80
82
|
import { deviceStore, removeDevicesWithUsers } from "./notifications/device-store-of.js";
|
|
81
83
|
import { historyStore, removeHistoryWithUsers } from "./notifications/history-store-of.js";
|
|
82
84
|
import { devicesPath, historyPath } from "./notifications/paths.js";
|
|
@@ -102,6 +104,7 @@ import { checkRoleLimits } from "./check-roles.js";
|
|
|
102
104
|
import { checkBuckets } from "./check-buckets.js";
|
|
103
105
|
import { checkParents, parentWarnings } from "./check-parents.js";
|
|
104
106
|
import { checkLookups } from "./check-lookups.js";
|
|
107
|
+
import { checkLiveReads } from "./check-live-reads.js";
|
|
105
108
|
import { checkPositionAfter } from "./check-position-after.js";
|
|
106
109
|
import { checkRecordBlocks } from "./view-blocks.js";
|
|
107
110
|
import { blockTrees } from "./meta-texts.js";
|
|
@@ -245,6 +248,12 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
245
248
|
const maps = mapSettings(options.maps, globalThis.process?.env ?? {});
|
|
246
249
|
const senders = notifications ? notificationSenders(notifications, globalThis.process?.env ?? {}, mobile) : [];
|
|
247
250
|
if (status) checkStatusAuth(auth);
|
|
251
|
+
const scope = appScope({
|
|
252
|
+
organizations: Boolean(auth?.organizations),
|
|
253
|
+
names: auth?.names,
|
|
254
|
+
...auth && { pinned: auth.pinnedOrganization }
|
|
255
|
+
});
|
|
256
|
+
const organizationScope = async () => (await scope()).tables;
|
|
248
257
|
const statusTables = status && auth && {
|
|
249
258
|
statuses: statusNames(status),
|
|
250
259
|
members: auth.names.table("member")
|
|
@@ -421,7 +430,8 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
421
430
|
mobile: Boolean(mobile)
|
|
422
431
|
}));
|
|
423
432
|
if (auth.mcp || auth.openIdProvider) mcpDiscovery(app, auth);
|
|
424
|
-
const
|
|
433
|
+
const handler = mobile ? auth.handleMobile : auth.handler;
|
|
434
|
+
const answer = auth.organizations ? answerInOrganization(handler, sessionActiveOrganization(auth)) : handler;
|
|
425
435
|
app.on(["GET", "POST"], `${authBasePath}/*`, async (c) => withoutSessionTokens(c.req.raw, await answer(c.req.raw)));
|
|
426
436
|
app.route(goTruePath, goTrueRoutes(auth));
|
|
427
437
|
if (auth.origins.length > 1) app.get(webauthnPath, (c) => c.json({ origins: auth.origins }));
|
|
@@ -518,6 +528,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
518
528
|
authenticate,
|
|
519
529
|
access: deps.accessOptions,
|
|
520
530
|
db,
|
|
531
|
+
scope,
|
|
521
532
|
records: (session) => callerRecords(deps, session),
|
|
522
533
|
channels,
|
|
523
534
|
decryptField,
|
|
@@ -558,6 +569,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
558
569
|
app.route("/", supabaseFunctionRoutes({
|
|
559
570
|
functions: apiFunctions,
|
|
560
571
|
db,
|
|
572
|
+
scope,
|
|
561
573
|
keys: apiKeys,
|
|
562
574
|
caller: apiKeyCaller({
|
|
563
575
|
keys: apiKeys,
|
|
@@ -616,7 +628,10 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
616
628
|
verify
|
|
617
629
|
});
|
|
618
630
|
app.route(restPath, restRoutes({
|
|
619
|
-
deps
|
|
631
|
+
deps: {
|
|
632
|
+
...deps,
|
|
633
|
+
...auth && { storeTables: authStoreTables(auth) }
|
|
634
|
+
},
|
|
620
635
|
caller,
|
|
621
636
|
report
|
|
622
637
|
}));
|
|
@@ -688,6 +703,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
688
703
|
startRealtimePrune: prune,
|
|
689
704
|
stopHolding,
|
|
690
705
|
decryptField,
|
|
706
|
+
organizationScope,
|
|
691
707
|
metaPath: `${deps.systemPath}/meta`,
|
|
692
708
|
...links && { unsubscribe: links },
|
|
693
709
|
jobs: [
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { jobsSchema } from "../jobs/schema.js";
|
|
2
|
+
import { derivedName, derivedSchema, derivedTablesSql, fillJobName } from "./derived-sql.js";
|
|
3
|
+
import { resourceEntry } from "../schema-modules/resource-difference.js";
|
|
4
|
+
import { hasIndexes } from "../has-indexes.js";
|
|
5
|
+
import { sql } from "kysely";
|
|
6
|
+
//#region src/derived/derived-module.ts
|
|
7
|
+
const quote = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
8
|
+
/**
|
|
9
|
+
* Each derived value, by its name across resources: marked declared, with the job that computes its records once
|
|
10
|
+
* enqueued in the same transaction. Once the config no longer declares it, its mark, state, reads and pending changes
|
|
11
|
+
* go, so declaring it again fills it again.
|
|
12
|
+
*/
|
|
13
|
+
const values = {
|
|
14
|
+
name: "values",
|
|
15
|
+
title: "The declaration of a derived value, and the job that fills it",
|
|
16
|
+
version: 1,
|
|
17
|
+
compatibleFrom: 1,
|
|
18
|
+
sql: (_names, input) => {
|
|
19
|
+
const name = input;
|
|
20
|
+
return [`insert into "${derivedSchema}"."declared" ("name") values (${quote(name)}) on conflict do nothing;`, `select ${jobsSchema}.enqueue(${quote(fillJobName)}, ${quote(JSON.stringify({ name }))}::jsonb, key => ${quote(name)});`].join("\n");
|
|
21
|
+
},
|
|
22
|
+
drop: (_names, _table, _column, key) => [
|
|
23
|
+
"declared",
|
|
24
|
+
"reads",
|
|
25
|
+
"pending",
|
|
26
|
+
"values"
|
|
27
|
+
].map((table) => `delete from "${derivedSchema}"."${table}" where "name" = ${quote(key)};`).join("\n"),
|
|
28
|
+
keptWhileOthers: false
|
|
29
|
+
};
|
|
30
|
+
const tableOf = ({ table }) => ({
|
|
31
|
+
...table.schema !== void 0 && { schema: table.schema },
|
|
32
|
+
name: table.name
|
|
33
|
+
});
|
|
34
|
+
/** What the derived module takes from the app: each derived value of `models`, by its name across resources. */
|
|
35
|
+
const derivedInput = (models) => ({
|
|
36
|
+
names: {},
|
|
37
|
+
resources: { values: Object.fromEntries(models.flatMap((model) => (model.derived ?? []).map((value) => [derivedName(model.name, value.name), {
|
|
38
|
+
table: tableOf(model),
|
|
39
|
+
input: derivedName(model.name, value.name)
|
|
40
|
+
}]))) }
|
|
41
|
+
});
|
|
42
|
+
const rowsOf = async (db, query) => (await query.execute(db)).rows;
|
|
43
|
+
/**
|
|
44
|
+
* The derived schema as the database has it: step 1 once its tables, sequence and indexes are there, and each derived
|
|
45
|
+
* value `declared` marks, current when the input declares it, else recorded at no digest on the table of its resource's
|
|
46
|
+
* name, so the next migration drops its state. Refuses a schema of an earlier shape, which no step records.
|
|
47
|
+
*/
|
|
48
|
+
const readDerived = async (db, input) => {
|
|
49
|
+
const [found] = await rowsOf(db, sql`select to_regclass('derived.values') is not null as values,
|
|
50
|
+
to_regclass('derived.reads') is not null and to_regclass('derived.declared') is not null and to_regclass('derived.versions') is not null and to_regclass('derived.pending') is not null as complete`);
|
|
51
|
+
if (!found.values) return;
|
|
52
|
+
if (!(found.complete && await hasIndexes(db, "derived", "reads", ["reads_match", "reads_value"]) && await hasIndexes(db, "derived", "pending", ["pending_value"]))) throw new Error("The derived schema lacks its versions sequence, pending table or indexes, which no step of this version of Protobase records: bring it there with `protobase migration` and `protobase migrate` of the Protobase release before this one first, then run this command again");
|
|
53
|
+
const declared = (await rowsOf(db, sql`select "name" from "derived"."declared"`)).map((row) => row.name);
|
|
54
|
+
const given = input.resources[values.name] ?? {};
|
|
55
|
+
const entries = {};
|
|
56
|
+
for (const name of declared) {
|
|
57
|
+
const wanted = given[name];
|
|
58
|
+
entries[name] = wanted ? resourceEntry(values, input.names, wanted) : {
|
|
59
|
+
version: values.version,
|
|
60
|
+
digest: "",
|
|
61
|
+
table: { name: name.slice(0, name.lastIndexOf(".")) }
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
lastStep: 1,
|
|
66
|
+
replaceables: {},
|
|
67
|
+
...declared.length > 0 && { resources: { [values.name]: entries } }
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* The `derived` schema the resources' derived values keep their state in, and each value's declaration. Its tables are
|
|
72
|
+
* never dropped.
|
|
73
|
+
*/
|
|
74
|
+
const derivedModule = {
|
|
75
|
+
label: "the derived schema",
|
|
76
|
+
title: "The state of the resources' derived values and what they read",
|
|
77
|
+
steps: [{
|
|
78
|
+
step: 1,
|
|
79
|
+
name: "derived",
|
|
80
|
+
title: "The derived schema: the values, what they read, the changes pending and the values declared",
|
|
81
|
+
additive: true,
|
|
82
|
+
sql: () => `${derivedTablesSql()};`
|
|
83
|
+
}],
|
|
84
|
+
replaceables: [],
|
|
85
|
+
resourceReplaceables: [values],
|
|
86
|
+
read: readDerived
|
|
87
|
+
};
|
|
88
|
+
//#endregion
|
|
89
|
+
export { derivedInput, derivedModule };
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import { jobsSchema } from "../jobs/schema.js";
|
|
2
|
-
import { hasIndexes } from "../has-indexes.js";
|
|
3
|
-
import { migrationCommand } from "../changes/capture-schema.js";
|
|
4
|
-
import { sql } from "kysely";
|
|
5
1
|
//#region src/derived/derived-sql.ts
|
|
6
2
|
/** The schema derived values are kept in: their state, what they read and which are declared. */
|
|
7
3
|
const derivedSchema = "derived";
|
|
@@ -57,47 +53,5 @@ create table if not exists "${derivedSchema}"."pending" (
|
|
|
57
53
|
create table if not exists "${derivedSchema}"."declared" ("name" text primary key);
|
|
58
54
|
|
|
59
55
|
${indexes.map(([name, on]) => `create index if not exists "${name}" on "${derivedSchema}".${on}`).join(";\n")}`;
|
|
60
|
-
const found = async (db, relation) => (await sql`select to_regclass(${relation}) is not null as found`.execute(db)).rows[0].found;
|
|
61
|
-
const hasTables = async (db) => await found(db, "derived.values") && await found(db, "derived.reads") && await found(db, "derived.declared");
|
|
62
|
-
const isComplete = async (db) => await hasTables(db) && await found(db, "derived.versions") && await found(db, "derived.pending");
|
|
63
|
-
const versionsAfter = `select setval('"${derivedSchema}"."versions"', max("version")) from "${derivedSchema}"."values" having max("version") is not null`;
|
|
64
|
-
const readsWiden = `update "${derivedSchema}"."reads" set "eq_field" = null, "eq_value" = null where "eq_field" is not null`;
|
|
65
|
-
const declared = async (db) => new Set((await sql`select "name" from "derived"."declared"`.execute(db)).rows.map((row) => row.name));
|
|
66
|
-
const quote = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
67
|
-
/**
|
|
68
|
-
* The SQL that adds the `derived` schema and its tables, and for each derived value not declared before, marks it
|
|
69
|
-
* declared and enqueues the job that computes its records once. A value no longer declared loses its mark, state and
|
|
70
|
-
* reads, so declaring it again fills it again. `undefined` when there is nothing to do.
|
|
71
|
-
*/
|
|
72
|
-
const derivedMigration = async (db, models) => {
|
|
73
|
-
const names = derivedNames(models);
|
|
74
|
-
const exists = await hasTables(db);
|
|
75
|
-
if (names.length === 0 && !exists) return void 0;
|
|
76
|
-
const sequence = exists && await found(db, "derived.versions");
|
|
77
|
-
const pending = exists && await found(db, "derived.pending");
|
|
78
|
-
const tables = names.length === 0 || sequence && pending && await hasIndexes(db, "derived", "reads", ["reads_match", "reads_value"]) && await hasIndexes(db, "derived", "pending", ["pending_value"]);
|
|
79
|
-
const known = exists ? await declared(db) : /* @__PURE__ */ new Set();
|
|
80
|
-
const fresh = names.filter((name) => !known.has(name));
|
|
81
|
-
const gone = [...known].filter((name) => !names.includes(name));
|
|
82
|
-
if (tables && fresh.length === 0 && gone.length === 0) return void 0;
|
|
83
|
-
const removals = gone.flatMap((name) => [
|
|
84
|
-
"declared",
|
|
85
|
-
"reads",
|
|
86
|
-
...pending || !tables ? ["pending"] : [],
|
|
87
|
-
"values"
|
|
88
|
-
].map((table) => `delete from "${derivedSchema}"."${table}" where "name" = ${quote(name)}`));
|
|
89
|
-
const fills = fresh.flatMap((name) => [`insert into "${derivedSchema}"."declared" ("name") values (${quote(name)}) on conflict do nothing`, `select ${jobsSchema}.enqueue(${quote(fillJobName)}, ${quote(JSON.stringify({ name }))}::jsonb, key => ${quote(name)})`]);
|
|
90
|
-
return [
|
|
91
|
-
...tables ? [] : [derivedTablesSql(), ...exists && !sequence ? [versionsAfter, readsWiden] : []],
|
|
92
|
-
...removals,
|
|
93
|
-
...fills
|
|
94
|
-
].map((statement) => `${statement};`).join("\n\n");
|
|
95
|
-
};
|
|
96
|
-
/** Refuses to go on while a resource has derived values and the database lacks their tables; the project's migrations add them. */
|
|
97
|
-
const checkDerived = async (db, models) => {
|
|
98
|
-
if (derivedNames(models).length === 0) return;
|
|
99
|
-
if (await isComplete(db)) return;
|
|
100
|
-
throw new Error(`The derived schema is missing, and resources with .derived() keep their values' state in it. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
|
|
101
|
-
};
|
|
102
56
|
//#endregion
|
|
103
|
-
export {
|
|
57
|
+
export { derivedName, derivedNames, derivedSchema, derivedTablesSql, fillJobName };
|
|
@@ -7,14 +7,19 @@ import { CallsAccess } from "../calls/calls-access.js";
|
|
|
7
7
|
import { ChannelSender } from "../channels/channel-sender.js";
|
|
8
8
|
import { FunctionRecords } from "./records.js";
|
|
9
9
|
import { Capability } from "@protobase/schema";
|
|
10
|
-
import {
|
|
10
|
+
import { ScopedDb } from "@protobase/query";
|
|
11
11
|
//#region src/functions/define-function.d.ts
|
|
12
12
|
/** What every function gets: its name and the raw database. */
|
|
13
13
|
export type PublicFunctionContext = {
|
|
14
14
|
/** The function's name, as in `/api/functions/<name>`. */
|
|
15
15
|
name: string;
|
|
16
|
-
/**
|
|
17
|
-
|
|
16
|
+
/**
|
|
17
|
+
* The database, with no access rules or row filters, and the tenant scope of `.tenant()` resources neither: privileged
|
|
18
|
+
* work only. The tables whose rows belong to one organization, `member`, `invitation` and `personal_access_token`, it
|
|
19
|
+
* keeps to the caller's (`ScopedDb`); a public function's to none, so it reads none of their rows and writes none.
|
|
20
|
+
* `db.unscoped('<reason>')` reads them all.
|
|
21
|
+
*/
|
|
22
|
+
db: ScopedDb;
|
|
18
23
|
/** Broadcasts to the channel of a record, as the server, to whoever is on it (see `/api/channels`). */
|
|
19
24
|
channels: ChannelSender;
|
|
20
25
|
/** The caller, through the app's own `authenticate`: rejects with a 401 problem when the request carries no valid token. */
|
|
@@ -63,7 +68,8 @@ export type FunctionContext = PublicFunctionContext & FunctionCaller & {
|
|
|
63
68
|
/** What a function gets at `/api/sb/functions/v1/<name>`, where supabase-js calls it: the caller its keys and token make. */
|
|
64
69
|
export type KeyFunctionContext = {
|
|
65
70
|
name: string;
|
|
66
|
-
|
|
71
|
+
/** The database as a public function's: no organization's rows of the tables that hold them. */
|
|
72
|
+
db: ScopedDb;
|
|
67
73
|
/** The caller of the `apikey` header and bearer token: rejects with a 401 problem when they admit nobody. */
|
|
68
74
|
caller: () => Promise<Caller>;
|
|
69
75
|
};
|