53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
const Database = require('better-sqlite3');
|
|
const path = require('path');
|
|
|
|
function migrateLitterId(dbPath) {
|
|
console.log('Running litter_id migration...');
|
|
|
|
const db = new Database(dbPath);
|
|
db.pragma('foreign_keys = ON');
|
|
|
|
try {
|
|
// Check if litter_id column already exists
|
|
const tableInfo = db.prepare("PRAGMA table_info(dogs)").all();
|
|
const hasLitterId = tableInfo.some(col => col.name === 'litter_id');
|
|
|
|
if (hasLitterId) {
|
|
console.log('litter_id column already exists. Skipping migration.');
|
|
db.close();
|
|
return;
|
|
}
|
|
|
|
// Add litter_id column to dogs table
|
|
db.exec(`
|
|
ALTER TABLE dogs ADD COLUMN litter_id INTEGER;
|
|
`);
|
|
|
|
// Create index for litter_id
|
|
db.exec(`
|
|
CREATE INDEX IF NOT EXISTS idx_dogs_litter ON dogs(litter_id);
|
|
`);
|
|
|
|
// Add foreign key relationship (SQLite doesn't support ALTER TABLE ADD CONSTRAINT)
|
|
// So we'll rely on application-level constraint checking
|
|
|
|
console.log('✓ Added litter_id column to dogs table');
|
|
console.log('✓ Created index on litter_id');
|
|
console.log('Migration completed successfully!');
|
|
|
|
db.close();
|
|
} catch (error) {
|
|
console.error('Migration failed:', error.message);
|
|
db.close();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
module.exports = { migrateLitterId };
|
|
|
|
// Run migration if called directly
|
|
if (require.main === module) {
|
|
const dbPath = process.env.DB_PATH || path.join(__dirname, '../../data/breedr.db');
|
|
migrateLitterId(dbPath);
|
|
}
|