Skip to content

Commit 51d721d

Browse files
committed
fixed sql
1 parent 23ed01b commit 51d721d

File tree

6 files changed

+54
-11
lines changed

6 files changed

+54
-11
lines changed

client/src/cyber-forensics-platform/scripts/build-hook.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,14 @@ async function buildHook() {
1111
// Only initialize database if DATABASE_URL is present (production)
1212
if (process.env.DATABASE_URL) {
1313
console.log('🗄️ Initializing production database...');
14-
await initializeDatabase();
14+
try {
15+
await initializeDatabase();
16+
console.log('✅ Database initialization successful');
17+
} catch (error) {
18+
console.error('❌ Database initialization failed:', error);
19+
// Don't exit - let the build continue, database might already be initialized
20+
console.log('⚠️ Continuing with build despite database error');
21+
}
1522
} else {
1623
console.log('⚠️ DATABASE_URL not found, skipping database initialization');
1724
}

client/src/cyber-forensics-platform/scripts/init-db-postgres.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ const fs = require('fs').promises;
33
const path = require('path');
44

55
async function initializeDatabase() {
6+
if (!process.env.DATABASE_URL) {
7+
console.error('❌ DATABASE_URL environment variable is not set');
8+
throw new Error('DATABASE_URL is required for PostgreSQL initialization');
9+
}
10+
611
const pool = new Pool({
712
connectionString: process.env.DATABASE_URL,
813
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
@@ -11,13 +16,18 @@ async function initializeDatabase() {
1116
try {
1217
console.log('🚀 Initializing PostgreSQL database...');
1318

19+
// Test connection first
20+
await pool.query('SELECT NOW()');
21+
console.log('✅ Database connection successful');
22+
1423
// Read and execute the schema file
1524
const schemaPath = path.join(__dirname, '../database_schema_postgres.sql');
1625
const schema = await fs.readFile(schemaPath, 'utf8');
1726

27+
console.log('📄 Executing database schema...');
1828
await pool.query(schema);
1929

20-
console.log('✅ PostgreSQL database initialized successfully');
30+
console.log('✅ PostgreSQL database schema applied successfully');
2131

2232
// Create a default competition if none exists
2333
const existingCompetitions = await pool.query('SELECT COUNT(*) as count FROM competitions');
@@ -31,11 +41,13 @@ async function initializeDatabase() {
3141
JSON.stringify({ theme: 'default', difficulty: 'mixed' })
3242
]);
3343
console.log('✅ Default competition created');
44+
} else {
45+
console.log('ℹ️ Database already contains competitions, skipping default creation');
3446
}
3547

3648
} catch (error) {
3749
console.error('❌ Error initializing database:', error);
38-
process.exit(1);
50+
throw error; // Re-throw to let caller handle
3951
} finally {
4052
await pool.end();
4153
}

client/src/cyber-forensics-platform/src/app/api/challenges/generate/route.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,14 @@ export async function POST(request: NextRequest) {
4343
return NextResponse.json({ error: 'Description and competition ID are required' }, { status: 400 });
4444
}
4545

46+
console.log('🔗 Environment:', {
47+
NODE_ENV: process.env.NODE_ENV,
48+
DATABASE_URL: process.env.DATABASE_URL ? 'Present' : 'Missing',
49+
OPENAI_API_KEY: process.env.OPENAI_API_KEY ? 'Present' : 'Missing'
50+
});
51+
4652
const db = getDatabase();
53+
console.log('📊 Database instance created:', db.constructor.name);
4754
await db.connect();
4855

4956
// Build context for intelligent linking
@@ -438,7 +445,7 @@ Create complete, professional websites with realistic business content.`
438445
if (linkToPrevious && previousChallengeData) {
439446
// Find the previous challenge's node
440447
const previousNodes = await db.query(
441-
'SELECT * FROM nodes WHERE challenge_id = (SELECT id FROM challenges WHERE id = ?)',
448+
'SELECT * FROM nodes WHERE challenge_id = $1',
442449
[previousChallengeData.id]
443450
);
444451

@@ -474,11 +481,21 @@ Create complete, professional websites with realistic business content.`
474481
} catch (error) {
475482
console.group(`❌ [${requestId}] Challenge Generation Error`);
476483
console.error('Error:', error);
484+
console.error('Error stack:', error instanceof Error ? error.stack : 'No stack trace');
477485
console.groupEnd();
478486

487+
// Close database connection if it was opened
488+
try {
489+
const db = getDatabase();
490+
await db.close();
491+
} catch (closeError) {
492+
console.error('Error closing database:', closeError);
493+
}
494+
479495
return NextResponse.json({
480496
error: 'Internal server error',
481497
details: error instanceof Error ? error.message : String(error),
498+
stack: error instanceof Error ? error.stack : undefined,
482499
requestId
483500
}, { status: 500 });
484501
}

client/src/cyber-forensics-platform/src/app/api/competitions/[id]/edges/route.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export async function POST(
5757
});
5858

5959
// Return the created edge
60-
const edge = await db.query('SELECT * FROM edges WHERE id = ?', [edgeId]);
60+
const edge = await db.query('SELECT * FROM edges WHERE id = $1', [edgeId]);
6161

6262
await db.close();
6363
return NextResponse.json(edge[0], { status: 201 });

client/src/cyber-forensics-platform/src/lib/database-postgres.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ class PostgresDatabaseManager {
1919
}
2020
}
2121

22-
// Close database connection
22+
// Close database connection - for PostgreSQL with connection pooling, we don't actually close
2323
async close() {
2424
try {
25-
await this.pool.end();
26-
console.log('📊 Database connection closed');
25+
// Don't close the pool as it's shared across requests
26+
// await this.pool.end();
27+
console.log('📊 Database connection closed (pool maintained)');
2728
} catch (err) {
2829
console.error('Database close error:', err);
2930
}
@@ -51,7 +52,7 @@ class PostgresDatabaseManager {
5152
try {
5253
const result = await this.pool.query(sql, params);
5354
return {
54-
id: result.rows[0]?.id || null,
55+
id: result.rows[0]?.id || result.insertId || null,
5556
changes: result.rowCount
5657
};
5758
} catch (err) {

client/src/cyber-forensics-platform/src/lib/database.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@ const sqlite3 = require('sqlite3').verbose();
22
const path = require('path');
33

44
// Import PostgreSQL manager for production
5-
const PostgresDatabaseManager = process.env.NODE_ENV === 'production' ?
6-
require('./database-postgres') : null;
5+
let PostgresDatabaseManager = null;
6+
if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL) {
7+
try {
8+
PostgresDatabaseManager = require('./database-postgres');
9+
} catch (error) {
10+
console.error('Failed to load PostgreSQL manager:', error);
11+
}
12+
}
713

814
class DatabaseManager {
915
constructor() {

0 commit comments

Comments
 (0)