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.

108 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 'mariadb':
  34. case 'mysql':
  35. dbClient = 'mysql2'
  36. break
  37. case 'mssql':
  38. dbClient = 'mssql'
  39. break
  40. case 'sqlite':
  41. dbClient = 'sqlite3'
  42. dbConfig = { filename: WIKI.config.db.storage }
  43. break
  44. default:
  45. WIKI.logger.error('Invalid DB Type')
  46. process.exit(1)
  47. }
  48. this.knex = Knex({
  49. client: dbClient,
  50. useNullAsDefault: true,
  51. asyncStackTraces: WIKI.IS_DEBUG,
  52. connection: dbConfig,
  53. pool: {
  54. async afterCreate(conn, done) {
  55. // -> Set Connection App Name
  56. switch (WIKI.config.db.type) {
  57. case 'postgres':
  58. await conn.query(`set application_name = 'Wiki.js'`)
  59. done()
  60. break
  61. default:
  62. done()
  63. break
  64. }
  65. }
  66. },
  67. debug: WIKI.IS_DEBUG
  68. })
  69. Objection.Model.knex(this.knex)
  70. // Load DB Models
  71. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  72. // Set init tasks
  73. let initTasks = {
  74. // -> Migrate DB Schemas
  75. async syncSchemas() {
  76. return self.knex.migrate.latest({
  77. directory: path.join(WIKI.SERVERPATH, 'db/migrations'),
  78. tableName: 'migrations'
  79. })
  80. }
  81. }
  82. let initTasksQueue = (WIKI.IS_MASTER) ? [
  83. initTasks.syncSchemas
  84. ] : [
  85. () => { return Promise.resolve() }
  86. ]
  87. // Perform init tasks
  88. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  89. return {
  90. ...this,
  91. ...models
  92. }
  93. }
  94. }