@protobase/server 0.129.1 → 0.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/dist/assistant/query-runner/grants-sql.js +32 -0
  2. package/dist/assistant/query-runner/query-input.js +33 -0
  3. package/dist/assistant/query-runner/query-module.js +44 -0
  4. package/dist/assistant/query-runner/query-runner.d.ts +8 -11
  5. package/dist/assistant/query-runner/query-runner.js +15 -57
  6. package/dist/assistant/query-runner/read-query.js +54 -0
  7. package/dist/assistant/query-runner/runner-sql.js +4 -20
  8. package/dist/assistant/query-runner/steps/001-role.js +19 -0
  9. package/dist/auth-store.d.ts +2 -2
  10. package/dist/auth-store.js +3 -3
  11. package/dist/better-auth/auth-schema.d.ts +13 -4
  12. package/dist/better-auth/auth-schema.js +40 -32
  13. package/dist/better-auth/auth-settings.d.ts +59 -11
  14. package/dist/better-auth/auth-settings.js +57 -13
  15. package/dist/better-auth/auth-tables.d.ts +6 -3
  16. package/dist/better-auth/auth-tables.js +12 -7
  17. package/dist/better-auth/authenticator.js +10 -2
  18. package/dist/better-auth/create-auth.d.ts +62 -7
  19. package/dist/better-auth/create-auth.js +55 -14
  20. package/dist/better-auth/device-sign-in-check.js +13 -0
  21. package/dist/better-auth/names/declaration.d.ts +18 -5
  22. package/dist/better-auth/names/declaration.js +3 -1
  23. package/dist/better-auth/names/modules/auth.js +9 -0
  24. package/dist/better-auth/names/modules/index.d.ts +34 -4
  25. package/dist/better-auth/names/modules/organizations.js +10 -3
  26. package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
  27. package/dist/better-auth/names/modules-on.js +25 -2
  28. package/dist/better-auth/names/resolve-names.d.ts +9 -1
  29. package/dist/better-auth/names/resolve-names.js +15 -9
  30. package/dist/better-auth/organizations/accept-invitation.js +5 -4
  31. package/dist/better-auth/organizations/add-every-user.js +3 -2
  32. package/dist/better-auth/organizations/host-scope.d.ts +10 -0
  33. package/dist/better-auth/organizations/host-scope.js +15 -0
  34. package/dist/better-auth/organizations/host.d.ts +12 -6
  35. package/dist/better-auth/organizations/host.js +99 -61
  36. package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
  37. package/dist/better-auth/organizations/kept-organizations.js +62 -0
  38. package/dist/better-auth/organizations/member-endpoints.js +4 -3
  39. package/dist/better-auth/organizations/options.d.ts +15 -0
  40. package/dist/better-auth/organizations/options.js +19 -1
  41. package/dist/better-auth/organizations/people-endpoint.js +3 -2
  42. package/dist/better-auth/organizations/pinned-membership.js +81 -0
  43. package/dist/better-auth/organizations/pinned-sessions.js +46 -0
  44. package/dist/better-auth/organizations/session-organization.js +3 -2
  45. package/dist/better-auth/organizations/store.js +14 -9
  46. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  47. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  48. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  49. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  50. package/dist/better-auth/store/adoption.js +25 -10
  51. package/dist/better-auth/store/drift.js +5 -4
  52. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  53. package/dist/better-auth/store/legacy-record.js +56 -0
  54. package/dist/better-auth/store/migration-sql.js +31 -26
  55. package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
  56. package/dist/better-auth/store/offline/baseline-store.js +15 -12
  57. package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
  58. package/dist/better-auth/store/offline/module-switches.js +94 -0
  59. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  60. package/dist/better-auth/store/offline/name-changes.js +5 -2
  61. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
  62. package/dist/better-auth/store/offline/offline-steps.js +29 -20
  63. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  64. package/dist/better-auth/store/offline/retired-watch.js +36 -0
  65. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  66. package/dist/better-auth/store/offline/settings-names.js +10 -3
  67. package/dist/better-auth/store/offline/store-model.d.ts +9 -1
  68. package/dist/better-auth/store/offline/store-model.js +22 -5
  69. package/dist/better-auth/store/resources-outside.js +1 -1
  70. package/dist/better-auth/store/step-record.d.ts +13 -0
  71. package/dist/better-auth/store/step-record.js +59 -0
  72. package/dist/better-auth/store/steps/index.js +6 -1
  73. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  74. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  75. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  76. package/dist/better-auth/store/steps/render.d.ts +3 -0
  77. package/dist/better-auth/store/steps/render.js +48 -25
  78. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  79. package/dist/better-auth/store/steps/step-lint.js +31 -10
  80. package/dist/better-auth/store/steps/step.d.ts +18 -0
  81. package/dist/better-auth/store/steps/step.js +7 -1
  82. package/dist/better-auth/store/store-db.d.ts +6 -0
  83. package/dist/better-auth/store/store-db.js +11 -5
  84. package/dist/better-auth/store/store-names.d.ts +4 -0
  85. package/dist/better-auth/token-standing.js +12 -7
  86. package/dist/better-auth/users.d.ts +7 -2
  87. package/dist/better-auth/users.js +25 -3
  88. package/dist/built-in-resources.js +1 -1
  89. package/dist/calls/calls-module.js +42 -0
  90. package/dist/calls/calls-sql.js +4 -30
  91. package/dist/changes/capture-names.d.ts +3 -1
  92. package/dist/changes/capture-names.js +5 -2
  93. package/dist/changes/capture-schema-sql.d.ts +10 -0
  94. package/dist/changes/capture-schema-sql.js +21 -0
  95. package/dist/changes/capture-schema.d.ts +0 -18
  96. package/dist/changes/capture-schema.js +1 -74
  97. package/dist/changes/capture-sql.js +30 -24
  98. package/dist/changes/changes-input.js +36 -0
  99. package/dist/changes/changes-module.js +44 -0
  100. package/dist/changes/read-capture.js +67 -0
  101. package/dist/changes/steps/001-outbox.js +23 -0
  102. package/dist/channels/sends-module.js +37 -0
  103. package/dist/channels/sends-schema-sql.js +5 -5
  104. package/dist/comments/comments-module.js +30 -0
  105. package/dist/comments/comments-sql.js +1 -22
  106. package/dist/computed/buckets-sql.d.ts +5 -1
  107. package/dist/computed/buckets-sql.js +39 -46
  108. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  109. package/dist/computed/buckets-targets.js +50 -0
  110. package/dist/computed/computed-input.js +65 -0
  111. package/dist/computed/computed-module.js +102 -0
  112. package/dist/computed/formula-sql.js +14 -1
  113. package/dist/computed/read-computed.js +100 -0
  114. package/dist/computed/rollup-sql.js +13 -10
  115. package/dist/config-exports.d.ts +2 -2
  116. package/dist/create-admin.js +21 -5
  117. package/dist/derived/derived-module.js +89 -0
  118. package/dist/derived/derived-sql.js +1 -47
  119. package/dist/functions/define-function.d.ts +10 -4
  120. package/dist/functions/routes.js +5 -3
  121. package/dist/functions/supabase-routes.js +7 -5
  122. package/dist/history/history-module.js +34 -0
  123. package/dist/index.d.ts +19 -28
  124. package/dist/index.js +11 -21
  125. package/dist/internal.d.ts +26 -10
  126. package/dist/internal.js +22 -8
  127. package/dist/jobs/functions-sql.js +7 -11
  128. package/dist/jobs/job-data.js +36 -0
  129. package/dist/jobs/job-types.d.ts +6 -3
  130. package/dist/jobs/jobs-module.d.ts +5 -0
  131. package/dist/jobs/jobs-module.js +84 -0
  132. package/dist/jobs/run-job.d.ts +1 -1
  133. package/dist/jobs/run-job.js +7 -5
  134. package/dist/jobs/runtime.d.ts +9 -4
  135. package/dist/jobs/runtime.js +11 -6
  136. package/dist/jobs/schema.d.ts +0 -11
  137. package/dist/jobs/schema.js +1 -59
  138. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  139. package/dist/live/notices-module.js +30 -0
  140. package/dist/live/notices-sql.js +2 -1
  141. package/dist/mail/feedback/feedback-schema.js +3 -30
  142. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  143. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  144. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  145. package/dist/migration-record/check-record.d.ts +9 -7
  146. package/dist/migration-record/check-record.js +12 -11
  147. package/dist/migration-record/module-needs.js +30 -0
  148. package/dist/migration-record/read-record.js +27 -15
  149. package/dist/migration-record/record-model.d.ts +7 -2
  150. package/dist/migration-record/record-model.js +14 -6
  151. package/dist/migration-record/startup-decision.js +18 -7
  152. package/dist/migration-sql/additive-statements.d.ts +4 -0
  153. package/dist/migration-sql/additive-statements.js +105 -0
  154. package/dist/notifications/devices-module.js +61 -0
  155. package/dist/notifications/history-module.js +50 -0
  156. package/dist/notifications/notifications-targets.js +23 -0
  157. package/dist/notifications/read-table.js +16 -0
  158. package/dist/notifications/schema-sql.js +1 -22
  159. package/dist/notifications/schema.js +1 -101
  160. package/dist/notifications/table-names.js +40 -0
  161. package/dist/organization-scope/app-scope.js +38 -0
  162. package/dist/organization-scope/auth-request-organization.js +71 -0
  163. package/dist/organization-scope/organization-tables.js +20 -0
  164. package/dist/organization-scope/sign-in-organization.js +21 -0
  165. package/dist/package.js +1 -1
  166. package/dist/personal-mail/shared-sender-store.js +4 -2
  167. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  168. package/dist/relation-found.js +6 -0
  169. package/dist/relay/read-relay.js +85 -0
  170. package/dist/relay/realtime-members-sql.js +51 -28
  171. package/dist/relay/relay-module.js +53 -0
  172. package/dist/relay/relay-targets.js +28 -0
  173. package/dist/relay/session-end.js +1 -3
  174. package/dist/relay/sessions-sql.js +4 -27
  175. package/dist/rest/table-routes.js +9 -2
  176. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  177. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  178. package/dist/schema-modules/module-difference.d.ts +31 -0
  179. package/dist/schema-modules/module-difference.js +98 -0
  180. package/dist/schema-modules/modules-sql.js +13 -0
  181. package/dist/schema-modules/modules.d.ts +37 -0
  182. package/dist/schema-modules/modules.js +56 -0
  183. package/dist/schema-modules/needed-modules.d.ts +41 -0
  184. package/dist/schema-modules/needed-modules.js +61 -0
  185. package/dist/schema-modules/resource-difference.js +83 -0
  186. package/dist/schema-modules/schema-module.d.ts +112 -0
  187. package/dist/schema-modules/schema-module.js +8 -0
  188. package/dist/status/status-module.js +63 -0
  189. package/dist/status/status-targets.js +21 -0
  190. package/dist/types.d.ts +6 -1
  191. package/dist/user-tables/reloading-admin.d.ts +1 -0
  192. package/dist/user-tables/reloading-admin.js +1 -0
  193. package/dist/user-tables/schema-sql.js +1 -14
  194. package/dist/user-tables/schema.js +4 -27
  195. package/dist/user-tables/user-tables-module.js +38 -0
  196. package/dist/webhooks/table/delivery-log-module.js +36 -0
  197. package/dist/webhooks/table/owner-roles.js +3 -2
  198. package/dist/webhooks/table/schema-sql.js +27 -26
  199. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  200. package/dist/webhooks/table/webhooks-targets.js +26 -0
  201. package/dist/webhooks/webhooks.js +1 -1
  202. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  203. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  204. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  205. package/dist/workflows/read-catalogue.js +23 -0
  206. package/dist/workflows/schema-sql.js +12 -9
  207. package/dist/workflows/status-sql.js +12 -6
  208. package/dist/workflows/storage/storage-module.js +39 -0
  209. package/dist/workflows/storage/storage-sql.js +8 -5
  210. package/dist/workflows/workflows-schema-module.js +49 -0
  211. package/dist/workflows/workflows-tables-sql.js +32 -0
  212. package/dist/workflows/workflows-targets.js +16 -0
  213. package/package.json +6 -6
  214. package/dist/assistant/query-runner/runner-plan.js +0 -30
  215. package/dist/better-auth/store/migrations-table.js +0 -27
  216. package/dist/better-auth/store/modules-off.js +0 -17
  217. package/dist/calls/calls-sql.d.ts +0 -11
  218. package/dist/changes/capture-plan.js +0 -79
  219. package/dist/channels/sends-schema.d.ts +0 -7
  220. package/dist/channels/sends-schema.js +0 -18
  221. package/dist/comments/comments-sql.d.ts +0 -14
  222. package/dist/computed/buckets-plan.d.ts +0 -2
  223. package/dist/computed/buckets-plan.js +0 -88
  224. package/dist/computed/buckets-schema.js +0 -39
  225. package/dist/computed/computed-plan.js +0 -81
  226. package/dist/computed/computed-schema.d.ts +0 -16
  227. package/dist/computed/computed-schema.js +0 -63
  228. package/dist/derived/derived-sql.d.ts +0 -12
  229. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  230. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  231. package/dist/notifications/schema.d.ts +0 -14
  232. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  233. package/dist/realtime/relay/relay-schema.js +0 -20
  234. package/dist/relay/realtime-members-schema.js +0 -67
  235. package/dist/relay/relay-schema.d.ts +0 -14
  236. package/dist/relay/relay-schema.js +0 -28
  237. package/dist/status/schema.d.ts +0 -12
  238. package/dist/status/schema.js +0 -33
  239. package/dist/user-tables/schema.d.ts +0 -11
  240. package/dist/webhooks/table/schema.d.ts +0 -16
  241. package/dist/webhooks/table/schema.js +0 -56
  242. package/dist/workflows/schema.d.ts +0 -13
  243. package/dist/workflows/schema.js +0 -88
