db.js 3.12 KB
Newer Older
1
const _ = require('lodash')
2
const autoload = require('auto-load')
3
const path = require('path')
4
const Promise = require('bluebird')
5 6
const Knex = require('knex')
const Objection = require('objection')
7

Nicolas Giard's avatar
Nicolas Giard committed
8 9
const migrationSource = require('../db/migrator-source')

10
/* global WIKI */
11

12
/**
13
 * ORM DB module
14 15
 */
module.exports = {
16 17
  Objection,
  knex: null,
18 19 20 21 22 23 24 25
  /**
   * Initialize DB
   *
   * @return     {Object}  DB instance
   */
  init() {
    let self = this

26
    let dbClient = null
Nick's avatar
Nick committed
27
    let dbConfig = (!_.isEmpty(process.env.DATABASE_URL)) ? process.env.DATABASE_URL : {
28
      host: WIKI.config.db.host,
29 30 31
      user: WIKI.config.db.user,
      password: WIKI.config.db.pass,
      database: WIKI.config.db.db,
32
      port: WIKI.config.db.port
33
    }
34

35 36
    const dbUseSSL = (WIKI.config.db.ssl === true || WIKI.config.db.ssl === 'true' || WIKI.config.db.ssl === 1 || WIKI.config.db.ssl === '1')

37 38 39
    switch (WIKI.config.db.type) {
      case 'postgres':
        dbClient = 'pg'
40 41 42 43

        if (dbUseSSL && _.isPlainObject(dbConfig)) {
          dbConfig.ssl = true
        }
44
        break
45
      case 'mariadb':
46 47
      case 'mysql':
        dbClient = 'mysql2'
48

49 50 51 52
        if (dbUseSSL && _.isPlainObject(dbConfig)) {
          dbConfig.ssl = true
        }

53 54 55 56 57 58 59 60
        // 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()
        }
61 62 63
        break
      case 'mssql':
        dbClient = 'mssql'
64 65 66 67 68 69 70

        if (_.isPlainObject(dbConfig)) {
          dbConfig.appName = 'Wiki.js'
          if (dbUseSSL) {
            dbConfig.encrypt = true
          }
        }
71 72 73
        break
      case 'sqlite':
        dbClient = 'sqlite3'
74
        dbConfig = { filename: WIKI.config.db.storage }
75 76 77 78 79
        break
      default:
        WIKI.logger.error('Invalid DB Type')
        process.exit(1)
    }
80

81 82 83
    this.knex = Knex({
      client: dbClient,
      useNullAsDefault: true,
84
      asyncStackTraces: WIKI.IS_DEBUG,
85
      connection: dbConfig,
86
      pool: {
87
        ...WIKI.config.pool,
88 89 90 91 92 93 94 95 96 97 98 99 100
        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
          }
        }
      },
101
      debug: WIKI.IS_DEBUG
102 103
    })

104
    Objection.Model.knex(this.knex)
105

106
    // Load DB Models
107

108
    const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
109

NGPixel's avatar
NGPixel committed
110 111
    // Set init tasks
    let initTasks = {
112 113 114
      // -> Migrate DB Schemas
      async syncSchemas() {
        return self.knex.migrate.latest({
Nicolas Giard's avatar
Nicolas Giard committed
115 116
          tableName: 'migrations',
          migrationSource
NGPixel's avatar
NGPixel committed
117 118 119 120
        })
      }
    }

121
    let initTasksQueue = (WIKI.IS_MASTER) ? [
122
      initTasks.syncSchemas
NGPixel's avatar
NGPixel committed
123
    ] : [
124
      () => { return Promise.resolve() }
NGPixel's avatar
NGPixel committed
125 126 127 128
    ]

    // Perform init tasks

129
    this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
130

131 132 133 134
    return {
      ...this,
      ...models
    }
135 136
  }
}