-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsetup.js
73 lines (61 loc) · 1.8 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
const fsp = require('node:fs').promises;
const path = require('node:path');
const pg = require('pg');
const metasql = require('metasql');
const POSTGRES = {
host: '127.0.0.1',
port: 5432,
database: 'postgres',
user: 'postgres',
password: 'postgres',
};
const APPLICATION = {
host: '127.0.0.1',
port: 5432,
database: 'application',
user: 'marcus',
password: 'marcus',
};
const DB = path.join(process.cwd(), './db');
const SCHEMAS = path.join(process.cwd(), './schemas');
const read = (name) => fsp.readFile(path.join(DB, name), 'utf8');
const execute = async (client, sql) => {
try {
await client.query(sql);
} catch (err) {
const { message, detail } = err;
console.error(`${sql}\n${message}\n${detail}\n`);
}
};
const notEmpty = (s) => s.trim() !== '';
const executeFile = async (client, name) => {
console.log(`Execute file: ${name}`);
const sql = await read(name);
const commands = sql.split(';\n').filter(notEmpty);
for (const command of commands) {
await execute(client, command);
}
};
(async () => {
await metasql.create(SCHEMAS, DB);
const databaseFile = path.join(DB, 'database.sql');
const structureFile = path.join(DB, 'structure.sql');
await fsp.rename(databaseFile, structureFile);
console.log('Generate typings domain.d.ts');
const typesFile = path.join(DB, 'database.d.ts');
const domainTypes = path.join(DB, 'domain.d.ts');
await fsp.rename(typesFile, domainTypes);
const inst = new pg.Client(POSTGRES);
await inst.connect();
await executeFile(inst, 'install.sql');
await inst.end();
const db = new pg.Client(APPLICATION);
await db.connect();
await executeFile(db, 'structure.sql');
await executeFile(db, 'data.sql');
await db.end();
console.log('Environment is ready');
})().catch((err) => {
console.error(err);
});