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