Open History to see the last commit
1import type postgres from "postgres"
2import type { PendingMutation } from "../types"
3
4/**
5 * Get the table name from the relation metadata
6 */
7function getTableName(relation?: Array<string>): string {
8 if (!relation || relation.length < 2) {
9 throw new Error(`could not find the table name`)
10 }
11
12 // The table name is typically the second element in the relation array
13 // e.g. ['public', 'todos'] -> 'todos'
14 return relation[1]
15}
16
17/**
18 * Process an array of PendingMutations and write to the database
19 */
20export async function processMutations(
21 sql: postgres.Sql<Record<string, unknown>>,
22 pendingMutations: Array<PendingMutation>
23): Promise<number> {
24 return await sql.begin(async (tx) => {
25 // Get the transaction ID
26 const [{ txid }] = await tx`SELECT txid_current() as txid`
27
28 // Process each mutation in order
29 for (const mutation of pendingMutations) {
30 // Get the table name from the relation metadata
31 const tableName = getTableName(
32 mutation.syncMetadata.relation as Array<string> | undefined
33 )
34
35 // Get the primary key columns from metadata
36 const primaryKey = (mutation.syncMetadata.primaryKey as
37 | Array<string>
38 | undefined) || [`id`]
39
40 // Process based on operation type
41 switch (mutation.type) {
42 case `insert`: {
43 const columns = Object.keys(mutation.modified)
44 const values = Object.values(mutation.modified)
45 const placeholders = values.map((_, i) => `$${i + 1}`).join(`, `)
46
47 await tx.unsafe(
48 `INSERT INTO ${tableName} (${columns.join(`, `)}) VALUES (${placeholders})`,
49 values
50 )
51 break
52 }
53
54 case `update`: {
55 // Build SET clause
56 const setColumns = Object.keys(mutation.changes)
57 const setValues = Object.values(mutation.changes)
58 const setClause = setColumns
59 .map((col, i) => `${col} = $${i + 1}`)
60 .join(`, `)
61
62 // Build WHERE clause for primary key columns starting after SET values
63 const whereClause = primaryKey
64 .map((column, i) => `${column} = $${i + setValues.length + 1}`)
65 .join(` AND `)
66
67 // Combine all values
68 const allValues = [
69 ...setValues,
70 ...primaryKey.map((k) => mutation.original[k]),
71 ]
72
73 await tx.unsafe(
74 `UPDATE ${tableName}
75 SET ${setClause}
76 WHERE ${whereClause}`,
77 allValues
78 )
79 break
80 }
81
82 case `delete`: {
83 // Build WHERE clause for primary key columns
84 const whereClause = primaryKey
85 .map((column, i) => `${column} = $${i + 1}`)
86 .join(` AND `)
87
88 // Extract primary key values in same order as columns
89 const primaryKeyValues = primaryKey.map((k) => mutation.original[k])
90
91 await tx.unsafe(
92 `DELETE FROM ${tableName}
93 WHERE ${whereClause}`,
94 primaryKeyValues
95 )
96 break
97 }
98
99 default:
100 throw new Error(`Unknown operation type: ${mutation.type}`)
101 }
102 }
103
104 return Number(txid)
105 })
106}