1 import { join } from 'path'
2 import { flattenDepth } from 'lodash'
3 require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
4 import * as Sequelize from 'sequelize'
5 import { AvatarModel } from '../models/avatar'
7 import { CONFIG } from './constants'
8 // Do not use barrel, we need to load database first
9 import { logger } from '../helpers/logger'
10 import { isTestInstance, readdirPromise } from '../helpers/core-utils'
12 import { VideoModel } from './../models/video/video-interface'
13 import { VideoTagModel } from './../models/video/video-tag-interface'
14 import { BlacklistedVideoModel } from './../models/video/video-blacklist-interface'
15 import { VideoFileModel } from './../models/video/video-file-interface'
16 import { VideoAbuseModel } from './../models/video/video-abuse-interface'
17 import { VideoChannelModel } from './../models/video/video-channel-interface'
18 import { UserModel } from '../models/account/user-interface'
19 import { AccountVideoRateModel } from '../models/account/account-video-rate-interface'
20 import { AccountFollowModel } from '../models/account/account-follow-interface'
21 import { TagModel } from './../models/video/tag-interface'
22 import { ServerModel } from '../models/server/server-interface'
23 import { OAuthTokenModel } from './../models/oauth/oauth-token-interface'
24 import { OAuthClientModel } from './../models/oauth/oauth-client-interface'
25 import { JobModel } from './../models/job/job-interface'
26 import { AccountModel } from './../models/account/account-interface'
27 import { ApplicationModel } from './../models/application/application-interface'
28 import { VideoChannelShareModel } from '../models/video/video-channel-share-interface'
29 import { VideoShareModel } from '../models/video/video-share-interface'
31 const dbname = CONFIG.DATABASE.DBNAME
32 const username = CONFIG.DATABASE.USERNAME
33 const password = CONFIG.DATABASE.PASSWORD
35 export type PeerTubeDatabase = {
36 sequelize?: Sequelize.Sequelize,
37 init?: (silent: boolean) => Promise<void>,
39 Application?: ApplicationModel,
41 Account?: AccountModel,
43 OAuthClient?: OAuthClientModel,
44 OAuthToken?: OAuthTokenModel,
47 AccountVideoRate?: AccountVideoRateModel,
48 AccountFollow?: AccountFollowModel,
50 VideoAbuse?: VideoAbuseModel,
51 VideoChannel?: VideoChannelModel,
52 VideoChannelShare?: VideoChannelShareModel,
53 VideoShare?: VideoShareModel,
54 VideoFile?: VideoFileModel,
55 BlacklistedVideo?: BlacklistedVideoModel,
56 VideoTag?: VideoTagModel,
60 const database: PeerTubeDatabase = {}
62 const sequelize = new Sequelize(dbname, username, password, {
64 host: CONFIG.DATABASE.HOSTNAME,
65 port: CONFIG.DATABASE.PORT,
66 benchmark: isTestInstance(),
67 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
68 operatorsAliases: false,
70 logging: (message: string, benchmark: number) => {
71 if (process.env.NODE_DB_LOG === 'false') return
73 let newMessage = message
74 if (isTestInstance() === true && benchmark !== undefined) {
75 newMessage += ' | ' + benchmark + 'ms'
78 logger.debug(newMessage)
82 database.sequelize = sequelize
84 database.init = async (silent: boolean) => {
85 const modelDirectory = join(__dirname, '..', 'models')
87 const filePaths = await getModelFiles(modelDirectory)
89 for (const filePath of filePaths) {
91 const model = sequelize.import(filePath)
93 database[model['name']] = model
95 logger.error('Cannot import database model %s.', filePath, err)
100 for (const modelName of Object.keys(database)) {
101 if ('associate' in database[modelName]) {
103 database[modelName].associate(database)
105 logger.error('Cannot associate model %s.', modelName, err)
111 if (!silent) logger.info('Database %s is ready.', dbname)
116 // ---------------------------------------------------------------------------
122 // ---------------------------------------------------------------------------
124 async function getModelFiles (modelDirectory: string) {
125 const files = await readdirPromise(modelDirectory)
126 const directories = files.filter(directory => {
129 directory.endsWith('.js.map') ||
130 directory === 'index.js' || directory === 'index.ts' ||
131 directory === 'utils.js' || directory === 'utils.ts'
137 const tasks: Promise<any>[] = []
139 // For each directory we read it and append model in the modelFilePaths array
140 for (const directory of directories) {
141 const modelDirectoryPath = join(modelDirectory, directory)
143 const promise = readdirPromise(modelDirectoryPath)
145 const filteredFiles = files
148 file === 'index.js' || file === 'index.ts' ||
149 file === 'utils.js' || file === 'utils.ts' ||
150 file.endsWith('-interface.js') || file.endsWith('-interface.ts') ||
151 file.endsWith('.js.map')
156 .map(file => join(modelDirectoryPath, file))
164 const filteredFilesArray: string[][] = await Promise.all(tasks)
165 return flattenDepth<string>(filteredFilesArray, 1)