database.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 './config'
  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. import { UserNotificationModel } from '../models/account/user-notification'
  34. import { UserNotificationSettingModel } from '../models/account/user-notification-setting'
  35. import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
  36. import { VideoPlaylistModel } from '../models/video/video-playlist'
  37. import { VideoPlaylistElementModel } from '../models/video/video-playlist-element'
  38. import { ThumbnailModel } from '../models/video/thumbnail'
  39. import { QueryTypes, Transaction } from 'sequelize'
  40. require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
  41. const dbname = CONFIG.DATABASE.DBNAME
  42. const username = CONFIG.DATABASE.USERNAME
  43. const password = CONFIG.DATABASE.PASSWORD
  44. const host = CONFIG.DATABASE.HOSTNAME
  45. const port = CONFIG.DATABASE.PORT
  46. const poolMax = CONFIG.DATABASE.POOL.MAX
  47. const sequelizeTypescript = new SequelizeTypescript({
  48. database: dbname,
  49. dialect: 'postgres',
  50. host,
  51. port,
  52. username,
  53. password,
  54. pool: {
  55. max: poolMax
  56. },
  57. benchmark: isTestInstance(),
  58. isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
  59. logging: (message: string, benchmark: number) => {
  60. if (process.env.NODE_DB_LOG === 'false') return
  61. let newMessage = message
  62. if (isTestInstance() === true && benchmark !== undefined) {
  63. newMessage += ' | ' + benchmark + 'ms'
  64. }
  65. logger.debug(newMessage)
  66. }
  67. })
  68. async function initDatabaseModels (silent: boolean) {
  69. sequelizeTypescript.addModels([
  70. ApplicationModel,
  71. ActorModel,
  72. ActorFollowModel,
  73. AvatarModel,
  74. AccountModel,
  75. OAuthClientModel,
  76. OAuthTokenModel,
  77. ServerModel,
  78. TagModel,
  79. AccountVideoRateModel,
  80. UserModel,
  81. VideoAbuseModel,
  82. VideoModel,
  83. VideoChangeOwnershipModel,
  84. VideoChannelModel,
  85. VideoShareModel,
  86. VideoFileModel,
  87. VideoCaptionModel,
  88. VideoBlacklistModel,
  89. VideoTagModel,
  90. VideoCommentModel,
  91. ScheduleVideoUpdateModel,
  92. VideoImportModel,
  93. VideoViewModel,
  94. VideoRedundancyModel,
  95. UserVideoHistoryModel,
  96. AccountBlocklistModel,
  97. ServerBlocklistModel,
  98. UserNotificationModel,
  99. UserNotificationSettingModel,
  100. VideoStreamingPlaylistModel,
  101. VideoPlaylistModel,
  102. VideoPlaylistElementModel,
  103. ThumbnailModel
  104. ])
  105. // Check extensions exist in the database
  106. await checkPostgresExtensions()
  107. // Create custom PostgreSQL functions
  108. await createFunctions()
  109. if (!silent) logger.info('Database %s is ready.', dbname)
  110. return
  111. }
  112. // ---------------------------------------------------------------------------
  113. export {
  114. initDatabaseModels,
  115. sequelizeTypescript
  116. }
  117. // ---------------------------------------------------------------------------
  118. async function checkPostgresExtensions () {
  119. const promises = [
  120. checkPostgresExtension('pg_trgm'),
  121. checkPostgresExtension('unaccent')
  122. ]
  123. return Promise.all(promises)
  124. }
  125. async function checkPostgresExtension (extension: string) {
  126. const query = `SELECT 1 FROM pg_available_extensions WHERE name = '${extension}' AND installed_version IS NOT NULL;`
  127. const options = {
  128. type: QueryTypes.SELECT as QueryTypes.SELECT,
  129. raw: true
  130. }
  131. const res = await sequelizeTypescript.query<object>(query, options)
  132. if (!res || res.length === 0) {
  133. // Try to create the extension ourselves
  134. try {
  135. await sequelizeTypescript.query(`CREATE EXTENSION ${extension};`, { raw: true })
  136. } catch {
  137. const errorMessage = `You need to enable ${extension} extension in PostgreSQL. ` +
  138. `You can do so by running 'CREATE EXTENSION ${extension};' as a PostgreSQL super user in ${CONFIG.DATABASE.DBNAME} database.`
  139. throw new Error(errorMessage)
  140. }
  141. }
  142. }
  143. async function createFunctions () {
  144. const query = `CREATE OR REPLACE FUNCTION immutable_unaccent(text)
  145. RETURNS text AS
  146. $func$
  147. SELECT public.unaccent('public.unaccent', $1::text)
  148. $func$ LANGUAGE sql IMMUTABLE;`
  149. return sequelizeTypescript.query(query, { raw: true })
  150. }