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.

120 lines
2.7 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. const migrationSource = require('../db/migrator-source')
  8. /* global WIKI */
  9. /**
  10. * ORM DB module
  11. */
  12. module.exports = {
  13. Objection,
  14. knex: null,
  15. /**
  16. * Initialize DB
  17. *
  18. * @return {Object} DB instance
  19. */
  20. init() {
  21. let self = this
  22. let dbClient = null
  23. let dbConfig = (!_.isEmpty(process.env.DATABASE_URL)) ? process.env.DATABASE_URL : {
  24. host: WIKI.config.db.host,
  25. user: WIKI.config.db.user,
  26. password: WIKI.config.db.pass,
  27. database: WIKI.config.db.db,
  28. port: WIKI.config.db.port,
  29. ssl: !_.isNil(WIKI.config.db.ssl) && WIKI.config.db.ssl !== false
  30. }
  31. switch (WIKI.config.db.type) {
  32. case 'postgres':
  33. dbClient = 'pg'
  34. break
  35. case 'mariadb':
  36. case 'mysql':
  37. dbClient = 'mysql2'
  38. // Fix mysql boolean handling...
  39. dbConfig.typeCast = (field, next) => {
  40. if (field.type === 'TINY' && field.length === 1) {
  41. let value = field.string()
  42. return value ? (value === '1') : null
  43. }
  44. return next()
  45. }
  46. break
  47. case 'mssql':
  48. dbClient = 'mssql'
  49. break
  50. case 'sqlite':
  51. dbClient = 'sqlite3'
  52. dbConfig = { filename: WIKI.config.db.storage }
  53. break
  54. default:
  55. WIKI.logger.error('Invalid DB Type')
  56. process.exit(1)
  57. }
  58. this.knex = Knex({
  59. client: dbClient,
  60. useNullAsDefault: true,
  61. asyncStackTraces: WIKI.IS_DEBUG,
  62. connection: dbConfig,
  63. pool: {
  64. ...WIKI.config.pool,
  65. async afterCreate(conn, done) {
  66. // -> Set Connection App Name
  67. switch (WIKI.config.db.type) {
  68. case 'postgres':
  69. await conn.query(`set application_name = 'Wiki.js'`)
  70. done()
  71. break
  72. default:
  73. done()
  74. break
  75. }
  76. }
  77. },
  78. debug: WIKI.IS_DEBUG
  79. })
  80. Objection.Model.knex(this.knex)
  81. // Load DB Models
  82. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  83. // Set init tasks
  84. let initTasks = {
  85. // -> Migrate DB Schemas
  86. async syncSchemas() {
  87. return self.knex.migrate.latest({
  88. tableName: 'migrations',
  89. migrationSource
  90. })
  91. }
  92. }
  93. let initTasksQueue = (WIKI.IS_MASTER) ? [
  94. initTasks.syncSchemas
  95. ] : [
  96. () => { return Promise.resolve() }
  97. ]
  98. // Perform init tasks
  99. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  100. return {
  101. ...this,
  102. ...models
  103. }
  104. }
  105. }