twitch-bot/bin/dbTool.js
2018-02-21 14:14:31 +08:00

69 lines
2.1 KiB
JavaScript

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)
})