@protobase/server 0.129.0 → 0.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/dist/assistant/query-runner/grants-sql.js +32 -0
  2. package/dist/assistant/query-runner/query-input.js +33 -0
  3. package/dist/assistant/query-runner/query-module.js +44 -0
  4. package/dist/assistant/query-runner/query-runner.d.ts +8 -11
  5. package/dist/assistant/query-runner/query-runner.js +15 -57
  6. package/dist/assistant/query-runner/read-query.js +54 -0
  7. package/dist/assistant/query-runner/runner-sql.js +4 -20
  8. package/dist/assistant/query-runner/steps/001-role.js +19 -0
  9. package/dist/auth-store.d.ts +2 -2
  10. package/dist/auth-store.js +3 -3
  11. package/dist/better-auth/auth-schema.d.ts +13 -4
  12. package/dist/better-auth/auth-schema.js +40 -32
  13. package/dist/better-auth/auth-settings.d.ts +59 -11
  14. package/dist/better-auth/auth-settings.js +57 -13
  15. package/dist/better-auth/auth-tables.d.ts +6 -3
  16. package/dist/better-auth/auth-tables.js +12 -7
  17. package/dist/better-auth/authenticator.js +10 -2
  18. package/dist/better-auth/create-auth.d.ts +62 -7
  19. package/dist/better-auth/create-auth.js +55 -14
  20. package/dist/better-auth/device-sign-in-check.js +13 -0
  21. package/dist/better-auth/names/declaration.d.ts +18 -5
  22. package/dist/better-auth/names/declaration.js +3 -1
  23. package/dist/better-auth/names/modules/auth.js +9 -0
  24. package/dist/better-auth/names/modules/index.d.ts +34 -4
  25. package/dist/better-auth/names/modules/organizations.js +10 -3
  26. package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
  27. package/dist/better-auth/names/modules-on.js +25 -2
  28. package/dist/better-auth/names/resolve-names.d.ts +9 -1
  29. package/dist/better-auth/names/resolve-names.js +15 -9
  30. package/dist/better-auth/organizations/accept-invitation.js +5 -4
  31. package/dist/better-auth/organizations/add-every-user.js +3 -2
  32. package/dist/better-auth/organizations/host-scope.d.ts +10 -0
  33. package/dist/better-auth/organizations/host-scope.js +15 -0
  34. package/dist/better-auth/organizations/host.d.ts +12 -6
  35. package/dist/better-auth/organizations/host.js +99 -61
  36. package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
  37. package/dist/better-auth/organizations/kept-organizations.js +62 -0
  38. package/dist/better-auth/organizations/member-endpoints.js +4 -3
  39. package/dist/better-auth/organizations/options.d.ts +15 -0
  40. package/dist/better-auth/organizations/options.js +19 -1
  41. package/dist/better-auth/organizations/people-endpoint.js +3 -2
  42. package/dist/better-auth/organizations/pinned-membership.js +81 -0
  43. package/dist/better-auth/organizations/pinned-sessions.js +46 -0
  44. package/dist/better-auth/organizations/session-organization.js +3 -2
  45. package/dist/better-auth/organizations/store.js +14 -9
  46. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  47. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  48. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  49. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  50. package/dist/better-auth/store/adoption.js +25 -10
  51. package/dist/better-auth/store/drift.js +5 -4
  52. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  53. package/dist/better-auth/store/legacy-record.js +56 -0
  54. package/dist/better-auth/store/migration-sql.js +31 -26
  55. package/dist/better-auth/store/offline/baseline-store.d.ts +35 -0
  56. package/dist/better-auth/store/offline/baseline-store.js +65 -0
  57. package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
  58. package/dist/better-auth/store/offline/module-switches.js +94 -0
  59. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  60. package/dist/better-auth/store/offline/name-changes.js +5 -2
  61. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -6
  62. package/dist/better-auth/store/offline/offline-steps.js +30 -20
  63. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  64. package/dist/better-auth/store/offline/retired-watch.js +36 -0
  65. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  66. package/dist/better-auth/store/offline/settings-names.js +10 -3
  67. package/dist/better-auth/store/offline/store-model.d.ts +9 -1
  68. package/dist/better-auth/store/offline/store-model.js +22 -5
  69. package/dist/better-auth/store/resources-outside.js +1 -1
  70. package/dist/better-auth/store/step-record.d.ts +13 -0
  71. package/dist/better-auth/store/step-record.js +59 -0
  72. package/dist/better-auth/store/steps/index.js +6 -1
  73. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  74. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  75. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  76. package/dist/better-auth/store/steps/render.d.ts +3 -0
  77. package/dist/better-auth/store/steps/render.js +48 -25
  78. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  79. package/dist/better-auth/store/steps/step-lint.js +31 -10
  80. package/dist/better-auth/store/steps/step.d.ts +18 -0
  81. package/dist/better-auth/store/steps/step.js +13 -4
  82. package/dist/better-auth/store/store-db.d.ts +6 -0
  83. package/dist/better-auth/store/store-db.js +11 -5
  84. package/dist/better-auth/store/store-names.d.ts +4 -0
  85. package/dist/better-auth/token-standing.js +12 -7
  86. package/dist/better-auth/users.d.ts +7 -2
  87. package/dist/better-auth/users.js +25 -3
  88. package/dist/built-in-resources.js +1 -1
  89. package/dist/calls/calls-module.js +42 -0
  90. package/dist/calls/calls-sql.js +4 -30
  91. package/dist/changes/capture-names.d.ts +3 -1
  92. package/dist/changes/capture-names.js +5 -2
  93. package/dist/changes/capture-schema-sql.d.ts +10 -0
  94. package/dist/changes/capture-schema-sql.js +21 -0
  95. package/dist/changes/capture-schema.d.ts +0 -18
  96. package/dist/changes/capture-schema.js +1 -74
  97. package/dist/changes/capture-sql.js +30 -24
  98. package/dist/changes/changes-input.js +36 -0
  99. package/dist/changes/changes-module.js +44 -0
  100. package/dist/changes/read-capture.js +67 -0
  101. package/dist/changes/steps/001-outbox.js +23 -0
  102. package/dist/channels/sends-module.js +37 -0
  103. package/dist/channels/sends-schema-sql.js +5 -5
  104. package/dist/comments/comments-module.js +30 -0
  105. package/dist/comments/comments-sql.js +1 -22
  106. package/dist/computed/buckets-sql.d.ts +5 -1
  107. package/dist/computed/buckets-sql.js +39 -46
  108. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  109. package/dist/computed/buckets-targets.js +50 -0
  110. package/dist/computed/computed-input.js +65 -0
  111. package/dist/computed/computed-module.js +102 -0
  112. package/dist/computed/formula-sql.js +14 -1
  113. package/dist/computed/read-computed.js +100 -0
  114. package/dist/computed/rollup-sql.js +13 -10
  115. package/dist/config-exports.d.ts +2 -2
  116. package/dist/create-admin.js +21 -5
  117. package/dist/derived/derived-module.js +89 -0
  118. package/dist/derived/derived-sql.js +1 -47
  119. package/dist/functions/define-function.d.ts +10 -4
  120. package/dist/functions/routes.js +5 -3
  121. package/dist/functions/supabase-routes.js +7 -5
  122. package/dist/history/history-module.js +34 -0
  123. package/dist/index.d.ts +19 -28
  124. package/dist/index.js +11 -21
  125. package/dist/internal.d.ts +27 -10
  126. package/dist/internal.js +22 -7
  127. package/dist/jobs/functions-sql.js +7 -11
  128. package/dist/jobs/job-data.js +36 -0
  129. package/dist/jobs/job-types.d.ts +6 -3
  130. package/dist/jobs/jobs-module.d.ts +5 -0
  131. package/dist/jobs/jobs-module.js +84 -0
  132. package/dist/jobs/run-job.d.ts +1 -1
  133. package/dist/jobs/run-job.js +7 -5
  134. package/dist/jobs/runtime.d.ts +9 -4
  135. package/dist/jobs/runtime.js +11 -6
  136. package/dist/jobs/schema.d.ts +0 -11
  137. package/dist/jobs/schema.js +1 -59
  138. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  139. package/dist/live/notices-module.js +30 -0
  140. package/dist/live/notices-sql.js +2 -1
  141. package/dist/mail/feedback/feedback-schema.js +3 -30
  142. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  143. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  144. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  145. package/dist/migration-record/check-record.d.ts +9 -7
  146. package/dist/migration-record/check-record.js +12 -11
  147. package/dist/migration-record/module-needs.js +30 -0
  148. package/dist/migration-record/read-record.js +27 -15
  149. package/dist/migration-record/record-model.d.ts +7 -2
  150. package/dist/migration-record/record-model.js +14 -6
  151. package/dist/migration-record/startup-decision.js +18 -7
  152. package/dist/migration-sql/additive-statements.d.ts +4 -0
  153. package/dist/migration-sql/additive-statements.js +105 -0
  154. package/dist/notifications/devices-module.js +61 -0
  155. package/dist/notifications/history-module.js +50 -0
  156. package/dist/notifications/notifications-targets.js +23 -0
  157. package/dist/notifications/read-table.js +16 -0
  158. package/dist/notifications/schema-sql.js +1 -22
  159. package/dist/notifications/schema.js +1 -101
  160. package/dist/notifications/table-names.js +40 -0
  161. package/dist/organization-scope/app-scope.js +38 -0
  162. package/dist/organization-scope/auth-request-organization.js +71 -0
  163. package/dist/organization-scope/organization-tables.js +20 -0
  164. package/dist/organization-scope/sign-in-organization.js +21 -0
  165. package/dist/package.js +1 -1
  166. package/dist/personal-mail/shared-sender-store.js +4 -2
  167. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  168. package/dist/relation-found.js +6 -0
  169. package/dist/relay/read-relay.js +85 -0
  170. package/dist/relay/realtime-members-sql.js +51 -28
  171. package/dist/relay/relay-module.js +53 -0
  172. package/dist/relay/relay-targets.js +28 -0
  173. package/dist/relay/session-end.js +1 -3
  174. package/dist/relay/sessions-sql.js +4 -27
  175. package/dist/rest/table-routes.js +9 -2
  176. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  177. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  178. package/dist/schema-modules/module-difference.d.ts +31 -0
  179. package/dist/schema-modules/module-difference.js +98 -0
  180. package/dist/schema-modules/modules-sql.js +13 -0
  181. package/dist/schema-modules/modules.d.ts +37 -0
  182. package/dist/schema-modules/modules.js +56 -0
  183. package/dist/schema-modules/needed-modules.d.ts +41 -0
  184. package/dist/schema-modules/needed-modules.js +61 -0
  185. package/dist/schema-modules/resource-difference.js +83 -0
  186. package/dist/schema-modules/schema-module.d.ts +112 -0
  187. package/dist/schema-modules/schema-module.js +8 -0
  188. package/dist/status/status-module.js +63 -0
  189. package/dist/status/status-targets.js +21 -0
  190. package/dist/types.d.ts +6 -1
  191. package/dist/user-tables/reloading-admin.d.ts +1 -0
  192. package/dist/user-tables/reloading-admin.js +1 -0
  193. package/dist/user-tables/schema-sql.js +1 -14
  194. package/dist/user-tables/schema.js +4 -27
  195. package/dist/user-tables/user-tables-module.js +38 -0
  196. package/dist/webhooks/table/delivery-log-module.js +36 -0
  197. package/dist/webhooks/table/owner-roles.js +3 -2
  198. package/dist/webhooks/table/schema-sql.js +27 -26
  199. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  200. package/dist/webhooks/table/webhooks-targets.js +26 -0
  201. package/dist/webhooks/webhooks.js +1 -1
  202. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  203. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  204. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  205. package/dist/workflows/read-catalogue.js +23 -0
  206. package/dist/workflows/schema-sql.js +12 -9
  207. package/dist/workflows/status-sql.js +12 -6
  208. package/dist/workflows/storage/storage-module.js +39 -0
  209. package/dist/workflows/storage/storage-sql.js +8 -5
  210. package/dist/workflows/workflows-schema-module.js +49 -0
  211. package/dist/workflows/workflows-tables-sql.js +32 -0
  212. package/dist/workflows/workflows-targets.js +16 -0
  213. package/package.json +6 -6
  214. package/dist/assistant/query-runner/runner-plan.js +0 -30
  215. package/dist/better-auth/store/migrations-table.js +0 -27
  216. package/dist/better-auth/store/modules-off.js +0 -17
  217. package/dist/calls/calls-sql.d.ts +0 -11
  218. package/dist/changes/capture-plan.js +0 -79
  219. package/dist/channels/sends-schema.d.ts +0 -7
  220. package/dist/channels/sends-schema.js +0 -18
  221. package/dist/comments/comments-sql.d.ts +0 -14
  222. package/dist/computed/buckets-plan.d.ts +0 -2
  223. package/dist/computed/buckets-plan.js +0 -88
  224. package/dist/computed/buckets-schema.js +0 -39
  225. package/dist/computed/computed-plan.js +0 -81
  226. package/dist/computed/computed-schema.d.ts +0 -16
  227. package/dist/computed/computed-schema.js +0 -63
  228. package/dist/derived/derived-sql.d.ts +0 -12
  229. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  230. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  231. package/dist/notifications/schema.d.ts +0 -14
  232. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  233. package/dist/realtime/relay/relay-schema.js +0 -20
  234. package/dist/relay/realtime-members-schema.js +0 -67
  235. package/dist/relay/relay-schema.d.ts +0 -14
  236. package/dist/relay/relay-schema.js +0 -28
  237. package/dist/status/schema.d.ts +0 -12
  238. package/dist/status/schema.js +0 -33
  239. package/dist/user-tables/schema.d.ts +0 -11
  240. package/dist/webhooks/table/schema.d.ts +0 -16
  241. package/dist/webhooks/table/schema.js +0 -56
  242. package/dist/workflows/schema.d.ts +0 -13
  243. package/dist/workflows/schema.js +0 -88
