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