database.ts 6.4 KB

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