You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.3 KiB

  1. const _ = require('lodash')
  2. const autoload = require('auto-load')
  3. const path = require('path')
  4. const Promise = require('bluebird')
  5. const Knex = require('knex')
  6. const Objection = require('objection')
  7. /* global WIKI */
  8. /**
  9. * ORM DB module
  10. */
  11. module.exports = {
  12. Objection,
  13. knex: null,
  14. /**
  15. * Initialize DB
  16. *
  17. * @return {Object} DB instance
  18. */
  19. init() {
  20. let self = this
  21. let dbClient = null
  22. let dbConfig = (!_.isEmpty(process.env.WIKI_DB_CONNSTR)) ? process.env.WIKI_DB_CONNSTR : {
  23. host: WIKI.config.db.host,
  24. user: WIKI.config.db.user,
  25. password: WIKI.config.db.pass,
  26. database: WIKI.config.db.db,
  27. port: WIKI.config.db.port
  28. }
  29. switch (WIKI.config.db.type) {
  30. case 'postgres':
  31. dbClient = 'pg'
  32. break
  33. case 'mysql':
  34. dbClient = 'mysql2'
  35. break
  36. case 'mssql':
  37. dbClient = 'mssql'
  38. break
  39. case 'sqlite':
  40. dbClient = 'sqlite3'
  41. dbConfig = { filename: WIKI.config.db.storage }
  42. break
  43. default:
  44. WIKI.logger.error('Invalid DB Type')
  45. process.exit(1)
  46. }
  47. this.knex = Knex({
  48. client: dbClient,
  49. useNullAsDefault: true,
  50. connection: dbConfig,
  51. pool: {
  52. async afterCreate(conn, done) {
  53. // -> Set Connection App Name
  54. switch (WIKI.config.db.type) {
  55. case 'postgres':
  56. await conn.query(`set application_name = 'Wiki.js'`)
  57. done()
  58. break
  59. default:
  60. done()
  61. break
  62. }
  63. }
  64. },
  65. debug: WIKI.IS_DEBUG
  66. })
  67. Objection.Model.knex(this.knex)
  68. // Load DB Models
  69. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  70. // Set init tasks
  71. let initTasks = {
  72. // -> Migrate DB Schemas
  73. async syncSchemas() {
  74. return self.knex.migrate.latest({
  75. directory: path.join(WIKI.SERVERPATH, 'db/migrations'),
  76. tableName: 'migrations'
  77. })
  78. }
  79. }
  80. let initTasksQueue = (WIKI.IS_MASTER) ? [
  81. initTasks.syncSchemas
  82. ] : [
  83. () => { return Promise.resolve() }
  84. ]
  85. // Perform init tasks
  86. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  87. return {
  88. ...this,
  89. ...models
  90. }
  91. }
  92. }