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