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.

96 lines
2.0 KiB

  1. 'use strict'
  2. /* global wiki */
  3. const fs = require('fs')
  4. const path = require('path')
  5. const _ = require('lodash')
  6. const Promise = require('bluebird')
  7. /**
  8. * PostgreSQL DB module
  9. */
  10. module.exports = {
  11. Sequelize: require('sequelize'),
  12. /**
  13. * Initialize DB
  14. *
  15. * @return {Object} DB instance
  16. */
  17. init() {
  18. let self = this
  19. let dbModelsPath = path.join(wiki.SERVERPATH, 'models')
  20. // Define Sequelize instance
  21. self.inst = new self.Sequelize(wiki.config.db.db, wiki.config.db.user, wiki.config.db.pass, {
  22. host: wiki.config.db.host,
  23. port: wiki.config.db.port,
  24. dialect: 'postgres',
  25. pool: {
  26. max: 10,
  27. min: 0,
  28. idle: 10000
  29. },
  30. logging: false
  31. })
  32. // Attempt to connect and authenticate to DB
  33. self.inst.authenticate().then(() => {
  34. wiki.logger.info('Database (PostgreSQL) connection: OK')
  35. }).catch(err => {
  36. wiki.logger.error('Failed to connect to MongoDB instance.')
  37. return err
  38. })
  39. // Load DB Models
  40. fs
  41. .readdirSync(dbModelsPath)
  42. .filter(function (file) {
  43. return (file.indexOf('.') !== 0 && file.indexOf('_') !== 0)
  44. })
  45. .forEach(function (file) {
  46. let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
  47. self[modelName] = self.inst.import(path.join(dbModelsPath, file))
  48. })
  49. // Associate DB Models
  50. require(path.join(dbModelsPath, '_relations.js'))(self)
  51. // Set init tasks
  52. let initTasks = {
  53. // -> Sync DB Schemas
  54. syncSchemas() {
  55. return self.inst.sync({
  56. force: false,
  57. logging: false
  58. })
  59. },
  60. // -> Set Connection App Name
  61. setAppName() {
  62. return self.inst.query(`set application_name = 'Wiki.js'`, { raw: true })
  63. }
  64. }
  65. let initTasksQueue = (wiki.IS_MASTER) ? [
  66. initTasks.syncSchemas,
  67. initTasks.setAppName
  68. ] : [
  69. initTasks.setAppName
  70. ]
  71. // Perform init tasks
  72. self.onReady = Promise.each(initTasksQueue, t => t())
  73. return self
  74. }
  75. }