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