-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathapply.ts
160 lines (147 loc) · 4.26 KB
/
apply.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import { ChangeMessage } from '@electric-sql/client'
import type { PGliteInterface, Transaction } from '@electric-sql/pglite'
import type { MapColumns, InsertChangeMessage } from './types'
export interface ApplyMessageToTableOptions {
pg: PGliteInterface | Transaction
table: string
schema?: string
message: ChangeMessage<any>
mapColumns?: MapColumns
primaryKey: string[]
debug: boolean
}
export async function applyMessageToTable({
pg,
table,
schema = 'public',
message,
mapColumns,
primaryKey,
debug,
}: ApplyMessageToTableOptions) {
const data = mapColumns ? doMapColumns(mapColumns, message) : message.value
switch (message.headers.operation) {
case 'insert': {
if (debug) console.log('inserting', data)
const columns = Object.keys(data)
return await pg.query(
`
INSERT INTO "${schema}"."${table}"
(${columns.map((s) => '"' + s + '"').join(', ')})
VALUES
(${columns.map((_v, i) => '$' + (i + 1)).join(', ')})
`,
columns.map((column) => data[column]),
)
}
case 'update': {
if (debug) console.log('updating', data)
const columns = Object.keys(data).filter(
// we don't update the primary key, they are used to identify the row
(column) => !primaryKey.includes(column),
)
if (columns.length === 0) return // nothing to update
return await pg.query(
`
UPDATE "${schema}"."${table}"
SET ${columns
.map((column, i) => '"' + column + '" = $' + (i + 1))
.join(', ')}
WHERE ${primaryKey
.map(
(column, i) =>
'"' + column + '" = $' + (columns.length + i + 1),
)
.join(' AND ')}
`,
[
...columns.map((column) => data[column]),
...primaryKey.map((column) => data[column]),
],
)
}
case 'delete': {
if (debug) console.log('deleting', data)
return await pg.query(
`
DELETE FROM "${schema}"."${table}"
WHERE ${primaryKey
.map((column, i) => '"' + column + '" = $' + (i + 1))
.join(' AND ')}
`,
[...primaryKey.map((column) => data[column])],
)
}
}
}
export interface ApplyMessagesToTableWithCopyOptions {
pg: PGliteInterface | Transaction
table: string
schema?: string
messages: InsertChangeMessage[]
mapColumns?: MapColumns
primaryKey: string[]
debug: boolean
}
export async function applyMessagesToTableWithCopy({
pg,
table,
schema = 'public',
messages,
mapColumns,
debug,
}: ApplyMessagesToTableWithCopyOptions) {
if (debug) console.log('applying messages with COPY')
// Map the messages to the data to be inserted
const data: Record<string, any>[] = messages.map((message) =>
mapColumns ? doMapColumns(mapColumns, message) : message.value,
)
// Get column names from the first message
const columns = Object.keys(data[0])
// Create CSV data
const csvData = data
.map((message) => {
return columns
.map((column) => {
const value = message[column]
// Escape double quotes and wrap in quotes if necessary
if (
typeof value === 'string' &&
(value.includes(',') || value.includes('"') || value.includes('\n'))
) {
return `"${value.replace(/"/g, '""')}"`
}
return value === null ? '\\N' : value
})
.join(',')
})
.join('\n')
const csvBlob = new Blob([csvData], { type: 'text/csv' })
// Perform COPY FROM
await pg.query(
`
COPY "${schema}"."${table}" (${columns.map((c) => `"${c}"`).join(', ')})
FROM '/dev/blob'
WITH (FORMAT csv, NULL '\\N')
`,
[],
{
blob: csvBlob,
},
)
if (debug) console.log(`Inserted ${messages.length} rows using COPY`)
}
function doMapColumns(
mapColumns: MapColumns,
message: ChangeMessage<any>,
): Record<string, any> {
if (typeof mapColumns === 'function') {
return mapColumns(message)
} else {
const mappedColumns: Record<string, any> = {}
for (const [key, value] of Object.entries(mapColumns)) {
mappedColumns[key] = message.value[value]
}
return mappedColumns
}
}