@protobase/server 0.129.1 → 0.130.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) 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.d.ts +1 -1
  46. package/dist/better-auth/organizations/store.js +14 -9
  47. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  48. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  49. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  50. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  51. package/dist/better-auth/store/adoption.js +25 -10
  52. package/dist/better-auth/store/drift.js +5 -4
  53. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  54. package/dist/better-auth/store/legacy-record.js +56 -0
  55. package/dist/better-auth/store/migration-sql.js +31 -26
  56. package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
  57. package/dist/better-auth/store/offline/archive-revival.js +25 -0
  58. package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
  59. package/dist/better-auth/store/offline/baseline-store.js +15 -12
  60. package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
  61. package/dist/better-auth/store/offline/contract-gate.js +35 -0
  62. package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
  63. package/dist/better-auth/store/offline/module-archive.js +95 -0
  64. package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
  65. package/dist/better-auth/store/offline/module-delete.js +99 -0
  66. package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
  67. package/dist/better-auth/store/offline/module-switches.js +113 -0
  68. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  69. package/dist/better-auth/store/offline/name-changes.js +5 -2
  70. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
  71. package/dist/better-auth/store/offline/offline-steps.js +29 -20
  72. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  73. package/dist/better-auth/store/offline/retired-watch.js +43 -0
  74. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  75. package/dist/better-auth/store/offline/settings-names.js +10 -3
  76. package/dist/better-auth/store/offline/store-model.d.ts +27 -1
  77. package/dist/better-auth/store/offline/store-model.js +22 -5
  78. package/dist/better-auth/store/resources-outside.js +1 -1
  79. package/dist/better-auth/store/step-record.d.ts +13 -0
  80. package/dist/better-auth/store/step-record.js +59 -0
  81. package/dist/better-auth/store/steps/index.js +6 -1
  82. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  83. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  84. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  85. package/dist/better-auth/store/steps/render.d.ts +3 -0
  86. package/dist/better-auth/store/steps/render.js +48 -25
  87. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  88. package/dist/better-auth/store/steps/step-lint.js +31 -10
  89. package/dist/better-auth/store/steps/step.d.ts +18 -0
  90. package/dist/better-auth/store/steps/step.js +7 -1
  91. package/dist/better-auth/store/store-db.d.ts +6 -0
  92. package/dist/better-auth/store/store-db.js +11 -5
  93. package/dist/better-auth/store/store-names.d.ts +4 -0
  94. package/dist/better-auth/store/store-sql.d.ts +1 -1
  95. package/dist/better-auth/token-standing.js +12 -7
  96. package/dist/better-auth/users.d.ts +7 -2
  97. package/dist/better-auth/users.js +25 -3
  98. package/dist/built-in-resources.js +1 -1
  99. package/dist/calls/calls-module.js +42 -0
  100. package/dist/calls/calls-sql.js +4 -30
  101. package/dist/changes/capture-names.d.ts +3 -1
  102. package/dist/changes/capture-names.js +5 -2
  103. package/dist/changes/capture-schema-sql.d.ts +10 -0
  104. package/dist/changes/capture-schema-sql.js +21 -0
  105. package/dist/changes/capture-schema.d.ts +0 -18
  106. package/dist/changes/capture-schema.js +1 -74
  107. package/dist/changes/capture-sql.js +30 -24
  108. package/dist/changes/changes-input.js +36 -0
  109. package/dist/changes/changes-module.js +44 -0
  110. package/dist/changes/read-capture.js +67 -0
  111. package/dist/changes/steps/001-outbox.js +23 -0
  112. package/dist/channels/sends-module.js +37 -0
  113. package/dist/channels/sends-schema-sql.js +5 -5
  114. package/dist/comments/comments-module.js +30 -0
  115. package/dist/comments/comments-sql.js +1 -22
  116. package/dist/computed/buckets-sql.d.ts +5 -1
  117. package/dist/computed/buckets-sql.js +39 -46
  118. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  119. package/dist/computed/buckets-targets.js +50 -0
  120. package/dist/computed/computed-input.js +65 -0
  121. package/dist/computed/computed-module.js +102 -0
  122. package/dist/computed/formula-sql.js +14 -1
  123. package/dist/computed/read-computed.js +100 -0
  124. package/dist/computed/rollup-sql.js +13 -10
  125. package/dist/config-exports.d.ts +2 -2
  126. package/dist/create-admin.js +21 -5
  127. package/dist/derived/derived-module.js +89 -0
  128. package/dist/derived/derived-sql.js +1 -47
  129. package/dist/functions/define-function.d.ts +10 -4
  130. package/dist/functions/routes.js +5 -3
  131. package/dist/functions/supabase-routes.js +7 -5
  132. package/dist/history/history-module.js +34 -0
  133. package/dist/index.d.ts +19 -28
  134. package/dist/index.js +11 -21
  135. package/dist/internal.d.ts +30 -10
  136. package/dist/internal.js +26 -8
  137. package/dist/jobs/functions-sql.js +7 -11
  138. package/dist/jobs/job-data.js +36 -0
  139. package/dist/jobs/job-types.d.ts +6 -3
  140. package/dist/jobs/jobs-module.d.ts +5 -0
  141. package/dist/jobs/jobs-module.js +84 -0
  142. package/dist/jobs/run-job.d.ts +1 -1
  143. package/dist/jobs/run-job.js +7 -5
  144. package/dist/jobs/runtime.d.ts +9 -4
  145. package/dist/jobs/runtime.js +11 -6
  146. package/dist/jobs/schema.d.ts +0 -11
  147. package/dist/jobs/schema.js +1 -59
  148. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  149. package/dist/live/notices-module.js +30 -0
  150. package/dist/live/notices-sql.js +2 -1
  151. package/dist/mail/feedback/feedback-schema.js +3 -30
  152. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  153. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  154. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  155. package/dist/migration-record/check-record.d.ts +9 -7
  156. package/dist/migration-record/check-record.js +12 -11
  157. package/dist/migration-record/module-needs.js +30 -0
  158. package/dist/migration-record/read-record.js +27 -15
  159. package/dist/migration-record/record-model.d.ts +7 -2
  160. package/dist/migration-record/record-model.js +14 -6
  161. package/dist/migration-record/startup-decision.js +18 -7
  162. package/dist/migration-sql/additive-statements.d.ts +4 -0
  163. package/dist/migration-sql/additive-statements.js +105 -0
  164. package/dist/notifications/devices-module.js +61 -0
  165. package/dist/notifications/history-module.js +50 -0
  166. package/dist/notifications/notifications-targets.js +23 -0
  167. package/dist/notifications/read-table.js +16 -0
  168. package/dist/notifications/schema-sql.js +1 -22
  169. package/dist/notifications/schema.js +1 -101
  170. package/dist/notifications/table-names.js +40 -0
  171. package/dist/organization-scope/app-scope.js +38 -0
  172. package/dist/organization-scope/auth-request-organization.js +71 -0
  173. package/dist/organization-scope/organization-tables.js +20 -0
  174. package/dist/organization-scope/sign-in-organization.js +21 -0
  175. package/dist/package.js +1 -1
  176. package/dist/personal-mail/shared-sender-store.js +4 -2
  177. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  178. package/dist/relation-found.js +6 -0
  179. package/dist/relay/read-relay.js +85 -0
  180. package/dist/relay/realtime-members-sql.js +51 -28
  181. package/dist/relay/relay-module.js +53 -0
  182. package/dist/relay/relay-targets.js +28 -0
  183. package/dist/relay/session-end.js +1 -3
  184. package/dist/relay/sessions-sql.js +4 -27
  185. package/dist/rest/table-routes.js +9 -2
  186. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  187. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  188. package/dist/schema-modules/module-difference.d.ts +31 -0
  189. package/dist/schema-modules/module-difference.js +98 -0
  190. package/dist/schema-modules/modules-sql.js +13 -0
  191. package/dist/schema-modules/modules.d.ts +37 -0
  192. package/dist/schema-modules/modules.js +56 -0
  193. package/dist/schema-modules/needed-modules.d.ts +41 -0
  194. package/dist/schema-modules/needed-modules.js +61 -0
  195. package/dist/schema-modules/resource-difference.js +83 -0
  196. package/dist/schema-modules/schema-module.d.ts +112 -0
  197. package/dist/schema-modules/schema-module.js +8 -0
  198. package/dist/status/status-module.js +63 -0
  199. package/dist/status/status-targets.js +21 -0
  200. package/dist/types.d.ts +6 -1
  201. package/dist/user-tables/reloading-admin.d.ts +1 -0
  202. package/dist/user-tables/reloading-admin.js +1 -0
  203. package/dist/user-tables/schema-sql.js +1 -14
  204. package/dist/user-tables/schema.js +4 -27
  205. package/dist/user-tables/user-tables-module.js +38 -0
  206. package/dist/webhooks/table/delivery-log-module.js +36 -0
  207. package/dist/webhooks/table/owner-roles.js +3 -2
  208. package/dist/webhooks/table/schema-sql.js +27 -26
  209. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  210. package/dist/webhooks/table/webhooks-targets.js +26 -0
  211. package/dist/webhooks/webhooks.js +1 -1
  212. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  213. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  214. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  215. package/dist/workflows/read-catalogue.js +23 -0
  216. package/dist/workflows/schema-sql.js +12 -9
  217. package/dist/workflows/status-sql.js +12 -6
  218. package/dist/workflows/storage/storage-module.js +39 -0
  219. package/dist/workflows/storage/storage-sql.js +8 -5
  220. package/dist/workflows/workflows-schema-module.js +49 -0
  221. package/dist/workflows/workflows-tables-sql.js +32 -0
  222. package/dist/workflows/workflows-targets.js +16 -0
  223. package/package.json +6 -6
  224. package/dist/assistant/query-runner/runner-plan.js +0 -30
  225. package/dist/better-auth/store/migrations-table.js +0 -27
  226. package/dist/better-auth/store/modules-off.js +0 -17
  227. package/dist/calls/calls-sql.d.ts +0 -11
  228. package/dist/changes/capture-plan.js +0 -79
  229. package/dist/channels/sends-schema.d.ts +0 -7
  230. package/dist/channels/sends-schema.js +0 -18
  231. package/dist/comments/comments-sql.d.ts +0 -14
  232. package/dist/computed/buckets-plan.d.ts +0 -2
  233. package/dist/computed/buckets-plan.js +0 -88
  234. package/dist/computed/buckets-schema.js +0 -39
  235. package/dist/computed/computed-plan.js +0 -81
  236. package/dist/computed/computed-schema.d.ts +0 -16
  237. package/dist/computed/computed-schema.js +0 -63
  238. package/dist/derived/derived-sql.d.ts +0 -12
  239. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  240. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  241. package/dist/notifications/schema.d.ts +0 -14
  242. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  243. package/dist/realtime/relay/relay-schema.js +0 -20
  244. package/dist/relay/realtime-members-schema.js +0 -67
  245. package/dist/relay/relay-schema.d.ts +0 -14
  246. package/dist/relay/relay-schema.js +0 -28
  247. package/dist/status/schema.d.ts +0 -12
  248. package/dist/status/schema.js +0 -33
  249. package/dist/user-tables/schema.d.ts +0 -11
  250. package/dist/webhooks/table/schema.d.ts +0 -16
  251. package/dist/webhooks/table/schema.js +0 -56
  252. package/dist/workflows/schema.d.ts +0 -13
  253. package/dist/workflows/schema.js +0 -88
