@protobase/server 0.129.0 → 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 +35 -0
  56. package/dist/better-auth/store/offline/baseline-store.js +65 -0
  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 -6
  62. package/dist/better-auth/store/offline/offline-steps.js +30 -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 +13 -4
  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 +27 -10
  126. package/dist/internal.js +22 -7
  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
@@ -2,11 +2,6 @@ import { quoteIdent } from "../changes/capture-sql.js";
2
2
  //#region src/notifications/schema-sql.ts
3
3
  /** A table by its schema, when one is named, and its name, quoted. */
4
4
  const qualified = ({ schema, table }) => schema ? `${quoteIdent(schema)}.${quoteIdent(table)}` : quoteIdent(table);
5
- /** The session column, added to a devices table written before devices kept the session they were registered in. */
6
- const deviceSessionColumnSql = ({ schema, table, columns }) => `alter table ${qualified({
7
- schema,
8
- table
9
- })} add column ${quoteIdent(columns.session_id)} text`;
10
5
  const quotedColumns = (columns) => Object.fromEntries(Object.entries(columns).map(([name, value]) => [name, quoteIdent(value)]));
11
6
  const kindCheck = (c) => `check (${c.kind} in ('web', 'apns', 'fcm', 'relay'))`;
12
7
  const fieldsCheck = (c) => `check (
@@ -16,22 +11,6 @@ const fieldsCheck = (c) => `check (
16
11
  or (${c.kind} = 'relay' and ${c.p256dh} is null and ${c.auth} is null and ${c.environment} is null and ${c.app_id} is null)
17
12
  )`;
18
13
  /**
19
- * The kind checks, replacing `constraints`, those of a devices table written before devices could be relay devices,
20
- * in one statement.
21
- */
22
- const deviceKindChecksSql = ({ schema, table, columns }, constraints) => {
23
- const c = quotedColumns(columns);
24
- const drops = constraints.map((name) => `drop constraint ${quoteIdent(name)}`);
25
- return `alter table ${qualified({
26
- schema,
27
- table
28
- })} ${[
29
- ...drops,
30
- `add ${kindCheck(c)}`,
31
- `add ${fieldsCheck(c)}`
32
- ].join(", ")}`;
33
- };
34
- /**
35
14
  * The devices table: the token unique, so registering one moves it; with auth, its user column points at auth's users
36
15
  * table and goes with the user. A field that does not apply to the kind must be NULL, and nothing has a default.
37
16
  */
@@ -63,4 +42,4 @@ const devicesTableSql = ({ schema, table, columns }, user) => {
63
42
  ];
64
43
  };
65
44
  //#endregion
66
- export { deviceKindChecksSql, deviceSessionColumnSql, devicesTableSql, qualified };
45
+ export { devicesTableSql, qualified };
@@ -1,105 +1,5 @@
1
- import { migrationCommand } from "../changes/capture-schema.js";
2
- import { historyNames, notificationsNames } from "./options.js";
3
- import { deviceKindChecksSql, deviceSessionColumnSql, devicesTableSql, qualified } from "./schema-sql.js";
4
- import { historyTableSql } from "./history-sql.js";
5
- import { legacyKindChecks } from "./legacy-kind-checks.js";
6
1
  import { sql } from "kysely";
7
2
  //#region src/notifications/schema.ts
8
- /** Auth's users table, as the store names it: devices point at it. */
9
- const authUsersTable = (auth) => ({
10
- schema: auth.names.schema,
11
- table: auth.names.table("user").name
12
- });
13
3
  const regclass = async (db, name) => (await sql`select to_regclass(${name})::oid as oid`.execute(db)).rows[0].oid;
14
- const userIdType = async (db, users, of = {
15
- feature: "notifications",
16
- rows: "devices"
17
- }) => {
18
- const oid = await regclass(db, qualified(users));
19
- if (oid === null) throw new Error(`${of.feature}: auth's users table ${qualified(users)} is not in the app's database, so ${of.rows} cannot point at it`);
20
- const { rows } = await sql`select format_type(atttypid, atttypmod) as type from pg_attribute where attrelid = ${oid} and attname = 'id'`.execute(db);
21
- return rows[0].type;
22
- };
23
- const columnsOf = async (db, oid) => (await sql`select attname as name, attnum as num from pg_attribute where attrelid = ${oid} and attnum > 0 and not attisdropped`.execute(db)).rows;
24
- const uniqueOn = async (db, oid, num) => (await sql`select exists (select from pg_index where indrelid = ${oid} and indisunique and indpred is null and indexprs is null and indnatts = 1 and indkey[0] = ${num}) as found`.execute(db)).rows[0].found;
25
- const cascadesFrom = async (db, oid, num, users) => (await sql`select exists (select from pg_constraint where conrelid = ${oid} and contype = 'f' and confdeltype = 'c'
26
- and conkey = array[${num}]::int2[] and confrelid = to_regclass(${qualified(users)})) as found`.execute(db)).rows[0].found;
27
- const lacksSessionColumn = async (db, names) => {
28
- const oid = await regclass(db, qualified(names));
29
- return oid !== null && !(await columnsOf(db, oid)).some((row) => row.name === names.columns.session_id);
30
- };
31
- const kindChecksWithoutRelay = async (db, names) => {
32
- const oid = await regclass(db, qualified(names));
33
- if (oid === null) return [];
34
- const { rows } = await sql`select c.conname as name, pg_get_constraintdef(c.oid) as def from pg_constraint c
35
- join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey)
36
- where c.conrelid = ${oid} and c.contype = 'c' and a.attname = ${names.columns.kind} order by c.conname`.execute(db);
37
- return legacyKindChecks(rows, names.columns);
38
- };
39
- /**
40
- * The SQL that adds the tables `notifications` keeps devices and each user's history in, under the names its options
41
- * give; with `auth`, their user columns point at auth's users table. Each table is left out when it exists or a store
42
- * of the app's own replaces it; an existing devices table without its session column gets that column, and one whose
43
- * checks allow no relay devices gets checks that do. `undefined` when nothing is left.
44
- */
45
- const notificationsMigration = async (db, options = {}, auth) => {
46
- const devices = !options.store && notificationsNames(options);
47
- const history = !options.historyStore && historyNames(options);
48
- const missing = async (names) => names && await regclass(db, qualified(names)) === null;
49
- const [needsDevices, needsHistory] = [await missing(devices), await missing(history)];
50
- const needsSession = devices && !needsDevices && await lacksSessionColumn(db, devices);
51
- const oldChecks = devices && !needsDevices ? await kindChecksWithoutRelay(db, devices) : [];
52
- if (!needsDevices && !needsHistory && !needsSession && oldChecks.length === 0) return void 0;
53
- const users = auth && authUsersTable(auth);
54
- const user = users && (needsDevices || needsHistory) ? {
55
- type: await userIdType(db, users),
56
- references: `${qualified(users)} (id)`
57
- } : { type: "text" };
58
- const statements = [
59
- ...needsDevices && devices ? devicesTableSql(devices, user) : [],
60
- ...needsSession && devices ? [deviceSessionColumnSql(devices)] : [],
61
- ...oldChecks.length > 0 && devices ? [deviceKindChecksSql(devices, oldChecks)] : [],
62
- ...needsHistory && history ? historyTableSql(history, user) : []
63
- ];
64
- return `${[...new Set(statements)].join(";\n\n")};`;
65
- };
66
- const missingTable = (what, table) => /* @__PURE__ */ new Error(`The ${what} table ${table} of notifications is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
67
- /**
68
- * Refuses to start while the devices table lacks what `notifications` needs, naming it: the table, each column under
69
- * its configured name, a unique index on the token alone, which moving a device relies on, and with `auth` a foreign key
70
- * from the user column that deletes a user's devices with the user. Nothing to check with a store of the app's own.
71
- */
72
- const checkDevicesTable = async (db, options, users) => {
73
- if (options.store) return;
74
- const names = notificationsNames(options);
75
- const devices = qualified(names);
76
- const oid = await regclass(db, devices);
77
- if (oid === null) throw missingTable("devices", devices);
78
- const found = await columnsOf(db, oid);
79
- const numOf = (column) => found.find((row) => row.name === names.columns[column])?.num;
80
- const missing = Object.keys(names.columns).find((column) => numOf(column) === void 0);
81
- if (missing !== void 0) throw new Error(`The devices table ${devices} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { devices: { columns: { ${missing}: ... } } } in protobase.config.ts`);
82
- if (!await uniqueOn(db, oid, numOf("token"))) throw new Error(`The devices table ${devices} needs a unique index on its token column "${names.columns.token}" alone, which moving a device to the user who registers it relies on`);
83
- if (users && !await cascadesFrom(db, oid, numOf("user_id"), users)) throw new Error(`The devices table ${devices} needs a foreign key from "${names.columns.user_id}" to ${qualified(users)} with on delete cascade, so a deleted user's devices go with them`);
84
- };
85
- /** Refuses to start while the history table lacks its table, a column or, with `auth`, the cascading foreign key. */
86
- const checkHistoryTable = async (db, options, users) => {
87
- if (options.historyStore) return;
88
- const names = historyNames(options);
89
- const history = qualified(names);
90
- const oid = await regclass(db, history);
91
- if (oid === null) throw missingTable("history", history);
92
- const found = await columnsOf(db, oid);
93
- const numOf = (column) => found.find((row) => row.name === names.columns[column])?.num;
94
- const missing = Object.keys(names.columns).find((column) => numOf(column) === void 0);
95
- if (missing !== void 0) throw new Error(`The history table ${history} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { history: { columns: { ${missing}: ... } } } in protobase.config.ts`);
96
- if (users && !await cascadesFrom(db, oid, numOf("user_id"), users)) throw new Error(`The history table ${history} needs a foreign key from "${names.columns.user_id}" to ${qualified(users)} with on delete cascade, so a deleted user's history goes with them`);
97
- };
98
- /** Refuses to start while the devices or the history table lacks what `notifications` needs, naming it. */
99
- const checkNotificationsSchema = async (db, options = {}, auth) => {
100
- const users = auth && authUsersTable(auth);
101
- await checkDevicesTable(db, options, users);
102
- await checkHistoryTable(db, options, users);
103
- };
104
4
  //#endregion
