-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
76 lines (67 loc) · 2.43 KB
/
util.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
import * as fs from 'fs';
import { provider, tableland } from "./tableland.js";
/*
This only works if and only if the last two columns are created_at and updated_at because
it will truncate that before finding the difference between the Tableland data and the data
in the script.
*/
export const insertDifference = async (tableName, previousRows, columns, nextRows, dryRun = false) => {
if (nextRows.length < previousRows.length) {
console.log("No new rows. This expects only new rows to be appended. Do not go back to edit the old ones.")
return
}
const prevRowsWithoutTimestamps = previousRows.map(prevRow => prevRow.slice(0, -2));
const newRows = nextRows.filter((values) => !prevRowsWithoutTimestamps.find(([_id, ...previousValues]) => previousValues.join(',') === values.join(',')))
if (newRows.length === 0) {
console.log('There are no new rows to insert')
return
}
const now = Date.now();
const queries = newRows.map((values) =>
buildInsertQuery(
tableName,
[...columns, 'created_at', 'updated_at'],
[...values, now, now]
))
console.log("Queries to be run...")
queries.forEach((query) => console.log("\t", query))
if (dryRun) return
try {
console.log("Inserting data into Tableland...")
const result = await tableland.write(queries.join(' '));
console.log("Successfully inserted data! Transaction hash:", result.hash)
return result;
} catch (error) {
console.log("Error inserting data for\n\t", tableName, "\n\t", error.message)
}
}
const buildInsertQuery = (tableName, columns, values) => {
if (columns.length !== values.length) {
throw new Error('The number of items in columns and values have to be the same.')
}
const sqlValues = values.map(value => {
if (value === null) {
return 'NULL'
}
switch (typeof value) {
case 'number':
return `${value}`;
default:
return `'${value}'`;
}
})
return `INSERT INTO ${tableName} (${columns.join(', ')}) VALUES (${sqlValues.join(', ')});`
}
export const getTableArtifact = async (tablePrefix) => {
try {
const { name: chainName } = await provider.getNetwork();
const artifactFilePath = `./artifacts/${chainName}/${tablePrefix}.json`;
const rawData = fs.readFileSync(artifactFilePath);
return JSON.parse(rawData);
} catch (error) {
if (error.code === 'ENOENT') {
console.log("File does not exist", artifactFilePath)
}
throw error;
}
}