wikijs-fork/server/core/db.js

121 lines
2.7 KiB
JavaScript
Raw Normal View History

const _ = require('lodash')
const autoload = require('auto-load')
const path = require('path')
2017-07-29 21:33:08 +00:00
const Promise = require('bluebird')
const Knex = require('knex')
const Objection = require('objection')
2019-01-26 23:35:56 +00:00
const migrationSource = require('../db/migrator-source')
/* global WIKI */
/**
* ORM DB module
*/
module.exports = {
Objection,
knex: null,
/**
* Initialize DB
*
* @return {Object} DB instance
*/
init() {
let self = this
let dbClient = null
let dbConfig = (!_.isEmpty(process.env.WIKI_DB_CONNSTR)) ? process.env.WIKI_DB_CONNSTR : {
host: WIKI.config.db.host,
user: WIKI.config.db.user,
password: WIKI.config.db.pass,
database: WIKI.config.db.db,
2019-06-01 04:23:07 +00:00
port: WIKI.config.db.port,
ssl: !_.isNil(WIKI.config.db.ssl) && WIKI.config.db.ssl !== false
}
switch (WIKI.config.db.type) {
case 'postgres':
dbClient = 'pg'
break
2018-09-08 19:49:36 +00:00
case 'mariadb':
case 'mysql':
dbClient = 'mysql2'
// Fix mysql boolean handling...
dbConfig.typeCast = (field, next) => {
if (field.type === 'TINY' && field.length === 1) {
let value = field.string()
return value ? (value === '1') : null
}
return next()
}
break
case 'mssql':
dbClient = 'mssql'
break
case 'sqlite':
dbClient = 'sqlite3'
dbConfig = { filename: WIKI.config.db.storage }
break
default:
WIKI.logger.error('Invalid DB Type')
process.exit(1)
}
this.knex = Knex({
client: dbClient,
useNullAsDefault: true,
2018-09-08 19:49:36 +00:00
asyncStackTraces: WIKI.IS_DEBUG,
connection: dbConfig,
2018-05-28 18:46:55 +00:00
pool: {
...WIKI.config.pool,
2018-05-28 18:46:55 +00:00
async afterCreate(conn, done) {
// -> Set Connection App Name
switch (WIKI.config.db.type) {
case 'postgres':
await conn.query(`set application_name = 'Wiki.js'`)
done()
break
default:
done()
break
}
}
},
debug: WIKI.IS_DEBUG
})
Objection.Model.knex(this.knex)
// Load DB Models
const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
2017-08-03 03:47:11 +00:00
// Set init tasks
let initTasks = {
// -> Migrate DB Schemas
async syncSchemas() {
return self.knex.migrate.latest({
2019-01-26 23:35:56 +00:00
tableName: 'migrations',
migrationSource
2017-08-03 03:47:11 +00:00
})
}
}
let initTasksQueue = (WIKI.IS_MASTER) ? [
2018-05-28 18:46:55 +00:00
initTasks.syncSchemas
2017-08-03 03:47:11 +00:00
] : [
2018-05-28 18:46:55 +00:00
() => { return Promise.resolve() }
2017-08-03 03:47:11 +00:00
]
// Perform init tasks
this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
return {
...this,
...models
}
}
}