-
Notifications
You must be signed in to change notification settings - Fork 24
/
setup.js
57 lines (45 loc) · 1.27 KB
/
setup.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
require('dotenv').config();
const fs = require('fs');
const util = require('util');
const { Client } = require('pg');
const connectionString = process.env.DATABASE_URL;
const readFileAsync = util.promisify(fs.readFile);
async function query(q) {
const client = new Client({ connectionString });
await client.connect();
try {
const result = await client.query(q);
const { rows } = result;
return rows;
} catch (err) {
throw err;
} finally {
await client.end();
}
}
async function main() {
console.info(`Set upp gagnagrunn á ${connectionString}`);
// droppa töflu ef til
await query('DROP TABLE IF EXISTS students');
console.info('Töflu eytt');
// búa til töflu út frá skema
try {
const createTable = await readFileAsync('./schema.sql');
await query(createTable.toString('utf8'));
console.info('Tafla búin til');
} catch (e) {
console.error('Villa við að búa til töflu:', e.message);
return;
}
// bæta færslum við töflu
try {
const insert = await readFileAsync('./insert.sql');
await query(insert.toString('utf8'));
console.info('Gögnum bætt við');
} catch (e) {
console.error('Villa við að bæta gögnum við:', e.message);
}
}
main().catch((err) => {
console.error(err);
});