Add bootstrap entrypoint and migrate DB schema setup to SQL files. Introduces bootstrap.js, many data/ddl/*.sql files, and a new runDDL() in modules/database.js (exports pool and runDDL). Remove legacy modules/databaseGlobals.js. Update repositories and code to use database.pool.query calls. Bump package version and set main to bootstrap.js. Clean up server.js to remove inline DB/cert init (now handled by bootstrap). Overall: refactor DB initialization to run ordered SQL DDL files and centralize startup logic.
89 lines
2.5 KiB
JavaScript
89 lines
2.5 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"])
|
|
await ddlConn.query(sql)
|
|
}
|
|
}
|
|
|
|
logger.log("MariaDB database successfully initialised!", ["MariaDB", "yellow"])
|
|
} catch (error) {
|
|
if (error?.fatal) {
|
|
logger.error("Critical error during DB initialisation: " + error.message, ["MariaDB", "yellow"])
|
|
logger.error(error)
|
|
throw error
|
|
} else {
|
|
logger.warn("Minimal error during DB initialisation: " + error.message, ["MariaDB", "yellow"])
|
|
}
|
|
|
|
} finally {
|
|
if (rootConn) {
|
|
await rootConn.end()
|
|
}
|
|
if (ddlConn) {
|
|
await ddlConn.end()
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
pool,
|
|
runDDL
|
|
} |