nowity 1.0.0 → 1.1.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 (50) hide show
  1. package/README.md +23 -5
  2. package/dist/client/confirmed-store.d.ts.map +1 -1
  3. package/dist/client/confirmed-store.js +4 -1
  4. package/dist/client/connection.d.ts.map +1 -1
  5. package/dist/client/connection.js +1 -2
  6. package/dist/client/nowity-client.d.ts +16 -3
  7. package/dist/client/nowity-client.d.ts.map +1 -1
  8. package/dist/client/nowity-client.js +54 -28
  9. package/dist/core/diff.d.ts.map +1 -1
  10. package/dist/core/diff.js +5 -4
  11. package/dist/core/normalize.d.ts.map +1 -1
  12. package/dist/core/normalize.js +6 -0
  13. package/dist/core/protocol.d.ts +10 -0
  14. package/dist/core/protocol.d.ts.map +1 -1
  15. package/dist/core/types.d.ts +2 -0
  16. package/dist/core/types.d.ts.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/server/api/bridge.js +11 -3
  21. package/dist/server/api/collector.js +2 -3
  22. package/dist/server/api/configure.d.ts +0 -5
  23. package/dist/server/api/configure.d.ts.map +1 -1
  24. package/dist/server/api/configure.js +0 -1
  25. package/dist/server/api/prerender.js +1 -2
  26. package/dist/server/api/runtime.d.ts +8 -0
  27. package/dist/server/api/runtime.d.ts.map +1 -1
  28. package/dist/server/api/runtime.js +2 -0
  29. package/dist/server/change-source/outbox-change-source.js +5 -5
  30. package/dist/server/change-source/wal-change-source.js +1 -1
  31. package/dist/server/evaluate.d.ts +11 -1
  32. package/dist/server/evaluate.d.ts.map +1 -1
  33. package/dist/server/evaluate.js +15 -4
  34. package/dist/server/mutator.d.ts +2 -1
  35. package/dist/server/mutator.d.ts.map +1 -1
  36. package/dist/server/query.d.ts +7 -0
  37. package/dist/server/query.d.ts.map +1 -1
  38. package/dist/server/setup-sql.d.ts +10 -0
  39. package/dist/server/setup-sql.d.ts.map +1 -0
  40. package/dist/server/{sql/setup.sql → setup-sql.js} +82 -36
  41. package/dist/server/setup.d.ts +1 -2
  42. package/dist/server/setup.d.ts.map +1 -1
  43. package/dist/server/setup.js +5 -53
  44. package/dist/server/ssr.js +1 -1
  45. package/dist/server/sync-engine.d.ts +2 -0
  46. package/dist/server/sync-engine.d.ts.map +1 -1
  47. package/dist/server/sync-engine.js +12 -12
  48. package/dist/server/ws-server.d.ts.map +1 -1
  49. package/dist/server/ws-server.js +25 -15
  50. package/package.json +2 -2
@@ -16,6 +16,7 @@ exports.createNowityRuntime = createNowityRuntime;
16
16
  */
17
17
  const ironbean_1 = require("ironbean");
18
18
  const contract_1 = require("../../api/contract");
19
+ const auth_1 = require("./auth");
19
20
  const db_1 = require("../db");
20
21
  const bridge_1 = require("./bridge");
21
22
  const execution_1 = require("./execution");
