@pgxsinkit/client 0.1.16 → 0.1.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/client",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "files": [
5
5
  "dist",
6
6
  "src",
@@ -22,8 +22,8 @@
22
22
  "build": "bun --cwd ../.. run build:public-packages"
23
23
  },
24
24
  "dependencies": {
25
- "@pgxsinkit/contracts": "^0.1.16",
26
- "@pgxsinkit/sync-engine": "^0.1.16"
25
+ "@pgxsinkit/contracts": "^0.1.17",
26
+ "@pgxsinkit/sync-engine": "^0.1.17"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@electric-sql/pglite": "0.4.5",
package/src/index.ts CHANGED
@@ -5,10 +5,10 @@ import { drizzle } from "drizzle-orm/pglite";
5
5
  import { defineRelations } from "drizzle-orm/relations";
6
6
 
7
7
  import type {
8
- ClientProjectionSpec,
9
8
  MutationDiagnostics,
10
9
  RegistryRelations,
11
10
  RegistryTables,
11
+ RegistryViews,
12
12
  SyncConfigInput,
13
13
  SyncRuntimeStatus,
14
14
  SyncTableCreateInput,
@@ -32,7 +32,6 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
32
32
  registry: TRegistry;
33
33
  electricUrl: string;
34
34
  writeUrl: string;
35
- batchWriteUrl?: string;
36
35
  getAuthToken?: () => Promise<string | undefined>;
37
36
  syncEnabled?: boolean;
38
37
  dataDir?: string;
@@ -55,6 +54,7 @@ export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey
55
54
  export interface SyncClient<TRegistry extends SyncTableRegistry> {
56
55
  drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
57
56
  pglite: ClientPGlite;
57
+ views: RegistryViews<TRegistry>;
58
58
  tables: {
59
59
  [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
60
60
  };
@@ -158,7 +158,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
158
158
  db: pglite,
159
159
  registry: options.registry,
160
160
  writeUrl: options.writeUrl,
161
- batchWriteUrl: options.batchWriteUrl ?? options.writeUrl,
162
161
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
163
162
  });
164
163
 
@@ -174,6 +173,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
174
173
  const client: SyncClient<TRegistry> = {
175
174
  drizzle: drizzleDb,
176
175
  pglite,
176
+ views: buildViews(options.registry),
177
177
  tables: Object.fromEntries(
178
178
  Object.keys(options.registry).map((tableKey) => [
179
179
  tableKey,
@@ -254,6 +254,12 @@ function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
254
254
  ) as RegistryTables<TRegistry>;
255
255
  }
256
256
 
257
+ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
258
+ return Object.fromEntries(
259
+ Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),
260
+ ) as RegistryViews<TRegistry>;
261
+ }
262
+
257
263
  function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
258
264
  registry: TRegistry,
259
265
  electricUrl: string,
@@ -273,12 +279,11 @@ function buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {
273
279
  mode: entry.mode,
274
280
  primaryKey: entry.primaryKey,
275
281
  shape: entry.shape,
276
- routes: entry.routes,
277
282
  clientProjection,
278
283
  };
279
284
  }
280
285
 
281
- function getClientProjection(entry: SyncTableEntry, tableKey: string): ClientProjectionSpec {
286
+ function getClientProjection(entry: SyncTableEntry, tableKey: string) {
282
287
  if (!entry.clientProjection) {
283
288
  throw new Error(`clientProjection is required for client table ${tableKey}`);
284
289
  }
package/src/mutation.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AnyPgTable } from "drizzle-orm/pg-core";
1
+ import { getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
  import { ZodObject } from "zod";
3
3
 
4
4
  import type {
@@ -66,7 +66,6 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
66
66
  db: MutationDb;
67
67
  registry: TRegistry;
68
68
  writeUrl: string;
69
- batchWriteUrl?: string;
70
69
  getAuthToken?: () => Promise<string | undefined>;
71
70
  }
72
71
 
@@ -78,7 +77,6 @@ interface TableContext {
78
77
  overlayTable: string;
79
78
  journalTable: string;
80
79
  journalSequence: string;
81
- routeBasePath?: string;
82
80
  pkColumnNames: string[];
83
81
  pkPropertyKeys: string[];
84
82
  recordIncludesOverlayState: boolean;
@@ -125,15 +123,6 @@ export function computeNextRetryAtUs(nowUs: string, attemptCount: number) {
125
123
  return (BigInt(nowUs) + BigInt(computeBackoffDelayMs(attemptCount)) * 1000n).toString();
126
124
  }
127
125
 
128
- export function shouldClearOverlayRow(syncedUpdatedAtUs: string, serverUpdatedAtUs: string | null) {
129
- console.log("Comparing timestamps for overlay clearing:", { syncedUpdatedAtUs, serverUpdatedAtUs });
130
- if (serverUpdatedAtUs === null) {
131
- return false;
132
- }
133
-
134
- return BigInt(syncedUpdatedAtUs) >= BigInt(serverUpdatedAtUs);
135
- }
136
-
137
126
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
138
127
  options: CreateMutationRuntimeOptions<TRegistry>,
139
128
  ): MutationRuntime<TRegistry> {
@@ -145,7 +134,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
145
134
  return undefined;
146
135
  };
147
136
 
148
- const tableContexts = buildTableContexts(options.registry, options.batchWriteUrl === undefined);
137
+ const tableContexts = buildTableContexts(options.registry);
149
138
  let flushQueue = Promise.resolve();
150
139
 
151
140
  const getTableContext = (table: SyncTableName<TRegistry>) => {
@@ -403,42 +392,27 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
403
392
  };
404
393
 
405
394
  const runFlush = async (table?: SyncTableName<TRegistry>) => {
406
- console.log(`Running runFlush for table: ${table ?? "all tables"}`);
407
- if (options.batchWriteUrl) {
408
- const affectedContexts = new Map<string, TableContext>();
409
- let processedCount = 0;
410
-
411
- do {
412
- const batchResult = await flushBatch(
413
- options.db,
414
- tableContexts as Record<string, TableContext>,
415
- options.batchWriteUrl,
416
- table,
417
- resolveAuthToken,
418
- );
419
-
420
- processedCount = batchResult.processedCount;
395
+ const affectedContexts = new Map<string, TableContext>();
396
+ let processedCount = 0;
397
+
398
+ do {
399
+ const batchResult = await flushBatch(
400
+ options.db,
401
+ tableContexts as Record<string, TableContext>,
402
+ options.writeUrl,
403
+ table,
404
+ resolveAuthToken,
405
+ );
421
406
 
422
- for (const context of batchResult.affectedContexts) {
423
- affectedContexts.set(context.key, context);
424
- }
425
- } while (processedCount > 0);
407
+ processedCount = batchResult.processedCount;
426
408
 
427
- for (const context of affectedContexts.values()) {
428
- await reconcileTable(options.db, context);
409
+ for (const context of batchResult.affectedContexts) {
410
+ affectedContexts.set(context.key, context);
429
411
  }
430
- } else {
431
- let processedCount = 0;
432
-
433
- do {
434
- processedCount = 0;
412
+ } while (processedCount > 0);
435
413
 
436
- const contexts = filterContexts(tableContexts, table);
437
-
438
- for (const context of contexts) {
439
- processedCount += await flushTable(options.db, context, options.writeUrl, resolveAuthToken);
440
- }
441
- } while (processedCount > 0);
414
+ for (const context of affectedContexts.values()) {
415
+ await reconcileTable(options.db, context);
442
416
  }
443
417
  };
444
418
 
@@ -483,7 +457,6 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
483
457
  });
484
458
  },
485
459
  flush: async (table) => {
486
- console.log(`Initiating flush for table: ${table ?? "all tables"}`);
487
460
  const nextFlush = flushQueue.then(() => runFlush(table));
488
461
  flushQueue = nextFlush.catch(() => undefined);
489
462
  await nextFlush;
@@ -734,30 +707,21 @@ type NormalizedBatchItem =
734
707
  order: number;
735
708
  };
736
709
 
737
- function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry, requireRouteBasePath: boolean) {
710
+ function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
738
711
  const localSchema = getSyncRegistrySchema(registry);
739
712
 
740
713
  return Object.fromEntries(
741
714
  Object.entries(registry)
742
715
  .filter(([, entry]) => entry.mode !== "readonly")
743
- .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema, requireRouteBasePath)]),
716
+ .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema)]),
744
717
  ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;
