60 lines
1.8 KiB
JavaScript
60 lines
1.8 KiB
JavaScript
const Database = require('better-sqlite3');
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
require('dotenv').config();
|
||
|
||
const dbFile = process.env.DATABASE_FILE || 'database.sqlite';
|
||
const dbPath = path.isAbsolute(dbFile) ? dbFile : path.join(__dirname, dbFile);
|
||
|
||
let db;
|
||
try {
|
||
// better-sqlite3 creates the database file synchronously on creation
|
||
db = new Database(dbPath);
|
||
console.log(`📂 SQLite database connected via better-sqlite3: ${dbPath}`);
|
||
} catch (err) {
|
||
console.error('💥 Failed to open SQLite database:', err.message);
|
||
process.exit(1);
|
||
}
|
||
|
||
// Wrap operations in async functions to maintain compatibility with server.js
|
||
async function query(sql, params = []) {
|
||
const stmt = db.prepare(sql);
|
||
const trimmedSql = sql.trim().toUpperCase();
|
||
const isMutating = trimmedSql.startsWith('INSERT') ||
|
||
trimmedSql.startsWith('UPDATE') ||
|
||
trimmedSql.startsWith('DELETE');
|
||
|
||
if (isMutating) {
|
||
const result = stmt.run(params);
|
||
return { insertId: result.lastInsertRowid, changes: result.changes };
|
||
} else {
|
||
return stmt.all(params);
|
||
}
|
||
}
|
||
|
||
async function initializeSchema() {
|
||
try {
|
||
const schemaPath = path.join(__dirname, 'schema.sql');
|
||
if (fs.existsSync(schemaPath)) {
|
||
const sql = fs.readFileSync(schemaPath, 'utf8');
|
||
// Executes multiple SQL statements in schema.sql
|
||
db.exec(sql);
|
||
try {
|
||
db.exec('ALTER TABLE requests ADD COLUMN tipo_solicitud TEXT;');
|
||
console.log('➕ Added tipo_solicitud column to existing requests table');
|
||
} catch (e) {
|
||
// Ignore if column already exists
|
||
}
|
||
console.log('✅ Database schema initialized/verified successfully');
|
||
}
|
||
} catch (error) {
|
||
console.error('⚠️ Failed to initialize schema automatically:', error.message);
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
query,
|
||
initializeSchema,
|
||
db
|
||
};
|