@@ -2,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 };
@@ -0,0 +1,65 @@
1
+ import { quoteIdent } from "../changes/capture-sql.js";
2
+ import { columnType } from "./column-sql.js";
3
+ import { bucketModels, bucketsTarget, hasBuckets } from "./buckets-targets.js";
4
+ import { formulaFields, formulaSql } from "./formula-sql.js";
5
+ import { rollupTargets } from "./rollup-targets.js";
6
+ //#region src/computed/computed-input.ts
7
+ /** Whether a resource has rollup or formula fields. */
8
+ const hasComputed = (model) => Object.values(model.fields).some((field) => field.rollup || field.formula !== void 0);
9
+ /** Whether the computed module serves a resource: it has rollups or formulas, or is a time rollup. */
10
+ const computedOn = (model) => hasComputed(model) || hasBuckets(model);
11
+ /** A table as SQL names it to Protobase's own functions: qualified, in `public` when the resource names no schema. */
12
+ const qualifiedTable = (table) => `${quoteIdent(table.schema ?? "public")}.${quoteIdent(table.name)}`;
13
+ const tableOf = ({ table }) => ({
14
+ ...table.schema !== void 0 && { schema: table.schema },
15
+ name: table.name
16
+ });
17
+ const modelTable = (model) => qualifiedTable(model.table);
18
+ const fieldKey = (model, field) => `${model.name}.${field.name}`;
19
+ const columnInput = (model, field, input) => ({
20
+ table: tableOf(model),
21
+ column: field.column,
22
+ input
23
+ });
24
+ /**
25
+ * What the computed module takes from the app's resources, by resource replaceable: each rollup's column and the
26
+ * function and trigger that keep it, each formula's column, and each time rollup's table and refresh function. A table
27
+ * the resource names without a schema is in `public`. Refuses a rollup whose resource, relation or field is not there.
28
+ */
29
+ const computedInput = (models) => {
30
+ const rollups = rollupTargets(models, modelTable);
31
+ const formulas = models.flatMap((model) => Object.values(model.fields).filter((field) => field.formula !== void 0).map((field) => ({
32
+ model,
33
+ field
34
+ })));
35
+ const readFormula = ({ from, field }) => {
36
+ const read = field.rollup.field === void 0 ? void 0 : from.fields[field.rollup.field];
37
+ return read?.formula === void 0 ? void 0 : formulaSql(from, read);
38
+ };
39
+ const readRollups = (model, field) => Object.values(model.fields).filter((other) => other.rollup && formulaFields(field.formula).has(other.name)).map((other) => `${quoteIdent(other.column)} ${columnType(other)}`);
40
+ return {
41
+ names: {},
42
+ resources: {
43
+ rollup_columns: Object.fromEntries(rollups.map((target) => [fieldKey(target.model, target.field), columnInput(target.model, target.field, target)])),
44
+ formulas: Object.fromEntries(formulas.map(({ model, field }) => [fieldKey(model, field), columnInput(model, field, {
45
+ table: modelTable(model),
46
+ model,
47
+ field,
48
+ readsRollups: readRollups(model, field)
49
+ })])),
50
+ rollups: Object.fromEntries(rollups.map((target) => {
51
+ const formula = readFormula(target);
52
+ return [fieldKey(target.model, target.field), columnInput(target.model, target.field, {
53
+ ...target,
54
+ ...formula !== void 0 && { readsFormula: formula }
55
+ })];
56
+ })),
57
+ time_rollups: Object.fromEntries(bucketModels(models).map(({ model, from }) => [model.name, {
58
+ table: tableOf(model),
59
+ input: bucketsTarget(model, from, modelTable)
60
+ }]))
61
+ }
62
+ };
63
+ };
64
+ //#endregion
65
+ export { computedInput, computedOn, hasComputed, qualifiedTable };
@@ -0,0 +1,102 @@
1
+ import { quoteIdent } from "../changes/capture-sql.js";
2
+ import { columnType } from "./column-sql.js";
3
+ import { addRollupColumnSql, backfillSql, dropRollupSql, rollupFunctionSql, rollupTriggerSql, rollupsSchema } from "./rollup-sql.js";
4
+ import { bucketsFillSql, createBucketsSql, dropBucketsTableSql } from "./buckets-sql.js";
5
+ import { addFormulaSql } from "./formula-sql.js";
6
+ import { qualifiedTable } from "./computed-input.js";
7
+ import { readComputed } from "./read-computed.js";
8
+ //#region src/computed/computed-module.ts
9
+ const statements = (list) => list.map((statement) => `${statement};`).join("\n");
10
+ const dropColumn = (table, column) => `-- Any index on the column goes with it, and has to be created again.\nalter table ${qualifiedTable(table)} drop column ${quoteIdent(column)};`;
11
+ /** Each rollup's column, which its function keeps; its rows are empty until the rollup's values are set. */
12
+ const rollupColumns = {
13
+ name: "rollup_columns",
14
+ title: "The column of a rollup field",
15
+ version: 1,
16
+ compatibleFrom: 1,
17
+ sql: (_names, input) => statements([addRollupColumnSql(input)]),
18
+ replace: (_names, table, column) => dropColumn(table, column),
19
+ keptWhileOthers: false
20
+ };
21
+ /**
22
+ * Each formula's generated column, marked with its expression. Its statements name the rollup columns it reads, so a
23
+ * rollup column made again takes the formula with it: dropped before it, the last replaceable's removals first, and
24
+ * added after it.
25
+ */
26
+ const formulas = {
27
+ name: "formulas",
28
+ title: "The generated column of a formula field",
29
+ version: 1,
30
+ compatibleFrom: 1,
31
+ sql: (_names, input) => {
32
+ const { table, model, field, readsRollups } = input;
33
+ return `${readsRollups.length === 0 ? "" : `-- It reads the rollup columns ${readsRollups.join(", ")}.\n`}${statements(addFormulaSql(table, model, field))}`;
34
+ },
35
+ replace: (_names, table, column) => dropColumn(table, column),
36
+ keptWhileOthers: false
37
+ };
38
+ const keeps = (target) => `-- It keeps ${target.table}.${quoteIdent(target.field.column)}, ${columnType(target.field)}${target.readsFormula === void 0 ? "" : `, from the formula ${target.readsFormula}`}.`;
39
+ /**
40
+ * The function and trigger that keep each rollup, made again by dropping the function, which takes its trigger with
41
+ * it, and gone with the rollup; its values are set from the records once the transaction commits.
42
+ */
43
+ const rollups = {
44
+ name: "rollups",
45
+ title: "The function and trigger that keep a rollup",
46
+ version: 1,
47
+ compatibleFrom: 1,
48
+ sql: (_names, input) => {
49
+ const target = input;
50
+ return `${keeps(target)}\n${statements([rollupFunctionSql(target), rollupTriggerSql(target)])}`;
51
+ },
52
+ replace: (_names, table, column) => `${dropRollupSql(table, column)};`,
53
+ drop: (_names, table, column) => `${dropRollupSql(table, column)};`,
54
+ after: (_names, input) => statements([backfillSql(input)]),
55
+ keptWhileOthers: false
56
+ };
57
+ /**
58
+ * Each time rollup's table, its indexes and refresh function, made again by dropping the table; filled once the
59
+ * transaction commits.
60
+ */
61
+ const timeRollups = {
62
+ name: "time_rollups",
63
+ title: "The table and refresh function of a time rollup",
64
+ version: 1,
65
+ compatibleFrom: 1,
66
+ sql: (_names, input) => statements(createBucketsSql(input)),
67
+ replace: (_names, table) => `${dropBucketsTableSql(qualifiedTable(table))};`,
68
+ after: (_names, input) => statements([bucketsFillSql(input)]),
69
+ keptWhileOthers: false
70
+ };
71
+ /**
72
+ * The rollup and formula fields' columns, the functions and triggers that keep the rollups, and the time rollups'
73
+ * tables and refresh functions, per resource. A column, table or refresh function the config no longer has stays, for
74
+ * a migration of the project's own to drop a deploy after the one that stops reading it; a rollup's function and
75
+ * trigger go with it.
76
+ */
77
+ const computedModule = {
78
+ label: "the rollups and formulas",
79
+ title: "The columns of the resources' rollup and formula fields, the triggers that keep the rollups, and the tables and refresh functions of their time rollups",
80
+ steps: [{
81
+ step: 1,
82
+ name: "rollups",
83
+ title: "The schema of the functions that keep rollups and refresh time rollups",
84
+ additive: true,
85
+ sql: () => `create schema if not exists ${quoteIdent(rollupsSchema)};`
86
+ }],
87
+ replaceables: [],
88
+ resourceReplaceables: [
89
+ rollupColumns,
90
+ formulas,
91
+ rollups,
92
+ timeRollups
93
+ ],
94
+ read: (db, input) => readComputed(db, input, [
95
+ rollupColumns,
96
+ formulas,
97
+ rollups,
98
+ timeRollups
99
+ ])
100
+ };
101
+ //#endregion
102
+ export { computedModule };
@@ -10,6 +10,19 @@ const expressionSql = (node, model) => {
10
10
  if (node.kind === "coalesce") return `coalesce(${node.args.map((arg) => expressionSql(arg, model)).join(", ")})`;
11
11
  return `round(${expressionSql(node.value, model)}${node.digits === void 0 ? "" : `, ${node.digits}`})`;
12
12
  };
