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