feat: basic database setup

This commit is contained in:
2025-09-08 22:42:20 +02:00
parent c59e315027
commit f4e41a5b9f
6 changed files with 251 additions and 0 deletions

70
backend/src/db.js Normal file
View File

@@ -0,0 +1,70 @@
// copied from one of my older projects
const mysql = require('mysql2/promise');
function getEnvVar(name) {
const value = process.env[name];
if (value === null) {
throw new Error(`Environment variable ${name} is not defined`);
}
return value;
}
const pool = mysql.createPool({
host: getEnvVar('MYSQL_HOST'),
user: getEnvVar('MYSQL_USER'),
password: getEnvVar('MYSQL_PASSWORD'),
database: getEnvVar('MYSQL_DB'),
});
const migrations = [
{
name: "init_dart_table",
up: async (conn) => {
await conn.query(`
CREATE TABLE dart (
id INT PRIMARY KEY AUTO_INCREMENT
)
`);
}
}
];
async function initDB() {
await pool.query(`
CREATE TABLE IF NOT EXISTS migrations (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL UNIQUE
);
`);
for (const m of migrations) {
const conn = await pool.getConnection();
try {
await conn.beginTransaction();
const [rows] = await conn.query(
`SELECT 1 FROM migrations WHERE name = ? LIMIT 1 FOR UPDATE`,
[m.name]
);
if (rows.length === 0) {
console.log(`Running migration: ${m.name}`);
await m.up(conn);
await conn.query(`INSERT INTO migrations (name) VALUES (?)`, [m.name]);
}
await conn.commit();
} catch (err) {
await conn.rollback();
throw err;
} finally {
conn.release();
}
}
}
module.exports = {
pool,
initDB
};