745
718
  }
746
719
 
747
- function buildTableContext(
748
- key: string,
749
- entry: SyncTableEntry<AnyPgTable>,
750
- localSchema: string,
751
- requireRouteBasePath: boolean,
752
- ): TableContext {
720
+ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, localSchema: string): TableContext {
753
721
  if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
754
722
  throw new Error(`overlay and journal tables are required for writable table ${key}`);
755
723
  }
756
724
 
757
- if (requireRouteBasePath && !entry.routes?.basePath) {
758
- throw new Error(`routes.basePath is required for writable table ${key}`);
759
- }
760
-
761
725
  const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({
762
726
  propertyKey,
763
727
  column,
@@ -776,12 +740,14 @@ function buildTableContext(
776
740
  return {
777
741
  key,
778
742
  entry,
779
- readModel: qualifyLocalIdentifier(localSchema, entry.clientProjection.readModel),
743
+ readModel: qualifyLocalIdentifier(
744
+ localSchema,
745
+ entry.view != null ? getViewConfig(entry.view).name : entry.clientProjection.syncedTable,
746
+ ),
780
747
  syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.syncedTable),
781
748
  overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),
782
749
  journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),
783
750
  journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
784
- ...(entry.routes?.basePath ? { routeBasePath: entry.routes.basePath } : {}),
785
751
  pkColumnNames: [...entry.primaryKey.columns],
786
752
  pkPropertyKeys,
787
753
  recordIncludesOverlayState: recordSchemaIncludesOverlayState(entry.schemas?.recordSchema),
@@ -1543,158 +1509,6 @@ function toSqlColumnPayload(context: TableContext, payload: Record<string, unkno
1543
1509
  return normalized;
1544
1510
  }
1545
1511
 
1546
- function filterProjectedPayload(context: TableContext, payload: Record<string, unknown>) {
1547
- const normalized: Record<string, unknown> = {};
1548
-
1549
- for (const { propertyKey, column } of context.columns) {
1550
- if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
1551
- normalized[propertyKey] = payload[propertyKey];
1552
- continue;
1553
- }
1554
-
1555
- if (Object.prototype.hasOwnProperty.call(payload, column.name)) {
1556
- normalized[column.name] = payload[column.name];
1557
- }
1558
- }
1559
-
1560
- return normalized;
1561
- }
1562
-
1563
- async function flushTable(
1564
- db: MutationDb,
1565
- context: TableContext,
1566
- writeUrl: string,
1567
- getAuthToken?: () => Promise<string | undefined>,
1568
- ) {
1569
- const result = await db.query<MutationRow>(
1570
- `
1571
- SELECT
1572
- mutation_id AS "mutationId",
1573
- entity_key_json AS "entityKeyJson",
1574
- mutation_seq AS "mutationSeq",
1575
- mutation_kind AS "mutationKind",
1576
- status,
1577
- payload_json AS "payloadJson",
1578
- attempt_count AS "attemptCount",
1579
- last_http_status AS "lastHttpStatus",
1580
- last_error AS "lastError",
1581
- conflict_reason AS "conflictReason",
1582
- next_retry_at_us::text AS "nextRetryAtUs",
1583
- server_updated_at_us::text AS "serverUpdatedAtUs"
1584
- FROM ${context.journalTable}
1585
- WHERE status IN ('pending', 'failed')
1586
- AND COALESCE(next_retry_at_us, 0) <= $1::bigint
1587
- AND NOT EXISTS (
1588
- SELECT 1
1589
- FROM ${context.journalTable} AS earlier
1590
- WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
1591
- AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
1592
- AND earlier.status IN ('pending', 'failed', 'sending')
1593
- )
1594
- ORDER BY enqueued_at_us ASC, mutation_seq ASC
1595
- LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
1596
- `,
1597
- [nowMicroseconds()],
1598
- );
1599
-
1600
- if (result.rows.length === 0) {
1601
- return 0;
1602
- }
1603
-
1604
- for (const mutation of result.rows) {
1605
- const sentAtUs = nowMicroseconds();
1606
- await setMutationStatus(db, context, mutation.mutationId, "sending", {
1607
- attemptCount: mutation.attemptCount + 1,
1608
- sentAtUs,
1609
- updatedAtUs: sentAtUs,
1610
- lastError: null,
1611
- nextRetryAtUs: null,
1612
- lastHttpStatus: null,
1613
- conflictReason: null,
1614
- });
1615
-
1616
- try {
1617
- const entityKey = JSON.parse(mutation.entityKeyJson) as Record<string, string>;
1618
- const payload = JSON.parse(mutation.payloadJson) as Record<string, unknown>;
1619
- let response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken?.());
1620
-
1621
- if ([401, 403].includes(response.status) && getAuthToken) {
1622
- response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken());
1623
- }
1624
-
1625
- const responseText = await response.text();
1626
- const responseJson = responseText.length > 0 ? JSON.parse(responseText) : null;
1627
-
1628
- if (!response.ok) {
1629
- const errorMessage =
1630
- responseJson && typeof responseJson.message === "string"
1631
- ? responseJson.message
1632
- : `Write API responded with ${response.status}`;
1633
-
1634
- if (mutation.mutationKind === "delete" && response.status === 404) {
1635
- await markDeleteAcknowledged(db, context, mutation.mutationId);
1636
- continue;
1637
- }
1638
-
1639
- throw new MutationRequestError(errorMessage, response.status);
1640
- }
1641
-
1642
- const ackedAtUs = nowMicroseconds();
1643
-
1644
- if (mutation.mutationKind === "delete") {
1645
- await markDeleteAcknowledged(db, context, mutation.mutationId);
1646
- } else {
1647
- const created = parseRecord(context, responseJson);
1648
- const createdRecord = ensureRecord(created);
1649
- const serverUpdatedAtUs = toOptionalString(createdRecord.updatedAtUs);
1650
-
1651
- await db.query(
1652
- `
1653
- UPDATE ${context.journalTable}
1654
- SET
1655
- status = 'acked',
1656
- acked_at_us = $2::bigint,
1657
- updated_at_us = $2::bigint,
1658
- server_updated_at_us = $3::bigint,
1659
- last_error = NULL,
1660
- last_http_status = 200,
1661
- conflict_reason = NULL,
1662
- next_retry_at_us = NULL
1663
- WHERE mutation_id = $1
1664
- `,
1665
- [mutation.mutationId, ackedAtUs, serverUpdatedAtUs],
1666
- );
1667
-
1668
- if (!(await hasLaterMutations(db, context, mutation.entityKeyJson, mutation.mutationSeq))) {
1669
- await updateOverlayTimestamps(db, context, entityKey, createdRecord, ackedAtUs);
1670
- }
1671
- }
1672
- } catch (error) {
1673
- const failedAtUs = nowMicroseconds();
1674
- const attemptCount = mutation.attemptCount + 1;
1675
- const nextRetryAtUs = computeNextRetryAtUs(failedAtUs, attemptCount);
1676
- const lastHttpStatus = error instanceof MutationRequestError ? error.status : null;
1677
- const conflictReason =
1678
- lastHttpStatus === 404 || lastHttpStatus === 409
1679
- ? error instanceof Error
1680
- ? error.message
1681
- : "Server conflict"
1682
- : null;
1683
-
1684
- await setMutationStatus(db, context, mutation.mutationId, "failed", {
1685
- attemptCount,
1686
- updatedAtUs: failedAtUs,
1687
- lastError: error instanceof Error ? error.message : "Unknown write failure",
1688
- nextRetryAtUs,
1689
- lastHttpStatus,
1690
- conflictReason,
1691
- });
1692
- }
1693
- }
1694
-
1695
- return result.rows.length;
1696
- }
1697
-
1698
1512
  async function reconcileTable(db: MutationDb, context: TableContext) {
1699
1513
  // PK-match only — no timestamp gate. The trigger on the synced table
1700
1514
  // handles real-time cleanup; this is a bulk recovery/fallback path.
@@ -1775,50 +1589,6 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
1775
1589
  }