13
+ /** The fields a formula reads, by name. */
14
+ const formulaFields = (formula) => {
15
+ const names = /* @__PURE__ */ new Set();
16
+ const visit = (node) => {
17
+ if (node.kind === "field") names.add(node.name);
18
+ if (node.kind === "negate") visit(node.operand);
19
+ if (node.kind === "binary") [node.left, node.right].forEach(visit);
20
+ if (node.kind === "coalesce") node.args.forEach(visit);
21
+ if (node.kind === "round") visit(node.value);
22
+ };
23
+ visit(parseFormula(formula));
24
+ return names;
25
+ };
13
26
  /** A formula field's generation expression, cast to its column's type. */
14
27
  const formulaSql = (model, field) => `(${expressionSql(parseFormula(field.formula), model)})::${columnType(field)}`;
15
28
  /** The comment that marks a formula's column as Protobase's, with the expression it was generated from. */
@@ -19,4 +32,4 @@ const isFormulaComment = (comment) => comment?.startsWith("protobase formula: ")
19
32
  /** The statements that add a formula's generated column to `table` and mark it. */
20
33
  const addFormulaSql = (table, model, field) => [`alter table ${table} add column ${quoteIdent(field.column)} ${columnType(field)} generated always as (${formulaSql(model, field)}) stored`, `comment on column ${table}.${quoteIdent(field.column)} is '${formulaComment(model, field).replaceAll("'", "''")}'`];
