database.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { Sequelize as SequelizeTypescript } from 'sequelize-typescript'
  2. import { isTestInstance } from '../helpers/core-utils'
  3. import { logger } from '../helpers/logger'
  4. import { AccountModel } from '../models/account/account'
  5. import { AccountVideoRateModel } from '../models/account/account-video-rate'
  6. import { UserModel } from '../models/account/user'
  7. import { ActorModel } from '../models/activitypub/actor'
  8. import { ActorFollowModel } from '../models/activitypub/actor-follow'
  9. import { ApplicationModel } from '../models/application/application'
  10. import { AvatarModel } from '../models/avatar/avatar'
  11. import { OAuthClientModel } from '../models/oauth/oauth-client'
  12. import { OAuthTokenModel } from '../models/oauth/oauth-token'
  13. import { ServerModel } from '../models/server/server'
  14. import { TagModel } from '../models/video/tag'
  15. import { VideoModel } from '../models/video/video'
  16. import { VideoAbuseModel } from '../models/video/video-abuse'
  17. import { VideoBlacklistModel } from '../models/video/video-blacklist'
  18. import { VideoChannelModel } from '../models/video/video-channel'
  19. import { VideoCommentModel } from '../models/video/video-comment'
  20. import { VideoFileModel } from '../models/video/video-file'
  21. import { VideoShareModel } from '../models/video/video-share'
  22. import { VideoTagModel } from '../models/video/video-tag'
  23. import { CONFIG } from './constants'
  24. import { ScheduleVideoUpdateModel } from '../models/video/schedule-video-update'
  25. import { VideoCaptionModel } from '../models/video/video-caption'
  26. import { VideoImportModel } from '../models/video/video-import'
  27. import { VideoViewModel } from '../models/video/video-views'
  28. import { VideoChangeOwnershipModel } from '../models/video/video-change-ownership'
  29. import { VideoRedundancyModel } from '../models/redundancy/video-redundancy'
  30. import { UserVideoHistoryModel } from '../models/account/user-video-history'
  31. import { AccountBlocklistModel } from '../models/account/account-blocklist'
  32. import { ServerBlocklistModel } from '../models/server/server-blocklist'
  33. require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
  34. const dbname = CONFIG.DATABASE.DBNAME
  35. const username = CONFIG.DATABASE.USERNAME
  36. const password = CONFIG.DATABASE.PASSWORD
  37. const host = CONFIG.DATABASE.HOSTNAME
  38. const port = CONFIG.DATABASE.PORT
  39. const poolMax = CONFIG.DATABASE.POOL.MAX
  40. const sequelizeTypescript = new SequelizeTypescript({
  41. database: dbname,
  42. dialect: 'postgres',
  43. host,
  44. port,
  45. username,
  46. password,
  47. pool: {
  48. max: poolMax
  49. },
  50. benchmark: isTestInstance(),
  51. isolationLevel: SequelizeTypescript.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
  52. operatorsAliases: false,
  53. logging: (message: string, benchmark: number) => {
  54. if (process.env.NODE_DB_LOG === 'false') return
  55. let newMessage = message
  56. if (isTestInstance() === true && benchmark !== undefined) {
  57. newMessage += ' | ' + benchmark + 'ms'
  58. }
  59. logger.debug(newMessage)
  60. }
  61. })
  62. async function initDatabaseModels (silent: boolean) {
  63. sequelizeTypescript.addModels([
  64. ApplicationModel,
  65. ActorModel,
  66. ActorFollowModel,
  67. AvatarModel,
  68. AccountModel,
  69. OAuthClientModel,
  70. OAuthTokenModel,
  71. ServerModel,
  72. TagModel,
  73. AccountVideoRateModel,
  74. UserModel,
  75. VideoAbuseModel,
  76. VideoChangeOwnershipModel,
  77. VideoChannelModel,
  78. VideoShareModel,
  79. VideoFileModel,
  80. VideoCaptionModel,
  81. VideoBlacklistModel,
  82. VideoTagModel,
  83. VideoModel,
  84. VideoCommentModel,
  85. ScheduleVideoUpdateModel,
  86. VideoImportModel,
  87. VideoViewModel,
  88. VideoRedundancyModel,
  89. UserVideoHistoryModel,
  90. AccountBlocklistModel,
  91. ServerBlocklistModel
  92. ])
  93. // Check extensions exist in the database
  94. await checkPostgresExtensions()
  95. // Create custom PostgreSQL functions
  96. await createFunctions()
  97. if (!silent) logger.info('Database %s is ready.', dbname)
  98. return
  99. }
  100. // ---------------------------------------------------------------------------
  101. export {
  102. initDatabaseModels,
  103. sequelizeTypescript
  104. }
  105. // ---------------------------------------------------------------------------
  106. async function checkPostgresExtensions () {
  107. const extensions = [
  108. 'pg_trgm',
  109. 'unaccent'
  110. ]
  111. for (const extension of extensions) {
  112. const query = `SELECT true AS enabled FROM pg_available_extensions WHERE name = '${extension}' AND installed_version IS NOT NULL;`
  113. const [ res ] = await sequelizeTypescript.query(query, { raw: true })
  114. if (!res || res.length === 0 || res[ 0 ][ 'enabled' ] !== true) {
  115. // Try to create the extension ourself
  116. try {
  117. await sequelizeTypescript.query(`CREATE EXTENSION ${extension};`, { raw: true })
  118. } catch {
  119. const errorMessage = `You need to enable ${extension} extension in PostgreSQL. ` +
  120. `You can do so by running 'CREATE EXTENSION ${extension};' as a PostgreSQL super user in ${CONFIG.DATABASE.DBNAME} database.`
  121. throw new Error(errorMessage)
  122. }
  123. }
  124. }
  125. }
  126. async function createFunctions () {
  127. const query = `CREATE OR REPLACE FUNCTION immutable_unaccent(text)
  128. RETURNS text AS
  129. $func$
  130. SELECT public.unaccent('public.unaccent', $1::text)
  131. $func$ LANGUAGE sql IMMUTABLE;`
  132. return sequelizeTypescript.query(query, { raw: true })
  133. }