@@ -1,79 +0,0 @@
1
- import { captureBody, captureFunctionSql, capturedBy, createTriggerSql, dropTriggerSql, outboxSql, quoteIdent, resourceTriggers, tableSql } from "./capture-sql.js";
2
- import { historyTableSql } from "../history/history-sql.js";
3
- import { checkLiveReads } from "../check-live-reads.js";
4
- import { noticesTableSql } from "../live/notices-sql.js";
5
- //#region src/changes/capture-plan.ts
6
- const sameTrigger = (found, wanted) => found.type === wanted.type && found.args.length === wanted.args.length && found.args.every((arg, index) => arg === wanted.args[index]);
7
- const tableOf = (state, model, pending) => {
8
- const table = state.tables[model.name];
9
- if (!table && pending.includes(model.name)) return `pending:${tableSql(model)}`;
10
- if (!table) throw new Error(`The table ${tableSql(model)} of resource "${model.name}" does not exist`);
11
- return table;
12
- };
13
- /**
14
- * Compares the database with the resources that declare events, history or live updates. Fails on what it cannot change safely: a
15
- * missing table, a captured view, two captured resources on one table, or a trigger of the same name that calls another function.
16
- * The tables of the `pending` resources may be missing: a migration written before this one creates them.
17
- */
18
- const capturePlan = (schema, models, state, pending = []) => {
19
- checkLiveReads(models);
20
- const captured = models.filter(capturedBy(models));
21
- const views = captured.filter((model) => state.views.includes(model.name)).map((model) => model.name);
22
- if (views.length > 0) throw new Error(`Resource "${views.join("\", \"")}" is backed by a view, which takes no trigger: give it no events, history or derived values, name it in no other resource's reads, and make it live with .live({ reads }) naming the resources of the tables it reads`);
23
- const capture = state.capture;
24
- const current = capture !== void 0 && capture.definer && capture.source === captureBody(schema);
25
- const wanted = captured.flatMap((model) => resourceTriggers(model).map((trigger) => ({
26
- model,
27
- trigger,
28
- table: tableOf(state, model, pending)
29
- })));
30
- const tables = /* @__PURE__ */ new Map();
31
- for (const { model, table } of wanted) {
32
- const other = tables.get(table);
33
- if (other && other !== model.name) throw new Error(`Not implemented: resources "${other}" and "${model.name}" both have events or history on table ${tableSql(model)}; declare them on one`);
34
- tables.set(table, model.name);
35
- }
36
- const create = wanted.filter(({ model, trigger, table }) => {
37
- const found = state.triggers.find((candidate) => candidate.table === table && candidate.name === trigger.name);
38
- if (found && found.function !== capture?.oid) throw new Error(`Table ${tableSql(model)} has a trigger "${trigger.name}" of its own; rename it, since events and history need that name`);
39
- return !found || !sameTrigger(found, trigger);
40
- });
41
- const drop = state.triggers.filter((found) => found.function === capture?.oid).filter((found) => !wanted.some(({ trigger, table }) => table === found.table && trigger.name === found.name));
42
- return {
43
- setup: captured.length > 0 && (!state.outbox || !current),
44
- history: models.some((model) => model.history) && (!state.history || !state.historyIndexed),
45
- historyMissing: models.some((model) => model.history) && !state.history,
46
- notices: models.some((model) => model.live) && !state.notices,
47
- create: create.map(({ model, trigger }) => ({
48
- model,
49
- trigger
50
- })),
51
- drop: drop.map(({ name, tableSql }) => ({
52
- name,
53
- tableSql
54
- }))
55
- };
56
- };
57
- /** The plan as SQL statements, each made to apply over what exists already; `undefined` when there is nothing to do. */
58
- const planSql = (schema, plan) => {
59
- const statements = [
60
- ...plan.setup ? [
61
- `create schema if not exists ${quoteIdent(schema)}`,
62
- outboxSql(schema),
63
- captureFunctionSql(schema)
64
- ] : [],
65
- ...plan.history ? [`create schema if not exists ${quoteIdent(schema)}`, historyTableSql(schema)] : [],
66
- ...plan.notices ? [`create schema if not exists ${quoteIdent(schema)}`, noticesTableSql(schema)] : [],
67
- ...plan.drop.map(({ name, tableSql }) => dropTriggerSql(name, tableSql)),
68
- ...plan.create.flatMap(({ model, trigger }) => [dropTriggerSql(trigger.name, tableSql(model)), createTriggerSql(schema, trigger, tableSql(model))])
69
- ];
70
- return statements.length === 0 ? void 0 : `${statements.join(";\n\n")};`;
71
- };
72
- /** The resources whose changes would not be captured or kept as the config declares: what a server refuses to start with. */
73
- const uncaptured = (plan, models) => [...new Set([
74
- ...plan.setup ? models.filter(capturedBy(models)) : plan.create.map(({ model }) => model),
75
- ...plan.historyMissing ? models.filter((model) => model.history) : [],
76
- ...plan.notices ? models.filter((model) => model.live) : []
77
- ].map((model) => model.name))];
78
- //#endregion
79
- export { capturePlan, planSql, uncaptured };
@@ -1,7 +0,0 @@
1
- import { Db } from "@protobase/query";
2
- //#region src/channels/sends-schema.d.ts
3
- /** The SQL that adds the `channels` schema `realtime: { sqlSends: true }` needs; `undefined` when it is there. */
4
- export declare const channelSendsMigration: (db: Db) => Promise<"create schema if not exists channels;\n\ncreate table if not exists channels.sends (\n id bigint generated always as identity primary key,\n resource text not null,\n key text not null,\n event text not null,\n payload jsonb not null,\n sent_at timestamptz not null default now()\n);\n\ncreate index if not exists sends_sent_at on channels.sends (sent_at);\n\ncreate or replace function channels.send(resource text, key text, event text, payload jsonb) returns void\n language sql security definer set search_path = ''\n as $$ insert into channels.sends (resource, key, event, payload) values (send.resource, send.key, send.event, send.payload) $$;\n\nrevoke execute on function channels.send(text, text, text, jsonb) from public;" | undefined>;
5
- /** Refuses to go on while the `channels` schema is missing; the project's migrations add it. */
6
- export declare const checkChannelSends: (db: Db) => Promise<void>;
7
- //#endregion
@@ -1,18 +0,0 @@
1
- import { sendsSchema, sendsSchemaSql } from "./sends-schema-sql.js";
2
- import { migrationCommand } from "../changes/capture-schema.js";
3
- import { sql } from "kysely";
4
- //#region src/channels/sends-schema.ts
5
- const sendsCurrent = async (db) => {
6
- const { rows } = await sql`select to_regclass(${`${sendsSchema}.sends`}) is not null
7
- and to_regprocedure(${`${sendsSchema}.send(text, text, text, jsonb)`}) is not null as found`.execute(db);
8
- return rows[0].found;
9
- };
10
- /** The SQL that adds the `channels` schema `realtime: { sqlSends: true }` needs; `undefined` when it is there. */
11
- const channelSendsMigration = async (db) => await sendsCurrent(db) ? void 0 : sendsSchemaSql;
12
- /** Refuses to go on while the `channels` schema is missing; the project's migrations add it. */
13
- const checkChannelSends = async (db) => {
14
- if (await sendsCurrent(db)) return;
15
- throw new Error(`The ${sendsSchema} schema that realtime.sqlSends needs is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
16
- };
17
- //#endregion
18
- export { channelSendsMigration, checkChannelSends };
@@ -1,14 +0,0 @@
1
- import { ResourceModel } from "@protobase/schema";
2
- import { Db } from "@protobase/query";
3
- //#region src/comments/comments-sql.d.ts
4
- /**
5
- * The SQL that adds the `comments` schema and its table, or the indexes it lacks, `undefined` when it has them all. The
6
- * table is never dropped.
7
- */
8
- export declare const commentsMigration: (db: Db) => Promise<string | undefined>;
9
- /**
10
- * Refuses to go on while a resource has `.comments()` and the database lacks their table; the project's migrations add
11
- * it. An index added since only speeds reads up, so a table without it still serves and `protobase migration` adds it.
12
- */
13
- export declare const checkComments: (db: Db, models: readonly ResourceModel[]) => Promise<void>;
14
- //#endregion
@@ -1,2 +0,0 @@
1
- import "./buckets-sql.js";
2
- import { ResourceModel } from "@protobase/schema";
@@ -1,88 +0,0 @@
1
- import { quoteIdent } from "../changes/capture-sql.js";
2
- import { rollupsSchema } from "./rollup-sql.js";
3
- import { bucketsBody, bucketsComment, bucketsFillSql, bucketsFunctionSql, createBucketsSql, dropBucketsTableSql, sumType } from "./buckets-sql.js";
4
- import { measureFieldName } from "@protobase/schema/internal";
5
- //#region src/computed/buckets-plan.ts
6
- /** The time rollups of the resources, with the resources they roll up. */
7
- const bucketModels = (models) => models.flatMap((model) => {
8
- if (!model.buckets) return [];
9
- const from = models.find((candidate) => candidate.name === model.buckets.from);
10
- if (!from) throw new Error(`Resource "${model.name}" is a time rollup of "${model.buckets.from}", which is not a resource`);
11
- return [{
12
- model,
13
- from
14
- }];
15
- });
16
- /** A time rollup with its tables and column types; fails on a source column the catalogue does not have. */
17
- const bucketsTarget = (model, from, found, table) => {
18
- if (!found.from) throw new Error(`The table of resource "${from.name}", which "${model.name}" rolls up, does not exist`);
19
- const { types } = found.from;
20
- const sourceColumn = (field) => {
21
- const column = from.fields[field].column;
22
- if (!types[column]) throw new Error(`Table ${found.from.sql} has no column ${quoteIdent(column)} for field "${from.name}.${field}"`);
23
- return column;
24
- };
25
- const { time, every, by, measures } = model.buckets;
26
- const timeColumn = sourceColumn(time);
27
- return {
28
- model,
29
- table,
30
- fromTable: found.from.sql,
31
- every,
32
- time: {
33
- column: timeColumn,
34
- zoned: types[timeColumn] === "timestamp with time zone"
35
- },
36
- by: by.map((field) => ({
37
- column: model.fields[field].column,
38
- from: sourceColumn(field),
39
- type: types[sourceColumn(field)]
40
- })),
41
- measures: Object.entries(measures).flatMap(([field, fns]) => fns.map((fn) => {
42
- const column = sourceColumn(field);
43
- return {
44
- fn,
45
- column: model.fields[measureFieldName(field, fn)].column,
46
- from: column,
47
- type: fn === "sum" ? sumType(types[column]) : types[column]
48
- };
49
- })),
50
- counts: Object.keys(measures).map((field) => ({
51
- column: model.fields[measureFieldName(field, "count")].column,
52
- from: sourceColumn(field)
53
- })),
54
- ...from.softDelete && { softDelete: sourceColumn(from.softDelete) }
55
- };
56
- };
57
- const targetStatements = (target, found) => {
58
- if (!found.table) return createBucketsSql(target);
59
- if (!found.table.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`);
60
- if (found.table.comment !== bucketsComment(target)) return [`-- The time rollup "${target.model.name}" changed: its table is created again and filled\n${dropBucketsTableSql(target)}`, ...createBucketsSql(target)];
61
- if (found.functionSource !== bucketsBody(target)) return [bucketsFunctionSql(target), bucketsFillSql(target)];
62
- return [];
63
- };
64
- /**
65
- * Compares the database with the resources' time rollups. A missing table is created, with its indexes, function and
66
- * values; a changed one is dropped and created again; a changed function is written again and refills the rollup. A
67
- * table of the project's own where a rollup is declared fails. The table and function of a rollup the config no longer
68
- * has stay: a migration of the project's own drops them, a deploy after the one that stops reading them.
69
- */
70
- const bucketsPlan = (models, state) => {
71
- const behind = [];
72
- const statements = [];
73
- for (const { model, from } of bucketModels(models)) {
74
- const found = state.rollups[model.name];
75
- const table = `${quoteIdent(model.table.schema ?? found.table?.schema ?? state.schema)}.${quoteIdent(model.table.name)}`;
76
- const target = bucketsTarget(model, from, found, table);
77
- const sql = targetStatements(target, found);
78
- if (sql.length === 0) continue;
79
- behind.push(model.name);
80
- statements.push(...sql);
81
- }
82
- return {
83
- statements: statements.length > 0 ? [`create schema if not exists ${quoteIdent(rollupsSchema)}`, ...statements] : [],
84
- behind
85
- };
86
- };
87
- //#endregion
88
- export { bucketModels, bucketsPlan, bucketsTarget };
@@ -1,39 +0,0 @@
1
- import { tableSql } from "../changes/capture-sql.js";
2
- import { rollupsSchema } from "./rollup-sql.js";
3
- import { bucketsFunctionName } from "./buckets-sql.js";
4
- import { bucketModels, bucketsPlan } from "./buckets-plan.js";
5
- import { sql } from "kysely";
6
- //#region src/computed/buckets-schema.ts
7
- const rowsOf = async (db, query) => (await query.execute(db)).rows;
8
- const readRollup = async (db, model, from) => {
9
- const [source] = await rowsOf(db, sql`select c.oid::text as oid, format('%I.%I', n.nspname, c.relname) as sql from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = to_regclass(${tableSql(from)})`);
10
- const columns = source ? await rowsOf(db, sql`select attname as name, format_type(atttypid, atttypmod) as type from pg_attribute where attrelid = ${source.oid}::oid and attnum > 0 and not attisdropped`) : [];
11
- const [table] = await rowsOf(db, sql`select n.nspname as schema, obj_description(c.oid, 'pg_class') as comment from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = to_regclass(${tableSql(model)})`);
12
- const [fn] = await rowsOf(db, sql`select p.prosrc as source from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${rollupsSchema} and p.proname = ${bucketsFunctionName({ model })} and p.pronargs = 1 and p.proargtypes[0] = 'timestamptz'::regtype`);
13
- return {
14
- from: source ? {
15
- sql: source.sql,
16
- types: Object.fromEntries(columns.map((column) => [column.name, column.type]))
17
- } : null,
18
- table: table ?? null,
19
- functionSource: fn?.source ?? null
20
- };
21
- };
22
- const readBucketsState = async (db, models) => {
23
- const [current] = await rowsOf(db, sql`select current_schema() as schema`);
24
- const rollups = {};
25
- for (const { model, from } of bucketModels(models)) rollups[model.name] = await readRollup(db, model, from);
26
- return {
27
- schema: current.schema,
28
- rollups
29
- };
30
- };
31
- /** Whether a resource is a time rollup. */
32
- const hasBuckets = (model) => model.buckets !== void 0;
33
- /** The statements that bring the database to the resources' time rollups, and the rollups that are behind. */
34
- const bucketsMigrationPlan = async (db, models) => models.some(hasBuckets) ? bucketsPlan(models, await readBucketsState(db, models)) : {
35
- statements: [],
36
- behind: []
37
- };
38
- //#endregion
39
- export { bucketsMigrationPlan, hasBuckets };
@@ -1,81 +0,0 @@
1
- import { quoteIdent } from "../changes/capture-sql.js";
2
- import { columnType } from "./column-sql.js";
3
- import { addRollupColumnSql, backfillSql, dropRollupFunctionSql, dropRollupTriggerSql, rollupBody, rollupFunctionName, rollupFunctionSql, rollupTriggerName, rollupTriggerSql, rollupsSchema } from "./rollup-sql.js";
4
- import { addFormulaSql, formulaComment, isFormulaComment } from "./formula-sql.js";
5
- import { rollupTargets } from "./rollup-targets.js";
6
- //#region src/computed/computed-plan.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
- const fieldName = (model, field) => `${model.name}.${field.name}`;
10
- const formulaStatements = (model, field, table, found) => {
11
- const name = `${table}.${quoteIdent(field.column)}`;
12
- if (!found) return addFormulaSql(table, model, field);
13
- if (!found.generated) throw new Error(`Column ${name} of formula field "${fieldName(model, field)}" is a plain column; drop or rename it in a migration, then write the formula's with \`protobase migration\``);
14
- if (!isFormulaComment(found.comment)) throw new Error(`Column ${name} of formula field "${fieldName(model, field)}" is a generated column of the project's own; drop it in a migration, or remove .formula()`);
15
- if (found.comment === formulaComment(model, field) && found.type === columnType(field)) return [];
16
- return [`-- The formula of "${fieldName(model, field)}" changed: its column is generated again, and an index on it has to be created again\nalter table ${table} drop column ${quoteIdent(field.column)}`, ...addFormulaSql(table, model, field)];
17
- };
18
- const rollupColumnStatements = (target, found) => {
19
- const name = `${target.table}.${quoteIdent(target.field.column)}`;
20
- if (!found) return [addRollupColumnSql(target)];
21
- if (found.generated) throw new Error(`Column ${name} of rollup field "${fieldName(target.model, target.field)}" is a generated column; drop it in a migration, then write the rollup's with \`protobase migration\``);
22
- if (found.type !== columnType(target.field)) throw new Error(`Column ${name} of rollup field "${fieldName(target.model, target.field)}" is ${found.type}, not ${columnType(target.field)} as the field declares; change one of them`);
23
- return [];
24
- };
25
- /**
26
- * Compares the database with the resources' rollup and formula fields. Fails on what it cannot change safely: a
27
- * missing table, a column of the project's own where one is declared, or a trigger of the same name that calls another
28
- * function. A changed formula's column is dropped and added again; a rollup's function, trigger and values are written
29
- * again when its column is new or its definition changed. Columns are never dropped otherwise.
30
- */
31
- const computedPlan = (models, state) => {
32
- const table = (model) => {
33
- const found = state.tables[model.name];
34
- if (!found) throw new Error(`The table of resource "${model.name}" does not exist`);
35
- return found;
36
- };
37
- const column = (model, field) => state.columns.find((found) => found.table === table(model).oid && found.name === field.column);
38
- const behind = [];
39
- const formulas = [];
40
- const regenerated = /* @__PURE__ */ new Set();
41
- for (const model of models) for (const field of Object.values(model.fields).filter((candidate) => candidate.formula !== void 0)) {
42
- const sql = formulaStatements(model, field, table(model).sql, column(model, field));
43
- if (sql.length === 0) continue;
44
- behind.push(fieldName(model, field));
45
- if (column(model, field)) regenerated.add(fieldName(model, field));
46
- formulas.push(...sql);
47
- }
48
- const readsRegenerated = ({ from, field }) => field.rollup.field !== void 0 && regenerated.has(`${from.name}.${field.rollup.field}`);
49
- const targets = rollupTargets(models, (model) => table(model).sql);
50
- const rollupColumns = [];
51
- const droppedTriggers = [];
52
- const rollups = [];
53
- for (const target of targets) {
54
- const columnSql = rollupColumnStatements(target, column(target.model, target.field));
55
- const fn = state.functions.find((found) => found.name === rollupFunctionName(target));
56
- const fromOid = table(target.from).oid;
57
- const own = state.triggers.find((found) => found.table === fromOid && found.name === rollupTriggerName(target));
58
- if (own && !state.functions.some((found) => found.oid === own.function)) throw new Error(`Table ${target.fromTable} has a trigger "${own.name}" of its own; rename it, since rollup field "${fieldName(target.model, target.field)}" needs that name`);
59
- const stale = fn ? state.triggers.filter((found) => found.function === fn.oid && (found.table !== fromOid || found.name !== rollupTriggerName(target))) : [];
60
- if (columnSql.length === 0 && fn !== void 0 && fn.definer && fn.source === rollupBody(target) && own?.function === fn.oid && stale.length === 0 && !readsRegenerated(target)) continue;
61
- behind.push(fieldName(target.model, target.field));
62
- rollupColumns.push(...columnSql);
63
- droppedTriggers.push(...stale.map((found) => dropRollupTriggerSql(found.name, found.tableSql)), dropRollupTriggerSql(rollupTriggerName(target), target.fromTable));
64
- rollups.push(rollupFunctionSql(target), rollupTriggerSql(target), backfillSql(target));
65
- }
66
- const wanted = targets.map(rollupFunctionName);
67
- const dropped = state.functions.filter((found) => !wanted.includes(found.name)).map((found) => dropRollupFunctionSql(found.name));
68
- return {
69
- statements: [
70
- ...rollups.length > 0 ? [`create schema if not exists ${quoteIdent(rollupsSchema)}`] : [],
71
- ...dropped,
72
- ...droppedTriggers,
73
- ...rollupColumns,
74
- ...formulas,
75
- ...rollups
76
- ],
77
- behind
78
- };
79
- };
80
- //#endregion
81
- export { computedPlan, hasComputed };
@@ -1,16 +0,0 @@
1
- import { ResourceModel } from "@protobase/schema";
2
- import { Db } from "@protobase/query";
3
- //#region src/computed/computed-schema.d.ts
4
- /**
5
- * The SQL that brings the database to the resources' rollup and formula fields: their columns, and for each rollup
6
- * the function and trigger that keep it, with its values set once; then their time rollups: each one's table, indexes
7
- * and refresh function, filled once. `undefined` when the database is current.
8
- */
9
- export declare const computedMigration: (db: Db, models: readonly ResourceModel[]) => Promise<string | undefined>;
10
- /**
11
- * Refuses to go on while a rollup or formula field's column, function or trigger, or a time rollup's table or refresh
12
- * function, is missing or out of date. The server never changes the schema itself: the project's migrations do, before
13
- * the new version serves. Reads nothing without such fields or rollups.
14
- */
15
- export declare const checkComputed: (db: Db, models: readonly ResourceModel[]) => Promise<void>;
16
- //#endregion
@@ -1,63 +0,0 @@
1
- import { tableSql } from "../changes/capture-sql.js";
2
- import { migrationCommand } from "../changes/capture-schema.js";
3
- import { rollupsSchema } from "./rollup-sql.js";
4
- import { bucketsMigrationPlan, hasBuckets } from "./buckets-schema.js";
5
- import { computedPlan, hasComputed } from "./computed-plan.js";
6
- import { sql } from "kysely";
7
- //#region src/computed/computed-schema.ts
8
- const rowsOf = async (db, query) => (await query.execute(db)).rows;
9
- const involved = (models) => {
10
- const computed = models.filter(hasComputed);
11
- const read = new Set(computed.flatMap((model) => Object.values(model.fields).flatMap((field) => field.rollup ? [field.rollup.from] : [])));
12
- return models.filter((model) => hasComputed(model) || read.has(model.name));
13
- };
14
- const readComputedState = async (db, models) => {
15
- const tables = {};
16
- for (const model of involved(models)) {
17
- const [found] = await rowsOf(db, sql`select c.oid::text as oid, format('%I.%I', n.nspname, c.relname) as sql from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = to_regclass(${tableSql(model)})`);
18
- tables[model.name] = found ?? null;
19
- }
20
- const wanted = models.filter(hasComputed).flatMap((model) => Object.values(model.fields).filter((field) => field.rollup || field.formula !== void 0).flatMap((field) => tables[model.name] ? [`${tables[model.name].oid}:${field.column}`] : []));
21
- const columns = await rowsOf(db, sql`select a.attrelid::text as "table", a.attname as name, format_type(a.atttypid, a.atttypmod) as type, a.attgenerated <> '' as generated, col_description(a.attrelid, a.attnum) as comment
22
- from pg_attribute a where a.attnum > 0 and not a.attisdropped and a.attrelid::text || ':' || a.attname = any(${wanted}::text[])`);
23
- const functions = await rowsOf(db, sql`select p.oid::text as oid, p.proname as name, p.prosrc as source, p.prosecdef as definer from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${rollupsSchema} and p.prorettype = 'trigger'::regtype`);
24
- const oids = Object.values(tables).flatMap((found) => found ? [found.oid] : []);
25
- return {
26
- tables,
27
- columns,
28
- functions,
29
- triggers: await rowsOf(db, sql`select t.tgrelid::text as "table", format('%I.%I', ns.nspname, c.relname) as "tableSql", t.tgname as name, t.tgfoid::text as "function"
30
- from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace ns on ns.oid = c.relnamespace
31
- where not t.tgisinternal and (t.tgfoid::text = any(${functions.map((found) => found.oid)}::text[]) or t.tgrelid::text = any(${oids}::text[]))`)
32
- };
33
- };
34
- const plan = async (db, models) => {
35
- const fields = computedPlan(models, await readComputedState(db, models));
36
- const buckets = await bucketsMigrationPlan(db, models);
37
- return {
38
- statements: [...fields.statements, ...buckets.statements],
39
- behind: [...fields.behind, ...buckets.behind]
40
- };
41
- };
42
- /**
43
- * The SQL that brings the database to the resources' rollup and formula fields: their columns, and for each rollup
44
- * the function and trigger that keep it, with its values set once; then their time rollups: each one's table, indexes
45
- * and refresh function, filled once. `undefined` when the database is current.
46
- */
47
- const computedMigration = async (db, models) => {
48
- const { statements } = await plan(db, models);
49
- return statements.length === 0 ? void 0 : `${statements.join(";\n\n")};`;
50
- };
51
- /**
52
- * Refuses to go on while a rollup or formula field's column, function or trigger, or a time rollup's table or refresh
53
- * function, is missing or out of date. The server never changes the schema itself: the project's migrations do, before
54
- * the new version serves. Reads nothing without such fields or rollups.
55
- */
56
- const checkComputed = async (db, models) => {
57
- if (!models.some((model) => hasComputed(model) || hasBuckets(model))) return;
58
- const { behind } = await plan(db, models);
59
- if (behind.length === 0) return;
60
- throw new Error(`The rollup and formula fields and time rollups ${behind.join(", ")} are not kept by the database as declared: their columns, tables, functions or triggers are missing or out of date. Write the change as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
61
- };
62
- //#endregion
63
- export { checkComputed, computedMigration };
@@ -1,12 +0,0 @@
1
- import { ResourceModel } from "@protobase/schema";
2
- import { Db } from "@protobase/query";
3
- //#region src/derived/derived-sql.d.ts
4
- /**
5
- * The SQL that adds the `derived` schema and its tables, and for each derived value not declared before, marks it
6
- * declared and enqueues the job that computes its records once. A value no longer declared loses its mark, state and
7
- * reads, so declaring it again fills it again. `undefined` when there is nothing to do.
8
- */
9
- export declare const derivedMigration: (db: Db, models: readonly ResourceModel[]) => Promise<string | undefined>;
10
- /** Refuses to go on while a resource has derived values and the database lacks their tables; the project's migrations add them. */
11
- export declare const checkDerived: (db: Db, models: readonly ResourceModel[]) => Promise<void>;
12
- //#endregion
@@ -1,7 +0,0 @@
1
- import { Db } from "@protobase/query";
2
- //#region src/mail/feedback/feedback-schema.d.ts
3
- /** The SQL that adds the feedback's schema and table, the indexes it lacks, or what an earlier version's table lacks; `undefined` when it has them all. */
4
- export declare const mailFeedbackMigration: (db: Db) => Promise<string | undefined>;
5
- /** Refuses to start while `mailFeedback` is on and its table, or the unique index a write stands on, is missing; the project's migrations add them. */
6
- export declare const checkMailFeedbackSchema: (db: Db) => Promise<void>;
7
- //#endregion
@@ -1,10 +0,0 @@
1
- import { Db } from "@protobase/query";
2
- //#region src/mail/unsubscribe/unsubscribe-schema.d.ts
3
- /** The SQL that adds the opt-outs' schema and table, or the indexes it lacks; `undefined` when it has them all. */
4
- export declare const unsubscribesMigration: (db: Db) => Promise<string | undefined>;
5
- /**
6
- * Refuses to start while `unsubscribe` is on and its table, or the unique index recording an opt-out stands on, is
7
- * missing; the project's migrations add them.
8
- */
9
- export declare const checkUnsubscribesSchema: (db: Db) => Promise<void>;
10
- //#endregion
@@ -1,14 +0,0 @@
1
- import { AdminAuth } from "../better-auth/create-auth.js";
2
- import { NotificationsOptions } from "./options.js";
3
- import { Db } from "@protobase/query";
4
- //#region src/notifications/schema.d.ts
5
- /**
6
- * The SQL that adds the tables `notifications` keeps devices and each user's history in, under the names its options
7
- * give; with `auth`, their user columns point at auth's users table. Each table is left out when it exists or a store
8
- * of the app's own replaces it; an existing devices table without its session column gets that column, and one whose
9
- * checks allow no relay devices gets checks that do. `undefined` when nothing is left.
10
- */
11
- export declare const notificationsMigration: (db: Db, options?: NotificationsOptions, auth?: AdminAuth) => Promise<string | undefined>;
12
- /** Refuses to start while the devices or the history table lacks what `notifications` needs, naming it. */
13
- export declare const checkNotificationsSchema: (db: Db, options?: NotificationsOptions, auth?: AdminAuth) => Promise<void>;
14
- //#endregion
@@ -1,7 +0,0 @@
1
- import { Db } from "@protobase/query";
2
- //#region src/realtime/relay/relay-schema.d.ts
3
- /** The SQL that adds the `realtime_relay` schema `realtime: { processes: 'many' }` needs; `undefined` when it is there. */
4
- export declare const realtimeRelayMigration: (db: Db) => Promise<string | undefined>;
5
- /** Refuses to go on while the `realtime_relay` schema is missing; the project's migrations add it. */
6
- export declare const checkRealtimeRelay: (db: Db) => Promise<void>;
7
- //#endregion
@@ -1,20 +0,0 @@
1
- import { migrationCommand } from "../../changes/capture-schema.js";
2
- import { relaySchema, relaySchemaSql, relayTables, spacedTables } from "./relay-schema-sql.js";
3
- import { sql } from "kysely";
4
- //#region src/realtime/relay/relay-schema.ts
5
- const relayCurrent = async (db) => {
6
- const names = relayTables.map((table) => `${relaySchema}.${table}`);
7
- const { rows } = await sql`select bool_and(to_regclass(name) is not null) as found from unnest(${names}::text[]) as name`.execute(db);
8
- if (!rows[0].found) return false;
9
- return (await sql`select count(*)::int as count from information_schema.columns
10
- where table_schema = ${relaySchema} and table_name = any(${[...spacedTables]}::text[]) and column_name = 'space'`.execute(db)).rows[0].count === spacedTables.length;
11
- };
12
- /** The SQL that adds the `realtime_relay` schema `realtime: { processes: 'many' }` needs; `undefined` when it is there. */
13
- const realtimeRelayMigration = async (db) => await relayCurrent(db) ? void 0 : relaySchemaSql;
14
- /** Refuses to go on while the `realtime_relay` schema is missing; the project's migrations add it. */
15
- const checkRealtimeRelay = async (db) => {
16
- if (await relayCurrent(db)) return;
17
- throw new Error(`The ${relaySchema} schema that realtime.processes "many" needs is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
18
- };
19
- //#endregion
20
- export { checkRealtimeRelay, realtimeRelayMigration };
@@ -1,67 +0,0 @@
1
- import { argsOf, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger } from "./realtime-members-sql.js";
2
- import { sql } from "kysely";
3
- //#region src/relay/realtime-members-schema.ts
4
- const storedArgs = (args) => Buffer.from(args.map((arg) => `${arg}\0`).join(""), "utf8").toString("hex");
5
- /**
6
- * Refuses channel tables that are partitions, or that inherit or are inherited from other than by partitioning: their
7
- * rows are written through a table the triggers do not stand on. A partitioned channel table is kept (see `membersSql`).
8
- */
9
- const refuseInherited = (tables) => {
10
- if (tables.length === 0) return;
11
- throw new Error(`realtime.members cannot keep the members of ${tables.join(", ")}: a partition or a table in an inheritance tree is not supported as a channel resource whose records list their members; use the partitioned table itself`);
12
- };
13
- /**
14
- * The listed tables as the database has them: each one and its partitions as SQL names them, and whether
15
- * it is refused (`refuseInherited`); and whether the members table exists.
16
- */
17
- const listedTables = async (db, listed) => {
18
- const { rows } = await sql`select name,
19
- to_regclass(name)::text as rel, to_regclass(${realtimeMembersTable}) is not null as members,
20
- exists (select from pg_class c where c.oid = to_regclass(name) and (c.relispartition or (c.relkind <> 'p' and exists (select from pg_inherits i where i.inhrelid = c.oid or i.inhparent = c.oid)))) as inherited,
21
- array(select tree.relid::regclass::text from pg_partition_tree(to_regclass(name)) as tree where tree.relid <> to_regclass(name) order by tree.relid::regclass::text) as partitions
22
- from unnest(${listed.map(({ table }) => table)}::text[]) with ordinality as listed(name, place) order by place`.execute(db);
23
- refuseInherited(rows.filter((row) => row.inherited).map((row) => row.name));
24
- return rows;
25
- };
26
- /**
27
- * Whether the triggers of this version stand on exactly the listed tables with their args, a truncate trigger on each
28
- * of their partitions too, each firing on every write (enabled, not only for replicas), as must the clones of the row
29
- * trigger Postgres keeps on the partitions, and the members table exists; the tables, as SQL names them, with any of
30
- * them but clones; and the partitions of each listed table. A partition attached later lacks its truncate trigger, so
31
- * startup asks for the migration that writes them all again.
32
- */
33
- const standingTriggers = async (db, listed) => {
34
- const tables = await listedTables(db, listed);
35
- const { rows } = await sql`select t.tgname as name,
36
- encode(t.tgargs, 'hex') as args, coalesce(obj_description(p.oid, 'pg_proc') = ${membersComment}, false) as current, t.tgenabled in ('O', 'A') as enabled,
37
- t.tgparentid <> 0 as clone, t.tgrelid::regclass::text as "table"
38
- from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace n on n.oid = p.pronamespace
39
- where n.nspname = ${realtimeSchema} and p.proname = 'members_kept'`.execute(db);
40
- const roots = rows.filter((row) => !row.clone);
41
- const expected = listed.flatMap((table, i) => {
42
- const { rel, partitions } = tables[i];
43
- const args = storedArgs(argsOf(table));
44
- return [`${rel}|${rowTrigger}|${args}`, ...[rel, ...partitions].map((on) => `${on}|${truncateTrigger}|${args}`)];
45
- });
46
- const found = roots.map((row) => `${row.table}|${row.name}|${row.args}`);
47
- const exact = expected.length === found.length && expected.every((entry) => found.includes(entry)) && rows.every((row) => row.current && row.enabled);
48
- const membersTable = listed.length === 0 || tables.every((row) => row.members && row.rel !== null);
49
- return {
50
- current: exact && membersTable,
51
- standing: [...new Set(roots.map((row) => row.table))],
52
- partitions: tables.map((row) => row.partitions)
53
- };
54
- };
55
- /** The SQL that keeps `realtime.members` for the listed tables (`membersSql`); `undefined` when it is current. */
56
- const realtimeMembersMigration = async (db, listed) => {
57
- const { current, standing, partitions } = await standingTriggers(db, listed);
58
- if (current) return;
59
- return `${membersSql(listed, standing, partitions).join(";\n\n")};`;
60
- };
61
- /** Refuses to start while `realtime.members` would not follow the listed tables' members. */
62
- const checkRealtimeMembers = async (db, listed, command) => {
63
- if ((await standingTriggers(db, listed)).current) return;
64
- throw new Error(`The realtime.members table, or the triggers that keep it on ${listed.map(({ table }) => table).join(", ")} and their partitions, is missing or out of date. Write it as a migration with \`${command}\`, apply it with the project's migrations, then start again.`);
65
- };
66
- //#endregion
67
- export { checkRealtimeMembers, realtimeMembersMigration, refuseInherited };
@@ -1,14 +0,0 @@
1
- import { RealtimeRelaySettings } from "./relay-options.js";
2
- import { AdminAuth } from "../better-auth/create-auth.js";
3
- import { ResourceModel } from "@protobase/schema";
4
- import { Db } from "@protobase/query";
5
- //#region src/relay/relay-schema.d.ts
6
- /**
7
- * The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
8
- * deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
9
- * their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
10
- */
11
- export declare const relayMigration: (db: Db, auth: AdminAuth | undefined, authWritten: boolean, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<string | undefined>;
12
- /** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
13
- export declare const checkRelaySchema: (db: Db, auth: AdminAuth | undefined, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<void>;
14
- //#endregion
@@ -1,28 +0,0 @@
1
- import { migrationCommand } from "../changes/capture-schema.js";
2
- import { relayModels } from "./relay-models.js";
3
- import { checkRelaySessions, relaySessionsMigration } from "./sessions-sql.js";
4
- import { listedTable } from "./realtime-members-sql.js";
5
- import { sessionsTable } from "./session-end.js";
6
- import { checkRealtimeMembers, realtimeMembersMigration } from "./realtime-members-schema.js";
7
- //#region src/relay/relay-schema.ts
8
- const needsAuth = (auth) => {
9
- if (!auth) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
10
- return auth;
11
- };
12
- const listedTables = (channels, models) => [...relayModels({ channels }, models).channels.values()].flatMap((channel) => channel.listed ? [listedTable(channel.listed)] : []);
13
- /**
14
- * The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
15
- * deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
16
- * their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
17
- */
18
- const relayMigration = async (db, auth, authWritten, channels, models) => {
19
- const parts = [await relaySessionsMigration(db, sessionsTable(needsAuth(auth)), authWritten), await realtimeMembersMigration(db, listedTables(channels, models))].filter((part) => part !== void 0);
20
- return parts.length > 0 ? parts.join("\n\n") : void 0;
21
- };
22
- /** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
23
- const checkRelaySchema = async (db, auth, channels, models) => {
24
- await checkRelaySessions(db, sessionsTable(needsAuth(auth)));
25
- await checkRealtimeMembers(db, listedTables(channels, models), migrationCommand);
26
- };
27
- //#endregion
28
- export { checkRelaySchema, relayMigration };
@@ -1,12 +0,0 @@
1
- import { AdminAuth } from "../better-auth/create-auth.js";
2
- import { StatusOptions } from "./options.js";
3
- import { Db } from "@protobase/query";
4
- //#region src/status/schema.d.ts
5
- /**
6
- * The SQL that adds the statuses table `status` keeps people's statuses in, its user column pointing at auth's users
7
- * table; `undefined` when it exists. An app without organizations is refused (see `checkStatusAuth`).
8
- */
9
- export declare const statusMigration: (db: Db, options: StatusOptions, auth: AdminAuth | undefined) => Promise<string | undefined>;
10
- /** Refuses to start while the statuses table is missing, or the app has no organizations. */
11
- export declare const checkStatusSchema: (db: Db, options: StatusOptions, auth: AdminAuth | undefined) => Promise<void>;
12
- //#endregion