21
34
  //#endregion
22
- export { addFormulaSql, formulaComment, formulaSql, isFormulaComment };
35
+ export { addFormulaSql, formulaComment, formulaFields, formulaSql, isFormulaComment };
@@ -0,0 +1,100 @@
1
+ import { quoteIdent } from "../changes/capture-sql.js";
2
+ import { columnType } from "./column-sql.js";
3
+ import { rollupBody, rollupFunctionName, rollupTriggerName, rollupsSchema } from "./rollup-sql.js";
4
+ import { bucketsBody, bucketsComment, bucketsFunctionName } from "./buckets-sql.js";
5
+ import { formulaComment, isFormulaComment } from "./formula-sql.js";
6
+ import { qualifiedTable } from "./computed-input.js";
7
+ import { resourceEntry } from "../schema-modules/resource-difference.js";
8
+ import { sql } from "kysely";
9
+ //#region src/computed/read-computed.ts
10
+ const rowsOf = async (db, query) => (await query.execute(db)).rows;
11
+ const placeKey = (table, column) => JSON.stringify([table, column]);
12
+ const readTables = async (db, tables) => rowsOf(db, sql`select t.name as "table", format('%I.%I', n.nspname, c.relname) as catalogue, obj_description(c.oid, 'pg_class') as comment
13
+ from unnest(${tables}::text[]) as t(name) join pg_class c on c.oid = to_regclass(t.name) join pg_namespace n on n.oid = c.relnamespace`);
14
+ const readColumns = async (db, places) => rowsOf(db, sql`select p.table, p.column, a.attgenerated <> '' as generated, format_type(a.atttypid, a.atttypmod) as type, col_description(a.attrelid, a.attnum) as comment
15
+ from unnest(${places.map(({ table }) => table)}::text[], ${places.map(({ column }) => column)}::text[]) as p("table", "column")
16
+ join pg_attribute a on a.attrelid = to_regclass(p.table) and a.attname = p.column
17
+ where a.attnum > 0 and not a.attisdropped`);
18
+ const readFunctions = async (db) => rowsOf(db, sql`select p.proname as name, p.prosrc as source, p.prosecdef as definer,
19
+ coalesce((select json_agg(json_build_object('table', format('%I.%I', ns.nspname, c.relname), 'name', t.tgname, 'enabled', t.tgenabled)) from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace ns on ns.oid = c.relnamespace where t.tgfoid = p.oid and not t.tgisinternal), '[]') as triggers
20
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${rollupsSchema}`);
21
+ const fieldName = ({ model, field }) => `${model.name}.${field.name}`;
22
+ /**
23
+ * The rollups and formulas as the database has them for `input`: step 1 once the rollups schema is there, and each
24
+ * resource's objects found, at the digest of its input when they are what this version or an earlier one made of it,
25
+ * else at none, so they are made again. Refuses a column or table of the project's own where the config declares one,
26
+ * and a rollup's column of another type. `undefined` when it has none of them.
27
+ */
28
+ const readComputed = async (db, input, replaceables) => {
29
+ const given = (name) => Object.entries(input.resources[name] ?? {});
30
+ const targets = [...given("rollups"), ...given("time_rollups")].map(([, { input: target }]) => target);
31
+ const tables = new Map((await readTables(db, [...new Set(targets.flatMap((target) => [target.table, target.fromTable]))])).map((found) => [found.table, found]));
32
+ const columnPlaces = [...given("rollup_columns"), ...given("formulas")].map(([, entry]) => ({
33
+ table: qualifiedTable(entry.table),
34
+ column: entry.column
35
+ }));
36
+ const columns = new Map((await readColumns(db, columnPlaces)).map((found) => [placeKey(found.table, found.column), found]));
37
+ const [schema] = await rowsOf(db, sql`select exists (select from pg_namespace where nspname = ${rollupsSchema}) as found`);
38
+ const functions = schema.found ? await readFunctions(db) : [];
39
+ const entries = {};
40
+ const record = (replaceable, key, given, current) => {
41
+ const entry = resourceEntry(replaceable, input.names, given);
42
+ entries[replaceable.name] = {
43
+ ...entries[replaceable.name],
44
+ [key]: current ? entry : {
45
+ ...entry,
46
+ digest: ""
47
+ }
48
+ };
49
+ };
50
+ const [rollupColumns, formulas, rollups, timeRollups] = replaceables;
51
+ for (const [key, entry] of given("rollup_columns")) {
52
+ const target = entry.input;
53
+ const found = columns.get(placeKey(qualifiedTable(entry.table), entry.column));
54
+ if (!found) continue;
55
+ const name = `${target.table}.${quoteIdent(entry.column)}`;
56
+ if (found.generated) throw new Error(`Column ${name} of rollup field "${fieldName(target)}" is a generated column; drop it in a migration, then write the rollup's with \`protobase migration\``);
57
+ if (found.type !== columnType(target.field)) throw new Error(`Column ${name} of rollup field "${fieldName(target)}" is ${found.type}, not ${columnType(target.field)} as the field declares; change one of them`);
58
+ record(rollupColumns, key, entry, true);
59
+ }
60
+ for (const [key, entry] of given("formulas")) {
61
+ const target = entry.input;
62
+ const found = columns.get(placeKey(qualifiedTable(entry.table), entry.column));
63
+ if (!found) continue;
64
+ const name = `${target.table}.${quoteIdent(entry.column)}`;
65
+ if (!found.generated) throw new Error(`Column ${name} of formula field "${fieldName(target)}" is a plain column; drop or rename it in a migration, then write the formula's with \`protobase migration\``);
66
+ if (!isFormulaComment(found.comment)) throw new Error(`Column ${name} of formula field "${fieldName(target)}" is a generated column of the project's own; drop it in a migration, or remove .formula()`);
67
+ record(formulas, key, entry, found.comment === formulaComment(target.model, target.field) && found.type === columnType(target.field));
68
+ }
69
+ const catalogued = (target) => ({
70
+ ...target,
71
+ table: tables.get(target.table)?.catalogue ?? target.table,
72
+ fromTable: tables.get(target.fromTable)?.catalogue ?? target.fromTable
73
+ });
74
+ for (const [key, entry] of given("rollups")) {
75
+ const target = entry.input;
76
+ const fn = functions.find((found) => found.name === rollupFunctionName(entry.table, entry.column));
77
+ if (!fn) continue;
78
+ const from = tables.get(target.fromTable)?.catalogue;
79
+ const body = fn.source === rollupBody(target) || fn.source === rollupBody(catalogued(target));
80
+ const [trigger] = fn.triggers;
81
+ const triggered = fn.triggers.length === 1 && trigger.name === rollupTriggerName(target) && trigger.table === from && ["O", "A"].includes(trigger.enabled);
82
+ record(rollups, key, entry, fn.definer && body && triggered);
83
+ }
84
+ for (const [key, entry] of given("time_rollups")) {
85
+ const target = entry.input;
86
+ const found = tables.get(target.table);
87
+ if (!found) continue;
88
+ if (!found.comment?.startsWith("protobase time rollup: ")) throw new Error(`Table ${target.table} of time rollup "${target.model.name}" is a table of the project's own; drop or rename it in a migration, or name another table`);
89
+ const fn = functions.find((candidate) => candidate.name === bucketsFunctionName(target));
90
+ record(timeRollups, key, entry, found.comment === bucketsComment(target) && fn?.source === bucketsBody(target));
91
+ }
92
+ if (!schema.found && Object.keys(entries).length === 0) return;
93
+ return {
94
+ lastStep: schema.found ? 1 : 0,
95
+ replaceables: {},
96
+ ...Object.keys(entries).length > 0 && { resources: entries }
97
+ };
98
+ };
99
+ //#endregion
100
+ export { readComputed };
@@ -3,15 +3,18 @@ import { columnType } from "./column-sql.js";
3
3
  //#region src/computed/rollup-sql.ts
