@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,63 +1,5 @@
1
- import { functionNames, functionsComment, functionsSql } from "./functions-sql.js";
2
- import { CompiledQuery } from "kysely";
3
- import { getConstructionPlans, getMigrationPlans } from "pg-boss";
4
1
  //#region src/jobs/schema.ts
5
2
  /** The schema the job queue lives in: pg-boss's tables and Protobase's functions. */
6
3
  const jobsSchema = "jobs";
7
- /** The command that writes what the database lacks as the project's next migration. */
8
- const migrationCommand = "protobase migration";
9
- /**
10
- * A pg-boss plan as a migration the project applies in its own transaction: without its BEGIN and COMMIT, without the
11
- * timeouts it sets for that transaction, which would hold for the project's later migrations too, and with index
12
- * builds that are not `CONCURRENTLY`, which Postgres refuses in a transaction. Migrations run while nothing else
13
- * writes, so a plain index build only costs a lock nobody waits on.
14
- */
15
- const migrationStatements = (plan) => {
16
- const match = /^\s*BEGIN;\n\s*SET LOCAL lock_timeout = \d+;\n\s*SET LOCAL idle_in_transaction_session_timeout = \d+;\n([\s\S]*?)\n\s*COMMIT;\n?([\s\S]*)$/.exec(plan);
17
- if (!match) throw new Error(`Unexpected pg-boss plan:\n${plan.slice(0, 200)}`);
18
- return `${match[1].trim()}\n${match[2]}`.replace(/\b(CREATE (?:UNIQUE )?INDEX|DROP INDEX|REINDEX INDEX) CONCURRENTLY\b/gi, "$1").trim();
19
- };
20
- const rows = async (db, text, parameters = []) => (await db.executeQuery(CompiledQuery.raw(text, parameters))).rows;
21
- /** What the database holds of the jobs schema: pg-boss's version, when installed, and whether Protobase's functions are current. */
22
- const readJobsSchema = async (db) => {
23
- const [{ installed }] = await rows(db, `select to_regclass('${jobsSchema}.version') is not null as installed`);
24
- if (!installed) return {
25
- pgBoss: void 0,
26
- functionsCurrent: false
27
- };
28
- const [version] = await rows(db, `select version from ${jobsSchema}.version`);
29
- const functions = await rows(db, `select p.proname as name, obj_description(p.oid, 'pg_proc') as comment from pg_proc p
30
- join pg_namespace n on n.oid = p.pronamespace where n.nspname = $1 and p.proname = any($2) order by p.proname`, [jobsSchema, functionNames]);
31
- const functionsCurrent = functionNames.every((name) => functions.some((found) => found.name === name && found.comment === functionsComment));
32
- return {
33
- pgBoss: version === void 0 ? void 0 : Number(version.version),
34
- functionsCurrent
35
- };
36
- };
37
- const newer = (version) => /* @__PURE__ */ new Error(`The jobs schema is at pg-boss schema version ${version}, newer than the 45 this version of Protobase runs; upgrade Protobase`);
38
- /**
39
- * The SQL that brings the jobs schema to what this version of Protobase runs: pg-boss's own construction plan when it
40
- * is missing, or its migration plan from the version installed, then Protobase's functions. `undefined` when current.
41
- */
42
- const jobsSchemaMigration = async (db) => {
43
- const { pgBoss, functionsCurrent } = await readJobsSchema(db);
44
- if (pgBoss !== void 0 && pgBoss > 45) throw newer(pgBoss);
45
- if (pgBoss === 45 && functionsCurrent) return void 0;
46
- const parts = [];
47
- if (pgBoss === void 0) parts.push(migrationStatements(getConstructionPlans(jobsSchema)));
48
- else if (pgBoss < 45) parts.push(migrationStatements(getMigrationPlans(jobsSchema, pgBoss)));
49
- parts.push(functionsSql(jobsSchema));
50
- return parts.join("\n\n");
51
- };
52
- /**
53
- * Refuses to go on while the jobs schema is missing or not the version this Protobase runs. The server never creates
54
- * or migrates it: the project's migrations do, before the new version serves.
55
- */
56
- const checkJobsSchema = async (db) => {
57
- const { pgBoss, functionsCurrent } = await readJobsSchema(db);
58
- if (pgBoss !== void 0 && pgBoss > 45) throw newer(pgBoss);
59
- if (pgBoss === 45 && functionsCurrent) return;
60
- throw new Error(`The jobs schema is ${pgBoss === void 0 ? "missing" : "behind this version of Protobase"}. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
61
- };
62
4
  //#endregion
63
- export { checkJobsSchema, jobsSchema, jobsSchemaMigration, migrationCommand, migrationStatements, readJobsSchema };
5
+ export { jobsSchema };
@@ -0,0 +1,483 @@
1
+ //#region src/jobs/steps/001-pg-boss-45.ts
2
+ /**
3
+ * pg-boss 12.37.1's construction plan of its schema version 45 in `jobs`, as `migrationStatements` writes it: copied once
4
+ * and never changed. A pg-boss bump copies its migration plan into the jobs module's next step by hand (`jobs-module.test.ts`).
5
+ */
6
+ const pgBoss45 = String.raw`SELECT pg_advisory_xact_lock(('x' || encode(sha224((current_database() || '.pgboss.jobs')::bytea), 'hex'))::bit(64)::bigint);
7
+ CREATE SCHEMA IF NOT EXISTS jobs;
8
+
9
+ CREATE TYPE jobs.job_state AS ENUM (
10
+ 'created',
11
+ 'retry',
12
+ 'active',
13
+ 'completed',
14
+ 'cancelled',
15
+ 'failed'
16
+ )
17
+ ;
18
+
19
+ CREATE FUNCTION jobs.job_now()
20
+ RETURNS timestamp with time zone AS
21
+ $$
22
+ SELECT pg_catalog.now();
23
+ $$
24
+ LANGUAGE sql STABLE;
25
+ ;
26
+
27
+ CREATE TABLE jobs.version (
28
+ version int primary key,
29
+ cron_on timestamp with time zone,
30
+ bam_on timestamp with time zone,
31
+ flow_on timestamp with time zone,
32
+ reindex_on timestamp with time zone,
33
+ monitor_backoff_on timestamp with time zone
34
+ )
35
+ ;
36
+
37
+ CREATE TABLE jobs.queue (
38
+ name text NOT NULL,
39
+ policy text NOT NULL,
40
+ retry_limit int NOT NULL,
41
+ retry_delay int NOT NULL,
42
+ retry_backoff bool NOT NULL,
43
+ retry_delay_max int,
44
+ expire_seconds int NOT NULL,
45
+ retention_seconds int NOT NULL,
46
+ deletion_seconds int NOT NULL,
47
+ dead_letter text REFERENCES jobs.queue (name) CHECK (dead_letter IS DISTINCT FROM name),
48
+ partition bool NOT NULL,
49
+ table_name text NOT NULL,
50
+ deferred_count int NOT NULL default 0,
51
+ blocked_count int NOT NULL default 0,
52
+ queued_count int NOT NULL default 0,
53
+ ready_count int NOT NULL default 0,
54
+ warning_queued int NOT NULL default 0,
55
+ active_count int NOT NULL default 0,
56
+ failed_count int NOT NULL default 0,
57
+ total_count int NOT NULL default 0,
58
+ created_delta int NOT NULL default 0,
59
+ completed_delta int NOT NULL default 0,
60
+ failed_delta int NOT NULL default 0,
61
+ delta_on timestamp with time zone,
62
+ delta_seconds int,
63
+ wait_bins int[],
64
+ run_bins int[],
65
+ ready_oldest_seconds int,
66
+ ready_history int[] NOT NULL default '{}',
67
+ heartbeat_seconds int,
68
+ notify bool NOT NULL DEFAULT false,
69
+ singletons_active text[],
70
+ monitor_claim_on timestamp with time zone,
71
+ monitor_on timestamp with time zone,
72
+ maintain_on timestamp with time zone,
73
+ created_on timestamp with time zone not null default now(),
74
+ updated_on timestamp with time zone not null default now(),
75
+ PRIMARY KEY (name)
76
+ )
77
+ ;
78
+
79
+ CREATE TABLE jobs.schedule (
80
+ name text REFERENCES jobs.queue ON DELETE CASCADE,
81
+ key text not null DEFAULT '',
82
+ kind text not null DEFAULT 'cron' CHECK (kind IN ('cron', 'rrule')),
83
+ cron text not null,
84
+ timezone text DEFAULT 'UTC',
85
+ data jsonb,
86
+ options jsonb,
87
+ created_on timestamp with time zone not null default now(),
88
+ updated_on timestamp with time zone not null default now(),
89
+ last_job_id uuid,
90
+ PRIMARY KEY (name, key)
91
+ )
92
+ ;
93
+
94
+ CREATE TABLE jobs.subscription (
95
+ event text not null,
96
+ name text not null REFERENCES jobs.queue ON DELETE CASCADE,
97
+ created_on timestamp with time zone not null default now(),
98
+ updated_on timestamp with time zone not null default now(),
99
+ PRIMARY KEY(event, name)
100
+ )
101
+ ;
102
+
103
+ CREATE TABLE jobs.bam (
104
+ id uuid PRIMARY KEY default gen_random_uuid(),
105
+ name text NOT NULL,
106
+ version int NOT NULL,
107
+ status text NOT NULL DEFAULT 'pending',
108
+ queue text,
109
+ table_name text NOT NULL,
110
+ command text NOT NULL,
111
+ error text,
112
+ created_on timestamp with time zone NOT NULL DEFAULT clock_timestamp(),
113
+ started_on timestamp with time zone,
114
+ completed_on timestamp with time zone
115
+ )
116
+ ;
117
+
118
+ CREATE FUNCTION jobs.job_table_format(command text, table_name text)
119
+ RETURNS text AS
120
+ $$
121
+ SELECT format(
122
+ regexp_replace(
123
+ regexp_replace(command, '\.job\y', '.%1$I', 'g'),
124
+ '\yjob_i(\d+)', '%1$s_i\1', 'g'
125
+ ),
126
+ table_name
127
+ );
128
+ $$
129
+ LANGUAGE sql IMMUTABLE;
130
+ ;
131
+
132
+ CREATE FUNCTION jobs.job_table_run(command text, tbl_name text DEFAULT NULL, queue_name text DEFAULT NULL)
133
+ RETURNS VOID AS
134
+ $$
135
+ DECLARE
136
+ tbl RECORD;
137
+ BEGIN
138
+ IF queue_name IS NOT NULL THEN
139
+ SELECT table_name INTO tbl_name FROM jobs.queue WHERE name = queue_name;
140
+ END IF;
141
+
142
+ IF tbl_name IS NOT NULL THEN
143
+ EXECUTE jobs.job_table_format(command, tbl_name);
144
+ RETURN;
145
+ END IF;
146
+
147
+ EXECUTE jobs.job_table_format(command, 'job_common');
148
+
149
+ FOR tbl IN SELECT table_name FROM jobs.queue WHERE partition = true
150
+ LOOP
151
+ EXECUTE jobs.job_table_format(command, tbl.table_name);
152
+ END LOOP;
153
+ END;
154
+ $$
155
+ LANGUAGE plpgsql;
156
+ ;
157
+
158
+ CREATE FUNCTION jobs.job_table_run_async(command_name text, version int, command text, tbl_name text DEFAULT NULL, queue_name text DEFAULT NULL)
159
+ RETURNS VOID AS
160
+ $$
161
+ BEGIN
162
+ IF queue_name IS NOT NULL THEN
163
+ SELECT table_name INTO tbl_name FROM jobs.queue WHERE name = queue_name;
164
+ END IF;
165
+
166
+ IF tbl_name IS NOT NULL THEN
167
+ INSERT INTO jobs.bam (name, version, status, queue, table_name, command)
168
+ VALUES (
169
+ command_name,
170
+ version,
171
+ 'pending',
172
+ queue_name,
173
+ tbl_name,
174
+ jobs.job_table_format(command, tbl_name)
175
+ );
176
+ RETURN;
177
+ END IF;
178
+
179
+ INSERT INTO jobs.bam (name, version, status, queue, table_name, command)
180
+ SELECT
181
+ command_name,
182
+ version,
183
+ 'pending',
184
+ NULL,
185
+ 'job_common',
186
+ jobs.job_table_format(command, 'job_common')
187
+ UNION ALL
188
+ SELECT
189
+ command_name,
190
+ version,
191
+ 'pending',
192
+ queue.name,
193
+ queue.table_name,
194
+ jobs.job_table_format(command, queue.table_name)
195
+ FROM jobs.queue
196
+ WHERE partition = true;
197
+ END;
198
+ $$
199
+ LANGUAGE plpgsql;
200
+ ;
201
+
202
+ CREATE TABLE jobs.job (
203
+ id uuid not null default gen_random_uuid(),
204
+ name text not null,
205
+ priority integer not null default(0),
206
+ data jsonb,
207
+ state jobs.job_state not null default 'created',
208
+ retry_limit integer not null default 2,
209
+ retry_count integer not null default 0,
210
+ retry_delay integer not null default 0,
211
+ retry_backoff boolean not null default false,
212
+ retry_delay_max integer,
213
+ expire_seconds int not null default 900,
214
+ deletion_seconds int not null default 604800,
215
+ singleton_key text,
216
+ singleton_on timestamp without time zone,
217
+ group_id text,
218
+ group_tier text,
219
+ start_after timestamp with time zone not null default now(),
220
+ created_on timestamp with time zone not null default now(),
221
+ started_on timestamp with time zone,
222
+ completed_on timestamp with time zone,
223
+ keep_until timestamp with time zone NOT NULL default now() + interval '1209600',
224
+ output jsonb,
225
+ dead_letter text,
226
+ policy text,
227
+ heartbeat_on timestamp with time zone,
228
+ heartbeat_seconds int,
229
+ blocked boolean not null default false,
230
+ blocking boolean not null default false,
231
+ pending_dependencies int not null default 0,
232
+ source_name text,
233
+ source_id uuid,
234
+ source_created_on timestamp with time zone,
235
+ source_retry_count int,
236
+ source_output jsonb,
237
+ source_root_id uuid,
238
+ trace_context jsonb,
239
+ upsert_by_key bool
240
+ ) PARTITION BY LIST (name)
241
+ ;
242
+ ALTER TABLE jobs.job ADD PRIMARY KEY (name, id);
243
+
244
+ CREATE TABLE jobs.job_common (LIKE jobs.job INCLUDING GENERATED INCLUDING DEFAULTS);
245
+
246
+ SELECT jobs.job_table_run($cmd$ALTER TABLE jobs.job ADD PRIMARY KEY (name, id)$cmd$, 'job_common');
247
+ SELECT jobs.job_table_run($cmd$ALTER TABLE jobs.job ADD CONSTRAINT q_fkey FOREIGN KEY (name) REFERENCES jobs.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED$cmd$, 'job_common');
248
+ SELECT jobs.job_table_run($cmd$ALTER TABLE jobs.job ADD CONSTRAINT dlq_fkey FOREIGN KEY (dead_letter) REFERENCES jobs.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED$cmd$, 'job_common');
249
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i1 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state = 'created' AND policy = 'short'$cmd$, 'job_common');
250
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i2 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state = 'active' AND policy = 'singleton'$cmd$, 'job_common');
251
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i3 ON jobs.job (name, state, COALESCE(singleton_key, '')) WHERE state <= 'active' AND policy = 'stately'$cmd$, 'job_common');
252
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i6 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state <= 'active' AND policy = 'exclusive'$cmd$, 'job_common');
253
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i8 ON jobs.job (name, singleton_key) WHERE state IN ('active', 'retry', 'failed') AND policy = 'key_strict_fifo'$cmd$, 'job_common');
254
+ SELECT jobs.job_table_run($cmd$CREATE INDEX job_i10 ON jobs.job (name, singleton_key, state DESC, created_on, id) INCLUDE (start_after) WHERE state < 'active' AND NOT blocked AND policy = 'key_strict_fifo'$cmd$, 'job_common');
255
+ SELECT jobs.job_table_run($cmd$ALTER TABLE jobs.job ADD CONSTRAINT job_key_strict_fifo_singleton_key_check CHECK (NOT (policy = 'key_strict_fifo' AND singleton_key IS NULL))$cmd$, 'job_common');
256
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i4 ON jobs.job (name, singleton_on, COALESCE(singleton_key, '')) WHERE state <> 'cancelled' AND singleton_on IS NOT NULL$cmd$, 'job_common');
257
+ SELECT jobs.job_table_run($cmd$CREATE INDEX job_i11 ON jobs.job (name, priority DESC, created_on, start_after) WHERE state < 'active' AND NOT blocked$cmd$, 'job_common');
258
+ SELECT jobs.job_table_run($cmd$CREATE INDEX job_i7 ON jobs.job (name, group_id) WHERE state = 'active' AND group_id IS NOT NULL$cmd$, 'job_common');
259
+ SELECT jobs.job_table_run($cmd$CREATE INDEX job_i9 ON jobs.job (name, id) WHERE blocking AND state = 'completed'$cmd$, 'job_common');
260
+ SELECT jobs.job_table_run($cmd$CREATE INDEX job_i12 ON jobs.job (source_root_id) WHERE source_root_id IS NOT NULL$cmd$, 'job_common');
261
+ SELECT jobs.job_table_run($cmd$CREATE UNIQUE INDEX job_i13 ON jobs.job (name, singleton_key) WHERE state = 'created' AND upsert_by_key$cmd$, 'job_common');
262
+
263
+ ALTER TABLE jobs.job ATTACH PARTITION jobs.job_common DEFAULT;
264
+ ;
265
+
266
+ CREATE TABLE jobs.warning (
267
+ id uuid PRIMARY KEY default gen_random_uuid(),
268
+ type text NOT NULL,
269
+ message text NOT NULL,
270
+ data jsonb,
271
+ created_on timestamp with time zone NOT NULL DEFAULT now()
272
+ )
273
+ ;
274
+ CREATE INDEX warning_i1 ON jobs.warning (created_on DESC);
275
+
276
+ CREATE TABLE jobs.queue_stats (
277
+ id uuid NOT NULL DEFAULT gen_random_uuid(),
278
+ name text NOT NULL,
279
+ deferred_count int NOT NULL DEFAULT 0,
280
+ queued_count int NOT NULL DEFAULT 0,
281
+ ready_count int NOT NULL DEFAULT 0,
282
+ active_count int NOT NULL DEFAULT 0,
283
+ failed_count int NOT NULL DEFAULT 0,
284
+ total_count int NOT NULL DEFAULT 0,
285
+ created_delta int,
286
+ completed_delta int,
287
+ failed_delta int,
288
+ delta_seconds int,
289
+ delta_on timestamptz,
290
+ wait_bins int[],
291
+ run_bins int[],
292
+ ready_oldest_seconds int,
293
+ captured_on timestamptz NOT NULL DEFAULT now(),
294
+ PRIMARY KEY (id, captured_on)
295
+ ) PARTITION BY RANGE (captured_on)
296
+ ;
297
+ CREATE INDEX queue_stats_i1 ON jobs.queue_stats (name, captured_on DESC) INCLUDE (deferred_count, queued_count, ready_count, active_count, failed_count, total_count);
298
+
299
+ DO $$
300
+ DECLARE
301
+ d date;
302
+ i int;
303
+ part_name text;
304
+ BEGIN
305
+ FOR i IN 0..1 LOOP
306
+ d := (jobs.job_now() AT TIME ZONE 'UTC')::date + i;
307
+ part_name := 'queue_stats_' || to_char(d, 'YYYYMMDD');
308
+ IF NOT EXISTS (
309
+ SELECT 1 FROM pg_class c
310
+ JOIN pg_namespace n ON n.oid = c.relnamespace
311
+ WHERE n.nspname = 'jobs' AND c.relname = part_name
312
+ ) THEN
313
+ EXECUTE format(
314
+ 'CREATE TABLE jobs.%I PARTITION OF jobs.queue_stats FOR VALUES FROM (%L) TO (%L)',
315
+ part_name,
316
+ to_char(d, 'YYYY-MM-DD') || ' 00:00:00+00',
317
+ to_char(d + 1, 'YYYY-MM-DD') || ' 00:00:00+00'
318
+ );
319
+ END IF;
320
+ END LOOP;
321
+ END;
322
+ $$
323
+ ;
324
+
325
+ CREATE TABLE jobs.job_dependency (
326
+ child_name text NOT NULL,
327
+ child_id uuid NOT NULL,
328
+ parent_name text NOT NULL,
329
+ parent_id uuid NOT NULL,
330
+ PRIMARY KEY (child_name, child_id, parent_name, parent_id)
331
+ )
332
+ ;
333
+ CREATE INDEX IF NOT EXISTS job_dep_parent_idx ON jobs.job_dependency (parent_name, parent_id);
334
+
335
+ CREATE TABLE jobs.instance (
336
+ id uuid PRIMARY KEY,
337
+ name text,
338
+ host text NOT NULL,
339
+ pid int NOT NULL,
340
+ version text NOT NULL,
341
+ node_version text NOT NULL,
342
+ application_name text,
343
+ heartbeat_seconds int NOT NULL,
344
+ supervise bool NOT NULL,
345
+ schedule bool NOT NULL,
346
+ migrate bool NOT NULL,
347
+ persist_queue_stats bool NOT NULL,
348
+ persist_warnings bool NOT NULL,
349
+ pool_max int,
350
+ pool_total int,
351
+ pool_idle int,
352
+ pool_waiting int,
353
+ workers jsonb NOT NULL DEFAULT '[]'::jsonb,
354
+ metrics jsonb,
355
+ config jsonb NOT NULL DEFAULT '{}'::jsonb,
356
+ crash_restarts int NOT NULL DEFAULT 0,
357
+ crash_restarts_since timestamptz,
358
+ started_on timestamptz NOT NULL DEFAULT now(),
359
+ heartbeat_on timestamptz NOT NULL DEFAULT now(),
360
+ stopped_on timestamptz
361
+ )
362
+ ;
363
+
364
+ CREATE FUNCTION jobs.create_queue(queue_name text, options jsonb)
365
+ RETURNS VOID AS
366
+ $$
367
+ DECLARE
368
+ tablename varchar := CASE WHEN options->>'partition' = 'true'
369
+ THEN 'j' || encode(sha224(queue_name::bytea), 'hex')
370
+ ELSE 'job_common'
371
+ END;
372
+ queue_created_on timestamptz;
373
+ BEGIN
374
+
375
+ WITH q as (
376
+ INSERT INTO jobs.queue (
377
+ name,
378
+ policy,
379
+ retry_limit,
380
+ retry_delay,
381
+ retry_backoff,
382
+ retry_delay_max,
383
+ expire_seconds,
384
+ retention_seconds,
385
+ deletion_seconds,
386
+ warning_queued,
387
+ dead_letter,
388
+ partition,
389
+ table_name,
390
+ heartbeat_seconds,
391
+ notify,
392
+ created_on,
393
+ updated_on
394
+ )
395
+ VALUES (
396
+ queue_name,
397
+ options->>'policy',
398
+ COALESCE((options->>'retryLimit')::int, 2),
399
+ COALESCE((options->>'retryDelay')::int, 0),
400
+ COALESCE((options->>'retryBackoff')::bool, false),
401
+ (options->>'retryDelayMax')::int,
402
+ COALESCE((options->>'expireInSeconds')::int, 900),
403
+ COALESCE((options->>'retentionSeconds')::int, 1209600),
404
+ COALESCE((options->>'deleteAfterSeconds')::int, 604800),
405
+ COALESCE((options->>'warningQueueSize')::int, 0),
406
+ options->>'deadLetter',
407
+ COALESCE((options->>'partition')::bool, false),
408
+ tablename,
409
+ (options->>'heartbeatSeconds')::int,
410
+ COALESCE((options->>'notify')::bool, false),
411
+ jobs.job_now(),
412
+ jobs.job_now()
413
+ )
414
+ ON CONFLICT DO NOTHING
415
+ RETURNING created_on
416
+ )
417
+ SELECT created_on into queue_created_on from q;
418
+
419
+ IF queue_created_on IS NULL OR options->>'partition' IS DISTINCT FROM 'true' THEN
420
+ RETURN;
421
+ END IF;
422
+
423
+ EXECUTE format('CREATE TABLE jobs.%I (LIKE jobs.job INCLUDING DEFAULTS)', tablename);
424
+
425
+ EXECUTE jobs.job_table_format($cmd$ALTER TABLE jobs.job ADD PRIMARY KEY (name, id)$cmd$, tablename);
426
+ EXECUTE jobs.job_table_format($cmd$ALTER TABLE jobs.job ADD CONSTRAINT q_fkey FOREIGN KEY (name) REFERENCES jobs.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED$cmd$, tablename);
427
+ EXECUTE jobs.job_table_format($cmd$ALTER TABLE jobs.job ADD CONSTRAINT dlq_fkey FOREIGN KEY (dead_letter) REFERENCES jobs.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED$cmd$, tablename);
428
+
429
+ EXECUTE jobs.job_table_format($cmd$CREATE INDEX job_i11 ON jobs.job (name, priority DESC, created_on, start_after) WHERE state < 'active' AND NOT blocked$cmd$, tablename);
430
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i4 ON jobs.job (name, singleton_on, COALESCE(singleton_key, '')) WHERE state <> 'cancelled' AND singleton_on IS NOT NULL$cmd$, tablename);
431
+ EXECUTE jobs.job_table_format($cmd$CREATE INDEX job_i7 ON jobs.job (name, group_id) WHERE state = 'active' AND group_id IS NOT NULL$cmd$, tablename);
432
+ EXECUTE jobs.job_table_format($cmd$CREATE INDEX job_i9 ON jobs.job (name, id) WHERE blocking AND state = 'completed'$cmd$, tablename);
433
+ EXECUTE jobs.job_table_format($cmd$CREATE INDEX job_i12 ON jobs.job (source_root_id) WHERE source_root_id IS NOT NULL$cmd$, tablename);
434
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i13 ON jobs.job (name, singleton_key) WHERE state = 'created' AND upsert_by_key$cmd$, tablename);
435
+
436
+ IF options->>'policy' = 'short' THEN
437
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i1 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state = 'created' AND policy = 'short'$cmd$, tablename);
438
+ ELSIF options->>'policy' = 'singleton' THEN
439
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i2 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state = 'active' AND policy = 'singleton'$cmd$, tablename);
440
+ ELSIF options->>'policy' = 'stately' THEN
441
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i3 ON jobs.job (name, state, COALESCE(singleton_key, '')) WHERE state <= 'active' AND policy = 'stately'$cmd$, tablename);
442
+ ELSIF options->>'policy' = 'exclusive' THEN
443
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i6 ON jobs.job (name, COALESCE(singleton_key, '')) WHERE state <= 'active' AND policy = 'exclusive'$cmd$, tablename);
444
+ ELSIF options->>'policy' = 'key_strict_fifo' THEN
445
+ EXECUTE jobs.job_table_format($cmd$CREATE UNIQUE INDEX job_i8 ON jobs.job (name, singleton_key) WHERE state IN ('active', 'retry', 'failed') AND policy = 'key_strict_fifo'$cmd$, tablename);
446
+ EXECUTE jobs.job_table_format($cmd$CREATE INDEX job_i10 ON jobs.job (name, singleton_key, state DESC, created_on, id) INCLUDE (start_after) WHERE state < 'active' AND NOT blocked AND policy = 'key_strict_fifo'$cmd$, tablename);
447
+ EXECUTE jobs.job_table_format($cmd$ALTER TABLE jobs.job ADD CONSTRAINT job_key_strict_fifo_singleton_key_check CHECK (NOT (policy = 'key_strict_fifo' AND singleton_key IS NULL))$cmd$, tablename);
448
+ END IF;
449
+
450
+ EXECUTE format('ALTER TABLE jobs.%I ADD CONSTRAINT cjc CHECK (name=%L)', tablename, queue_name);
451
+ EXECUTE format('ALTER TABLE jobs.job ATTACH PARTITION jobs.%I FOR VALUES IN (%L)', tablename, queue_name);
452
+ END;
453
+ $$
454
+ LANGUAGE plpgsql;
455
+ ;
456
+
457
+ CREATE FUNCTION jobs.delete_queue(queue_name text)
458
+ RETURNS VOID AS
459
+ $$
460
+ DECLARE
461
+ v_table varchar;
462
+ v_partition bool;
463
+ BEGIN
464
+
465
+ SELECT table_name, partition
466
+ FROM jobs.queue
467
+ WHERE name = queue_name
468
+ INTO v_table, v_partition;
469
+
470
+ IF v_partition THEN
471
+ EXECUTE format('DROP TABLE IF EXISTS jobs.%I', v_table);
472
+ ELSE
473
+ EXECUTE format('DELETE FROM jobs.%I WHERE name = %L', v_table, queue_name);
474
+ END IF;
475
+
476
+ DELETE FROM jobs.queue WHERE name = queue_name;
477
+ END;
478
+ $$
479
+ LANGUAGE plpgsql;
480
+ ;
481
+ INSERT INTO jobs.version(version) VALUES ('45');`;
482
+ //#endregion
483
+ export { pgBoss45 };
@@ -0,0 +1,30 @@
1
+ import { quoteIdent } from "../changes/capture-sql.js";
2
+ import { noticesTableSql } from "./notices-sql.js";
3
+ import { sql } from "kysely";
4
+ //#region src/live/notices-module.ts
5
+ /** The notices table as the database has it: step 1 once it is there. */
6
+ const readNotices = async (db, { names }) => {
7
+ const { rows } = await sql`select to_regclass(${`${quoteIdent(names.schema)}."notices"`}) is not null as found`.execute(db);
8
+ return rows[0].found ? {
9
+ lastStep: 1,
10
+ replaceables: {},
11
+ names
12
+ } : void 0;
13
+ };
14
+ /** The notices table the open pages of the resources with `.live()` refresh from, in the schema `events` names (`names.schema`). */
15
+ const noticesModule = {
16
+ label: "the notices table",
17
+ title: "The notices table of the resources with live updates",
18
+ steps: [{
19
+ step: 1,
20
+ name: "notices",
21
+ title: "The notices table",
22
+ additive: true,
23
+ sql: (names) => `create schema if not exists ${quoteIdent(names.schema)};\n${noticesTableSql(names.schema)};`
24
+ }],
25
+ replaceables: [],
26
+ resourceReplaceables: [],
27
+ read: readNotices
28
+ };
29
+ //#endregion
30
+ export { noticesModule };
@@ -3,7 +3,8 @@ import { sql } from "kysely";
3
3
  //#region src/live/notices-sql.ts
4
4
  /**
5
5
  * The recent changes of the resources with `.live()`, which open pages refresh from: a row per record and transaction,
6
- * its key and never its values. `id` grows in commit order, since one dispatch writes at a time.
6
+ * its key and never its values. `id` grows in commit order, since one dispatch writes at a time. Step 1 of the notices
7
+ * module (`notices-module.ts`): frozen once released, as every step is.
7
8
  */
8
9
  const noticesTableSql = (schema) => {
9
10
  const table = `${quoteIdent(schema)}."notices"`;
@@ -1,13 +1,10 @@
1
- import { hasIndexes } from "../../has-indexes.js";
2
- import { migrationCommand } from "../../changes/capture-schema.js";
3
1
  import { feedbackSchema, feedbackTable } from "./feedback-store.js";
4
- import { sql } from "kysely";
5
2
  //#region src/mail/feedback/feedback-schema.ts
6
3
  /**
7
4
  * The table's indexes by name: the unique one a report sent again stands on, a missing recipient counting as one, and
8
5
  * those of the admin list's filters and sort: the recipient, the message ids an app looks a send up by, and the type.
9
6
  */
10
- const indexes = [
7
+ const feedbackIndexes = [
11
8
  [
12
9
  "feedback_provider_event_recipient_once",
13
10
  "unique",
@@ -39,7 +36,7 @@ const indexes = [
39
36
  "(\"created_at\")"
40
37
  ]
41
38
  ];
42
- const indexesSql = () => indexes.map(([name, kind, columns]) => `create ${kind ? `${kind} ` : ""}index if not exists "${name}" on ${feedbackTable} ${columns};`).join("\n");
39
+ const indexesSql = () => feedbackIndexes.map(([name, kind, columns]) => `create ${kind ? `${kind} ` : ""}index if not exists "${name}" on ${feedbackTable} ${columns};`).join("\n");
43
40
  const namesRecipient = `constraint "feedback_names_recipient" check ("recipient" is not null or ("type" = 'complaint' and "message_id" is not null))`;
44
41
  /** A row per recipient of each bounce or complaint report; a value the report does not state is NULL. */
45
42
  const feedbackTableSql = () => `create schema if not exists "${feedbackSchema}";
