ニジカ投稿局 https://tv.nizika.tv
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.

database.ts 9.4 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { isTestOrDevInstance } from '@peertube/peertube-node-utils'
  2. import { ActorCustomPageModel } from '@server/models/account/actor-custom-page.js'
  3. import { AutomaticTagModel } from '@server/models/automatic-tag/automatic-tag.js'
  4. import { VideoAutomaticTagModel } from '@server/models/automatic-tag/video-automatic-tag.js'
  5. import { CommentAutomaticTagModel } from '@server/models/automatic-tag/comment-automatic-tag.js'
  6. import { RunnerJobModel } from '@server/models/runner/runner-job.js'
  7. import { RunnerRegistrationTokenModel } from '@server/models/runner/runner-registration-token.js'
  8. import { RunnerModel } from '@server/models/runner/runner.js'
  9. import { TrackerModel } from '@server/models/server/tracker.js'
  10. import { VideoTrackerModel } from '@server/models/server/video-tracker.js'
  11. import { UserExportModel } from '@server/models/user/user-export.js'
  12. import { UserImportModel } from '@server/models/user/user-import.js'
  13. import { UserNotificationModel } from '@server/models/user/user-notification.js'
  14. import { UserRegistrationModel } from '@server/models/user/user-registration.js'
  15. import { UserVideoHistoryModel } from '@server/models/user/user-video-history.js'
  16. import { UserModel } from '@server/models/user/user.js'
  17. import { StoryboardModel } from '@server/models/video/storyboard.js'
  18. import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync.js'
  19. import { VideoChapterModel } from '@server/models/video/video-chapter.js'
  20. import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
  21. import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting.js'
  22. import { VideoLiveSessionModel } from '@server/models/video/video-live-session.js'
  23. import { VideoPasswordModel } from '@server/models/video/video-password.js'
  24. import { VideoSourceModel } from '@server/models/video/video-source.js'
  25. import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section.js'
  26. import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
  27. import { WatchedWordsListModel } from '@server/models/watched-words/watched-words-list.js'
  28. import pg from 'pg'
  29. import { QueryTypes, Transaction } from 'sequelize'
  30. import { Sequelize as SequelizeTypescript } from 'sequelize-typescript'
  31. import { logger } from '../helpers/logger.js'
  32. import { AbuseMessageModel } from '../models/abuse/abuse-message.js'
  33. import { AbuseModel } from '../models/abuse/abuse.js'
  34. import { VideoAbuseModel } from '../models/abuse/video-abuse.js'
  35. import { VideoCommentAbuseModel } from '../models/abuse/video-comment-abuse.js'
  36. import { AccountBlocklistModel } from '../models/account/account-blocklist.js'
  37. import { AccountVideoRateModel } from '../models/account/account-video-rate.js'
  38. import { AccountModel } from '../models/account/account.js'
  39. import { ActorFollowModel } from '../models/actor/actor-follow.js'
  40. import { ActorImageModel } from '../models/actor/actor-image.js'
  41. import { ActorModel } from '../models/actor/actor.js'
  42. import { ApplicationModel } from '../models/application/application.js'
  43. import { OAuthClientModel } from '../models/oauth/oauth-client.js'
  44. import { OAuthTokenModel } from '../models/oauth/oauth-token.js'
  45. import { VideoRedundancyModel } from '../models/redundancy/video-redundancy.js'
  46. import { PluginModel } from '../models/server/plugin.js'
  47. import { ServerBlocklistModel } from '../models/server/server-blocklist.js'
  48. import { ServerModel } from '../models/server/server.js'
  49. import { UserNotificationSettingModel } from '../models/user/user-notification-setting.js'
  50. import { ScheduleVideoUpdateModel } from '../models/video/schedule-video-update.js'
  51. import { TagModel } from '../models/video/tag.js'
  52. import { ThumbnailModel } from '../models/video/thumbnail.js'
  53. import { VideoBlacklistModel } from '../models/video/video-blacklist.js'
  54. import { VideoCaptionModel } from '../models/video/video-caption.js'
  55. import { VideoChangeOwnershipModel } from '../models/video/video-change-ownership.js'
  56. import { VideoChannelModel } from '../models/video/video-channel.js'
  57. import { VideoCommentModel } from '../models/video/video-comment.js'
  58. import { VideoFileModel } from '../models/video/video-file.js'
  59. import { VideoImportModel } from '../models/video/video-import.js'
  60. import { VideoLiveModel } from '../models/video/video-live.js'
  61. import { VideoPlaylistElementModel } from '../models/video/video-playlist-element.js'
  62. import { VideoPlaylistModel } from '../models/video/video-playlist.js'
  63. import { VideoShareModel } from '../models/video/video-share.js'
  64. import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist.js'
  65. import { VideoTagModel } from '../models/video/video-tag.js'
  66. import { VideoModel } from '../models/video/video.js'
  67. import { VideoViewModel } from '../models/view/video-view.js'
  68. import { CONFIG } from './config.js'
  69. import { AccountAutomaticTagPolicyModel } from '@server/models/automatic-tag/account-automatic-tag-policy.js'
  70. pg.defaults.parseInt8 = true // Avoid BIGINT to be converted to string
  71. const dbname = CONFIG.DATABASE.DBNAME
  72. const username = CONFIG.DATABASE.USERNAME
  73. const password = CONFIG.DATABASE.PASSWORD
  74. const host = CONFIG.DATABASE.HOSTNAME
  75. const port = CONFIG.DATABASE.PORT
  76. const poolMax = CONFIG.DATABASE.POOL.MAX
  77. let dialectOptions: any = {}
  78. if (CONFIG.DATABASE.SSL) {
  79. dialectOptions = {
  80. ssl: {
  81. rejectUnauthorized: false
  82. }
  83. }
  84. }
  85. const sequelizeTypescript = new SequelizeTypescript({
  86. database: dbname,
  87. dialect: 'postgres',
  88. dialectOptions,
  89. host,
  90. port,
  91. username,
  92. password,
  93. pool: {
  94. max: poolMax
  95. },
  96. benchmark: isTestOrDevInstance(),
  97. isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
  98. logging: (message: string, benchmark: number) => {
  99. if (process.env.NODE_DB_LOG === 'false') return
  100. let newMessage = 'Executed SQL request'
  101. if (isTestOrDevInstance() === true && benchmark !== undefined) {
  102. newMessage += ' in ' + benchmark + 'ms'
  103. }
  104. logger.debug(newMessage, { sql: message, tags: [ 'sql' ] })
  105. }
  106. })
  107. function checkDatabaseConnectionOrDie () {
  108. sequelizeTypescript.authenticate()
  109. .then(() => logger.debug('Connection to PostgreSQL has been established successfully.'))
  110. .catch(err => {
  111. logger.error('Unable to connect to PostgreSQL database.', { err })
  112. process.exit(-1)
  113. })
  114. }
  115. async function initDatabaseModels (silent: boolean) {
  116. sequelizeTypescript.addModels([
  117. ApplicationModel,
  118. ActorModel,
  119. ActorFollowModel,
  120. ActorImageModel,
  121. AccountModel,
  122. OAuthClientModel,
  123. OAuthTokenModel,
  124. ServerModel,
  125. TagModel,
  126. AccountVideoRateModel,
  127. UserModel,
  128. AbuseMessageModel,
  129. AbuseModel,
  130. VideoCommentAbuseModel,
  131. VideoAbuseModel,
  132. VideoModel,
  133. VideoChangeOwnershipModel,
  134. VideoChannelModel,
  135. VideoShareModel,
  136. VideoFileModel,
  137. VideoSourceModel,
  138. VideoChapterModel,
  139. VideoCaptionModel,
  140. VideoBlacklistModel,
  141. VideoTagModel,
  142. VideoCommentModel,
  143. ScheduleVideoUpdateModel,
  144. VideoImportModel,
  145. VideoViewModel,
  146. VideoRedundancyModel,
  147. UserVideoHistoryModel,
  148. VideoLiveModel,
  149. VideoLiveSessionModel,
  150. VideoLiveReplaySettingModel,
  151. AccountBlocklistModel,
  152. ServerBlocklistModel,
  153. UserNotificationModel,
  154. UserNotificationSettingModel,
  155. VideoStreamingPlaylistModel,
  156. VideoPlaylistModel,
  157. VideoPlaylistElementModel,
  158. LocalVideoViewerModel,
  159. LocalVideoViewerWatchSectionModel,
  160. ThumbnailModel,
  161. TrackerModel,
  162. VideoTrackerModel,
  163. PluginModel,
  164. ActorCustomPageModel,
  165. UserImportModel,
  166. VideoJobInfoModel,
  167. VideoChannelSyncModel,
  168. UserRegistrationModel,
  169. VideoPasswordModel,
  170. RunnerRegistrationTokenModel,
  171. RunnerModel,
  172. RunnerJobModel,
  173. StoryboardModel,
  174. UserExportModel,
  175. VideoAutomaticTagModel,
  176. CommentAutomaticTagModel,
  177. AutomaticTagModel,
  178. WatchedWordsListModel,
  179. AccountAutomaticTagPolicyModel
  180. ])
  181. // Check extensions exist in the database
  182. await checkPostgresExtensions()
  183. // Create custom PostgreSQL functions
  184. await createFunctions()
  185. if (!silent) logger.info('Database %s is ready.', dbname)
  186. }
  187. // ---------------------------------------------------------------------------
  188. export {
  189. checkDatabaseConnectionOrDie, initDatabaseModels, sequelizeTypescript
  190. }
  191. // ---------------------------------------------------------------------------
  192. async function checkPostgresExtensions () {
  193. const promises = [
  194. checkPostgresExtension('pg_trgm'),
  195. checkPostgresExtension('unaccent')
  196. ]
  197. return Promise.all(promises)
  198. }
  199. async function checkPostgresExtension (extension: string) {
  200. const query = `SELECT 1 FROM pg_available_extensions WHERE name = '${extension}' AND installed_version IS NOT NULL;`
  201. const options = {
  202. type: QueryTypes.SELECT as QueryTypes.SELECT,
  203. raw: true
  204. }
  205. const res = await sequelizeTypescript.query<object>(query, options)
  206. if (!res || res.length === 0) {
  207. // Try to create the extension ourselves
  208. try {
  209. await sequelizeTypescript.query(`CREATE EXTENSION ${extension};`, { raw: true })
  210. } catch {
  211. const errorMessage = `You need to enable ${extension} extension in PostgreSQL. ` +
  212. `You can do so by running 'CREATE EXTENSION ${extension};' as a PostgreSQL super user in ${CONFIG.DATABASE.DBNAME} database.`
  213. throw new Error(errorMessage)
  214. }
  215. }
  216. }
  217. function createFunctions () {
  218. const query = `CREATE OR REPLACE FUNCTION immutable_unaccent(text)
  219. RETURNS text AS
  220. $func$
  221. SELECT public.unaccent('public.unaccent', $1::text)
  222. $func$ LANGUAGE sql IMMUTABLE;`
  223. return sequelizeTypescript.query(query, { raw: true })
  224. }