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