@pgxsinkit/client 0.1.15 → 0.1.17

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.
package/src/schema.ts CHANGED
@@ -1,14 +1,21 @@
1
- import type { AnyPgTable } from "drizzle-orm/pg-core";
1
+ import { getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
 
3
3
  import {
4
4
  getLocalSyncPrimaryKeyColumns,
5
5
  getSyncRegistrySchema,
6
6
  getProjectedColumns,
7
- type ClientProjectionSpec,
8
7
  type SyncTableEntry,
9
8
  type SyncTableRegistry,
10
9
  } from "@pgxsinkit/contracts";
11
10
 
11
+ /** Internal fully-qualified projection used within schema generation. */
12
+ interface ResolvedProjection {
13
+ syncedTable: string;
14
+ overlayTable?: string;
15
+ journalTable?: string;
16
+ readModel: string;
17
+ }
18
+
12
19
  type TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number]["column"];
13
20
 
14
21
  export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
@@ -111,6 +118,41 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
111
118
  `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_status_seq_idx ON ${projection.journalTable} (entity_key_json, status, mutation_seq);`,
112
119
  );
113
120
 
121
+ // Trigger: automatically clear overlay + journal entries when the sync
122
+ // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
123
+ // (row removed on server, synced back via Electric).
124
+ const triggerFnName = `${projection.syncedTable}_reconcile_on_sync`;
125
+
126
+ const pkMatchSql = (alias: string) =>
127
+ primaryKeyColumns
128
+ .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
129
+ .join(" AND ");
130
+ const pkOverlayMatchSql = primaryKeyColumns
131
+ .map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
132
+ .join(" AND ");
133
+
134
+ statements.push(
135
+ `CREATE OR REPLACE FUNCTION ${triggerFnName}() RETURNS TRIGGER AS $$\n` +
136
+ `BEGIN\n` +
137
+ ` DELETE FROM ${projection.journalTable}\n` +
138
+ ` WHERE status = 'acked' AND (${pkMatchSql(projection.journalTable)});\n` +
139
+ ` DELETE FROM ${projection.overlayTable} AS "overlay"\n` +
140
+ ` WHERE (${pkOverlayMatchSql})\n` +
141
+ ` AND NOT EXISTS (\n` +
142
+ ` SELECT 1 FROM ${projection.journalTable} AS j\n` +
143
+ ` WHERE (${pkMatchSql("j")})\n` +
144
+ ` );\n` +
145
+ ` RETURN COALESCE(NEW, OLD);\n` +
146
+ `END;\n` +
147
+ `$$ LANGUAGE plpgsql;`,
148
+ );
149
+
150
+ statements.push(
151
+ `CREATE OR REPLACE TRIGGER ${triggerFnName}\n` +
152
+ `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\n` +
153
+ `FOR EACH ROW EXECUTE FUNCTION ${triggerFnName}();`,
154
+ );
155
+
114
156
  statements.push(
115
157
  `CREATE OR REPLACE VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
116
158
  entry,
@@ -125,7 +167,7 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
125
167
 
126
168
  function buildReadModelViewSql(
127
169
  entry: SyncTableEntry<AnyPgTable>,
128
- projection: ClientProjectionSpec,
170
+ projection: ResolvedProjection,
129
171
  columnNames: string[],
130
172
  ) {
131
173
  if (!projection.overlayTable) {
@@ -373,14 +415,15 @@ function buildPrimaryKeyMatch(primaryKeyColumns: string[]) {
373
415
  return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
374
416
  }
375
417
 
376
- function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ClientProjectionSpec {
418
+ function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {
377
419
  const projection = baseProjection(entry, tableKey);
420
+ const readModelName = entry.view != null ? getViewConfig(entry.view).name : projection.syncedTable;
378
421
 
379
422
  return {
380
423
  syncedTable: qualifyIdentifier(localSchema, projection.syncedTable),
381
424
  ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),
382
425
  ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),
383
- readModel: qualifyIdentifier(localSchema, projection.readModel),
426
+ readModel: qualifyIdentifier(localSchema, readModelName),
384
427
  };
385
428
  }
386
429