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'
6 import { CONFIG } from './constants'
7 // Do not use barrel, we need to load database first
8 import { logger } from '../helpers/logger'
9 import { isTestInstance, readdirPromise } from '../helpers/core-utils'
11 import { VideoModel } from './../models/video/video-interface'
12 import { VideoTagModel } from './../models/video/video-tag-interface'
13 import { BlacklistedVideoModel } from './../models/video/video-blacklist-interface'
14 import { VideoFileModel } from './../models/video/video-file-interface'
15 import { VideoAbuseModel } from './../models/video/video-abuse-interface'
16 import { VideoChannelModel } from './../models/video/video-channel-interface'
17 import { UserModel } from '../models/account/user-interface'
18 import { AccountVideoRateModel } from '../models/account/account-video-rate-interface'
19 import { AccountFollowModel } from '../models/account/account-follow-interface'
20 import { TagModel } from './../models/video/tag-interface'
21 import { ServerModel } from '../models/server/server-interface'
22 import { OAuthTokenModel } from './../models/oauth/oauth-token-interface'
23 import { OAuthClientModel } from './../models/oauth/oauth-client-interface'
24 import { JobModel } from './../models/job/job-interface'
25 import { AccountModel } from './../models/account/account-interface'
26 import { ApplicationModel } from './../models/application/application-interface'
27 import { VideoChannelShareModel } from '../models/video/video-channel-share-interface'
28 import { VideoShareModel } from '../models/video/video-share-interface'
30 const dbname = CONFIG.DATABASE.DBNAME
31 const username = CONFIG.DATABASE.USERNAME
32 const password = CONFIG.DATABASE.PASSWORD
34 export type PeerTubeDatabase = {
35 sequelize?: Sequelize.Sequelize,
36 init?: (silent: boolean) => Promise<void>,
38 Application?: ApplicationModel,
39 Account?: AccountModel,
41 OAuthClient?: OAuthClientModel,
42 OAuthToken?: OAuthTokenModel,
45 AccountVideoRate?: AccountVideoRateModel,
46 AccountFollow?: AccountFollowModel,
48 VideoAbuse?: VideoAbuseModel,
49 VideoChannel?: VideoChannelModel,
50 VideoChannelShare?: VideoChannelShareModel,
51 VideoShare?: VideoShareModel,
52 VideoFile?: VideoFileModel,
53 BlacklistedVideo?: BlacklistedVideoModel,
54 VideoTag?: VideoTagModel,
58 const database: PeerTubeDatabase = {}
60 const sequelize = new Sequelize(dbname, username, password, {
62 host: CONFIG.DATABASE.HOSTNAME,
63 port: CONFIG.DATABASE.PORT,
64 benchmark: isTestInstance(),
65 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
66 operatorsAliases: false,
68 logging: (message: string, benchmark: number) => {
69 if (process.env.NODE_DB_LOG === 'false') return
71 let newMessage = message
72 if (isTestInstance() === true && benchmark !== undefined) {
73 newMessage += ' | ' + benchmark + 'ms'
76 logger.debug(newMessage)
80 database.sequelize = sequelize
82 database.init = async (silent: boolean) => {
83 const modelDirectory = join(__dirname, '..', 'models')
85 const filePaths = await getModelFiles(modelDirectory)
87 for (const filePath of filePaths) {
89 const model = sequelize.import(filePath)
91 database[model['name']] = model
93 logger.error('Cannot import database model %s.', filePath, err)
98 for (const modelName of Object.keys(database)) {
99 if ('associate' in database[modelName]) {
101 database[modelName].associate(database)
103 logger.error('Cannot associate model %s.', modelName, err)
109 if (!silent) logger.info('Database %s is ready.', dbname)
114 // ---------------------------------------------------------------------------
120 // ---------------------------------------------------------------------------
122 async function getModelFiles (modelDirectory: string) {
123 const files = await readdirPromise(modelDirectory)
124 const directories = files.filter(directory => {
127 directory.endsWith('.js.map') ||
128 directory === 'index.js' || directory === 'index.ts' ||
129 directory === 'utils.js' || directory === 'utils.ts'
135 const tasks: Promise<any>[] = []
137 // For each directory we read it and append model in the modelFilePaths array
138 for (const directory of directories) {
139 const modelDirectoryPath = join(modelDirectory, directory)
141 const promise = readdirPromise(modelDirectoryPath)
143 const filteredFiles = files
146 file === 'index.js' || file === 'index.ts' ||
147 file === 'utils.js' || file === 'utils.ts' ||
148 file.endsWith('-interface.js') || file.endsWith('-interface.ts') ||
149 file.endsWith('.js.map')
154 .map(file => join(modelDirectoryPath, file))
162 const filteredFilesArray: string[][] = await Promise.all(tasks)
163 return flattenDepth<string>(filteredFilesArray, 1)