add dbtool

This commit is contained in:
Jay 2018-02-21 14:14:31 +08:00
parent efbbed07ed
commit 0270978b12
4 changed files with 80 additions and 1 deletions

69
bin/dbTool.js Normal file
View File

@ -0,0 +1,69 @@
const pg = require('pg')
const config = require('../config')
const path = require('path')
const fs = require('fs')
const versions = require('./dbVersion.json').versions
const schemaPath = path.resolve(__dirname, '../schema')
if (!Array.isArray(versions) || versions.length === 0) {
throw new Error('Schema version empty')
}
const client = new pg.Client({
host: config.database.host,
port: config.database.port,
user: config.database.user,
password: config.database.pass,
database: config.database.db_name
})
// auto start function
;
!(async function () {
let flag = false
await client.connect()
await client.query(`select now()`)
console.log('Database Connected')
let version = -1
let checkTable = await client.query(`select exists(select 1 from "information_schema"."tables" where "table_schema" = $1 and "table_name" = $2) as exists`, ['public', 'version_ctrl'])
if (checkTable.rows.length > 0 && checkTable.rows[0].exists === true) {
let checkVersion = await client.query(`select max(version) as version from "public"."version_ctrl"`)
if (checkVersion.rows.length > 0 && 'version' in checkVersion.rows[0] && isFinite(checkVersion.rows[0].version)) {
version = checkVersion.rows[0].version
}
}
let runVer = versions.filter(t => t.version > version).sort((a, b) => a.version - b.version)
if (runVer.length === 0) return
await client.query('begin')
try {
// write table query
for (let i in runVer) {
let qstr = fs.readFileSync(path.resolve(schemaPath, runVer[i].file)).toString()
await client.query(qstr)
let query = `insert into "public"."version_ctrl" ("version", "ctime", "querystr") values ($1, now(), $2)`
let param = [runVer[i].version, qstr]
await client.query(query, param)
}
await client.query('commit')
} catch (err) {
flag = true
console.log(err)
await client.query('rollback')
}
await client.end()
if (flag) throw new Error('Not Finish')
})().then(() => {
console.log('Finish')
process.exit(0)
}).catch(err => {
console.error(err)
process.exit(1)
})

5
bin/dbVersion.json Normal file
View File

@ -0,0 +1,5 @@
{
"versions":[
{"file": "main.sql", "version": 1}
]
}

View File

@ -90,6 +90,9 @@ r.get('/twitch/oauth', async (c, n) => {
resolve(null)
return
}
try {
body = JSON.parse(body)
}catch (err){}
resolve(body)
})
})

View File

@ -1 +1,3 @@
<%- JSON.stringify(data) %>
<pre>
<%- JSON.stringify(data, null, 2) %>
</pre>