@@ -30,25 +30,6 @@ const capturedBy = (models) => {
30
30
  const read = new Set(models.flatMap((model) => [...(model.derived ?? []).flatMap((value) => value.reads), ...model.liveReads ?? []]));
31
31
  return (model) => isCaptured(model) || read.has(model.name);
32
32
  };
33
- /**
34
- * The outbox: one row per changed row, written in the writer's transaction. `transaction` is the writer's transaction
35
- * id; `database_role` the role that wrote; `dispatch_after` holds back a change that the process which wrote it is
36
- * delivering itself. The `alter` adds the role to an outbox of an earlier version.
37
- */
38
- const outboxSql = (schema) => `create table if not exists ${quoteIdent(schema)}."outbox" (
39
- "id" bigint generated always as identity primary key,
40
- "transaction" bigint not null,
41
- "resource" text not null,
42
- "op" text not null,
43
- "old" jsonb,
44
- "new" jsonb,
45
- "changed" text[],
46
- "actor" jsonb,
47
- "database_role" text,
48
- "dispatch_after" timestamptz not null default now(),
49
- "created_at" timestamptz not null default now()
50
- );
51
- alter table ${quoteIdent(schema)}."outbox" add column if not exists "database_role" text`;
52
33
  /** The job that turns captured changes into events and deliveries: one per writing transaction, run one at a time. */