1776
1590
  }
1777
1591
 
1778
- async function sendMutationRequest(
1779
- writeUrl: string,
1780
- context: TableContext,
1781
- entityKey: Record<string, string>,
1782
- payload: Record<string, unknown>,
1783
- bearerToken?: string,
1784
- ) {
1785
- if (!context.routeBasePath) {
1786
- throw new Error(`routes.basePath is required for direct mutation requests on table ${context.key}`);
1787
- }
1788
-
1789
- switch (payload.kind) {
1790
- case "create":
1791
- return fetch(`${writeUrl}${context.routeBasePath}`, {
1792
- method: "POST",
1793
- headers: buildRequestHeaders(bearerToken),
1794
- body: JSON.stringify(
1795
- filterProjectedPayload(context, stripManagedFields(context, ensureRecord(payload.value), "create")),
1796
- ),
1797
- });
1798
- case "update":
1799
- return fetch(
1800
- `${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
1801
- {
1802
- method: "PATCH",
1803
- headers: buildRequestHeaders(bearerToken),
1804
- body: JSON.stringify(
1805
- filterProjectedPayload(context, stripManagedFields(context, ensureRecord(payload.patch), "update")),
1806
- ),
1807
- },
1808
- );
1809
- case "delete":
1810
- return fetch(
1811
- `${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
1812
- {
1813
- method: "DELETE",
1814
- headers: buildRequestHeaders(bearerToken),
1815
- },
1816
- );
1817
- default:
1818
- throw new Error(`Unknown mutation kind for table ${context.key}`);
1819
- }
1820
- }
1821
-
1822
1592
  function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1823
1593
  if (!bearerToken) {
1824
1594
  return {
@@ -1832,57 +1602,6 @@ function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1832
1602
  };
1833
1603
  }
1834
1604
 
1835
- function getSingleEntityKeyValue(context: TableContext, entityKey: Record<string, string>) {
1836
- if (context.pkPropertyKeys.length !== 1) {
1837
- throw new Error(`Only single-column primary keys are supported for routes on table ${context.key}`);
1838
- }
1839
-
1840
- return entityKey[context.pkPropertyKeys[0]!]!;
1841
- }
1842
-
1843
- async function setMutationStatus(
1844
- db: MutationDb,
1845
- context: TableContext,
1846
- mutationId: string,
1847
- status: MutationStatus,
1848
- options: {
1849
- attemptCount: number;
1850
- updatedAtUs: string;
1851
- sentAtUs?: string | null;
1852
- nextRetryAtUs?: string | null;
1853
- lastError?: string | null;
1854
- lastHttpStatus?: number | null;
1855
- conflictReason?: string | null;
1856
- },
1857
- ) {
1858
- await db.query(
1859
- `
1860
- UPDATE ${context.journalTable}
1861
- SET
1862
- status = $2,
1863
- attempt_count = $3,
1864
- sent_at_us = COALESCE($4::bigint, sent_at_us),
1865
- updated_at_us = $5::bigint,
1866
- last_error = $6,
1867
- next_retry_at_us = $7::bigint,
1868
- last_http_status = $8,
1869
- conflict_reason = $9
1870
- WHERE mutation_id = $1
1871
- `,
1872
- [
1873
- mutationId,
1874
- status,
1875
- options.attemptCount,
1876
- options.sentAtUs ?? null,
1877
- options.updatedAtUs,
1878
- options.lastError ?? null,
1879
- options.nextRetryAtUs ?? null,
1880
- options.lastHttpStatus ?? null,
1881
- options.conflictReason ?? null,
1882
- ],
1883
- );
1884
- }
1885
-
1886
1605
  async function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {
1887
1606
  if (updates.length === 0) {
1888
1607
  return;
@@ -2003,68 +1722,6 @@ async function applyMutationStatusUpdates(db: MutationDb, context: TableContext,
2003
1722
  );
2004
1723
  }
2005
1724
 
2006
- async function markDeleteAcknowledged(db: MutationDb, context: TableContext, mutationId: string) {
2007
- const ackedAtUs = nowMicroseconds();
2008
-
2009
- await db.query(
2010
- `
2011
- UPDATE ${context.journalTable}
2012
- SET
2013
- status = 'acked',
2014
- acked_at_us = $2::bigint,
2015
- updated_at_us = $2::bigint,
2016
- last_error = NULL,
2017
- last_http_status = 204,
2018
- conflict_reason = NULL,
2019
- next_retry_at_us = NULL
2020
- WHERE mutation_id = $1
2021
- `,
2022
- [mutationId, ackedAtUs],
2023
- );
2024
- }
2025
-
2026
- async function hasLaterMutations(db: MutationDb, context: TableContext, entityKeyJson: string, mutationSeq: number) {
2027
- const result = await db.query<{ count: number }>(
2028
- `
2029
- SELECT COUNT(*)::int AS count
2030
- FROM ${context.journalTable}
2031
- WHERE entity_key_json = $1
2032
- AND mutation_seq > $2
2033
- `,
2034
- [entityKeyJson, mutationSeq],
2035
- );
2036
-
2037
- return (result.rows[0]?.count ?? 0) > 0;
2038
- }
2039
-
2040
- async function updateOverlayTimestamps(
2041
- db: MutationDb,
2042
- context: TableContext,
2043
- entityKey: Record<string, string>,
2044
- record: Record<string, unknown>,
2045
- localUpdatedAtUs: string,
2046
- ) {
2047
- if (!hasProperty(context, "createdAtUs") || !hasProperty(context, "updatedAtUs")) {
2048
- return;
2049
- }
2050
-
2051
- await db.query(
2052
- `
2053
- UPDATE ${context.overlayTable}
2054
- SET
2055
- created_at_us = $${context.pkPropertyKeys.length + 1}::bigint,
2056
- updated_at_us = $${context.pkPropertyKeys.length + 2}::bigint,
2057
- local_updated_at_us = $${context.pkPropertyKeys.length + 3}::bigint
2058
- WHERE ${buildWhereClause(context)}
2059
- `,
2060
- [...buildWhereParams(context, entityKey), String(record.createdAtUs), String(record.updatedAtUs), localUpdatedAtUs],
2061
- );
2062
- }
2063
-
2064
- function buildWhereClause(context: TableContext) {
2065
- return context.pkColumnNames.map((columnName, index) => `${columnName} = $${index + 1}`).join(" AND ");
2066
- }
2067
-
2068
1725
  function buildColumnEquality(columnNames: string[], leftAlias: string, rightAlias: string) {
2069
1726
  return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
2070
1727
  }
@@ -2089,10 +1746,6 @@ function escapeSqlString(value: string) {
2089
1746
  return value.replace(/'/g, "''");
2090
1747
  }
2091
1748
 
2092
- function buildWhereParams(context: TableContext, entityKey: Record<string, string>) {
2093
- return context.pkPropertyKeys.map((propertyKey) => entityKey[propertyKey]);
2094
- }
2095
-
2096
1749
  function formatSqlValuePlaceholder(position: number, columnName: string) {
2097
1750
  return /_at_us$/.test(columnName) ? `$${position}::bigint` : `$${position}`;
2098
1751
  }
@@ -2117,23 +1770,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
2117
1770
  return typeof value === "object" && value !== null;
2118
1771
  }
2119
1772
 
2120
- function toOptionalString(value: unknown) {
2121
- if (value === undefined || value === null) {
2122
- return null;
2123
- }
2124
-
2125
- switch (typeof value) {
2126
- case "string":
2127
- return value;
2128
- case "number":
2129
- case "boolean":
2130
- case "bigint":
2131
- return String(value);
2132
- default:
2133
- return JSON.stringify(value);
2134
- }
2135
- }
2136
-
2137
1773
  class MutationRequestError extends Error {
2138
1774
  constructor(
2139
1775
  message: string,
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) {
@@ -160,7 +167,7 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
160
167
 
161
168
  function buildReadModelViewSql(
162
169
  entry: SyncTableEntry<AnyPgTable>,
163
- projection: ClientProjectionSpec,
170
+ projection: ResolvedProjection,
164
171
  columnNames: string[],
165
172
  ) {
166
173
  if (!projection.overlayTable) {
@@ -408,14 +415,15 @@ function buildPrimaryKeyMatch(primaryKeyColumns: string[]) {
408
415
  return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
409
416
  }
410
417
 
411
- function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ClientProjectionSpec {
418
+ function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {
412
419
  const projection = baseProjection(entry, tableKey);
420
+ const readModelName = entry.view != null ? getViewConfig(entry.view).name : projection.syncedTable;
413
421
 
414
422
  return {
415
423
  syncedTable: qualifyIdentifier(localSchema, projection.syncedTable),
416
424
  ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),
417
425
  ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),
418
- readModel: qualifyIdentifier(localSchema, projection.readModel),
426
+ readModel: qualifyIdentifier(localSchema, readModelName),
419
427
  };
420
428
  }
421
429