-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmigrate.js
More file actions
89 lines (77 loc) · 2.77 KB
/
Copy pathmigrate.js
File metadata and controls
89 lines (77 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');
// Load environment variables only in non-Docker environments
// In Docker, environment variables are already set via docker-compose
if (process.env.NODE_ENV !== 'production') {
try {
// Try to load dotenv if available (for local development)
const dotenv = require('dotenv');
const envPath = fs.existsSync(path.join(__dirname, '..', '.env.local'))
? path.join(__dirname, '..', '.env.local')
: fs.existsSync(path.join(__dirname, '..', '.env.production'))
? path.join(__dirname, '..', '.env.production')
: path.join(__dirname, '..', '.env');
if (fs.existsSync(envPath)) {
dotenv.config({ path: envPath });
}
} catch (err) {
// dotenv not available (production build), use existing env vars
console.log('Using environment variables from system');
}
}
const pool = new Pool({
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT || '5432'),
user: process.env.DATABASE_USER || 'studyield',
password: process.env.DATABASE_PASSWORD || '',
database: process.env.DATABASE_NAME || 'studyield',
});
async function migrate() {
const client = await pool.connect();
try {
// Create migrations table if it doesn't exist
await client.query(`
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)
`);
// Get executed migrations
const { rows: executed } = await client.query('SELECT name FROM migrations');
const executedNames = new Set(executed.map(r => r.name));
// Get migration files
const migrationsDir = path.join(__dirname, '..', 'migrations');
const files = fs.readdirSync(migrationsDir)
.filter(f => f.endsWith('.sql'))
.sort();
for (const file of files) {
if (executedNames.has(file)) {
console.log(`Skipping ${file} (already executed)`);
continue;
}
console.log(`Running migration: ${file}`);
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
await client.query('BEGIN');
try {
await client.query(sql);
await client.query('INSERT INTO migrations (name) VALUES ($1)', [file]);
await client.query('COMMIT');
console.log(`✓ Migration ${file} completed`);
} catch (error) {
await client.query('ROLLBACK');
console.error(`✗ Migration ${file} failed:`, error.message);
throw error;
}
}
console.log('\nAll migrations completed successfully!');
} finally {
client.release();
await pool.end();
}
}
migrate().catch(err => {
console.error('Migration failed:', err);
process.exit(1);
});