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