-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdialect-sqlite.js
More file actions
83 lines (74 loc) · 1.83 KB
/
dialect-sqlite.js
File metadata and controls
83 lines (74 loc) · 1.83 KB
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
const sqlite3 = require('better-sqlite3').verbose();
let connection;
function connect(dbname) {
return new Promise((resolve) => {
connection = new sqlite3.Database(dbname, (err) => {
if (err) console.log(err.message);
console.log('db created');
resolve();
});
});
}
function runCommand(sql, args = []) {
return new Promise((resolve) => {
connection.all(sql, args, (err, rows) => {
if (err) throw err;
resolve(rows);
});
});
}
async function tableExists(table) {
const results = await command(`select * from sqlite_master where type='table' and name = '${table}'`);
return results.length > 0;
}
async function configure(newConfig) {
await connect(newConfig.database);
process.on('SIGINT', async () => {
console.log('calling db close');
await connection.close();
});
}
async function close() {
connection.close();
}
async function command(sql, args = []) {
sql = sql.replace(/\$\d/, '?');
return await runCommand(sql, args);
}
async function select(sql, args = []) {
const result = await command(sql, args);
return result;
}
let migration_table = '';
async function getPastMigrations() {
const sql = `select id from ${migration_table}`;
const migrations = await command(sql);
if (migrations.length < 1) {
return [];
}
return migrations.map((r) => Number(r.id));
}
async function createSchema(tablename) {
migration_table = tablename;
const exists = await tableExists(migration_table);
if (!exists) {
const createSql = `
create table ${migration_table} (
id integer primary key,
name text,
up text,
dn text,
run_at date_time default current_timestamp
)
`;
await command(createSql);
}
}
module.exports = {
configure,
command,
select,
createSchema,
getPastMigrations,
close,
};