@pgxsinkit/client 0.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.
package/src/schema.ts ADDED
@@ -0,0 +1,302 @@
1
+ import type { AnyPgTable } from "drizzle-orm/pg-core";
2
+
3
+ import {
4
+ getLocalSyncPrimaryKeyColumns,
5
+ getSyncRegistrySchema,
6
+ getProjectedColumns,
7
+ type ClientProjectionSpec,
8
+ type SyncTableEntry,
9
+ type SyncTableRegistry,
10
+ } from "@pgxsinkit/contracts";
11
+
12
+ type TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number]["column"];
13
+
14
+ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
15
+ const statements: string[] = [];
16
+ const localSchema = getSyncRegistrySchema(registry);
17
+
18
+ if (localSchema !== "public") {
19
+ statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
20
+ }
21
+
22
+ for (const [tableKey, entry] of Object.entries(registry)) {
23
+ const projection = getClientProjection(entry, tableKey, localSchema);
24
+ const columns = getProjectedColumns(entry).map(({ column }) => column);
25
+ const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
26
+ const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns);
27
+
28
+ statements.push(`CREATE TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
29
+
30
+ if (entry.mode === "readonly") {
31
+ continue;
32
+ }
33
+
34
+ if (!projection.overlayTable || !projection.journalTable) {
35
+ throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);
36
+ }
37
+
38
+ const journalTableName = entry.clientProjection?.journalTable;
39
+
40
+ if (!journalTableName) {
41
+ throw new Error(`journal table is required for writable table ${tableKey}`);
42
+ }
43
+
44
+ const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
45
+ const column = columns.find((candidate) => candidate.name === columnName);
46
+
47
+ if (!column) {
48
+ throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
49
+ }
50
+
51
+ return column;
52
+ });
53
+ const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
54
+ const journalSequenceName = buildJournalSequenceName(journalTableName);
55
+ const qualifiedJournalSequenceName = qualifyIdentifier(localSchema, journalSequenceName);
56
+
57
+ statements.push(
58
+ `CREATE TABLE IF NOT EXISTS ${projection.overlayTable} (\n ${[
59
+ ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames)),
60
+ "overlay_kind VARCHAR(24) NOT NULL",
61
+ "local_updated_at_us BIGINT NOT NULL",
62
+ ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),
63
+ ].join(",\n ")}\n);`,
64
+ );
65
+
66
+ statements.push(
67
+ `CREATE SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,
68
+ );
69
+
70
+ statements.push(
71
+ `CREATE TABLE IF NOT EXISTS ${projection.journalTable} (\n ${[
72
+ "mutation_id UUID PRIMARY KEY",
73
+ ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column)} NOT NULL`),
74
+ "entity_key_json TEXT NOT NULL",
75
+ `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
76
+ "mutation_kind VARCHAR(24) NOT NULL",
77
+ "status VARCHAR(24) NOT NULL",
78
+ "payload_json TEXT NOT NULL",
79
+ "attempt_count INTEGER NOT NULL DEFAULT 0",
80
+ "last_error TEXT",
81
+ "last_http_status INTEGER",
82
+ "conflict_reason TEXT",
83
+ "server_updated_at_us BIGINT",
84
+ "enqueued_at_us BIGINT NOT NULL",
85
+ "next_retry_at_us BIGINT",
86
+ "sent_at_us BIGINT",
87
+ "acked_at_us BIGINT",
88
+ "updated_at_us BIGINT NOT NULL",
89
+ ].join(",\n ")}\n);`,
90
+ );
91
+
92
+ statements.push(
93
+ `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_status_idx ON ${projection.journalTable} (status, enqueued_at_us);`,
94
+ );
95
+ statements.push(
96
+ `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_status_retry_idx ON ${projection.journalTable} (status, next_retry_at_us, enqueued_at_us);`,
97
+ );
98
+ statements.push(
99
+ `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_pk_seq_idx ON ${projection.journalTable} (${entry.primaryKey.columns.join(", ")}, mutation_seq);`,
100
+ );
101
+ statements.push(
102
+ `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_seq_idx ON ${projection.journalTable} (entity_key_json, mutation_seq);`,
103
+ );
104
+ statements.push(
105
+ `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_status_seq_idx ON ${projection.journalTable} (entity_key_json, status, mutation_seq);`,
106
+ );
107
+
108
+ statements.push(
109
+ `CREATE OR REPLACE VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
110
+ entry,
111
+ projection,
112
+ columns.map((column) => column.name),
113
+ )};`,
114
+ );
115
+ }
116
+
117
+ return `${statements.join("\n\n")}\n`;
118
+ }
119
+
120
+ function buildReadModelViewSql(
121
+ entry: SyncTableEntry<AnyPgTable>,
122
+ projection: ClientProjectionSpec,
123
+ columnNames: string[],
124
+ ) {
125
+ if (!projection.overlayTable) {
126
+ throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);
127
+ }
128
+
129
+ const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);
130
+ const syncedLocalUpdatedExpression = columnNames.includes("updated_at_us") ? "t.updated_at_us" : "CAST(0 AS BIGINT)";
131
+
132
+ return [
133
+ "SELECT",
134
+ ` ${columnNames.join(",\n ")},`,
135
+ " overlay_kind,",
136
+ " local_updated_at_us",
137
+ `FROM ${projection.overlayTable}`,
138
+ `WHERE overlay_kind <> 'pending_delete'`,
139
+ "UNION ALL",
140
+ "SELECT",
141
+ ` ${columnNames.map((name) => `t.${name}`).join(",\n ")},`,
142
+ ` 'synced' AS overlay_kind,`,
143
+ ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,
144
+ `FROM ${projection.syncedTable} AS t`,
145
+ "WHERE NOT EXISTS (",
146
+ " SELECT 1",
147
+ ` FROM ${projection.overlayTable} AS o`,
148
+ ` WHERE ${pkMatch}`,
149
+ ")",
150
+ ].join("\n");
151
+ }
152
+
153
+ function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[]) {
154
+ return [
155
+ ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns)),
156
+ ...buildCompositePrimaryKeyClauses(primaryKeyColumns),
157
+ ].join(",\n ");
158
+ }
159
+
160
+ function buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[]) {
161
+ const typeSql = mapColumnType(column);
162
+ const notNullSql = column.notNull ? " NOT NULL" : "";
163
+ const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? " PRIMARY KEY" : "";
164
+ return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;
165
+ }
166
+
167
+ function buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {
168
+ if (primaryKeyColumns.length <= 1) {
169
+ return [];
170
+ }
171
+
172
+ return [`PRIMARY KEY (${primaryKeyColumns.join(", ")})`];
173
+ }
174
+
175
+ function mapColumnType(column: TableColumn) {
176
+ const baseTypeSql = readBaseColumnTypeSql(column);
177
+ const dimensions = readArrayDimensions(column);
178
+
179
+ if (dimensions > 0) {
180
+ return `${baseTypeSql}${"[]".repeat(dimensions)}`;
181
+ }
182
+
183
+ return baseTypeSql;
184
+ }
185
+
186
+ function readBaseColumnTypeSql(column: TableColumn) {
187
+ const sqlType = readColumnSqlType(column);
188
+
189
+ if (sqlType) {
190
+ return sqlType;
191
+ }
192
+
193
+ switch (column.columnType) {
194
+ case "PgUUID":
195
+ return "UUID";
196
+ case "PgText":
197
+ return "TEXT";
198
+ case "PgVarchar":
199
+ return `VARCHAR(${readVarcharLength(column) ?? 255})`;
200
+ case "PgBigInt64":
201
+ case "PgBigInt53":
202
+ return "BIGINT";
203
+ case "PgInteger":
204
+ case "PgSerial":
205
+ case "PgSmallInt":
206
+ return "INTEGER";
207
+ case "PgBoolean":
208
+ return "BOOLEAN";
209
+ case "PgJson":
210
+ case "PgJsonb":
211
+ return "JSONB";
212
+ case "PgReal":
213
+ case "PgDoublePrecision":
214
+ return "REAL";
215
+ case "PgTimestamp":
216
+ case "PgTimestampString":
217
+ return "TIMESTAMP";
218
+ default:
219
+ if (column.dataType.includes("uuid")) {
220
+ return "UUID";
221
+ }
222
+
223
+ if (column.dataType.includes("bigint")) {
224
+ return "BIGINT";
225
+ }
226
+
227
+ if (column.dataType.includes("json")) {
228
+ return "JSONB";
229
+ }
230
+
231
+ if (column.dataType.includes("float")) {
232
+ return "REAL";
233
+ }
234
+
235
+ if (column.dataType === "string") {
236
+ return "TEXT";
237
+ }
238
+
239
+ throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);
240
+ }
241
+ }
242
+
243
+ function readColumnSqlType(column: TableColumn) {
244
+ const candidate = column as TableColumn & {
245
+ getSQLType?: () => string;
246
+ };
247
+
248
+ return typeof candidate.getSQLType === "function" ? candidate.getSQLType() : undefined;
249
+ }
250
+
251
+ function readArrayDimensions(column: TableColumn) {
252
+ const arrayColumn = column as TableColumn & { dimensions?: number };
253
+ return arrayColumn.dimensions ?? 0;
254
+ }
255
+
256
+ function readVarcharLength(column: TableColumn) {
257
+ const varcharColumn = column as { config?: { length?: number } };
258
+ return varcharColumn.config?.length;
259
+ }
260
+
261
+ function buildPrimaryKeyMatch(primaryKeyColumns: string[]) {
262
+ return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
263
+ }
264
+
265
+ function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ClientProjectionSpec {
266
+ const projection = baseProjection(entry, tableKey);
267
+
268
+ return {
269
+ syncedTable: qualifyIdentifier(localSchema, projection.syncedTable),
270
+ ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),
271
+ ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),
272
+ readModel: qualifyIdentifier(localSchema, projection.readModel),
273
+ };
274
+ }
275
+
276
+ function baseProjection(entry: SyncTableEntry, tableKey: string) {
277
+ if (!entry.clientProjection) {
278
+ throw new Error(`clientProjection is required for local client table ${tableKey}`);
279
+ }
280
+
281
+ return entry.clientProjection;
282
+ }
283
+
284
+ function qualifyIdentifier(schemaName: string, objectName: string) {
285
+ if (schemaName === "public") {
286
+ return objectName;
287
+ }
288
+
289
+ return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;
290
+ }
291
+
292
+ function quoteIdentifier(value: string) {
293
+ return `"${value.replace(/"/g, '""')}"`;
294
+ }
295
+
296
+ function quoteSqlStringLiteral(value: string) {
297
+ return `'${value.replace(/'/g, "''")}'`;
298
+ }
299
+
300
+ function buildJournalSequenceName(journalTable: string) {
301
+ return `${journalTable}_mutation_seq`;
302
+ }