@@ -26,6 +27,7 @@ function createNowityRuntime(config) {
26
27
  const prisma = (0, tracked_client_1.trackReads)(config.prisma, tracker);
27
28
  if (config.db)
28
29
  (0, ironbean_1.take)(config.db).setFactory(() => (0, execution_1.ambientPrisma)());
30
+ (0, ironbean_1.take)(auth_1.Authenticator).bindTo((config.auth ?? auth_1.AnonymousAuthenticator));
29
31
  const contracts = (0, contract_1.resolveContracts)();
30
32
  for (const service of config.services ?? []) {
31
33
  if (!(0, contract_1.contractOf)(service)) {
@@ -97,7 +97,7 @@ class OutboxChangeSource {
97
97
  // A clean shutdown gives its watermark back immediately, rather than
98
98
  // holding retention until it ages out.
99
99
  await this.pool
100
- .query(`SELECT nowity_consumer_forget($1)`, [this.consumerId])
100
+ .query(`SELECT nowity.nowity_consumer_forget($1)`, [this.consumerId])
101
101
  .catch(() => undefined);
102
102
  this.publishedCursor = null;
103
103
  if (this.listener) {
@@ -168,7 +168,7 @@ class OutboxChangeSource {
168
168
  async publishCursor() {
169
169
  if (this.publishedCursor === this.cursor)
170
170
  return;
171
- await this.pool.query(`SELECT nowity_consumer_seen($1, $2)`, [
171
+ await this.pool.query(`SELECT nowity.nowity_consumer_seen($1, $2)`, [
172
172
  this.consumerId,
173
173
  this.cursor.toString(),
174
174
  ]);
@@ -182,14 +182,14 @@ class OutboxChangeSource {
182
182
  * rather than each other's.
183
183
  */
184
184
  async prune() {
185
- const { rows } = await this.pool.query(`SELECT nowity_prune_outbox($1::interval) AS deleted`, [
185
+ const { rows } = await this.pool.query(`SELECT nowity.nowity_prune_outbox($1::interval) AS deleted`, [
186
186
  this.pruneStaleAfter,
187
187
  ]);
188
188
  return Number(rows[0]?.deleted ?? 0);
189
189
  }
190
190
  async fetch() {
191
191
  const { rows } = (await this.pool.query(`SELECT ${SELECT_COLUMNS}
192
- FROM nowity_outbox
192
+ FROM nowity.nowity_outbox
193
193
  WHERE xid > $1::xid8
194
194
  AND xid < pg_snapshot_xmin(pg_current_snapshot())
195
195
  ORDER BY xid, seq
@@ -204,7 +204,7 @@ class OutboxChangeSource {
204
204
  return trimmed;
205
205
  // A single transaction larger than the batch size: fetch it whole.
206
206
  const { rows: whole } = (await this.pool.query(`SELECT ${SELECT_COLUMNS}
207
- FROM nowity_outbox
207
+ FROM nowity.nowity_outbox
208
208
  WHERE xid = $1::xid8
209
209
  ORDER BY seq`, [lastXid]));
210
210
  return whole;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WalChangeSource = void 0;
4
4
  const pg_logical_replication_1 = require("pg-logical-replication");
5
5
  const normalize_1 = require("../../core/normalize");
6
- const ALWAYS_EXCLUDED = ["nowity_outbox", "nowity_scope_epoch", "nowity_client"];
6
+ const ALWAYS_EXCLUDED = ["nowity_outbox", "nowity_scope_epoch", "nowity_consumer", "nowity_client"];
7
7
  /**
8
8
  * Change source built on PostgreSQL logical replication + wal2json.
9
9
  *
@@ -15,6 +15,10 @@ export interface QueryOutput {
15
15
  keys?: ReadKeySet;
16
16
  /** Entity of the primary rows, when the execution derived it. */
17
17
  entity?: string;
18
+ /** Field the primary rows are keyed by. */
19
+ idField: string;
20
+ /** Fields the `extra` rows are keyed by, per entity, where not `id`. */
21
+ extraIdFields: Record<string, string>;
18
22
  /** The query returned one row rather than a list. */
19
23
  single?: boolean;
20
24
  /** How the rows are ordered, when the execution could tell. */
@@ -31,9 +35,15 @@ export declare function emptyOutput(): QueryOutput;
31
35
  * the two can never disagree about what a query returns.
32
36
  */
33
37
  export declare function evaluateQuery(def: QueryDef, args: unknown, session: SessionInfo, snap: SnapshotContext): Promise<QueryOutput>;
34
- /** Rows of an output as plain arrays, ready to be serialised. */
38
+ /**
39
+ * Rows of an output as plain arrays, ready to be serialised — with the fields
40
+ * they are keyed by, so the browser files them under the same ids the server
41
+ * diffs them by instead of guessing from the entity name.
42
+ */
35
43
  export declare function outputRows(output: QueryOutput): {
36
44
  rows: Row[];
37
45
  extra?: Record<string, Row[]>;
46
+ idField?: string;
47
+ extraIdFields?: Record<string, string>;
38
48
  };
39
49
  //# sourceMappingURL=evaluate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"evaluate.d.ts","sourceRoot":"","sources":["../../src/server/evaluate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAC5C,OAAO,EAAiB,KAAK,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,SAAS,CAAC;AAEzE,6EAA6E;AAC7E,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC1B,uEAAuE;IACvE,GAAG,EAAE,QAAQ,EAAE,CAAC;IAChB,iDAAiD;IACjD,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;IACvC,mEAAmE;IACnE,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KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;IACvC,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,wEAAwE;IACxE,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,OAAO,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qDAAqD;IACrD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,+DAA+D;IAC/D,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;IACnB,qEAAqE;IACrE,MAAM,CAAC,EAAE,SAAS,CAAC;CACtB;AAED,wBAAgB,WAAW,IAAI,WAAW,CAEzC;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAC/B,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,WAAW,EACpB,IAAI,EAAE,eAAe,GACtB,OAAO,CAAC,WAAW,CAAC,CAuCtB;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG;IAC7C,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC1C,CAWA"}
@@ -6,7 +6,7 @@ exports.outputRows = outputRows;
6
6
  const normalize_1 = require("../core/normalize");
7
7
  const query_1 = require("./query");
8
8
  function emptyOutput() {
9
- return { index: new Map(), ids: [], extra: new Map() };
9
+ return { index: new Map(), ids: [], extra: new Map(), idField: "id", extraIdFields: {} };
10
10
  }
11
11
  /**
12
12
  * Run a query definition against one read snapshot and normalise its result.
@@ -17,7 +17,8 @@ function emptyOutput() {
17
17
  */
18
18
  async function evaluateQuery(def, args, session, snap) {
19
19
  const result = (0, query_1.toQueryResult)(await def.run(args, { db: snap, session }));
20
- const idField = def.idField ?? "id";
20
+ const idField = result.idField ?? def.idField ?? "id";
21
+ const extraIdFields = {};
21
22
  const ids = [];
22
23
  const index = new Map();
23
24
  for (const raw of result.rows) {
@@ -28,7 +29,9 @@ async function evaluateQuery(def, args, session, snap) {
28
29
  }
29
30
  const extra = new Map();
30
31
  for (const [entity, rows] of Object.entries(result.extra ?? {})) {
31
- const field = def.extraIdFields?.[entity] ?? "id";
32
+ const field = result.extraIdFields?.[entity] ?? def.extraIdFields?.[entity] ?? "id";
33
+ if (field !== "id")
34
+ extraIdFields[entity] = field;
32
35
  const map = new Map();
33
36
  for (const raw of rows) {
34
37
  const row = (0, normalize_1.normalizeRow)(raw);
@@ -40,6 +43,8 @@ async function evaluateQuery(def, args, session, snap) {
40
43
  index,
41
44
  ids,
42
45
  extra,
46
+ idField,
47
+ extraIdFields,
43
48
  ...(result.tables ? { tables: result.tables } : {}),
44
49
  ...(result.keys ? { keys: result.keys } : {}),
45
50
  ...(result.entity ? { entity: result.entity } : {}),
@@ -48,7 +53,11 @@ async function evaluateQuery(def, args, session, snap) {
48
53
  ...(result.filter ? { filter: result.filter } : {}),
49
54
  };
50
55
  }
51
- /** Rows of an output as plain arrays, ready to be serialised. */
56
+ /**
57
+ * Rows of an output as plain arrays, ready to be serialised — with the fields
58
+ * they are keyed by, so the browser files them under the same ids the server
59
+ * diffs them by instead of guessing from the entity name.
60
+ */
52
61
  function outputRows(output) {
53
62
  const extra = {};
54
63
  for (const [entity, map] of output.extra) {
@@ -57,5 +66,7 @@ function outputRows(output) {
57
66
  return {
58
67
  rows: output.ids.map((id) => output.index.get(id)),
59
68
  ...(Object.keys(extra).length ? { extra } : {}),
69
+ ...(output.idField !== "id" ? { idField: output.idField } : {}),
70
+ ...(Object.keys(output.extraIdFields).length ? { extraIdFields: output.extraIdFields } : {}),
60
71
  };
61
72
  }
@@ -44,7 +44,8 @@ export interface MutatorContext {
44
44
  */
45
45
  export interface MutatorDef<A = any> {
46
46
  name: string;
47
- server(args: A, ctx: MutatorContext): Promise<void>;
47
+ /** What it resolves with is handed back to the caller, as JSON. */
48
+ server(args: A, ctx: MutatorContext): Promise<unknown>;
48
49
  }
49
50
  /** Thrown by a mutator to reject the write with a message meant for the user. */
50
51
  export declare class MutationRejected extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"mutator.d.ts","sourceRoot":"","sources":["../../src/server/mutator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAC3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE3C,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC3C,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,WAAW;IACxB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACjE;AAED,qBAAa,aAAc,YAAW,WAAW;IACjC,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,IAAI;IAEjC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAkBtE;AAED,qBAAa,iBAAkB,YAAW,WAAW;IAE7C,OAAO,CAAC,QAAQ,CAAC,MAAM;IAGvB,OAAO,CAAC,QAAQ,CAAC,SAAS;gBAHT,MAAM,EAAE;QACrB,YAAY,CAAC,CAAC,EAAE,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AC/B,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1D;AAED,iFAAiF;AACjF,qBAAa,gBAAiB,SAAQ,KAAK;gBAC3B,OAAO,EAAE,MAAM;CAI9B;AAED,qBAAa,eAAe;IACxB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAsC;IAE3D,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAQ5C,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC;IAMlC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;CAG7B"}
@@ -44,6 +44,13 @@ export interface QueryResult {
44
44
  * layer derives it from the Prisma model that produced them).
45
45
  */
46
46
  entity?: string;
47
+ /**
48
+ * Field carrying the identity of each primary row, when only the execution
49
+ * can tell (the Prisma model's primary key). Beats {@link QueryDef.idField}.
50
+ */
51
+ idField?: string;
52
+ /** The same for the `extra` entity sets, keyed by entity name. */
53
+ extraIdFields?: Record<string, string>;
47
54
  /** The endpoint returned a single row (or null), not a list. */
48
55
  single?: boolean;
49
56
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../src/server/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAE5C,+DAA+D;AAC/D,MAAM,WAAW,WAAW;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,MAAM,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Aa,aAAa;IACtB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAoC;IAEzD,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC;IAaxC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC;IAMhC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI1B,KAAK,IAAI,MAAM,EAAE;CAGpB;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,GAAG,GAAG,EAAE,GAAG,WAAW,CAEtE"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Nowity's schema: change capture, authorization epochs, mutation bookkeeping.
3
+ *
4
+ * A string in code rather than a `.sql` file beside it: a file has to be found
5
+ * at run time, and `__dirname` means something different — or nothing — once a
6
+ * bundler has been through the module. Idempotent, so it runs at every boot;
7
+ * paste it into a migration instead if the schema is managed that way.
8
+ */
9
+ export declare const NOWITY_SETUP_SQL = "-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.\n--\n-- Everything lives in its own schema, `nowity`. The application's schema is the\n-- application's: a Prisma `db push` compares `public` against schema.prisma and\n-- would offer to drop tables it did not declare.\n\nCREATE SCHEMA IF NOT EXISTS nowity;\n\n-- Up to 1.0 the tables and functions lived in `public`. Tables move with their\n-- data; the capture function moves too, because every tracked table's trigger\n-- points at it by oid \u2014 moving it keeps them firing, dropping it would take them\n-- all with it. The rest is recreated below, so the old copies just go.\nDO $$\nDECLARE\n v_table text;\nBEGIN\n FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP\n IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN\n EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);\n END IF;\n END LOOP;\n IF to_regprocedure('public.nowity_capture()') IS NOT NULL\n AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN\n ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;\n END IF;\nEND;\n$$;\n\nDROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);\nDROP FUNCTION IF EXISTS public.nowity_untrack(regclass);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);\nDROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);\n--\n-- Design notes (see \"Implementa\u010Dn\u00ED zad\u00E1n\u00ED\" \u00A75.1 in the design doc):\n--\n-- The outbox is filled by a trigger, not by application code. That way *any*\n-- writer \u2014 Prisma, a raw SQL migration, a psql session \u2014 produces change events,\n-- and the application never has to remember to publish them.\n--\n-- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what\n-- makes gap-free reading possible: a `bigserial` alone is not enough, because\n-- sequence values are handed out before commit, so a reader ordering by `seq`\n-- can walk past a row belonging to a transaction that commits later. Readers\n-- therefore only consume rows whose `xid` is below the oldest in-flight\n-- transaction id (see OutboxChangeSource).\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_outbox (\n seq bigserial PRIMARY KEY,\n xid xid8 NOT NULL DEFAULT pg_current_xact_id(),\n tbl text NOT NULL,\n op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),\n pk jsonb NOT NULL,\n before jsonb,\n after jsonb,\n client_id text,\n mutation_id bigint,\n created_at timestamptz NOT NULL DEFAULT clock_timestamp()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);\n\n-- Authorization epoch per scope (typically one project / tenant / workspace).\n-- Bumped whenever a row in a permission table changes; every snapshot and patch\n-- carries the epoch it was computed under.\n--\n-- `last_position` is what makes the bump happen once per *change* rather than\n-- once per reader. Several sync processes see the same transaction and each\n-- would otherwise increment this row, so one permission change would cost N\n-- writes to one very hot row \u2014 and an at-least-once replay would inflate it on a\n-- single process too.\nCREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (\n scope text PRIMARY KEY,\n version bigint NOT NULL DEFAULT 1,\n last_position text\n);\n\nALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;\n\n-- Where each sync process has read the outbox up to.\n--\n-- Only ever a retention watermark: a process that restarts resumes from the\n-- current transaction horizon, never from here, so a cursor left behind by a\n-- crashed node can hold rows back but can never make one skip a change.\nCREATE TABLE IF NOT EXISTS nowity.nowity_consumer (\n consumer_id text PRIMARY KEY,\n cursor_xid xid8 NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Last mutation of each client the server has durably processed. Written in the\n-- same transaction as the mutation itself, so it can never disagree with the\n-- data.\n--\n-- `session_token` is which connection currently owns the id. Two connections\n-- sharing one client id is a write-losing bug, and within a single process the\n-- engine can see both and complain \u2014 with several sync processes neither can see\n-- the other's sessions, and the collision is otherwise perfectly silent: both\n-- sides keep numbering from one, each takes the other's mutation for a replay of\n-- its own, and every second write is acknowledged and discarded. The token moves\n-- that argument into the one place both processes share.\nCREATE TABLE IF NOT EXISTS nowity.nowity_client (\n client_id text PRIMARY KEY,\n last_mutation_id bigint NOT NULL DEFAULT 0,\n session_token text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;\n\n-- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.\nCREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$\nDECLARE\n v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);\n v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;\n v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;\n v_source jsonb := COALESCE(v_after, v_before);\n v_pk jsonb;\nBEGIN\n SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk\n FROM unnest(v_pk_cols) AS col;\n\n INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)\n VALUES (\n TG_TABLE_NAME,\n lower(TG_OP),\n v_pk,\n v_before,\n v_after,\n NULLIF(current_setting('nowity.client_id', true), ''),\n NULLIF(current_setting('nowity.mutation_id', true), '')::bigint\n );\n\n -- Wake the sync engine up at commit. The payload is intentionally tiny; it\n -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).\n PERFORM pg_notify('nowity_change', TG_TABLE_NAME);\n\n RETURN NULL; -- AFTER trigger, return value is ignored\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Attach change capture to a table.\nCREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])\nRETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\n EXECUTE format(\n 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '\n 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',\n p_table, p_pk\n );\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- The single-argument form is gone: left in place it would be an overload of the\n-- one below, and `nowity.nowity_bump_epoch($1)` would stop resolving.\nDROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);\n\n-- Increment the authorization epoch of a scope and return the current value.\n--\n-- With a position, the increment happens only the first time that position is\n-- seen for the scope. Whichever process gets there first does the write and the\n-- rest read the same answer, because the `ON CONFLICT` takes a row lock and they\n-- queue behind it.\n--\n-- Skipping the increment on a replay is not a missed invalidation: the epoch had\n-- already moved when the position was first handled, and a process replaying it\n-- still recomputes its subscriptions and stamps them with the value it reads\n-- here.\nCREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)\nRETURNS bigint AS $$\nDECLARE\n v_version bigint;\nBEGIN\n INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)\n VALUES (p_scope, 1, p_position)\n ON CONFLICT (scope) DO UPDATE\n SET version = e.version\n + CASE\n WHEN p_position IS NULL THEN 1\n WHEN e.last_position IS DISTINCT FROM p_position THEN 1\n ELSE 0\n END,\n last_position = COALESCE(p_position, e.last_position)\n RETURNING version INTO v_version;\n RETURN v_version;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record how far a consumer has read, for retention only.\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)\nRETURNS void AS $$\nBEGIN\n INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)\n VALUES (p_consumer, p_cursor::xid8)\n ON CONFLICT (consumer_id) DO UPDATE\n SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$\nBEGIN\n DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Delete outbox rows every live consumer has already read.\n--\n-- \"Live\" is a wall-clock judgement, and it is the only unsafe part of retention:\n-- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows\n-- it had not reached may be deleted. It resumes from the transaction horizon\n-- rather than from its old cursor, so it does not read a hole \u2014 it simply never\n-- learns about those changes and its clients keep whatever they had until\n-- something else touches it. Set the interval well above any pause a healthy\n-- process can take.\n--\n-- With no live consumers at all this deletes nothing. An empty table means \"the\n-- readers have not registered yet\", not \"nobody will ever read this\".\nCREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')\nRETURNS bigint AS $$\nDECLARE\n v_min xid8;\n v_deleted bigint;\nBEGIN\n -- `ORDER BY \u2026 LIMIT 1` rather than `min()`: xid8 has the comparison\n -- operators but not the aggregate.\n SELECT cursor_xid INTO v_min\n FROM nowity.nowity_consumer\n WHERE updated_at > now() - p_stale_after\n ORDER BY cursor_xid\n LIMIT 1;\n\n IF v_min IS NULL THEN\n RETURN 0;\n END IF;\n\n DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;\n GET DIAGNOSTICS v_deleted = ROW_COUNT;\n RETURN v_deleted;\nEND;\n$$ LANGUAGE plpgsql;\n";
10
+ //# sourceMappingURL=setup-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,2pVAyP5B,CAAC"}
@@ -1,4 +1,49 @@
1
- -- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOWITY_SETUP_SQL = void 0;
4
+ /**
5
+ * Nowity's schema: change capture, authorization epochs, mutation bookkeeping.
6
+ *
7
+ * A string in code rather than a `.sql` file beside it: a file has to be found
8
+ * at run time, and `__dirname` means something different — or nothing — once a
9
+ * bundler has been through the module. Idempotent, so it runs at every boot;
10
+ * paste it into a migration instead if the schema is managed that way.
11
+ */
12
+ exports.NOWITY_SETUP_SQL = `-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.
13
+ --
14
+ -- Everything lives in its own schema, \`nowity\`. The application's schema is the
15
+ -- application's: a Prisma \`db push\` compares \`public\` against schema.prisma and
16
+ -- would offer to drop tables it did not declare.
17
+
18
+ CREATE SCHEMA IF NOT EXISTS nowity;
19
+
20
+ -- Up to 1.0 the tables and functions lived in \`public\`. Tables move with their
21
+ -- data; the capture function moves too, because every tracked table's trigger
22
+ -- points at it by oid — moving it keeps them firing, dropping it would take them
23
+ -- all with it. The rest is recreated below, so the old copies just go.
24
+ DO $$
25
+ DECLARE
26
+ v_table text;
27
+ BEGIN
28
+ FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP
29
+ IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN
30
+ EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);
31
+ END IF;
32
+ END LOOP;
33
+ IF to_regprocedure('public.nowity_capture()') IS NOT NULL
34
+ AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN
35
+ ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;
36
+ END IF;
37
+ END;
38
+ $$;
39
+
40
+ DROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);
41
+ DROP FUNCTION IF EXISTS public.nowity_untrack(regclass);
42
+ DROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);
43
+ DROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);
44
+ DROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);
45
+ DROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);
46
+ DROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);
2
47
  --
3
48
  -- Design notes (see "Implementační zadání" §5.1 in the design doc):
4
49
  --
@@ -6,14 +51,14 @@
6
51
  -- writer — Prisma, a raw SQL migration, a psql session — produces change events,
7
52
  -- and the application never has to remember to publish them.
8
53
  --
9
- -- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what
10
- -- makes gap-free reading possible: a `bigserial` alone is not enough, because
11
- -- sequence values are handed out before commit, so a reader ordering by `seq`
54
+ -- \`xid\` is the transaction id assigned by \`pg_current_xact_id()\`. It is what
55
+ -- makes gap-free reading possible: a \`bigserial\` alone is not enough, because
56
+ -- sequence values are handed out before commit, so a reader ordering by \`seq\`
12
57
  -- can walk past a row belonging to a transaction that commits later. Readers
13
- -- therefore only consume rows whose `xid` is below the oldest in-flight
58
+ -- therefore only consume rows whose \`xid\` is below the oldest in-flight
14
59
  -- transaction id (see OutboxChangeSource).
15
60
 
16
- CREATE TABLE IF NOT EXISTS nowity_outbox (
61
+ CREATE TABLE IF NOT EXISTS nowity.nowity_outbox (
17
62
  seq bigserial PRIMARY KEY,
18
63
  xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
19
64
  tbl text NOT NULL,
@@ -26,31 +71,31 @@ CREATE TABLE IF NOT EXISTS nowity_outbox (
26
71
  created_at timestamptz NOT NULL DEFAULT clock_timestamp()
27
72
  );
28
73
 
29
- CREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity_outbox (xid, seq);
74
+ CREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);
30
75
 
31
76
  -- Authorization epoch per scope (typically one project / tenant / workspace).
32
77
  -- Bumped whenever a row in a permission table changes; every snapshot and patch
33
78
  -- carries the epoch it was computed under.
34
79
  --
35
- -- `last_position` is what makes the bump happen once per *change* rather than
80
+ -- \`last_position\` is what makes the bump happen once per *change* rather than
36
81
  -- once per reader. Several sync processes see the same transaction and each
37
82
  -- would otherwise increment this row, so one permission change would cost N
38
83
  -- writes to one very hot row — and an at-least-once replay would inflate it on a
39
84
  -- single process too.
40
- CREATE TABLE IF NOT EXISTS nowity_scope_epoch (
85
+ CREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (
41
86
  scope text PRIMARY KEY,
42
87
  version bigint NOT NULL DEFAULT 1,
43
88
  last_position text
44
89
  );
45
90
 
46
- ALTER TABLE nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;
91
+ ALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;
47
92
 
48
93
  -- Where each sync process has read the outbox up to.
49
94
  --
50
95
  -- Only ever a retention watermark: a process that restarts resumes from the
51
96
  -- current transaction horizon, never from here, so a cursor left behind by a
52
97
  -- crashed node can hold rows back but can never make one skip a change.
53
- CREATE TABLE IF NOT EXISTS nowity_consumer (
98
+ CREATE TABLE IF NOT EXISTS nowity.nowity_consumer (
54
99
  consumer_id text PRIMARY KEY,
55
100
  cursor_xid xid8 NOT NULL,
56
101
  updated_at timestamptz NOT NULL DEFAULT now()
@@ -60,24 +105,24 @@ CREATE TABLE IF NOT EXISTS nowity_consumer (
60
105
  -- same transaction as the mutation itself, so it can never disagree with the
61
106
  -- data.
62
107
  --
63
- -- `session_token` is which connection currently owns the id. Two connections
108
+ -- \`session_token\` is which connection currently owns the id. Two connections
64
109
  -- sharing one client id is a write-losing bug, and within a single process the
65
110
  -- engine can see both and complain — with several sync processes neither can see
66
111
  -- the other's sessions, and the collision is otherwise perfectly silent: both
67
112
  -- sides keep numbering from one, each takes the other's mutation for a replay of
68
113
  -- its own, and every second write is acknowledged and discarded. The token moves
69
114
  -- that argument into the one place both processes share.
70
- CREATE TABLE IF NOT EXISTS nowity_client (
115
+ CREATE TABLE IF NOT EXISTS nowity.nowity_client (
71
116
  client_id text PRIMARY KEY,
72
117
  last_mutation_id bigint NOT NULL DEFAULT 0,
73
118
  session_token text,
74
119
  updated_at timestamptz NOT NULL DEFAULT now()
75
120
  );
76
121
 
77
- ALTER TABLE nowity_client ADD COLUMN IF NOT EXISTS session_token text;
122
+ ALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;
78
123
 
79
124
  -- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.
80
- CREATE OR REPLACE FUNCTION nowity_capture() RETURNS trigger AS $$
125
+ CREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$
81
126
  DECLARE
82
127
  v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);
83
128
  v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;
@@ -88,7 +133,7 @@ BEGIN
88
133
  SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk
89
134
  FROM unnest(v_pk_cols) AS col;
90
135
 
91
- INSERT INTO nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)
136
+ INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)
92
137
  VALUES (
93
138
  TG_TABLE_NAME,
94
139
  lower(TG_OP),
@@ -108,80 +153,80 @@ END;
108
153
  $$ LANGUAGE plpgsql;
109
154
 
110
155
  -- Attach change capture to a table.
111
- CREATE OR REPLACE FUNCTION nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])
156
+ CREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])
112
157
  RETURNS void AS $$
113
158
  BEGIN
114
159
  EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);
115
160
  EXECUTE format(
116
161
  'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '
117
- 'FOR EACH ROW EXECUTE FUNCTION nowity_capture(%L)',
162
+ 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',
118
163
  p_table, p_pk
119
164
  );
120
165
  END;
121
166
  $$ LANGUAGE plpgsql;
122
167
 
123
- CREATE OR REPLACE FUNCTION nowity_untrack(p_table regclass) RETURNS void AS $$
168
+ CREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$
124
169
  BEGIN
125
170
  EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);
126
171
  END;
127
172
  $$ LANGUAGE plpgsql;
128
173
 
129
174
  -- The single-argument form is gone: left in place it would be an overload of the
130
- -- one below, and `nowity_bump_epoch($1)` would stop resolving.
131
- DROP FUNCTION IF EXISTS nowity_bump_epoch(text);
175
+ -- one below, and \`nowity.nowity_bump_epoch($1)\` would stop resolving.
176
+ DROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);
132
177
 
133
178
  -- Increment the authorization epoch of a scope and return the current value.
134
179
  --
135
180
  -- With a position, the increment happens only the first time that position is
136
181
  -- seen for the scope. Whichever process gets there first does the write and the
137
- -- rest read the same answer, because the `ON CONFLICT` takes a row lock and they
182
+ -- rest read the same answer, because the \`ON CONFLICT\` takes a row lock and they
138
183
  -- queue behind it.
139
184
  --
140
185
  -- Skipping the increment on a replay is not a missed invalidation: the epoch had
141
186
  -- already moved when the position was first handled, and a process replaying it
142
187
  -- still recomputes its subscriptions and stamps them with the value it reads
143
188
  -- here.
144
- CREATE OR REPLACE FUNCTION nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)
189
+ CREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)
145
190
  RETURNS bigint AS $$
146
191
  DECLARE
147
192
  v_version bigint;
148
193
  BEGIN
149
- INSERT INTO nowity_scope_epoch (scope, version, last_position)
194
+ INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)
150
195
  VALUES (p_scope, 1, p_position)
151
196
  ON CONFLICT (scope) DO UPDATE
152
- SET version = nowity_scope_epoch.version
197
+ SET version = e.version
153
198
  + CASE
154
199
  WHEN p_position IS NULL THEN 1
155
- WHEN nowity_scope_epoch.last_position IS DISTINCT FROM p_position THEN 1
200
+ WHEN e.last_position IS DISTINCT FROM p_position THEN 1
156
201
  ELSE 0
157
202
  END,
158
- last_position = COALESCE(p_position, nowity_scope_epoch.last_position)
203
+ last_position = COALESCE(p_position, e.last_position)
159
204
  RETURNING version INTO v_version;
160
205
  RETURN v_version;
161
206
  END;
162
207
  $$ LANGUAGE plpgsql;
163
208
 
164
209
  -- Record how far a consumer has read, for retention only.
165
- CREATE OR REPLACE FUNCTION nowity_consumer_seen(p_consumer text, p_cursor text)
210
+ CREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)
166
211
  RETURNS void AS $$
167
212
  BEGIN
168
- INSERT INTO nowity_consumer (consumer_id, cursor_xid)
213
+ INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)
169
214
  VALUES (p_consumer, p_cursor::xid8)
170
215
  ON CONFLICT (consumer_id) DO UPDATE
171
216
  SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();
172
217
  END;
173
218
  $$ LANGUAGE plpgsql;
174
219
 
175
- CREATE OR REPLACE FUNCTION nowity_consumer_forget(p_consumer text) RETURNS void AS $$
220
+ CREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$
176
221
  BEGIN
177
- DELETE FROM nowity_consumer WHERE consumer_id = p_consumer;
222
+ DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;
178
223
  END;
179
224
  $$ LANGUAGE plpgsql;
180
225
 
181
226
  -- Delete outbox rows every live consumer has already read.
182
227
  --
183
228
  -- "Live" is a wall-clock judgement, and it is the only unsafe part of retention:
184
- -- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows
229
+ -- a consumer quiet for longer than \`p_stale_after\` is treated as gone, and rows
185
230
  -- it had not reached may be deleted. It resumes from the transaction horizon
186
231
  -- rather than from its old cursor, so it does not read a hole — it simply never
187
232
  -- learns about those changes and its clients keep whatever they had until
@@ -190,16 +235,16 @@ $$ LANGUAGE plpgsql;
190
235
  --
191
236
  -- With no live consumers at all this deletes nothing. An empty table means "the
192
237
  -- readers have not registered yet", not "nobody will ever read this".
193
- CREATE OR REPLACE FUNCTION nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')
238
+ CREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')
194
239
  RETURNS bigint AS $$
195
240
  DECLARE
196
241
  v_min xid8;
197
242
  v_deleted bigint;
198
243
  BEGIN
199
- -- `ORDER BY … LIMIT 1` rather than `min()`: xid8 has the comparison
244
+ -- \`ORDER BY … LIMIT 1\` rather than \`min()\`: xid8 has the comparison
200
245
  -- operators but not the aggregate.
201
246
  SELECT cursor_xid INTO v_min
202
- FROM nowity_consumer
247
+ FROM nowity.nowity_consumer
203
248
  WHERE updated_at > now() - p_stale_after
204
249
  ORDER BY cursor_xid
205
250
  LIMIT 1;
@@ -208,8 +253,9 @@ BEGIN
208
253
  RETURN 0;
209
254
  END IF;
210
255
 
211
- DELETE FROM nowity_outbox WHERE xid <= v_min;
256
+ DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;
212
257
  GET DIAGNOSTICS v_deleted = ROW_COUNT;
213
258
  RETURN v_deleted;
214
259
  END;
215
260
  $$ LANGUAGE plpgsql;
261
+ `;
@@ -4,12 +4,11 @@ import type { Pool } from "pg";
4
4
  * `['id']` is assumed when a plain array of table names is given.
5
5
  */
6
6
  export type TrackedTables = string[] | Record<string, string[]>;
7
- export declare const NOWITY_SETUP_SQL_PATH: string;
8
7
  /**
9
8
  * Install Nowity's change capture and attach it to the given tables.
10
9
  *
11
10
  * Idempotent, so it can run at boot. In a real deployment put the contents of
12
- * `setup.sql` into a migration instead and call {@link trackTable} from it.
11
+ * {@link NOWITY_SETUP_SQL} into a migration instead and call {@link trackTable} from it.
13
12
  */
14
13
  export declare function setupNowity(pool: Pool, tables?: TrackedTables): Promise<void>;
15
14
  /** Attach the capture trigger to one table. */
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/server/setup.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAE/B;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAchE,eAAO,MAAM,qBAAqB,QAA2C,CAAC;AAE9E;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,GAAE,aAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAUvF;AAED,+CAA+C;AAC/C,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,GAAE,MAAM,EAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhG;AAED,wBAAsB,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE3E;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAErF"}
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/server/setup.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAG/B;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAEhE;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,GAAE,aAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAUvF;AAED,+CAA+C;AAC/C,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,GAAE,MAAM,EAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhG;AAED,wBAAsB,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE3E;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAErF"}
@@ -1,66 +1,18 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.NOWITY_SETUP_SQL_PATH = void 0;
37
3
  exports.setupNowity = setupNowity;
38
4
  exports.trackTable = trackTable;
39
5
  exports.untrackTable = untrackTable;
40
6
  exports.setReplicaIdentityFull = setReplicaIdentityFull;
41
- const fs = __importStar(require("fs"));
42
- const path = __importStar(require("path"));
43
- function readSetupSql() {
44
- // Works both from `src` (ts-node) and from `dist` (the build copies sql/).
45
- const candidates = [
46
- path.join(__dirname, "sql", "setup.sql"),
47
- path.join(__dirname, "..", "..", "src", "server", "sql", "setup.sql"),
48
- ];
49
- for (const candidate of candidates) {
50
- if (fs.existsSync(candidate))
51
- return fs.readFileSync(candidate, "utf8");
52
- }
53
- throw new Error(`Cannot locate setup.sql (looked in ${candidates.join(", ")})`);
54
- }
55
- exports.NOWITY_SETUP_SQL_PATH = path.join(__dirname, "sql", "setup.sql");
7
+ const setup_sql_1 = require("./setup-sql");
56
8
  /**
57
9
  * Install Nowity's change capture and attach it to the given tables.
58
10
  *
59
11
  * Idempotent, so it can run at boot. In a real deployment put the contents of
60
- * `setup.sql` into a migration instead and call {@link trackTable} from it.
12
+ * {@link NOWITY_SETUP_SQL} into a migration instead and call {@link trackTable} from it.
61
13
  */
62
14
  async function setupNowity(pool, tables = []) {
63
- await pool.query(readSetupSql());
15
+ await pool.query(setup_sql_1.NOWITY_SETUP_SQL);
64
16
  const entries = Array.isArray(tables)
65
17
  ? tables.map((table) => [table, ["id"]])
66
18
  : Object.entries(tables);
@@ -70,10 +22,10 @@ async function setupNowity(pool, tables = []) {
70
22
  }
71
23
  /** Attach the capture trigger to one table. */
72
24
  async function trackTable(pool, table, pk = ["id"]) {
73
- await pool.query(`SELECT nowity_track($1::regclass, $2::text[])`, [quoteIdent(table), pk]);
25
+ await pool.query(`SELECT nowity.nowity_track($1::regclass, $2::text[])`, [quoteIdent(table), pk]);
74
26
  }
75
27
  async function untrackTable(pool, table) {
76
- await pool.query(`SELECT nowity_untrack($1::regclass)`, [quoteIdent(table)]);
28
+ await pool.query(`SELECT nowity.nowity_untrack($1::regclass)`, [quoteIdent(table)]);
77
29
  }
78
30
  /**
79
31
  * Make `UPDATE`/`DELETE` put the whole previous row into the WAL.
@@ -38,6 +38,6 @@ async function readOne(snap, opts, request) {
38
38
  return { ...base, ids: output.ids, ...(0, evaluate_1.outputRows)(output) };
39
39
  }
40
40
  async function readEpoch(snap, scope) {
41
- const { rows } = await snap.query(`SELECT version::text AS version FROM nowity_scope_epoch WHERE scope = $1`, [scope]);
41
+ const { rows } = await snap.query(`SELECT version::text AS version FROM nowity.nowity_scope_epoch WHERE scope = $1`, [scope]);
42
42
  return rows.length ? Number(rows[0].version) : 0;
43
43
  }