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.

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