37 lines
942 B
TypeScript
37 lines
942 B
TypeScript
import initSqlJs from 'sql.js';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
const DATA_DIR = path.resolve(process.cwd(), 'data');
|
|
const DB_PATH = path.join(DATA_DIR, 'recipes.db');
|
|
const SCHEMA_PATH = path.resolve(process.cwd(), 'src/backend/db/schema.sql');
|
|
|
|
async function ensureDataDir() {
|
|
if (!fs.existsSync(DATA_DIR)) {
|
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
console.log(`Created data directory at ${DATA_DIR}`);
|
|
}
|
|
}
|
|
|
|
async function applyMigrations() {
|
|
await ensureDataDir();
|
|
|
|
const schema = fs.readFileSync(SCHEMA_PATH, 'utf8');
|
|
const SQL = await initSqlJs();
|
|
const db = new SQL.Database();
|
|
|
|
// Run all SQL statements
|
|
db.exec(schema);
|
|
|
|
// Export and save to file
|
|
const data = db.export();
|
|
fs.writeFileSync(DB_PATH, Buffer.from(data));
|
|
console.log(`Database migrated: ${DB_PATH}`);
|
|
}
|
|
|
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
applyMigrations();
|
|
}
|
|
|
|
export { applyMigrations };
|