]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/initializers/database.ts
Merge branch 'release/3.2.0' into develop
[github/Chocobozzz/PeerTube.git] / server / initializers / database.ts
CommitLineData
d95d1559 1import { QueryTypes, Transaction } from 'sequelize'
3fd3ab2d 2import { Sequelize as SequelizeTypescript } from 'sequelize-typescript'
f4796856
C
3import { TrackerModel } from '@server/models/server/tracker'
4import { VideoTrackerModel } from '@server/models/server/video-tracker'
7d9ba5c0
C
5import { UserModel } from '@server/models/user/user'
6import { UserNotificationModel } from '@server/models/user/user-notification'
7import { UserVideoHistoryModel } from '@server/models/user/user-video-history'
3fd3ab2d
C
8import { isTestInstance } from '../helpers/core-utils'
9import { logger } from '../helpers/logger'
c6c0fa6c
C
10import { AbuseModel } from '../models/abuse/abuse'
11import { AbuseMessageModel } from '../models/abuse/abuse-message'
12import { VideoAbuseModel } from '../models/abuse/video-abuse'
13import { VideoCommentAbuseModel } from '../models/abuse/video-comment-abuse'
3fd3ab2d 14import { AccountModel } from '../models/account/account'
d95d1559 15import { AccountBlocklistModel } from '../models/account/account-blocklist'
3fd3ab2d 16import { AccountVideoRateModel } from '../models/account/account-video-rate'
7d9ba5c0
C
17import { ActorModel } from '../models/actor/actor'
18import { ActorFollowModel } from '../models/actor/actor-follow'
19import { ActorImageModel } from '../models/actor/actor-image'
3fd3ab2d 20import { ApplicationModel } from '../models/application/application'
3fd3ab2d
C
21import { OAuthClientModel } from '../models/oauth/oauth-client'
22import { OAuthTokenModel } from '../models/oauth/oauth-token'
d95d1559
C
23import { VideoRedundancyModel } from '../models/redundancy/video-redundancy'
24import { PluginModel } from '../models/server/plugin'
3fd3ab2d 25import { ServerModel } from '../models/server/server'
d95d1559 26import { ServerBlocklistModel } from '../models/server/server-blocklist'
7d9ba5c0 27import { UserNotificationSettingModel } from '../models/user/user-notification-setting'
d95d1559 28import { ScheduleVideoUpdateModel } from '../models/video/schedule-video-update'
3fd3ab2d 29import { TagModel } from '../models/video/tag'
d95d1559 30import { ThumbnailModel } from '../models/video/thumbnail'
3fd3ab2d 31import { VideoModel } from '../models/video/video'
3fd3ab2d 32import { VideoBlacklistModel } from '../models/video/video-blacklist'
d95d1559
C
33import { VideoCaptionModel } from '../models/video/video-caption'
34import { VideoChangeOwnershipModel } from '../models/video/video-change-ownership'
3fd3ab2d 35import { VideoChannelModel } from '../models/video/video-channel'
6d852470 36import { VideoCommentModel } from '../models/video/video-comment'
3fd3ab2d 37import { VideoFileModel } from '../models/video/video-file'
fbad87b0 38import { VideoImportModel } from '../models/video/video-import'
c6c0fa6c 39import { VideoLiveModel } from '../models/video/video-live'
418d092a
C
40import { VideoPlaylistModel } from '../models/video/video-playlist'
41import { VideoPlaylistElementModel } from '../models/video/video-playlist-element'
d95d1559
C
42import { VideoShareModel } from '../models/video/video-share'
43import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
44import { VideoTagModel } from '../models/video/video-tag'
45import { VideoViewModel } from '../models/video/video-view'
46import { CONFIG } from './config'
fdbda9e3 47
3fd3ab2d 48require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
8c308c2b 49
65fcc311
C
50const dbname = CONFIG.DATABASE.DBNAME
51const username = CONFIG.DATABASE.USERNAME
52const password = CONFIG.DATABASE.PASSWORD
228077ef
C
53const host = CONFIG.DATABASE.HOSTNAME
54const port = CONFIG.DATABASE.PORT
1c3386e8 55const poolMax = CONFIG.DATABASE.POOL.MAX
8c308c2b 56
6bc672da
C
57let dialectOptions: any = {}
58
59if (CONFIG.DATABASE.SSL) {
60 dialectOptions = {
61 ssl: {
62 rejectUnauthorized: false
63 }
64 }
65}
66
3fd3ab2d
C
67const sequelizeTypescript = new SequelizeTypescript({
68 database: dbname,
feb4bdfd 69 dialect: 'postgres',
6bc672da 70 dialectOptions,
228077ef
C
71 host,
72 port,
3fd3ab2d
C
73 username,
74 password,
1c3386e8
RK
75 pool: {
76 max: poolMax
77 },
65fcc311 78 benchmark: isTestInstance(),
1735c825 79 isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
075f16ca 80 logging: (message: string, benchmark: number) => {
165cdc75
C
81 if (process.env.NODE_DB_LOG === 'false') return
82
2a6cf69c 83 let newMessage = 'Executed SQL request'
769d3321 84 if (isTestInstance() === true && benchmark !== undefined) {
2a6cf69c 85 newMessage += ' in ' + benchmark + 'ms'
7920c273
C
86 }
87
452b3bea 88 logger.debug(newMessage, { sql: message, tags: [ 'sql' ] })
7920c273 89 }
feb4bdfd
C
90})
91
74055dc8
C
92function checkDatabaseConnectionOrDie () {
93 sequelizeTypescript.authenticate()
94 .then(() => logger.debug('Connection to PostgreSQL has been established successfully.'))
95 .catch(err => {
96
97 logger.error('Unable to connect to PostgreSQL database.', { err })
98 process.exit(-1)
99 })
100}
4f24f16e 101
91fea9fc 102async function initDatabaseModels (silent: boolean) {
3fd3ab2d
C
103 sequelizeTypescript.addModels([
104 ApplicationModel,
50d6de9c
C
105 ActorModel,
106 ActorFollowModel,
f4796856 107 ActorImageModel,
3fd3ab2d 108 AccountModel,
3fd3ab2d
C
109 OAuthClientModel,
110 OAuthTokenModel,
111 ServerModel,
112 TagModel,
113 AccountVideoRateModel,
3fd3ab2d 114 UserModel,
edbc9325 115 AbuseMessageModel,
d95d1559
C
116 AbuseModel,
117 VideoCommentAbuseModel,
3fd3ab2d 118 VideoAbuseModel,
b876eaf1 119 VideoModel,
74d63469 120 VideoChangeOwnershipModel,
3fd3ab2d 121 VideoChannelModel,
3fd3ab2d
C
122 VideoShareModel,
123 VideoFileModel,
40e87e9e 124 VideoCaptionModel,
3fd3ab2d
C
125 VideoBlacklistModel,
126 VideoTagModel,
2baea0c7 127 VideoCommentModel,
fbad87b0 128 ScheduleVideoUpdateModel,
6b616860 129 VideoImportModel,
c48e82b5 130 VideoViewModel,
6e46de09 131 VideoRedundancyModel,
7ad9b984 132 UserVideoHistoryModel,
c6c0fa6c 133 VideoLiveModel,
7ad9b984 134 AccountBlocklistModel,
cef534ed
C
135 ServerBlocklistModel,
136 UserNotificationModel,
09209296 137 UserNotificationSettingModel,
418d092a
C
138 VideoStreamingPlaylistModel,
139 VideoPlaylistModel,
e8bafea3 140 VideoPlaylistElementModel,
f023a19c 141 ThumbnailModel,
d9a2a031
C
142 TrackerModel,
143 VideoTrackerModel,
f023a19c 144 PluginModel
3fd3ab2d 145 ])
b769007f 146
57c36b27
C
147 // Check extensions exist in the database
148 await checkPostgresExtensions()
149
150 // Create custom PostgreSQL functions
151 await createFunctions()
152
f5028693 153 if (!silent) logger.info('Database %s is ready.', dbname)
b769007f 154}
65fcc311
C
155
156// ---------------------------------------------------------------------------
157
e02643f3 158export {
91fea9fc 159 initDatabaseModels,
74055dc8 160 checkDatabaseConnectionOrDie,
3fd3ab2d 161 sequelizeTypescript
74889a71 162}
57c36b27
C
163
164// ---------------------------------------------------------------------------
165
166async function checkPostgresExtensions () {
0b2f03d3
C
167 const promises = [
168 checkPostgresExtension('pg_trgm'),
169 checkPostgresExtension('unaccent')
57c36b27
C
170 ]
171
0b2f03d3
C
172 return Promise.all(promises)
173}
174
175async function checkPostgresExtension (extension: string) {
3acc5084 176 const query = `SELECT 1 FROM pg_available_extensions WHERE name = '${extension}' AND installed_version IS NOT NULL;`
1735c825
C
177 const options = {
178 type: QueryTypes.SELECT as QueryTypes.SELECT,
179 raw: true
180 }
181
3acc5084 182 const res = await sequelizeTypescript.query<object>(query, options)
57c36b27 183
3acc5084 184 if (!res || res.length === 0) {
1735c825 185 // Try to create the extension ourselves
0b2f03d3
C
186 try {
187 await sequelizeTypescript.query(`CREATE EXTENSION ${extension};`, { raw: true })
57c36b27 188
0b2f03d3
C
189 } catch {
190 const errorMessage = `You need to enable ${extension} extension in PostgreSQL. ` +
191 `You can do so by running 'CREATE EXTENSION ${extension};' as a PostgreSQL super user in ${CONFIG.DATABASE.DBNAME} database.`
192 throw new Error(errorMessage)
57c36b27
C
193 }
194 }
195}
196
f0ad4710 197function createFunctions () {
2cebd797
C
198 const query = `CREATE OR REPLACE FUNCTION immutable_unaccent(text)
199 RETURNS text AS
200$func$
201SELECT public.unaccent('public.unaccent', $1::text)
202$func$ LANGUAGE sql IMMUTABLE;`
57c36b27
C
203
204 return sequelizeTypescript.query(query, { raw: true })
205}