91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
const mariadb = require("mariadb")
|
|
const logger = require("./logger")
|
|
const fs = require("fs/promises")
|
|
const path = require("path")
|
|
|
|
const dbConfig = {
|
|
host: process.env.DATABASE_HOST,
|
|
user: process.env.DATABASE_USER,
|
|
password: process.env.DATABASE_PASSWORD,
|
|
database: process.env.DATABASE_NAME,
|
|
acquireTimeout: 20000,
|
|
connectTimeout: 20000,
|
|
bigIntAsNumber: true,
|
|
insertIdAsNumber: true,
|
|
decimalAsNumber: true
|
|
}
|
|
|
|
const pool = mariadb.createPool({
|
|
...dbConfig,
|
|
connectionLimit: Number(process.env.DATABASE_CONNECTION_LIMIT) || 10
|
|
})
|
|
|
|
async function runDDL() {
|
|
let rootConn
|
|
let ddlConn
|
|
|
|
try {
|
|
rootConn = await mariadb.createConnection({
|
|
host: dbConfig.host,
|
|
user: dbConfig.user,
|
|
password: dbConfig.password,
|
|
connectTimeout: dbConfig.connectTimeout
|
|
})
|
|
|
|
await rootConn.query(
|
|
`CREATE DATABASE IF NOT EXISTS \`${dbConfig.database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`
|
|
)
|
|
logger.log(`Base de données '${dbConfig.database}' vérifiée.`, ["MariaDB", "yellow"])
|
|
await rootConn.end()
|
|
rootConn = null
|
|
|
|
ddlConn = await mariadb.createConnection({
|
|
...dbConfig,
|
|
multipleStatements: true
|
|
})
|
|
|
|
logger.log("Checking and synchronising the schema...", ["MariaDB", "yellow"])
|
|
|
|
const ddlDir = path.join(process.cwd(), "data", "ddl")
|
|
const files = await fs.readdir(ddlDir)
|
|
|
|
const sqlFiles = files
|
|
.filter(file => file.endsWith(".sql"))
|
|
.sort()
|
|
|
|
for (const file of sqlFiles) {
|
|
const filePath = path.join(ddlDir, file)
|
|
const sql = await fs.readFile(filePath, "utf-8")
|
|
|
|
if (sql.trim()) {
|
|
logger.log(`Execution of ${file.bold || file}`, ["DDL", "yellow"])
|
|
try {
|
|
await ddlConn.query(sql)
|
|
} catch (error) {
|
|
if (error?.fatal) {
|
|
logger.error(`Critical error during execution of ${file}: ` + error.message, ["MariaDB", "yellow"])
|
|
throw error
|
|
}
|
|
logger.warn(`Minimal error in ${file} (skipped): ` + error.message, ["MariaDB", "yellow"])
|
|
}
|
|
}
|
|
}
|
|
|
|
logger.log("MariaDB database successfully initialised!", ["MariaDB", "yellow"])
|
|
} catch (error) {
|
|
logger.error("DB initialisation aborted: " + error.message, ["MariaDB", "yellow"])
|
|
throw error
|
|
} finally {
|
|
if (rootConn) {
|
|
await rootConn.end()
|
|
}
|
|
if (ddlConn) {
|
|
await ddlConn.end()
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
pool,
|
|
runDDL
|
|
} |