96 lines
2.8 KiB
JavaScript
96 lines
2.8 KiB
JavaScript
const mysql = require('mysql2/promise');
|
|
const path = require('path');
|
|
const dotenv = require('dotenv');
|
|
const fs = require('fs');
|
|
|
|
dotenv.config({ path: path.join(__dirname, '../.env') });
|
|
|
|
const dbConfig = {
|
|
host: process.env.DB_HOST,
|
|
user: process.env.DB_USER,
|
|
password: process.env.DB_PASSWORD,
|
|
database: process.env.DB_NAME,
|
|
multipleStatements: true
|
|
};
|
|
|
|
// Helper function to output progress in JSON format
|
|
function outputProgress(data) {
|
|
if (!data.status) {
|
|
data = {
|
|
status: 'running',
|
|
...data
|
|
};
|
|
}
|
|
console.log(JSON.stringify(data));
|
|
}
|
|
|
|
async function resetDatabase() {
|
|
outputProgress({
|
|
operation: 'Starting database reset',
|
|
message: 'Connecting to database...'
|
|
});
|
|
|
|
const connection = await mysql.createConnection(dbConfig);
|
|
|
|
try {
|
|
// Get list of all tables efficiently
|
|
outputProgress({
|
|
operation: 'Getting table list',
|
|
message: 'Retrieving all table names...'
|
|
});
|
|
|
|
// More efficient query to get table names
|
|
const [tables] = await connection.query(`
|
|
SELECT GROUP_CONCAT(table_name) as tables
|
|
FROM information_schema.tables
|
|
WHERE table_schema = DATABASE()`
|
|
);
|
|
|
|
if (!tables[0].tables) {
|
|
outputProgress({
|
|
operation: 'No tables found',
|
|
message: 'Database is already empty'
|
|
});
|
|
} else {
|
|
// Disable foreign key checks and drop all tables in one query
|
|
outputProgress({
|
|
operation: 'Dropping tables',
|
|
message: 'Dropping all tables...'
|
|
});
|
|
|
|
await connection.query('SET FOREIGN_KEY_CHECKS = 0');
|
|
|
|
// Create DROP TABLE statements for all tables at once
|
|
const dropQuery = `DROP TABLE IF EXISTS ${tables[0].tables.split(',').map(table => '`' + table + '`').join(', ')}`;
|
|
await connection.query(dropQuery);
|
|
|
|
await connection.query('SET FOREIGN_KEY_CHECKS = 1');
|
|
}
|
|
|
|
// Read and execute schema directly instead of spawning a process
|
|
outputProgress({
|
|
operation: 'Running database setup',
|
|
message: 'Creating new tables...'
|
|
});
|
|
|
|
const schemaSQL = fs.readFileSync(path.join(__dirname, '../db/schema.sql'), 'utf8');
|
|
await connection.query(schemaSQL);
|
|
|
|
outputProgress({
|
|
status: 'complete',
|
|
operation: 'Database reset complete',
|
|
message: 'Database has been reset and tables recreated'
|
|
});
|
|
} catch (error) {
|
|
outputProgress({
|
|
status: 'error',
|
|
error: error.message
|
|
});
|
|
process.exit(1);
|
|
} finally {
|
|
await connection.end();
|
|
}
|
|
}
|
|
|
|
// Run the reset
|
|
resetDatabase();
|