2
0

db.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. * PostgreSQL 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. const 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. filename: WIKI.config.db.storage
  29. }
  30. switch (WIKI.config.db.type) {
  31. case 'postgres':
  32. dbClient = 'pg'
  33. break
  34. case 'mysql':
  35. dbClient = 'mysql2'
  36. break
  37. case 'mssql':
  38. dbClient = 'mssql'
  39. break
  40. case 'sqlite':
  41. dbClient = 'sqlite3'
  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. debug: WIKI.IS_DEBUG
  52. })
  53. Objection.Model.knex(this.knex)
  54. // Load DB Models
  55. const models = autoload(path.join(WIKI.SERVERPATH, 'db/models'))
  56. // Set init tasks
  57. let initTasks = {
  58. // -> Migrate DB Schemas
  59. async syncSchemas() {
  60. return self.knex.migrate.latest({
  61. directory: path.join(WIKI.SERVERPATH, 'db/migrations'),
  62. tableName: 'migrations'
  63. })
  64. },
  65. // -> Set Connection App Name
  66. async setAppName() {
  67. switch (WIKI.config.db.type) {
  68. case 'postgres':
  69. return self.knex.raw(`set application_name = 'Wiki.js'`)
  70. }
  71. }
  72. }
  73. let initTasksQueue = (WIKI.IS_MASTER) ? [
  74. initTasks.syncSchemas,
  75. initTasks.setAppName
  76. ] : [
  77. initTasks.setAppName
  78. ]
  79. // Perform init tasks
  80. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  81. return {
  82. ...this,
  83. ...models
  84. }
  85. }
  86. }