53
34
  const dispatchJobName = "changes.dispatch";
54
35
  /** Every dispatch job's group in its ordered queue, so only one runs at a time, across processes too. */
@@ -111,6 +92,14 @@ end
111
92
  const captureFunctionSql = (schema) => `create or replace function ${quoteIdent(schema)}."capture"() returns trigger language plpgsql security definer set search_path = pg_catalog, pg_temp as $capture$${captureBody(schema)}$capture$`;
112
93
  /** The columns that hold fields, each once: a relation's are the ones holding the other record's key. */
113
94
  const columnsOf = (fields) => [...new Set(fields.flatMap((field) => field.relation?.columns ?? [field.column]))];
95
+ const suffixed = (name, suffix) => `${identifier(name, 63 - new TextEncoder().encode(suffix).length)}${suffix}`;
96
+ /** The names of the two triggers on `table`: inserts and deletes, and updates. */
97
+ const triggerNames = (table) => [suffixed(table.name, "_changes"), suffixed(table.name, "_changes_update")];
98
+ /**
99
+ * The names an earlier version gave the triggers of a table whose name is too long for them, cut at 63 bytes so both
100
+ * were one name, that `triggerNames` no longer gives: dropped before the triggers are made.
101
+ */
102
+ const cutNames = (table) => [.../* @__PURE__ */ new Set([identifier(`${table.name}_changes`), identifier(`${table.name}_changes_update`)])].filter((name) => !triggerNames(table).includes(name));
114
103
  /**
115
104
  * The two triggers of a resource whose changes are captured: inserts and deletes, and updates that change the row. The
116
105
  * fields history ignores are left out of both, and an update fires only when it changes another's columns.
@@ -123,13 +112,14 @@ const resourceTriggers = (model) => {
123
112
  textArray(columnsOf(fields.filter((field) => !field.sensitive))),
124
113
  textArray(columnsOf(fields.filter((field) => field.sensitive)))
125
114
  ];
115
+ const [insertDelete, updateName] = triggerNames(model.table);
126
116
  const update = {
127
- name: identifier(`${model.table.name}_changes_update`),
117
+ name: updateName,
128
118
  type: 17,
129
119
  args
130
120
  };
131
121
  return [{
132
- name: identifier(`${model.table.name}_changes`),
122
+ name: insertDelete,
133
123
  type: 13,
134
124
  args
135
125
  }, ignored.length > 0 ? {
@@ -138,10 +128,13 @@ const resourceTriggers = (model) => {
138
128
  } : update];
139
129
  };
140
130
  const dropTriggerSql = (name, table) => `drop trigger if exists ${quoteIdent(name)} on ${table}`;
131
+ /**
132
+ * The condition an update must meet to fire a trigger that names `columns`: any column changed without them. Each
133
+ * column is compared on its own, as Postgres words a row comparison back, so the catalogue's condition reads the same.
134
+ */
141
135
  const rowsDiffer = (columns) => {
142
136
  if (!columns) return "old.* is distinct from new.*";
143
- const row = (side) => `(${columns.map((column) => `${side}.${quoteIdent(column)}`).join(", ")})`;
144
- return `${row("old")} is distinct from ${row("new")}`;
137
+ return columns.map((column) => `(old.${quoteIdent(column)} is distinct from new.${quoteIdent(column)})`).join(" or ");
145
138
  };
