db.js 2.62 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
27
    let dbConfig = (!_.isEmpty(process.env.WIKI_DB_CONNSTR)) ? process.env.WIKI_DB_CONNSTR : {
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 37 38
    switch (WIKI.config.db.type) {
      case 'postgres':
        dbClient = 'pg'
        break
39
      case 'mariadb':
40 41
      case 'mysql':
        dbClient = 'mysql2'
42 43 44 45 46 47 48 49 50

        // 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()
        }
51 52 53 54 55 56
        break
      case 'mssql':
        dbClient = 'mssql'
        break
      case 'sqlite':
        dbClient = 'sqlite3'
57
        dbConfig = { filename: WIKI.config.db.storage }
58 59 60 61 62
        break
      default:
        WIKI.logger.error('Invalid DB Type')
        process.exit(1)
    }
63

64 65 66
    this.knex = Knex({
      client: dbClient,
      useNullAsDefault: true,
67
      asyncStackTraces: WIKI.IS_DEBUG,
68
      connection: dbConfig,
69 70 71 72 73 74 75 76 77 78 79 80 81 82
      pool: {
        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
          }
        }
      },
83
      debug: WIKI.IS_DEBUG
84 85
    })

86
    Objection.Model.knex(this.knex)
87

88
    // Load DB Models
89

90
    const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
91

NGPixel's avatar
NGPixel committed
92 93
    // Set init tasks
    let initTasks = {
94 95 96
      // -> Migrate DB Schemas
      async syncSchemas() {
        return self.knex.migrate.latest({
Nicolas Giard's avatar
Nicolas Giard committed
97 98
          tableName: 'migrations',
          migrationSource
NGPixel's avatar
NGPixel committed
99 100 101 102
        })
      }
    }

103
    let initTasksQueue = (WIKI.IS_MASTER) ? [
104
      initTasks.syncSchemas
NGPixel's avatar
NGPixel committed
105
    ] : [
106
      () => { return Promise.resolve() }
NGPixel's avatar
NGPixel committed
107 108 109 110
    ]

    // Perform init tasks

111
    this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
112

113 114 115 116
    return {
      ...this,
      ...models
    }
117 118
  }
}