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.

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