@@ -60,29 +57,5 @@ create table if not exists ${feedbackTable} (
60
57
  );
61
58
 
62
59
  ${indexesSql()}`;
63
- /**
64
- * A table of an earlier version, whose every record named its recipient, made to take a complaint without one: its
65
- * unique index replaced by one that counts a missing recipient as one, which a write of that version stands on too. It
66
- * runs again on a table that has the constraint but lost that index, so it replaces the constraint rather than adding it.
67
- */
68
- const recipientOptionalSql = () => `alter table ${feedbackTable} alter column "recipient" drop not null,
69
- drop constraint if exists "feedback_names_recipient",
70
- add ${namesRecipient};
71
- ${indexesSql()}
72
- drop index if exists "${feedbackSchema}"."feedback_provider_event_recipient";`;
73
- const hasTable = async (db) => (await sql`select to_regclass(${feedbackTable}) is not null as found`.execute(db)).rows[0].found;
74
- /** 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. */
75
- const mailFeedbackMigration = async (db) => {
76
- if (!await hasTable(db)) return feedbackTableSql();
77
- if (!await hasIndexes(db, "mail", "feedback", [indexes[0][0]])) return recipientOptionalSql();
78
- if (await hasIndexes(db, "mail", "feedback", indexes.map(([name]) => name))) return;
79
- return feedbackTableSql();
80
- };
81
- /** 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. */
82
- const checkMailFeedbackSchema = async (db) => {
83
- const [unique] = indexes[0];
84
- if (await hasTable(db) && await hasIndexes(db, "mail", "feedback", [unique])) return;
85
- throw new Error(`The table ${feedbackTable} of mailFeedback, or its unique index ${unique}, is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
86
- };
87
60
  //#endregion