105
- export { authUsersTable, checkNotificationsSchema, notificationsMigration, regclass, userIdType };
5
+ export { regclass };
@@ -0,0 +1,40 @@
1
+ import { qualified } from "./schema-sql.js";
2
+ //#region src/notifications/table-names.ts
3
+ /** The auth store's users table, or the table that holds the user ids (`users.keyTable`), and the type of its ids. */
4
+ const usersTarget = (store) => {
5
+ if (!store) return {
6
+ users: "",
7
+ idType: "text"
8
+ };
9
+ const users = store.users.keyTable ?? {
10
+ schema: store.schema,
11
+ table: store.names.table("user").name
12
+ };
13
+ return {
14
+ users: qualified(users),
15
+ idType: store.uuidIds ? "uuid" : "text"
16
+ };
17
+ };
18
+ /** A table's names and the users it points at, as a module's names. */
19
+ const moduleNames = ({ schema, table, columns }, { users, idType }) => ({
20
+ schema,
21
+ table,
22
+ users,
23
+ user_id_type: idType,
24
+ ...Object.fromEntries(Object.entries(columns).map(([column, name]) => [`column.${column}`, name]))
25
+ });
26
+ /** The table's names and the users it points at from a module's names, for `columns`. */
27
+ const tableNames = (names, columns) => ({
28
+ table: {
29
+ schema: names.schema,
30
+ table: names.table,
31
+ columns: Object.fromEntries(columns.map((column) => [column, names[`column.${column}`]]))
32
+ },
33
+ user: {
34
+ type: names.user_id_type,
35
+ ...names.users && { references: `${names.users} (id)` }
36
+ },
37
+ users: names.users || void 0
38
+ });
39
+ //#endregion
40
+ export { moduleNames, tableNames, usersTarget };
@@ -0,0 +1,38 @@
1
+ import { keptNamesOf } from "../better-auth/organizations/kept-organizations.js";
2
+ import { noOrganizationTables, organizationTables, sessionOrganization } from "./organization-tables.js";
3
+ //#region src/organization-scope/app-scope.ts
4
+ const unscoped = {
5
+ tables: noOrganizationTables,
6
+ pinned: void 0,
7
+ organizationOf: () => void 0
8
+ };
9
+ /**
10
+ * The app's scope, read once the store says whether organizations were on. With organizations on, the session's
11
+ * active organization. While they are off after being on, the tables they kept, under their names with organizations
12
+ * on, and the pinned organization, for work about none and for a session of it, whose `tenant` is its id; a session
13
+ * of another tenant, such as an outside app's, works in none. An app that never had organizations scopes nothing.
14
+ */
15
+ const appScope = ({ organizations, names, pinned }) => {
16
+ if (organizations) {
17
+ const on = {
18
+ tables: organizationTables(names),
19
+ pinned: void 0,
20
+ organizationOf: sessionOrganization
21
+ };
22
+ return async () => on;
23
+ }
24
+ const kept = names && pinned && keptNamesOf(names);
25
+ if (!kept) return async () => unscoped;
26
+ const tables = organizationTables(kept);
27
+ return async () => {
28
+ const pin = await pinned();
29
+ if (!pin) return unscoped;
30
+ return {
31
+ tables,
32
+ pinned: pin.id,
33
+ organizationOf: (session) => session?.tenant === pin.id ? pin.id : void 0
34
+ };
35
+ };
36
+ };
37
+ //#endregion
38
+ export { appScope };
@@ -0,0 +1,71 @@
1
+ import { inSignInScope } from "./sign-in-organization.js";
2
+ import { authBasePath } from "../better-auth/auth-base-path.js";
3
+ import { everyOrganization } from "@protobase/query";
4
+ //#region src/organization-scope/auth-request-organization.ts
5
+ const acrossPaths = {
6
+ "/organization/list": "a user lists the organizations they are a member of",
7
+ "/organization/list-user-invitations": "a user lists the invitations to their address, from every organization",
8
+ "/organization/get-invitation": "an invitation is found by its id for the person it invites, before they are a member",
9
+ "/organization/reject-invitation": "an invitation is found by its id for the person it invites, before they are a member",
10
+ "/organization/cancel-invitation": "an invitation is found by its id, before the caller's right is checked in its organization",
11
+ "/organization/create": "creating an organization counts the creator's organizations and makes them the new one's first member"
12
+ };
13
+ const bodyOrganization = async (request) => {
14
+ if (request.method !== "POST" || !request.headers.get("content-type")?.includes("application/json")) return;
15
+ let body;
16
+ try {
17
+ body = await request.clone().json();
18
+ } catch (error) {
19
+ if (error instanceof SyntaxError) return;
20
+ throw error;
21
+ }
22
+ const named = body?.organizationId;
23
+ return typeof named === "string" && named !== "" ? named : void 0;
24
+ };
25
+ /** A request that names one organization in its query and another in its body, which is refused. */
26
+ const conflictingOrganizations = Symbol("the query and the body name different organizations");
27
+ const namedOrganization = async (request) => {
28
+ const inQuery = new URL(request.url).searchParams.get("organizationId") || void 0;
29
+ if (request.method !== "POST") return inQuery;
30
+ const inBody = await bodyOrganization(request);
31
+ if (inQuery !== void 0 && inBody !== void 0 && inQuery !== inBody) return conflictingOrganizations;
32
+ return inBody ?? inQuery;
33
+ };
34
+ /**
35
+ * The organization an `/api/auth/*` request works in: every organization for the endpoints that read across them, saying
36
+ * why; the one it names as `organizationId` where its endpoint reads it, where Better Auth checks the caller's membership
37
+ * itself (`conflictingOrganizations` when a POST names two); for another
38
+ * organization endpoint, the session's active organization (`activeOrganization`, read only then); none for the rest,
39
+ * sign-in, sessions and tokens among them, whose reads of the organization's tables name the organization they read in
40
+ * or why they cross organizations.
41
+ */
42
+ const authRequestOrganization = async (request, activeOrganization) => {
43
+ const path = new URL(request.url).pathname.slice(authBasePath.length);
44
+ const across = acrossPaths[path];
45
+ if (across) return everyOrganization(across);
46
+ const named = await namedOrganization(request);
47
+ if (named !== void 0) return named;
48
+ if (path.startsWith("/organization/")) return activeOrganization();
49
+ };
50
+ /**
51
+ * `answer`, Better Auth's handler, with each request's sign-in queries in the organization it works in
52
+ * (`authRequestOrganization`); promises it starts, its background tasks too, stay there. A request naming two
53
+ * organizations is refused with `400`.
54
+ */
55
+ const answerInOrganization = (answer, activeOrganization) => async (request) => {
56
+ const organization = await authRequestOrganization(request, () => activeOrganization(request));
57
+ if (organization === conflictingOrganizations) return Response.json({
58
+ code: "CONFLICTING_ORGANIZATIONS",
59
+ message: "Name the organization once: the query and the body name different ones."
60
+ }, { status: 400 });
61
+ return inSignInScope(organization, () => answer(request));
62
+ };
63
+ /** The active organization of the request's session, read without refreshing it; none without a session. */
64
+ const sessionActiveOrganization = (auth) => async (request) => {
65
+ return ((await auth.api.getSession({
66
+ headers: request.headers,
67
+ query: { disableRefresh: true }
68
+ }))?.session)?.activeOrganizationId ?? void 0;
69
+ };
70
+ //#endregion
71
+ export { answerInOrganization, authRequestOrganization, conflictingOrganizations, sessionActiveOrganization };
@@ -0,0 +1,20 @@
1
+ //#region src/organization-scope/organization-tables.ts
2
+ /**
3
+ * The store's tables whose rows each belong to one organization, under the names the app gives them, on their
4
+ * `organization_id`: `member`, `invitation` and `personal_access_token` while organizations are on, none otherwise.
5
+ */
6
+ const organizationTables = (names) => ({ tables: Object.values(names?.tables ?? {}).flatMap((table) => {
7
+ const column = table.columns.organization_id;
8
+ if (table.scope !== "organization" || !column) return [];
9
+ return [{
10
+ ...table.schema !== void 0 && { schema: table.schema },
11
+ table: table.name,
12
+ column: column.name
13
+ }];
14
+ }) });
15
+ /** No scoped table: the scope of an app without organizations. */
16
+ const noOrganizationTables = { tables: [] };
17
+ /** The organization a session works in: its active one, with organizations on; none for anyone else. */
18
+ const sessionOrganization = (session) => session?.organization?.id;
19
+ //#endregion
20
+ export { noOrganizationTables, organizationTables, sessionOrganization };
@@ -0,0 +1,21 @@
1
+ import { everyOrganization } from "@protobase/query";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ //#region src/organization-scope/sign-in-organization.ts
4
+ const current = new AsyncLocalStorage();
5
+ /**
6
+ * Where sign-in's database (`appAuthOptions`) finds the organization each query works in: the one the work around it
7
+ * set with `inOrganization`, every one within `acrossOrganizations`, and none outside both, which sees no row of the
8
+ * organization's tables and writes none.
9
+ */
10
+ const signInOrganization = () => current.getStore();
11
+ /** Runs `work` with sign-in's queries kept to `scope`: an organization, none, or every one (`everyOrganization`). */
12
+ const inSignInScope = (scope, work) => current.run(scope, work);
13
+ /** Runs `work` with sign-in's queries kept to `organization`; undefined keeps them to none. */
14
+ const inOrganization = (organization, work) => current.run(organization, work);
15
+ /**
16
+ * Runs `work` with sign-in's queries reading every organization's rows: `reason` says why the work crosses
17
+ * organizations, such as "a user lists their own memberships". Refused without one.
18
+ */
19
+ const acrossOrganizations = (reason, work) => current.run(everyOrganization(reason), work);
20
+ //#endregion
21
+ export { acrossOrganizations, inOrganization, inSignInScope, signInOrganization };
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.129.0";
2
+ var version = "0.130.0";
3
3
  //#endregion
