-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitialize-database.js
More file actions
91 lines (79 loc) · 2.5 KB
/
initialize-database.js
File metadata and controls
91 lines (79 loc) · 2.5 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
90
91
#!/usr/bin/env node
import { exec } from 'child_process';
import { promisify } from 'util';
import { Pool } from 'pg';
import { logger } from './dist/server/logger.js';
// Promisify exec for cleaner async usage
const execAsync = promisify(exec);
// Function to check if database tables exist
async function checkTablesExist() {
logger.info('Checking if database tables exist...');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
try {
const client = await pool.connect();
try {
// Query to check if the users table exists
const result = await client.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'users'
)
`);
const tablesExist = result.rows[0].exists;
logger.info(`Database tables ${tablesExist ? 'exist' : 'do not exist'}`);
return tablesExist;
} finally {
client.release();
}
} catch (err) {
logger.error('Error checking database tables:', err.message);
return false;
} finally {
await pool.end();
}
}
// Function to initialize database
async function initializeDatabase() {
try {
// First, check database connection
logger.info('Running database connection check...');
await execAsync('node check-database.js');
logger.info('Database connection check passed');
// Check if tables already exist
const tablesExist = await checkTablesExist();
if (!tablesExist) {
// Run database migration to create tables
logger.info('Running database migration to create tables...');
const { stdout, stderr } = await execAsync('npx drizzle-kit push');
logger.info('Database migration output:');
logger.info(stdout);
if (stderr) {
logger.warn('Database migration stderr:', stderr);
}
logger.info('Database tables created successfully');
} else {
logger.info('Database tables already exist, skipping migration');
}
return true;
} catch (err) {
logger.error('Database initialization failed:', err.message);
return false;
}
}
// Execute the initialization
initializeDatabase()
.then(success => {
if (success) {
logger.info('Database initialization completed successfully');
} else {
logger.error('Database initialization failed');
process.exit(1);
}
})
.catch(err => {
logger.error('Unexpected error during database initialization:', err);
process.exit(1);
});