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