4
4
  export { version };
@@ -1,3 +1,4 @@
1
+ import { acrossOrganizations } from "../organization-scope/sign-in-organization.js";
1
2
  import { sql } from "kysely";
2
3
  //#region src/personal-mail/shared-sender-store.ts
3
4
  /**
@@ -17,7 +18,7 @@ const sharedSenderReader = (store, { organizations, verifiers }) => async (userI
17
18
  const proved = verifiers.length === 0 ? sql`null::timestamptz` : sql`(select max(${v.settled_at}) from ${verification} where ${v.sender_id} = ${sender}.id and ${v.verifier} = any(${[...verifiers]}::text[]) and ${v.state} = 'verified' and ${v.valid_until} > now())`;
18
19
  const inReach = member ? sql`and ${sender}.${c.user_id} in (select theirs.${member.columns.user_id} from ${member} as mine join ${member} as theirs on theirs.${member.columns.organization_id} = mine.${member.columns.organization_id} where mine.${member.columns.user_id} = ${userId})` : sql``;
19
20
  const named = id === void 0 ? sql`` : sql`and ${sender}.id = ${id}`;
20
- const { rows } = await sql`select ${sender}.id, ${sender}.${c.user_id} as "userId", ${sender}.${c.connection_id} as "connectionId", ${sender}.${c.address} as address,
21
+ const query = sql`select ${sender}.id, ${sender}.${c.user_id} as "userId", ${sender}.${c.connection_id} as "connectionId", ${sender}.${c.address} as address,
21
22
  ${sender}.${c.name} as name, ${sender}.${c.shared_at} as "sharedAt", ${sender}.${c.signature} as signature, false as "isDefault", ${sender}.${c.created_at} as "createdAt",
22
23
  ${sender}.${c.typed_at} as "typedAt", ${sender}.${c.listed_at} as "listedAt", ${sender}.${c.provider_state} as "providerState",
23
24
  ${sender}.${c.provider_state_read_at} as "providerStateReadAt", ${sender}.${c.removed_at} as "removedAt",
@@ -26,7 +27,8 @@ const sharedSenderReader = (store, { organizations, verifiers }) => async (userI
26
27
  from ${sender}
27
28
  left join ${account} on ${account}.id = ${sender}.${c.connection_id} and ${account}.${a.user_id} = ${sender}.${c.user_id}
28
29
  where ${sender}.${c.shared_at} is not null and ${sender}.${c.user_id} <> ${userId} ${named} ${inReach}
29
- order by ${sender}.${c.created_at}, ${sender}.${c.address_key}, ${sender}.id`.execute(s.db);
30
+ order by ${sender}.${c.created_at}, ${sender}.${c.address_key}, ${sender}.id`;
31
+ const { rows } = await (member ? acrossOrganizations("a user reads the addresses shared with them by people of their own organizations", () => query.execute(s.db)) : query.execute(s.db));
30
32
  return rows.map((row) => ({
31
33
  ...row,
32
34
  account: row.account && {
@@ -0,0 +1,37 @@
1
+ import { relaySchema, relaySchemaSql, relayTables, spacedTables } from "./relay-schema-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/realtime/relay/realtime-relay-module.ts
4
+ /**
5
+ * The `realtime_relay` schema as the database has it: step 1 once every table is there with its `space` column.
6
+ * Refuses one written before the record channels, which no step records.
7
+ */
8
+ const readRealtimeRelay = async (db) => {
9
+ const names = relayTables.map((table) => `${relaySchema}.${table}`);
10
+ const { rows } = await sql`select
11
+ (select count(*)::int from unnest(${names}::text[]) as name where to_regclass(name) is not null) as found,
12
+ (select count(*)::int from information_schema.columns where table_schema = ${relaySchema} and table_name = any(${[...spacedTables]}::text[]) and column_name = 'space') as spaced`.execute(db);
13
+ const { found, spaced } = rows[0];
14
+ if (found === 0) return;
15
+ if (found < relayTables.length || spaced < spacedTables.length) throw new Error(`The ${relaySchema} schema lacks tables or columns no step of this version of Protobase records: bring it there with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
16
+ return {
17
+ lastStep: 1,
18
+ replaceables: {}
19
+ };
20
+ };
21
+ /** The `realtime_relay` schema that carries broadcasts and presence between the processes serving the app. Never dropped. */
22
+ const realtimeRelayModule = {
23
+ label: `the ${relaySchema} schema`,
24
+ title: "The relay of Realtime broadcasts and presence between the processes serving the app",
25
+ steps: [{
26
+ step: 1,
27
+ name: "relay",
28
+ title: "The frames, presences, processes and rates tables",
29
+ additive: true,
30
+ sql: () => relaySchemaSql
31
+ }],
32
+ replaceables: [],
33
+ resourceReplaceables: [],
34
+ read: readRealtimeRelay
35
+ };
36
+ //#endregion
37
+ export { realtimeRelayModule };
@@ -0,0 +1,6 @@
1
+ import { sql } from "kysely";
2
+ //#region src/relation-found.ts
3
+ /** Whether the database has a relation of the name, as SQL writes it, such as `"webhooks"."subscriptions"`. Only reads the catalogue. */
4
+ const relationFound = async (db, name) => (await sql`select to_regclass(${name}) is not null as found`.execute(db)).rows[0].found;
5
+ //#endregion
6
+ export { relationFound };
@@ -0,0 +1,85 @@
1
+ import { sessionsCurrent } from "./sessions-sql.js";
2
+ import { argsOf, realtimeMembersTable, realtimeSchema } from "./realtime-members-sql.js";
3
+ import { resourceEntry } from "../schema-modules/resource-difference.js";
4
+ import { sql } from "kysely";
5
+ //#region src/relay/read-relay.ts
6
+ const triggerArgs = (hex) => new TextDecoder().decode(Buffer.from(hex, "hex")).split("\0").slice(0, -1);
7
+ const readTriggers = async (db) => (await sql`select t.tgrelid::regclass::text as "table",
8
+ n.nspname as schema, c.relname, t.tgname as name,
9
+ encode(t.tgargs, 'hex') as args,
10
+ t.tgenabled in ('O', 'A') and not exists (
11
+ with recursive clones as (select oid, tgenabled from pg_trigger where tgparentid = t.oid
12
+ union all select c.oid, c.tgenabled from pg_trigger c join clones on c.tgparentid = clones.oid)
13
+ select from clones where tgenabled not in ('O', 'A')
14
+ ) as enabled,
15
+ array(select tree.relid::regclass::text from pg_partition_tree(t.tgrelid) as tree where tree.relid <> t.tgrelid order by 1) as partitions
16
+ from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace pn on pn.oid = p.pronamespace
17
+ join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
18
+ where pn.nspname = ${realtimeSchema} and p.proname = 'members_kept' and t.tgparentid = 0`.execute(db)).rows.map((row) => ({
19
+ ...row,
20
+ args: triggerArgs(row.args)
21
+ }));
22
+ const regclassText = async (db, tables) => (await sql`select to_regclass(name)::text as text from unnest(${tables}::text[]) with ordinality as listed(name, place) order by place`.execute(db)).rows.map((row) => row.text);
23
+ /**
24
+ * Whether `found` keeps `listed` on its table `rel`: the row trigger and a truncate trigger on it and on each of its
25
+ * partitions, with its arguments, every one firing.
26
+ */
27
+ const keeps = (found, listed, rel) => {
28
+ const args = argsOf(listed).join("\0");
29
+ const own = found.filter((trigger) => trigger.args.join("\0") === args && (trigger.table === rel || found.some((root) => root.table === rel && root.partitions.includes(trigger.table))));
30
+ const row = own.find((trigger) => trigger.table === rel && trigger.name === "realtime_members");
31
+ if (!row) return false;
32
+ return [rel, ...row.partitions].every((table) => own.some((trigger) => trigger.table === table && trigger.name === "realtime_members_truncated")) && own.every((trigger) => trigger.enabled);
33
+ };
34
+ /**
35
+ * The relay's objects as the database has them for `input`: step 1 once `realtime.members` is there, the sessions
36
+ * trigger at its version when it stands on the sessions table with this version's function, the members functions at
37
+ * the version their comment names, and each listed resource whose table has the triggers this version writes, else at
38
+ * no digest, so they are written again; and the row triggers on tables no listed resource has, by the resource their
39
+ * first argument names, so they are dropped. Refuses members functions of a version no step records.
40
+ */
41
+ const readRelay = (members) => async (db, input) => {
42
+ const [state] = (await sql`select to_regclass(${realtimeMembersTable}) is not null as table,
43
+ (select obj_description(p.oid, 'pg_proc') from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${realtimeSchema} and p.proname = 'members_kept' and p.pronargs = 0) as comment`.execute(db)).rows;
44
+ const sessions = await sessionsCurrent(db, input.names.sessions);
45
+ if (!state.table && !sessions) return;
46
+ const version = state.comment?.match(/^Protobase realtime members (\d+)$/)?.[1];
47
+ if (state.comment && Number(version) !== 3) throw new Error(`The functions that keep realtime.members are at ${version === void 0 ? "a version" : `version ${version}`} no step of this version of Protobase records: bring them to version 3 with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
48
+ const found = await readTriggers(db);
49
+ const given = Object.entries(input.resources[members.name] ?? {});
50
+ const rels = await regclassText(db, given.map(([, { input: listed }]) => listed.table));
51
+ const entries = {};
52
+ given.forEach(([key, one], i) => {
53
+ const rel = rels[i];
54
+ if (!rel || !found.some((trigger) => trigger.table === rel && trigger.name === "realtime_members")) return;
55
+ const entry = resourceEntry(members, input.names, one);
56
+ entries[key] = keeps(found, one.input, rel) ? entry : {
57
+ ...entry,
58
+ digest: ""
59
+ };
60
+ });
61
+ for (const trigger of found) {
62
+ const [resource] = trigger.args;
63
+ if (trigger.name !== "realtime_members" || resource === void 0 || rels.includes(trigger.table)) continue;
64
+ const key = entries[resource] ? `${resource} on ${trigger.table}` : resource;
65
+ entries[key] = {
66
+ version: members.version,
67
+ digest: "",
68
+ table: {
69
+ schema: trigger.schema,
70
+ name: trigger.relname
71
+ }
72
+ };
73
+ }
74
+ return {
75
+ lastStep: state.table ? 1 : 0,
76
+ replaceables: {
77
+ ...sessions && { sessions: 1 },
78
+ ...version !== void 0 && { members: 3 }
79
+ },
80
+ names: input.names,
81
+ ...Object.keys(entries).length > 0 && { resources: { [members.name]: entries } }
82
+ };
83
+ };
84
+ //#endregion
85
+ export { readRelay };
@@ -16,16 +16,8 @@ const listedTable = ({ model, field }) => ({
16
16
  deleted: model.softDelete === void 0 ? "" : model.fields[model.softDelete].column
17
17
  });
18
18
  const literal = (text) => `'${text.replaceAll("'", "''")}'`;
19
- /**
20
- * The members table, keyed by channel so a notice's audience is read by its key, with an index by person for their
21
- * tickets and co-members; `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the
22
- * trigger function. A truncate, of the table or of one of its partitions, writes the resource's members again from the
23
- * table as it stands, so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
24
- * delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
25
- * from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
26
- * swaps two records' keys leaves each key with the members its record lists.
27
- */
28
- const baseSql = [
19
+ /** The members table, keyed by channel so a notice's audience is read by its key, with an index by person for their tickets and co-members. */
20
+ const membersTableSql = [
29
21
  `create schema if not exists ${realtimeSchema}`,
30
22
  `create table if not exists ${realtimeMembersTable} (
31
23
  resource text not null,
@@ -33,7 +25,17 @@ const baseSql = [
33
25
  user_id text not null,
34
26
  primary key (resource, channel_key, user_id)
35
27
  )`,
36
- `create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)`,
28
+ `create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)`
29
+ ];
30
+ /**
31
+ * `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the trigger function. A
32
+ * truncate, of the table or of one of its partitions, writes the resource's members again from the table as it stands,
33
+ * so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
34
+ * delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
35
+ * from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
36
+ * swaps two records' keys leaves each key with the members its record lists.
37
+ */
38
+ const membersFunctionsSql = [
37
39
  `create or replace function ${realtimeSchema}.listed_members(entry jsonb, members_column text, deleted_column text) returns setof text
38
40
  language sql immutable as $$
39
41
  select distinct member from jsonb_array_elements_text(
@@ -88,14 +90,33 @@ const argsOf = ({ resource, key, members, deleted }) => [
88
90
  members,
89
91
  deleted
90
92
  ];
91
- /** A truncate trigger's SQL on a channel table or one of its partitions, as SQL names it. */
92
- const truncateSql = (listed, on) => `create trigger ${truncateTrigger} after truncate on ${on} for each statement execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`;
93
- const listedTableSql = (listed, partitions) => {
93
+ const refusedSql = (table) => `exists (select from pg_class c where c.oid = ${literal(table)}::regclass and (c.relispartition or (c.relkind <> 'p' and exists (select from pg_inherits i where i.inhrelid = c.oid or i.inhparent = c.oid))))`;
94
+ const partitionsSql = (table) => `select relid from pg_partition_tree(to_regclass(${literal(table)})) where relid <> to_regclass(${literal(table)})`;
95
+ /**
96
+ * The triggers that keep `realtime.members` on one listed table, written whole: its row trigger, cloned onto its
97
+ * partitions by Postgres, and its truncate trigger on it and on each partition it has as the statements run, then its
98
+ * rows written again from the table. A partition or inheriting table is refused. Writes made while the triggers are
99
+ * off, such as with `session_replication_role = replica`, are not kept until they are written again.
100
+ */
101
+ const listedTableSql = (listed) => {
94
102
  const { resource, table, key, members, deleted } = listed;
103
+ const args = argsOf(listed).map(literal).join(", ");
95
104
  return [
96
- `create trigger ${rowTrigger} after insert or delete or update on ${table} for each row execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`,
97
- truncateSql(listed, table),
98
- ...partitions.map((partition) => truncateSql(listed, partition)),
105
+ `do $members$ begin
106
+ if ${refusedSql(table)} then
107
+ raise exception 'realtime.members cannot keep the members of %: 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', ${literal(table)};
108
+ end if;
109
+ end $members$`,
110
+ `drop trigger if exists ${rowTrigger} on ${table}`,
111
+ `drop trigger if exists ${truncateTrigger} on ${table}`,
112
+ `create trigger ${rowTrigger} after insert or delete or update on ${table} for each row execute function ${realtimeSchema}.members_kept(${args})`,
113
+ `create trigger ${truncateTrigger} after truncate on ${table} for each statement execute function ${realtimeSchema}.members_kept(${args})`,
114
+ `do $members$ declare part regclass; begin
115
+ for part in ${partitionsSql(table)} loop
116
+ execute format('drop trigger if exists ${truncateTrigger} on %s', part);
117
+ execute format('create trigger ${truncateTrigger} after truncate on %s for each statement execute function ${realtimeSchema}.members_kept(%s)', part, ${literal(args)});
118
+ end loop;
119
+ end $members$`,
99
120
  `delete from ${realtimeMembersTable} where resource = ${literal(resource)}`,
100
121
  `insert into ${realtimeMembersTable} (resource, channel_key, user_id)
101
122
  select ${literal(resource)}, to_jsonb(t) ->> ${literal(key)}, member from ${table} t
@@ -104,17 +125,19 @@ const listedTableSql = (listed, partitions) => {
104
125
  ];
105
126
  };
106
127
  /**
107
- * The SQL that keeps `realtime.members` for the listed tables: the table and its functions, the triggers of every
108
- * table that has them dropped (`standing`, as SQL names each), each listed table's written, a truncate trigger on each
109
- * of its partitions (`partitions`, by listed table, as SQL names each) included, its rows written again
110
- * from the table, and the rows of resources no longer listed deleted. Writes made while the triggers are off, such as
111
- * with `session_replication_role = replica`, are not kept until the next migration that writes it.
128
+ * Drops the triggers that keep `realtime.members` on a table, on its partitions too, then the rows of each resource
129
+ * whose row trigger stands nowhere any more, by the resource its first argument names.
112
130
  */
113
- const membersSql = (listed, standing, partitions) => [
114
- ...baseSql,
115
- ...standing.flatMap((table) => [`drop trigger if exists ${rowTrigger} on ${table}`, `drop trigger if exists ${truncateTrigger} on ${table}`]),
116
- ...listed.flatMap((table, i) => listedTableSql(table, partitions[i] ?? [])),
117
- `delete from ${realtimeMembersTable} where resource <> all(array[${listed.map(({ resource }) => literal(resource)).join(", ")}]::text[])`
131
+ const dropListedSql = (table) => [
132
+ `drop trigger if exists ${rowTrigger} on ${table}`,
133
+ `drop trigger if exists ${truncateTrigger} on ${table}`,
134
+ `do $members$ declare part regclass; begin
135
+ for part in ${partitionsSql(table)} loop
136
+ execute format('drop trigger if exists ${truncateTrigger} on %s', part);
137
+ end loop;
138
+ end $members$`,
139
+ `delete from ${realtimeMembersTable} m where not exists (select from pg_trigger t where t.tgname = '${rowTrigger}' and t.tgparentid = 0
140
+ and t.tgfoid = '${realtimeSchema}.members_kept()'::regprocedure and convert_from(substring(t.tgargs from 1 for position('\\x00'::bytea in t.tgargs) - 1), 'UTF8') = m.resource)`
118
141
  ];
119
142
  //#endregion
120
- export { argsOf, listedTable, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger };
143
+ export { argsOf, dropListedSql, listedTable, listedTableSql, membersComment, membersFunctionsSql, membersTableSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger };