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