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