4
4
  /** The schema of the functions that keep rollups. */
5
5
  const rollupsSchema = "rollups";
6
- /** The function that keeps one rollup, named for its resource's table and column. */
7
- const rollupFunctionName = ({ model, field }) => identifier([
8
- model.table.schema,
9
- model.table.name,
10
- field.column
6
+ /** The function that keeps one rollup, named for its resource's table, as the resource names it, and column. */
7
+ const rollupFunctionName = (table, column) => identifier([
8
+ table.schema,
9
+ table.name,
10
+ column
11
11
  ].filter(Boolean).join("_"));
12
+ const targetFunctionName = ({ model, field }) => rollupFunctionName(model.table, field.column);
12
13
  /** The trigger on `from`'s table that calls it. */
13
- const rollupTriggerName = (target) => identifier(`${rollupFunctionName(target)}_rollup`);
14
- const functionSql = (target) => `${quoteIdent(rollupsSchema)}.${quoteIdent(rollupFunctionName(target))}`;
14
+ const rollupTriggerName = (target) => identifier(`${targetFunctionName(target)}_rollup`);
15
+ /** The function that keeps the rollup of `table`'s `column`, qualified. */
16
+ const rollupFunctionSqlName = (table, column) => `${quoteIdent(rollupsSchema)}.${quoteIdent(rollupFunctionName(table, column))}`;
17
+ const functionSql = (target) => rollupFunctionSqlName(target.model.table, target.field.column);
15
18
  const viaColumn = ({ from, field }) => quoteIdent(from.fields[field.rollup.via].column);
16
19
  const keyColumn = ({ model }) => quoteIdent(model.fields[model.primaryKey[0]].column);
17
20
  const aggregateSql = ({ from, field }) => {
@@ -54,11 +57,11 @@ const readColumns = ({ from, field }) => [
54
57
  ].filter((name) => name !== void 0).map((name) => quoteIdent(from.fields[name].column));
55
58
  /** A rollup's trigger: after inserts, deletes and updates of the columns it reads, for each row. */
56
59
  const rollupTriggerSql = (target) => `create trigger ${quoteIdent(rollupTriggerName(target))} after insert or delete or update of ${readColumns(target).join(", ")} on ${target.fromTable} for each row execute function ${functionSql(target)}()`;
57
- const dropRollupTriggerSql = (name, table) => `drop trigger if exists ${quoteIdent(name)} on ${table}`;
58
- const dropRollupFunctionSql = (name) => `drop function if exists ${quoteIdent(rollupsSchema)}.${quoteIdent(name)}() cascade`;
60
+ /** Drops the function that keeps the rollup of `table`'s `column`, and with it the trigger that calls it. */
61
+ const dropRollupSql = (table, column) => `drop function if exists ${rollupFunctionSqlName(table, column)}() cascade`;
59
62
  /** Sets every record's rollup from what `from` has now. */
60
63
  const backfillSql = (target) => refreshSql(target, "true");
61
64
  /** The statement that adds the rollup's column, empty until the backfill sets it. */
62
65
  const addRollupColumnSql = ({ table, field }) => `alter table ${table} add column ${quoteIdent(field.column)} ${columnType(field)}`;
63
66
  //#endregion
64
- export { addRollupColumnSql, backfillSql, dropRollupFunctionSql, dropRollupTriggerSql, rollupBody, rollupFunctionName, rollupFunctionSql, rollupTriggerName, rollupTriggerSql, rollupsSchema };
67
+ export { addRollupColumnSql, backfillSql, dropRollupSql, rollupBody, rollupFunctionName, rollupFunctionSql, rollupFunctionSqlName, rollupTriggerName, rollupTriggerSql, rollupsSchema };
@@ -1,3 +1,5 @@
1
+ import { webhooksModule } from "./webhooks/table/webhooks-module.js";
2
+ import { workflowsModule } from "./workflows/workflows-module.js";
1
3
  import { ownedTableNames } from "./user-tables/owned-definitions.js";
2
4
  import { definitionsSchema, userTablesSchema } from "./user-tables/names.js";
3
5
  import { CheckedDefinition } from "./user-tables/check-definition.js";
@@ -5,6 +7,4 @@ import { maxTextLength } from "./user-tables/definition-resource.js";
5
7
  import { userTableResources } from "./user-tables/user-table-resources.js";
6
8
  import { configExports } from "./resource-source.js";
7
9
  import { builtInResources } from "./built-in-resources.js";
8
- import { webhooksModule } from "./webhooks/table/webhooks-module.js";
9
- import { workflowsModule } from "./workflows/workflows-module.js";
10
10
  export { type CheckedDefinition, builtInResources, configExports, definitionsSchema, maxTextLength, ownedTableNames, userTableResources, userTablesSchema, webhooksModule, workflowsModule };