2017-07-23 03:56:46 +00:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
/* global wiki */
|
|
|
|
|
|
|
|
const fs = require('fs')
|
|
|
|
const path = require('path')
|
|
|
|
const _ = require('lodash')
|
2017-07-29 21:33:08 +00:00
|
|
|
const Promise = require('bluebird')
|
2017-07-23 03:56:46 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* PostgreSQL DB module
|
|
|
|
*/
|
|
|
|
module.exports = {
|
|
|
|
|
|
|
|
Sequelize: require('sequelize'),
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initialize DB
|
|
|
|
*
|
|
|
|
* @return {Object} DB instance
|
|
|
|
*/
|
|
|
|
init() {
|
|
|
|
let self = this
|
|
|
|
|
|
|
|
let dbModelsPath = path.join(wiki.SERVERPATH, 'models')
|
|
|
|
|
|
|
|
// Define Sequelize instance
|
|
|
|
|
|
|
|
self.inst = new self.Sequelize(wiki.config.db.db, wiki.config.db.user, wiki.config.db.pass, {
|
|
|
|
host: wiki.config.db.host,
|
|
|
|
port: wiki.config.db.port,
|
|
|
|
dialect: 'postgres',
|
|
|
|
pool: {
|
|
|
|
max: 10,
|
|
|
|
min: 0,
|
|
|
|
idle: 10000
|
2017-07-29 21:33:08 +00:00
|
|
|
},
|
|
|
|
logging: false
|
2017-07-23 03:56:46 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// Attempt to connect and authenticate to DB
|
|
|
|
|
|
|
|
self.inst.authenticate().then(() => {
|
2017-07-30 04:04:57 +00:00
|
|
|
wiki.logger.info('Database (PostgreSQL) connection: OK')
|
2017-07-23 03:56:46 +00:00
|
|
|
}).catch(err => {
|
|
|
|
wiki.logger.error('Failed to connect to MongoDB instance.')
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
|
|
|
|
// Load DB Models
|
|
|
|
|
|
|
|
fs
|
|
|
|
.readdirSync(dbModelsPath)
|
|
|
|
.filter(function (file) {
|
|
|
|
return (file.indexOf('.') !== 0 && file.indexOf('_') !== 0)
|
|
|
|
})
|
|
|
|
.forEach(function (file) {
|
|
|
|
let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
|
|
|
|
self[modelName] = self.inst.import(path.join(dbModelsPath, file))
|
|
|
|
})
|
|
|
|
|
|
|
|
// Associate DB Models
|
|
|
|
|
|
|
|
require(path.join(dbModelsPath, '_relations.js'))(self)
|
|
|
|
|
2017-08-03 03:47:11 +00:00
|
|
|
// Set init tasks
|
|
|
|
|
|
|
|
let initTasks = {
|
|
|
|
// -> Sync DB Schemas
|
|
|
|
syncSchemas() {
|
|
|
|
return self.inst.sync({
|
|
|
|
force: false,
|
|
|
|
logging: false
|
|
|
|
})
|
|
|
|
},
|
|
|
|
// -> Set Connection App Name
|
|
|
|
setAppName() {
|
|
|
|
return self.inst.query(`set application_name = 'Wiki.js'`, { raw: true })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let initTasksQueue = (wiki.IS_MASTER) ? [
|
|
|
|
initTasks.syncSchemas,
|
|
|
|
initTasks.setAppName
|
|
|
|
] : [
|
|
|
|
initTasks.setAppName
|
|
|
|
]
|
|
|
|
|
|
|
|
// Perform init tasks
|
|
|
|
|
|
|
|
self.onReady = Promise.each(initTasksQueue, t => t())
|
2017-07-23 03:56:46 +00:00
|
|
|
|
|
|
|
return self
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|