2018-06-26 16:59:53 +00:00
/* eslint-disable no-unused-expressions */
2018-07-13 05:30:54 +00:00
require ( 'module-alias/register' )
2018-06-26 16:59:53 +00:00
const pg = require ( 'pg' )
2018-07-13 05:30:54 +00:00
const config = require ( '@config/index' )
2018-06-26 16:59:53 +00:00
const path = require ( 'path' )
const fs = require ( 'fs' )
const dbVersion = require ( './dbVersion.json' )
const versions = dbVersion . 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 . dbname
} )
// auto start function
! ( async function ( ) {
let flag = false
await client . connect ( )
await client . query ( ` select now() ` )
console . log ( 'Database Connected' )
if ( process . env [ 'NODE_ENV' ] === 'test' ) {
if ( 'test' in dbVersion && Array . isArray ( dbVersion . test ) ) {
for ( let i in dbVersion . test ) {
let qstr = fs . readFileSync ( path . resolve ( schemaPath , dbVersion . test [ i ] . file ) ) . toString ( )
await client . query ( qstr )
}
}
}
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 )
} )