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