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'
28 const dbname = CONFIG.DATABASE.DBNAME
29 const username = CONFIG.DATABASE.USERNAME
30 const password = CONFIG.DATABASE.PASSWORD
33 sequelize?: Sequelize.Sequelize,
34 init?: (silent: boolean) => Promise<void>,
36 Application?: ApplicationModel,
37 Account?: AccountModel,
39 OAuthClient?: OAuthClientModel,
40 OAuthToken?: OAuthTokenModel,
43 AccountVideoRate?: AccountVideoRateModel,
44 AccountFollow?: AccountFollowModel,
46 VideoAbuse?: VideoAbuseModel,
47 VideoChannel?: VideoChannelModel,
48 VideoFile?: VideoFileModel,
49 BlacklistedVideo?: BlacklistedVideoModel,
50 VideoTag?: VideoTagModel,
54 const sequelize = new Sequelize(dbname, username, password, {
56 host: CONFIG.DATABASE.HOSTNAME,
57 port: CONFIG.DATABASE.PORT,
58 benchmark: isTestInstance(),
59 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
60 operatorsAliases: false,
62 logging: (message: string, benchmark: number) => {
63 let newMessage = message
64 if (isTestInstance() === true && benchmark !== undefined) {
65 newMessage += ' | ' + benchmark + 'ms'
68 logger.debug(newMessage)
72 database.sequelize = sequelize
74 database.init = async (silent: boolean) => {
75 const modelDirectory = join(__dirname, '..', 'models')
77 const filePaths = await getModelFiles(modelDirectory)
79 for (const filePath of filePaths) {
81 const model = sequelize.import(filePath)
83 database[model['name']] = model
85 logger.error('Cannot import database model %s.', filePath, err)
90 for (const modelName of Object.keys(database)) {
91 if ('associate' in database[modelName]) {
92 database[modelName].associate(database)
96 if (!silent) logger.info('Database %s is ready.', dbname)
101 // ---------------------------------------------------------------------------
107 // ---------------------------------------------------------------------------
109 async function getModelFiles (modelDirectory: string) {
110 const files = await readdirPromise(modelDirectory)
111 const directories = files.filter(directory => {
114 directory.endsWith('.js.map') ||
115 directory === 'index.js' || directory === 'index.ts' ||
116 directory === 'utils.js' || directory === 'utils.ts'
122 const tasks: Promise<any>[] = []
124 // For each directory we read it and append model in the modelFilePaths array
125 for (const directory of directories) {
126 const modelDirectoryPath = join(modelDirectory, directory)
128 const promise = readdirPromise(modelDirectoryPath)
130 const filteredFiles = files
133 file === 'index.js' || file === 'index.ts' ||
134 file === 'utils.js' || file === 'utils.ts' ||
135 file.endsWith('-interface.js') || file.endsWith('-interface.ts') ||
136 file.endsWith('.js.map')
141 .map(file => join(modelDirectoryPath, file))
149 const filteredFilesArray: string[][] = await Promise.all(tasks)
150 return flattenDepth<string>(filteredFilesArray, 1)