88
- export { checkMailFeedbackSchema, feedbackTableSql, mailFeedbackMigration };
61
+ export { feedbackIndexes, feedbackTableSql };
@@ -0,0 +1,37 @@
1
+ import { feedbackTable } from "./feedback-store.js";
2
+ import { hasIndexes } from "../../has-indexes.js";
3
+ import { relationFound } from "../../relation-found.js";
4
+ import { feedbackIndexes, feedbackTableSql } from "./feedback-schema.js";
5
+ //#region src/mail/feedback/mail-feedback-module.ts
6
+ /**
7
+ * The feedback table as the database has it: step 1 once it is there with every index. Refuses one without them, such
8
+ * as one written before a complaint could leave its recipient out, which no step records.
9
+ */
10
+ const readMailFeedback = async (db) => {
11
+ if (!await relationFound(db, feedbackTable)) return;
12
+ if (!await hasIndexes(db, "mail", "feedback", feedbackIndexes.map(([name]) => name))) throw new Error(`The table ${feedbackTable} of mailFeedback lacks indexes 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`);
13
+ return {
14
+ lastStep: 1,
15
+ replaceables: {}
16
+ };
17
+ };
18
+ /**
19
+ * The table of the bounces and complaints of the mail the app sends, with `mailFeedback`: before the change capture,
20
+ * whose triggers capture its events. Never dropped.
21
+ */
22
+ const mailFeedbackModule = {
23
+ label: "the mail feedback table",
24
+ title: "The table of the bounces and complaints of the mail the app sends",
25
+ steps: [{
26
+ step: 1,
27
+ name: "feedback",
28
+ title: "The feedback table and its indexes",
29
+ additive: true,
30
+ sql: () => feedbackTableSql()
31
+ }],
32
+ replaceables: [],
33
+ resourceReplaceables: [],
34
+ read: readMailFeedback
35
+ };
36
+ //#endregion
37
+ export { mailFeedbackModule };