feat: basic database setup
This commit is contained in:
70
backend/src/db.js
Normal file
70
backend/src/db.js
Normal 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
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
require('dotenv').config()
|
||||
const db = require('./db');
|
||||
|
||||
db.initDB();
|
||||
Reference in New Issue
Block a user