146
139
  const createTriggerSql = (schema, trigger, table) => {
147
140
  const timing = trigger.type & 16 ? "after update" : "after insert or delete";
@@ -149,5 +142,18 @@ const createTriggerSql = (schema, trigger, table) => {
149
142
  const args = trigger.args.map(quoteLiteral).join(", ");
150
143
  return `create trigger ${quoteIdent(trigger.name)} ${timing} on ${table} for each row${when} execute function ${quoteIdent(schema)}."capture"(${args})`;
151
144
  };
145
+ /** One resource's triggers, each dropped and made again, so a trigger of an earlier shape is replaced. */
146
+ const resourceCaptureSql = (schema, { table, triggers, replaces = [] }) => [...replaces.map((name) => `${dropTriggerSql(name, table)};`), ...triggers.flatMap((trigger) => [`${dropTriggerSql(trigger.name, table)};`, `${createTriggerSql(schema, trigger, table)};`])].join("\n");
147
+ /** What the triggers of `model` are made from. */
148
+ const resourceCapture = (model) => {
149
+ const replaces = cutNames(model.table);
150
+ return {
151
+ table: tableSql(model),
152
+ triggers: resourceTriggers(model),
153
+ ...replaces.length > 0 && { replaces }
154
+ };
155
+ };
156
+ /** Drops the triggers a resource on `table` had. */
157
+ const dropCaptureSql = (table) => [...cutNames(table), ...triggerNames(table)].map((name) => `${dropTriggerSql(name, qualified(table))};`).join("\n");
152
158
  //#endregion
153
- export { captureBody, captureFunctionSql, capturedBy, createTriggerSql, dispatchGroup, dispatchJobName, dropTriggerSql, identifier, isCaptured, outboxSql, quoteIdent, resourceTriggers, tableSql };
159
+ export { captureBody, captureFunctionSql, capturedBy, createTriggerSql, dispatchGroup, dispatchJobName, dropCaptureSql, dropTriggerSql, identifier, isCaptured, quoteIdent, resourceCapture, resourceCaptureSql, resourceTriggers, rowsDiffer, tableSql, triggerNames };
@@ -0,0 +1,36 @@
1
+ import { capturedBy, quoteIdent, resourceCapture } from "./capture-sql.js";
2
+ import { changesSchema } from "./events-options.js";
3
+ import { checkLiveReads } from "../check-live-reads.js";
4
+ //#region src/changes/changes-input.ts
5
+ const tableKey = ({ table }) => `${quoteIdent(table.schema ?? "public")}.${quoteIdent(table.name)}`;
6
+ const tableOf = ({ table }) => ({
7
+ ...table.schema !== void 0 && { schema: table.schema },
8
+ name: table.name
9
+ });
10
+ /**
11
+ * What the change capture module takes from the app: the changes schema `events` names, and the triggers of each of
12
+ * `models`, kept only for one whose changes are not captured (`capturedBy`), so its triggers follow its fields while
13
+ * older code may still capture it. Refuses two captured resources on one table, and live reads `checkLiveReads` refuses.
14
+ */
15
+ const changesInput = (models, events) => {
16
+ checkLiveReads(models);
17
+ const captured = capturedBy(models);
18
+ const tables = /* @__PURE__ */ new Map();
19
+ for (const model of models.filter(captured)) {
20
+ const other = tables.get(tableKey(model));
21
+ if (other) throw new Error(`Not implemented: resources "${other}" and "${model.name}" both have events or history on table ${tableKey(model)}; declare them on one`);
22
+ tables.set(tableKey(model), model.name);
23
+ }
24
+ const kept = models.filter((model) => !captured(model) && !tables.has(tableKey(model)));
25
+ const triggers = Object.fromEntries([...models.filter(captured), ...kept].map((model) => [model.name, {
26
+ table: tableOf(model),
27
+ input: resourceCapture(model),
28
+ ...!captured(model) && { kept: true }
29
+ }]));
30
+ return {
31
+ names: { schema: changesSchema(events) },
32
+ resources: { triggers }
33
+ };
34
+ };
35
+ //#endregion
36
+ export { changesInput };
@@ -0,0 +1,44 @@
1
+ import { captureFunctionSql, dropCaptureSql, resourceCaptureSql } from "./capture-sql.js";
2
+ import { readCapture } from "./read-capture.js";
3
+ import { outboxStep } from "./steps/001-outbox.js";
4
+ //#region src/changes/changes-module.ts
5
+ /**
6
+ * The triggers that capture one resource's changes. Kept on a resource that no longer needs them while another still
7
+ * does, so the code still running while the migration deploys, or the version before once rolled back, still captures
8
+ * it, as the dispatch job still drains the outbox; once none does, they go.
9
+ */
10
+ const triggers = {
11
+ name: "triggers",
12
+ title: "The triggers that capture the changes",
13
+ version: 1,
14
+ compatibleFrom: 1,
15
+ sql: (names, input) => resourceCaptureSql(names.schema, input),
16
+ drop: (_names, table) => dropCaptureSql(table),
17
+ keptWhileOthers: true
18
+ };
19
+ /**
20
+ * The change capture the resources' events, history, live updates and derived values need, in the schema `events`
21
+ * names (`names.schema`): the outbox, `capture()`, and each captured resource's triggers. Its tables are never dropped.
22
+ */
23
+ const changesModule = {
24
+ label: "the change capture",
25
+ title: "The change capture the resources' events and history need",
26
+ steps: [{
27
+ step: 1,
28
+ name: "outbox",
29
+ title: "The outbox of captured changes",
30
+ additive: true,
31
+ sql: (names) => outboxStep(names.schema)
32
+ }],
33
+ replaceables: [{
34
+ name: "capture",
35
+ title: "The function the triggers call, capture()",
36
+ version: 1,
37
+ compatibleFrom: 1,
38
+ sql: (names) => `${captureFunctionSql(names.schema)};`
39
+ }],
40
+ resourceReplaceables: [triggers],
41
+ read: readCapture(triggers)
42
+ };
43
+ //#endregion
44
+ export { changesModule };
@@ -0,0 +1,67 @@
1
+ import { captureBody, quoteIdent, rowsDiffer } from "./capture-sql.js";
2
+ import { resourceEntry } from "../schema-modules/resource-difference.js";
3
+ import { sql } from "kysely";
4
+ const rowsOf = async (db, query) => (await query.execute(db)).rows;
5
+ const triggerArgs = (hex) => {
6
+ const bytes = new Uint8Array((hex.match(/../g) ?? []).map((pair) => parseInt(pair, 16)));
7
+ return new TextDecoder().decode(bytes).split("\0").slice(0, -1);
8
+ };
9
+ const comparable = (condition) => condition.toLowerCase().replace(/["()\s]/g, "");
10
+ const condition = (trigger) => trigger.type & 16 ? rowsDiffer(trigger.columns) : "";
11
+ const sameTriggers = (found, wanted) => found.length === wanted.triggers.length && wanted.triggers.every((trigger) => found.some((one) => one.enabled && one.name === trigger.name && one.type === trigger.type && one.args.join("\0") === trigger.args.join("\0") && comparable(one.when) === comparable(condition(trigger))));
12
+ const readTriggers = async (db, captureOid) => (await rowsOf(db, sql`select n.nspname as schema, c.relname as table, t.tgname as name,
13
+ t.tgtype::int as type, encode(t.tgargs, 'hex') as args, t.tgenabled <> 'D' as enabled,
14
+ coalesce(substring(pg_get_triggerdef(t.oid) from ' WHEN (.*) EXECUTE FUNCTION '), '') as when
15
+ from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
16
+ where not t.tgisinternal and t.tgfoid::text = ${captureOid} order by n.nspname, c.relname, t.tgname`)).map((trigger) => ({
17
+ ...trigger,
18
+ args: triggerArgs(trigger.args)
19
+ }));
20
+ const onTable = (found, table) => found.table === table.name && (table.schema === void 0 || found.schema === table.schema);
21
+ /**
22
+ * The change capture as the database has it for `input`: step 1 once the outbox is there, `capture()` at its version
23
+ * when its body is the one this version writes, and each resource of the input whose table has triggers calling it,
24
+ * at the digest of its input when they are the ones it makes, enabled, else at none, so they are written again; and the
25
+ * triggers on other tables, by the resource they capture (`readTriggers`). Refuses an outbox of an earlier shape, which
26
+ * no step records.
27
+ */
28
+ const readCapture = (triggers) => async (db, input) => {
29
+ const schema = input.names.schema;
30
+ const [outbox] = await rowsOf(db, sql`select to_regclass(${`${quoteIdent(schema)}."outbox"`}) is not null as found,
31
+ exists (select from information_schema.columns where table_schema = ${schema} and table_name = 'outbox' and column_name = 'database_role') as role`);
32
+ if (!outbox.found) return;
33
+ if (!outbox.role) throw new Error(`The outbox of the change capture in schema "${schema}" lacks its database_role column, which 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`);
34
+ const [capture] = await rowsOf(db, sql`select p.oid::text as oid, p.prosrc as source, p.prosecdef as definer from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${schema} and p.proname = 'capture' and p.pronargs = 0`);
35
+ const current = capture && capture.definer && capture.source === captureBody(schema);
36
+ const found = capture ? await readTriggers(db, capture.oid) : [];
37
+ const entries = {};
38
+ for (const [key, given] of Object.entries(input.resources[triggers.name] ?? {})) {
39
+ const own = found.filter((one) => onTable(one, given.table));
40
+ if (own.length === 0) continue;
41
+ const entry = resourceEntry(triggers, input.names, given);
42
+ entries[key] = sameTriggers(own, given.input) ? entry : {
43
+ ...entry,
44
+ digest: ""
45
+ };
46
+ }
47
+ for (const one of found) {
48
+ const resource = one.args[0] ?? one.name;
49
+ if (entries[resource] || Object.values(input.resources[triggers.name] ?? {}).some((given) => onTable(one, given.table))) continue;
50
+ entries[resource] = {
51
+ version: triggers.version,
52
+ digest: "",
53
+ table: {
54
+ schema: one.schema,
55
+ name: one.table
56
+ }
57
+ };
58
+ }
59
+ return {
60
+ lastStep: 1,
61
+ replaceables: current ? { capture: 1 } : {},
62
+ names: input.names,
63
+ ...Object.keys(entries).length > 0 && { resources: { [triggers.name]: entries } }
64
+ };
65
+ };
66
+ //#endregion
67
+ export { readCapture };
@@ -0,0 +1,23 @@
1
+ import { quoteIdent } from "../capture-sql.js";
2
+ //#region src/changes/steps/001-outbox.ts
3
+ /**
4
+ * The outbox: one row per changed row, written in the writer's transaction. `transaction` is the writer's transaction
5
+ * id; `database_role` the role that wrote; `dispatch_after` holds back a change that the process which wrote it is
6
+ * delivering itself.
7
+ */
8
+ const outboxStep = (schema) => `create schema if not exists ${quoteIdent(schema)};
9
+ create table if not exists ${quoteIdent(schema)}."outbox" (
10
+ "id" bigint generated always as identity primary key,
11
+ "transaction" bigint not null,
12
+ "resource" text not null,
13
+ "op" text not null,
14
+ "old" jsonb,
15
+ "new" jsonb,
16
+ "changed" text[],
17
+ "actor" jsonb,
18
+ "database_role" text,
19
+ "dispatch_after" timestamptz not null default now(),
20
+ "created_at" timestamptz not null default now()
21
+ );`;
22
+ //#endregion
23
+ export { outboxStep };
@@ -0,0 +1,37 @@
1
+ import { sendFunctionSql, sendsSchema, sendsTableSql } from "./sends-schema-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/channels/sends-module.ts
4
+ /** The `channels` schema as the database has it: step 1 once the sends table is there, and `send()` once it is. */
5
+ const readSends = async (db) => {
6
+ const { rows } = await sql`select to_regclass(${`${sendsSchema}.sends`}) is not null as table,
7
+ to_regprocedure(${`${sendsSchema}.send(text, text, text, jsonb)`}) is not null as send`.execute(db);
8
+ const found = rows[0];
9
+ if (!found.table) return;
10
+ return {
11
+ lastStep: 1,
12
+ replaceables: found.send ? { send: 1 } : {}
13
+ };
14
+ };
15
+ /** The `channels` schema of SQL's broadcasts to the record channels, and `channels.send()`. Never dropped. */
16
+ const channelSendsModule = {
17
+ label: `the ${sendsSchema} schema`,
18
+ title: "SQL's broadcasts to the record channels, channels.send()",
19
+ steps: [{
20
+ step: 1,
21
+ name: "sends",
22
+ title: "The sends table",
23
+ additive: true,
24
+ sql: () => sendsTableSql
25
+ }],
26
+ replaceables: [{
27
+ name: "send",
28
+ title: "The function SQL sends with, channels.send()",
29
+ version: 1,
30
+ compatibleFrom: 1,
31
+ sql: () => sendFunctionSql
32
+ }],
33
+ resourceReplaceables: [],
34
+ read: readSends
35
+ };
36
+ //#endregion
37
+ export { channelSendsModule };
@@ -8,7 +8,7 @@ const sendsSchema = "channels";
8
8
  * so that no other role, such as one of `/api/sb/rest/v1`'s, sends as the server; a trigger function that sends for
9
9
  * them is `security definer`.
10
10
  */
11
- const sendsSchemaSql = `create schema if not exists ${sendsSchema};
11
+ const sendsTableSql = `create schema if not exists ${sendsSchema};
12
12
 
13
13
  create table if not exists ${sendsSchema}.sends (
14
14
  id bigint generated always as identity primary key,
@@ -19,12 +19,12 @@ create table if not exists ${sendsSchema}.sends (
19
19
  sent_at timestamptz not null default now()
20
20
  );
21
21
 
22
- create index if not exists sends_sent_at on ${sendsSchema}.sends (sent_at);
23
-
24
- create or replace function ${sendsSchema}.send(resource text, key text, event text, payload jsonb) returns void
22
+ create index if not exists sends_sent_at on ${sendsSchema}.sends (sent_at);`;
23
+ /** `send()` at version 1 of `channelSendsModule`'s replaceable: a change to it bumps its version. */
24
+ const sendFunctionSql = `create or replace function ${sendsSchema}.send(resource text, key text, event text, payload jsonb) returns void
25
25
  language sql security definer set search_path = ''
26
26
  as $$ insert into ${sendsSchema}.sends (resource, key, event, payload) values (send.resource, send.key, send.event, send.payload) $$;
27
27
 
28
28
  revoke execute on function ${sendsSchema}.send(text, text, text, jsonb) from public;`;
29
29
  //#endregion
30
- export { sendsSchema, sendsSchemaSql };
30
+ export { sendFunctionSql, sendsSchema, sendsTableSql };
@@ -0,0 +1,30 @@
1
+ import { commentsIndexes, commentsTable, commentsTableSql } from "./comments-sql.js";
2
+ import { hasIndexes } from "../has-indexes.js";
3
+ import { relationFound } from "../relation-found.js";
4
+ //#region src/comments/comments-module.ts
5
+ /** The comments table as the database has it: step 1 once it is there with every index. Refuses one without them, which no step records. */
6
+ const readComments = async (db) => {
7
+ if (!await relationFound(db, "\"comments\".\"comments\"")) return;
8
+ if (!await hasIndexes(db, "comments", "comments", commentsIndexes.map(([name]) => name))) throw new Error(`The comments table ${commentsTable} lacks indexes no step of this version of Protobase records: add them with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
9
+ return {
10
+ lastStep: 1,
11
+ replaceables: {}
12
+ };
13
+ };
14
+ /** The comments table of the resources with `.comments()`, in a `comments` schema of its own. Never dropped. */
15
+ const commentsModule = {
16
+ label: "the comments table",
17
+ title: "The comments table of the resources with comments",
18
+ steps: [{
19
+ step: 1,
20
+ name: "comments",
21
+ title: "The comments table and its indexes",
22
+ additive: true,
23
+ sql: () => `create schema if not exists "comments";\n${commentsTableSql()};`
24
+ }],
25
+ replaceables: [],
26
+ resourceReplaceables: [],
27
+ read: readComments
28
+ };
29
+ //#endregion
30
+ export { commentsModule };
@@ -1,6 +1,3 @@
1
- import { hasIndexes } from "../has-indexes.js";
2
- import { migrationCommand } from "../changes/capture-schema.js";
3
- import { sql } from "kysely";
4
1
  //#region src/comments/comments-sql.ts
5
2
  /** The table the comments of every resource with `.comments()` are kept in, in a schema of its own. */
6
3
  const commentsTable = "\"comments\".\"comments\"";
@@ -27,23 +24,5 @@ const commentsTableSql = () => `create table if not exists ${commentsTable} (
27
24
  "created_at" timestamptz not null default now()
28
25
  );
29
26
  ${commentsIndexes.map(([name, columns]) => `create index if not exists "${name}" on ${commentsTable} (${columns})`).join(";\n")}`;
30
- const hasCommentsTable = async (db) => (await sql`select to_regclass('comments.comments') is not null as found`.execute(db)).rows[0].found;
31
- /**
32
- * The SQL that adds the `comments` schema and its table, or the indexes it lacks, `undefined` when it has them all. The
33
- * table is never dropped.
34
- */
35
- const commentsMigration = async (db) => {
36
- if (await hasCommentsTable(db) && await hasIndexes(db, "comments", "comments", commentsIndexes.map(([name]) => name))) return void 0;
37
- return `create schema if not exists "comments";\n\n${commentsTableSql()};`;
38
- };
39
- /**
40
- * Refuses to go on while a resource has `.comments()` and the database lacks their table; the project's migrations add
41
- * it. An index added since only speeds reads up, so a table without it still serves and `protobase migration` adds it.
42
- */
43
- const checkComments = async (db, models) => {
44
- if (!models.some((model) => model.comments)) return;
45
- if (await hasCommentsTable(db)) return;
46
- throw new Error(`The comments schema is missing, and resources with .comments() keep their comments in comments.comments. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
47
- };
48
27
  //#endregion
49
- export { checkComments, commentsMigration, commentsTable, commentsTableSql };
28
+ export { commentsIndexes, commentsTable, commentsTableSql };
@@ -1 +1,5 @@
1
- import { ResourceModel } from "@protobase/schema";
1
+ import { ResourceModel } from "@protobase/schema";
2
+ //#region src/computed/buckets-sql.d.ts
3
+ /** The comment that marks a table as a time rollup Protobase keeps. */
4
+ export declare const bucketsCommentPrefix = "protobase time rollup: ";
5
+ //#endregion
@@ -2,18 +2,8 @@ import { identifier, quoteIdent } from "../changes/capture-sql.js";
2
2
  import { rollupsSchema } from "./rollup-sql.js";
3
3
  import { createHash } from "node:crypto";
4
4
  //#region src/computed/buckets-sql.ts
5
- /** The comment that marks a table as a time rollup Protobase keeps, with the statements it was created by. */
5
+ /** The comment that marks a table as a time rollup Protobase keeps. */
6
6
  const bucketsCommentPrefix = "protobase time rollup: ";
7
- const sumDigits = 10;
8
- /** The type of a sum of a source column, from the source column's type as `format_type` names it. */
9
- const sumType = (type) => {
10
- if (type === "smallint" || type === "integer") return "bigint";
11
- if (type === "bigint") return `numeric(29,0)`;
12
- if (type === "numeric") return "numeric";
13
- const decimal = /^numeric\((\d+),(\d+)\)$/.exec(type);
14
- if (decimal) return `numeric(${Math.min(Number(decimal[1]) + sumDigits, 1e3)},${decimal[2]})`;
15
- throw new Error(`Not implemented: the sum of a ${type} column in a time rollup`);
16
- };
17
7
  /** The function that recomputes a time rollup's buckets, named for its table. */
18
8
  const bucketsFunctionName = ({ model }) => identifier(`${[model.table.schema, model.table.name].filter(Boolean).join("_")}_refresh`);
19
9
  const functionSql = (target) => `${quoteIdent(rollupsSchema)}.${quoteIdent(bucketsFunctionName(target))}`;
@@ -24,31 +14,38 @@ const indexName = (target, suffix) => {
24
14
  return quoteIdent(`${identifier(name, 54)}_${hash}`);
25
15
  };
26
16
  const groupColumns = (target) => ["bucket", ...target.by.map((column) => column.column)].map(quoteIdent);
17
+ const aggregateSql = ({ fn, from }) => `${fn}(c.${quoteIdent(from)})`;
18
+ const selectSql = (target) => [
19
+ `date_trunc('${target.every}', c.${quoteIdent(target.time)}::timestamptz) as ${quoteIdent("bucket")}`,
20
+ ...target.by.map(({ column, from }) => `c.${quoteIdent(from)} as ${quoteIdent(column)}`),
21
+ `count(*) as ${quoteIdent("events")}`,
22
+ ...target.measures.map((measure) => `${aggregateSql(measure)} as ${quoteIdent(measure.column)}`),
23
+ ...target.counts.map(({ column, from }) => `count(c.${quoteIdent(from)}) as ${quoteIdent(column)}`)
24
+ ];
25
+ const groupBySql = (target) => [1, ...target.by.map((_, index) => index + 2)].join(", ");
27
26
  /**
28
- * The statements that create a time rollup's table: its key `id`, `bucket`, the groups, the count `events`, the
29
- * measures and the counts of values; a unique btree index on `(bucket, groups...)`, which serves `bucket` and the refresh's upsert; and one on
30
- * `(group, bucket)` per group, so a filter on a group alone or with a range of buckets is served too.
27
+ * The statements that create a time rollup's table from the select its refresh runs, so Postgres types its columns as
28
+ * the source's and the aggregates': the bucket, the groups, the count `events`, the measures and the counts of values,
29
+ * then its key `id`; a unique btree index on `(bucket, groups...)`, which serves `bucket` and the refresh's upsert; and
30
+ * one on `(group, bucket)` per group, so a filter on a group alone or with a range of buckets is served too.
31
31
  */
32
32
  const bucketsTableSql = (target) => [
33
- `create table ${target.table} (${[
34
- `${quoteIdent("id")} bigint generated always as identity primary key`,
35
- `${quoteIdent("bucket")} timestamptz not null`,
36
- ...target.by.map(({ column, type }) => `${quoteIdent(column)} ${type} not null`),
37
- `${quoteIdent("events")} bigint not null`,
38
- ...target.measures.map(({ column, type }) => `${quoteIdent(column)} ${type}`),
39
- ...target.counts.map(({ column }) => `${quoteIdent(column)} bigint not null`)
40
- ].join(", ")})`,
33
+ `create table ${target.table} as select ${selectSql(target).join(", ")} from ${target.fromTable} as c group by ${groupBySql(target)} with no data`,
34
+ `alter table ${target.table} ${[`add column ${quoteIdent("id")} bigint generated always as identity primary key`, ...[
35
+ ...groupColumns(target),
36
+ quoteIdent("events"),
37
+ ...target.counts.map(({ column }) => quoteIdent(column))
38
+ ].map((column) => `alter column ${column} set not null`)].join(", ")}`,
41
39
  `create unique index ${indexName(target, "bucket_key")} on ${target.table} (${groupColumns(target).join(", ")})`,
42
40
  ...target.by.map(({ column }) => `create index ${indexName(target, `${column}_bucket`)} on ${target.table} (${quoteIdent(column)}, ${quoteIdent("bucket")})`)
43
41
  ];
44
- /** The comment on a time rollup's table, which names the statements that created it, so a changed rollup is found. */
45
- const bucketsComment = (target) => `${bucketsCommentPrefix}${bucketsTableSql(target).join("; ")}`;
42
+ /** The comment on a time rollup's table, which marks it as one and names the source's types it was made from. */
43
+ const bucketsComment = (target) => `${bucketsCommentPrefix}from ${target.fromTable} (${target.types.join(", ")})`;
46
44
  const quoteLiteral = (text) => `'${text.replaceAll("'", "''")}'`;
47
- const startSql = ({ every, time }) => `date_trunc('${every}', $1)${time.zoned ? "" : "::timestamp"}`;
48
- const aggregateSql = ({ fn, from }) => `${fn}(c.${quoteIdent(from)})`;
49
45
  /**
50
- * The body of a time rollup's refresh function: in one statement, it counts and aggregates the source's records and values from
51
- * the bucket `$1` falls in, upserts those buckets and deletes the later ones that no longer have records.
46
+ * The body of a time rollup's refresh function: in one statement, it counts and aggregates the source's records and
47
+ * values from the bucket `$1` falls in, upserts those buckets and deletes the later ones that no longer have records.
48
+ * That bucket's start is compared as a value of the time column's own type, so its index serves.
52
49
  */
53
50
  const bucketsBody = (target) => {
54
51
  const columns = [
@@ -56,45 +53,41 @@ const bucketsBody = (target) => {
56
53
  quoteIdent("events"),
57
54
  ...[...target.measures, ...target.counts].map(({ column }) => quoteIdent(column))
58
55
  ];
59
- const select = [
60
- `date_trunc('${target.every}', c.${quoteIdent(target.time.column)}::timestamptz) as ${quoteIdent("bucket")}`,
61
- ...target.by.map(({ column, from }) => `c.${quoteIdent(from)} as ${quoteIdent(column)}`),
62
- `count(*) as ${quoteIdent("events")}`,
63
- ...target.measures.map((measure) => `${aggregateSql(measure)} as ${quoteIdent(measure.column)}`),
64
- ...target.counts.map(({ column, from }) => `count(c.${quoteIdent(from)}) as ${quoteIdent(column)}`)
65
- ];
66
56
  const live = target.softDelete ? ` and c.${quoteIdent(target.softDelete)} is null` : "";
67
- const groupBy = [1, ...target.by.map((_, index) => index + 2)].join(", ");
68
57
  const same = groupColumns(target).map((column) => `fresh.${column} = r.${column}`).join(" and ");
69
58
  const updated = columns.slice(groupColumns(target).length).map((column) => `${column} = excluded.${column}`).join(", ");
70
59
  return `
60
+ <<refresh>>
61
+ declare
62
+ since ${target.fromTable}.${quoteIdent(target.time)}%type := date_trunc('${target.every}', $1);
63
+ begin
71
64
  with fresh as (
72
- select ${select.join(", ")}
65
+ select ${selectSql(target).join(", ")}
73
66
  from ${target.fromTable} as c
74
- where c.${quoteIdent(target.time.column)} >= ${startSql(target)}${live}
75
- group by ${groupBy}
67
+ where c.${quoteIdent(target.time)} >= refresh.since${live}
68
+ group by ${groupBySql(target)}
76
69
  ), gone as (
77
70
  delete from ${target.table} as r where r.${quoteIdent("bucket")} >= date_trunc('${target.every}', $1) and not exists (select from fresh where ${same})
78
71
  )
79
72
  insert into ${target.table} (${columns.join(", ")})
80
73
  select ${columns.join(", ")} from fresh
81
- on conflict (${groupColumns(target).join(", ")}) do update set ${updated}
74
+ on conflict (${groupColumns(target).join(", ")}) do update set ${updated};
75
+ end
82
76
  `;
83
77
  };
84
78
  /**
85
79
  * The refresh function runs as its caller, with a fixed search path and the tables qualified, in UTC, so buckets are
86
80
  * UTC hours and days whatever the session's time zone.
87
81
  */
88
- const bucketsFunctionSql = (target) => `create or replace function ${functionSql(target)}("from" timestamptz) returns void language sql set search_path = pg_catalog, pg_temp set timezone = 'UTC' as $buckets$${bucketsBody(target)}$buckets$`;
82
+ const bucketsFunctionSql = (target) => `create or replace function ${functionSql(target)}("from" timestamptz) returns void language plpgsql set search_path = pg_catalog, pg_temp set timezone = 'UTC' as $buckets$${bucketsBody(target)}$buckets$`;
89
83
  /** Recomputes every bucket. */
90
84
  const bucketsFillSql = (target) => `select ${functionSql(target)}('-infinity')`;
91
- /** The statements that create a time rollup's table, mark it, write its function and fill it. */
85
+ /** The statements that create a time rollup's table, mark it and write its function; it is empty until it is filled. */
92
86
  const createBucketsSql = (target) => [
93
87
  ...bucketsTableSql(target),
94
88
  `comment on table ${target.table} is ${quoteLiteral(bucketsComment(target))}`,
95
- bucketsFunctionSql(target),
96
- bucketsFillSql(target)
89
+ bucketsFunctionSql(target)
97
90
  ];
98
- const dropBucketsTableSql = (target) => `drop table ${target.table}`;
91
+ const dropBucketsTableSql = (table) => `drop table ${table}`;
99
92
  //#endregion
100
- export { bucketsBody, bucketsComment, bucketsCommentPrefix, bucketsFillSql, bucketsFunctionName, bucketsFunctionSql, bucketsTableSql, createBucketsSql, dropBucketsTableSql, sumType };
93
+ export { bucketsBody, bucketsComment, bucketsCommentPrefix, bucketsFillSql, bucketsFunctionName, bucketsFunctionSql, bucketsTableSql, createBucketsSql, dropBucketsTableSql };
@@ -1,7 +1,6 @@
1
- import "./buckets-plan.js";
1
+ import "./buckets-sql.js";
2
2
  import { ResourceModel } from "@protobase/schema";
3
- import { Db } from "@protobase/query";
4
- //#region src/computed/buckets-schema.d.ts
3
+ //#region src/computed/buckets-targets.d.ts
5
4
  /** Whether a resource is a time rollup. */
6
5
  export declare const hasBuckets: (model: ResourceModel) => boolean;
7
6
  //#endregion
@@ -0,0 +1,50 @@
1
+ import { measureFieldName } from "@protobase/schema/internal";
2
+ //#region src/computed/buckets-targets.ts
3
+ /** Whether a resource is a time rollup. */
4
+ const hasBuckets = (model) => model.buckets !== void 0;
5
+ /** The time rollups of the resources, with the resources they roll up. */
6
+ const bucketModels = (models) => models.flatMap((model) => {
7
+ if (!model.buckets) return [];
8
+ const from = models.find((candidate) => candidate.name === model.buckets.from);
9
+ if (!from) throw new Error(`Resource "${model.name}" is a time rollup of "${model.buckets.from}", which is not a resource`);
10
+ return [{
11
+ model,
12
+ from
13
+ }];
14
+ });
15
+ const declaredType = (field) => field.decimal ? `${field.type}(${field.decimal.precision},${field.decimal.scale})` : field.type;
16
+ /** A time rollup with its tables, as `tableSql` names a resource's, and the source's columns it reads. */
17
+ const bucketsTarget = (model, from, tableSql) => {
18
+ const { time, every, by, measures } = model.buckets;
19
+ const source = (field) => from.fields[field].column;
20
+ const read = [
21
+ time,
22
+ ...by,
23
+ ...Object.keys(measures),
24
+ ...from.softDelete ? [from.softDelete] : []
25
+ ];
26
+ return {
27
+ model,
28
+ table: tableSql(model),
29
+ fromTable: tableSql(from),
30
+ every,
31
+ time: source(time),
32
+ by: by.map((field) => ({
33
+ column: model.fields[field].column,
34
+ from: source(field)
35
+ })),
36
+ measures: Object.entries(measures).flatMap(([field, fns]) => fns.map((fn) => ({
37
+ fn,
38
+ column: model.fields[measureFieldName(field, fn)].column,
39
+ from: source(field)
40
+ }))),
41
+ counts: Object.keys(measures).map((field) => ({
42
+ column: model.fields[measureFieldName(field, "count")].column,
43
+ from: source(field)
44
+ })),
45
+ ...from.softDelete && { softDelete: source(from.softDelete) },
46
+ types: [...new Set(read)].map((field) => `${source(field)} ${declaredType(from.fields[field])}`)
47
+ };
48
+ };
49
+ //#endregion
50
+ export { bucketModels, bucketsTarget, hasBuckets };