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