-
Notifications
You must be signed in to change notification settings - Fork 0
/
incremental_deduped_sync_pg_to_pg.js
440 lines (415 loc) · 12.5 KB
/
incremental_deduped_sync_pg_to_pg.js
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
require("dotenv").config();
const fs = require("fs");
const cp = require("child_process");
const path = require("path");
const tablesConfig = require("./tables-config.json");
const axios = require("axios");
const srcKnex = require("knex")({
client: "pg",
connection: {
host: process.env.SOURCE_HOST,
database: process.env.SOURCE_DB,
user: process.env.SOURCE_USERNAME,
password: process.env.SOURCE_PASSWORD,
port: process.env.SOURCE_PORT,
},
searchPath: process.env.SOURCE_SCHEMA,
});
const destKnex = require("knex")({
client: "pg",
connection: {
host: process.env.DEST_HOST,
database: process.env.DEST_DB,
user: process.env.DEST_USERNAME,
password: process.env.DEST_PASSWORD,
port: process.env.DEST_PORT,
},
searchPath: process.env.DEST_SCHEMA,
});
async function main() {
log(`Script starting. found ${tablesConfig.length} tables to sync`);
try {
const summary = [];
for (let i = 0; i < tablesConfig.length; i++) {
log(`Starting replication for ${tablesConfig[i].name}`);
const { syncType, rowCount } = await initReplicationForTable(
tablesConfig[i]
);
summary.push({
name: tablesConfig[i].name,
sync_type: syncType,
row_count: syncType === "incremental" ? rowCount : null,
});
log(`Replication done for ${tablesConfig[i].name}`);
log(`Remaining tables to sync : ${tablesConfig.length - (i + 1)}`);
}
await webhookNotify(
`Pipeline ${
process.env.PIPELINE_NAME
} succeeded. Summary: ${tablesConfig.length} || ${summary.map(i => `${i.name}-${i.sync_type}-${i.sync_type==='incremental' ? i.row_count : 'NA'}`).join(' || ')}`
);
log(`Script completed`);
} catch (error) {
log(`Main function error ${error.stack}`, true);
await webhookNotify(`Pipeline ${process.env.PIPELINE_NAME} failed`);
} finally {
process.exit(0);
}
}
const webhookNotify = async (message) => {
try {
log(`Notifying webhook`);
await axios.post(process.env.WEBHOOK_URL, {
message: message,
});
} catch (error) {
log(`WebhookNotify function error ${error.stack}`, true);
}
};
const log = (msg, isError = false) => {
console.log(
`${new Date().toISOString()} [${isError ? "ERROR" : "INFO"}] ${msg}...`
);
};
const initReplicationForTable = async (table) => {
try {
const tableName = table.name;
const replicationKeyField = table.replication_key;
const uniqueCols = table.unique_cols;
let syncType = "";
let rowCount = 0;
let isResetNeededForTable = !(await areSchemasSameForTable(tableName));
if (isResetNeededForTable) {
await resetDestinationSchemaForTable(tableName);
await doPgDumpRestoreForTable(tableName);
await setReplicationKeyStateAfterInitialSync(
tableName,
replicationKeyField
);
syncType = "initial";
} else {
const replicationKeyState = loadReplicationKeyStateFromFile(tableName);
const { newReplicationKeyState, totalReplicatedRows } =
await performIncrementalReplicationForTable(
tableName,
replicationKeyField,
replicationKeyState
);
await deduplicateRowsForTableInDestination(uniqueCols, tableName);
if (newReplicationKeyState) {
saveReplicationKeyStateToFile(newReplicationKeyState, tableName);
}
syncType = "incremental";
rowCount = totalReplicatedRows;
}
return { syncType, rowCount };
} catch (error) {
log(`InitReplicationForTable function error ${error.stack}`, true);
throw error;
}
};
async function setReplicationKeyStateAfterInitialSync(
tableName,
replicationKeyField
) {
try {
log(`Setting replication key state after initial sync`);
const row = await destKnex
.withSchema(`${process.env.DEST_SCHEMA}`)
.table(tableName)
.max(replicationKeyField);
saveReplicationKeyStateToFile(
row.length && row[0].max
? row[0].max.toISOString()
: new Date(0).toISOString(),
tableName
);
} catch (error) {
log(
`SetReplicationKeyStateAfterInitialSync function error ${error.stack}`,
true
);
throw error;
}
}
async function doPgDumpRestoreForTable(tableName) {
try {
log(`Doing pgdump-restore`);
const pgDump = cp.spawnSync(
"pg_dump",
[
"-h",
process.env.SOURCE_HOST,
"-p",
process.env.SOURCE_PORT,
"-U",
process.env.SOURCE_USERNAME,
process.env.SOURCE_DB,
"-f",
"./dump.sql",
"--data-only",
"--table",
`${process.env.SOURCE_SCHEMA}.${tableName}`,
],
{
env: { ...process.env, PGPASSWORD: process.env.SOURCE_PASSWORD },
}
);
log(`Pgdump stdout ${pgDump.stdout}`);
log(`Pgdump stderr ${pgDump.stderr}`);
const sedOptions =
process.platform === "linux"
? ["-i", "-e", "/setval/d", "./dump.sql"]
: process.platform === "darwin"
? ["-i", "", "/setval/d", "./dump.sql"]
: null;
if (!sedOptions) throw new Error("sed options is null");
const sed = cp.spawnSync("sed", sedOptions);
log(`Sed stdout ${sed.stdout}`);
log(`Sed stderr ${sed.stderr}`);
const psql = cp.spawnSync(
"psql",
[
"-h",
process.env.DEST_HOST,
"-U",
process.env.DEST_USERNAME,
"-p",
process.env.DEST_PORT,
"-d",
process.env.DEST_DB,
"-f",
"./dump.sql",
],
{
env: { ...process.env, PGPASSWORD: process.env.DEST_PASSWORD },
}
);
log(`Psql stdout ${psql.stdout}`);
log(`Psql stderr ${psql.stderr}`);
} catch (error) {
log(`DoPgDumpRestoreForTable function error ${error.stack}`, true);
throw error;
}
}
async function deduplicateRowsForTableInDestination(uniqueCols, tableName) {
try {
log("Deduplicating rows in destination final using destination staging");
const whereClause = uniqueCols
.map(
(key) =>
`${process.env.DEST_SCHEMA}."${tableName}".${key} = ${process.env.DEST_SCHEMA}."${tableName}_stg".${key}`
)
.join(" AND ");
await destKnex.raw(`
DELETE FROM ${process.env.DEST_SCHEMA}."${tableName}"
WHERE EXISTS (
SELECT 1
FROM ${process.env.DEST_SCHEMA}."${tableName}_stg"
WHERE ${whereClause}
)
`);
await destKnex.raw(`
INSERT INTO ${process.env.DEST_SCHEMA}."${tableName}"
SELECT *
FROM ${process.env.DEST_SCHEMA}."${tableName}_stg"
`);
await destKnex.raw(`
DELETE FROM ${process.env.DEST_SCHEMA}."${tableName}_stg"
`);
} catch (error) {
log(
`DeduplicateRowsForTableInDestination function error ${error.stack}`,
true
);
throw error;
}
}
function saveReplicationKeyStateToFile(replicationKey, tableName) {
try {
log("Saving replication key state to file");
let temp = new Date(replicationKey);
temp = new Date(temp.getTime() + 1);
temp = temp.toISOString();
fs.writeFileSync(
path.resolve(__dirname, `./sync-state/${tableName}.txt`),
temp,
"utf8"
);
} catch (error) {
log(`SaveReplicationKeyStateToFile function error ${error.stack}`, true);
throw error;
}
}
async function performIncrementalReplicationForTable(
tableName,
replicationKeyField,
replicationKeyState
) {
try {
log("Performing incremental replication for table");
await destKnex.raw(`
DELETE FROM ${process.env.DEST_SCHEMA}."${tableName}_stg"
`);
let offset = 0;
let data, lastRow;
const batchSize = 1000;
let batchNo = 0;
let totalReplicatedRows = 0;
while (true) {
data = await srcKnex
.withSchema(process.env.SOURCE_SCHEMA)
.table(tableName)
.where(replicationKeyField, ">=", replicationKeyState)
.orderBy(replicationKeyField)
.offset(offset)
.limit(batchSize)
.select();
if (!data.length) {
log(`All modified rows replicated to destination staging`);
break;
}
// const serializedData = data.map((row) => {
// return Object.entries(row).reduce((acc, [key, value]) => {
// if (typeof value === "object" && value !== null) {
// if (value instanceof Date) {
// acc[key] = value.toISOString();
// }
// if (Array.isArray(value)) {
// acc[key] = value;
// } else {
// acc[key] = JSON.stringify(value);
// }
// } else {
// acc[key] = value;
// }
// return acc;
// }, {});
// });
serializedData = data;
await destKnex
.withSchema(process.env.DEST_SCHEMA)
.table(`${tableName}_stg`)
.insert(serializedData);
offset += batchSize;
lastRow = data[data.length - 1];
batchNo++;
log(`Replicated ${data.length} rows in batch number ${batchNo}`);
totalReplicatedRows += data.length;
}
return {
newReplicationKeyState: lastRow
? lastRow[replicationKeyField].toISOString()
: null,
totalReplicatedRows,
};
} catch (error) {
log(
`PerformIncrementalReplicationForTable function error ${error.stack}`,
true
);
throw error;
}
}
function loadReplicationKeyStateFromFile(tableName) {
try {
log("Loading replication key state from file");
const replicationKey = fs.readFileSync(
path.resolve(__dirname, `./sync-state/${tableName}.txt`),
"utf8"
);
return new Date(replicationKey);
} catch (error) {
log(`LoadReplicationKeyStateFromFile function error ${error.stack}`);
throw error;
}
}
const resetDestinationSchemaForTable = async (tableName) => {
try {
log(`Resetting destination table schema`);
const tableExists = await destKnex.schema
.withSchema(process.env.DEST_SCHEMA)
.hasTable(tableName);
const tableExistsStg = await destKnex.schema
.withSchema(process.env.DEST_SCHEMA)
.hasTable(`${tableName}_stg`);
if (tableExists) {
await destKnex.schema
.withSchema(process.env.DEST_SCHEMA)
.dropTable(tableName);
}
if (tableExistsStg) {
await destKnex.schema
.withSchema(process.env.DEST_SCHEMA)
.dropTable(`${tableName}_stg`);
}
const srcColumnInfoQuery = `
SELECT column_name, data_type, is_nullable, udt_name
FROM information_schema.columns
WHERE table_schema = '${process.env.SOURCE_SCHEMA}'
AND table_name = '${tableName}';
`;
const srcColumnInfo = await srcKnex.raw(srcColumnInfoQuery);
let queryStg = `CREATE TABLE "${process.env.DEST_SCHEMA}"."${tableName}_stg" (`;
let query = `CREATE TABLE "${process.env.DEST_SCHEMA}"."${tableName}" (`;
const columns = srcColumnInfo.rows.map((columnData) => {
const { column_name, data_type, is_nullable, udt_name } = columnData;
let columnDefinition = `"${column_name}" ${
data_type === "ARRAY"
? `${udt_name.replace("_", "")}[]`
: data_type === "USER-DEFINED"
? "text"
: data_type
}`;
if (is_nullable === "NO") {
columnDefinition += " NOT NULL";
}
return columnDefinition;
});
query += columns.join(", ");
query += ")";
queryStg += columns.join(", ");
queryStg += ")";
await destKnex.raw(query);
await destKnex.raw(queryStg);
} catch (error) {
log(`ResetDestinationSchemaForTable function error ${error.stack}`, true);
throw error;
}
};
const areSchemasSameForTable = async (tableName) => {
log(`Checking if schemas are equal`);
try {
const srcSchema = await srcKnex
.withSchema(process.env.SOURCE_SCHEMA)
.table(tableName)
.columnInfo();
const destStagingSchema = await destKnex
.withSchema(process.env.DEST_SCHEMA)
.table(`${tableName}_stg`)
.columnInfo();
const srcColumns = Object.keys(srcSchema);
const destStgCols = Object.keys(destStagingSchema);
if (srcColumns.length !== destStgCols.length) {
return false;
}
for (let columnName of srcColumns) {
if (
!destStagingSchema[columnName] ||
(srcSchema[columnName].type !== destStagingSchema[columnName].type &&
srcSchema[columnName].type !== "USER-DEFINED" &&
destStagingSchema[columnName].type !== "text")
) {
console.log(
`${srcSchema[columnName].type} ${destStagingSchema[columnName].type}`
);
return false;
}
}
return true;
} catch (error) {
log(`AreSchemasSameForTable function error ${error.stack}`, true);
throw error;
}
};
main();