Files
bookmarksite/backend/test-db-setup.js
Rainer Koschnick 0abee5b794 Add comprehensive database setup and user management system
- Implement PostgreSQL database schema with users and bookmarks tables
- Add database connection pooling with retry logic and error handling
- Create migration system with automatic schema initialization
- Add database CLI tools for management (init, status, validate, etc.)
- Include comprehensive error handling and diagnostics
- Add development seed data and testing utilities
- Implement health monitoring and connection pool statistics
- Create detailed documentation and troubleshooting guide

Database features:
- Users table with authentication fields and email verification
- Bookmarks table with user association and metadata
- Proper indexes for performance optimization
- Automatic timestamp triggers
- Transaction support with rollback handling
- Connection pooling (20 max connections, 30s idle timeout)
- Graceful shutdown handling

CLI commands available:
- npm run db:init - Initialize database
- npm run db:status - Check database status
- npm run db:validate - Validate schema
- npm run db:test - Run database tests
- npm run db:diagnostics - Full diagnostics
2025-07-19 23:21:50 +02:00

117 lines
4.5 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Test script to verify database setup is working correctly
* This script tests the database connection, schema creation, and basic operations
*/
require('dotenv').config();
const dbConnection = require('./src/database/connection');
const dbInitializer = require('./src/database/init');
const dbUtils = require('./src/database/utils');
async function testDatabaseSetup() {
console.log('🧪 Testing Database Setup...\n');
let testsPassed = 0;
let testsTotal = 0;
function test(name, condition) {
testsTotal++;
if (condition) {
console.log(`${name}`);
testsPassed++;
} else {
console.log(`${name}`);
}
}
try {
// Test 1: Database Connection
console.log('1. Testing database connection...');
await dbConnection.connect();
test('Database connection established', dbConnection.isConnected);
// Test 2: Health Check
console.log('\n2. Testing health check...');
const health = await dbConnection.healthCheck();
test('Health check returns healthy status', health.healthy);
test('Connection pool is configured', health.poolSize >= 0);
// Test 3: Database Initialization
console.log('\n3. Testing database initialization...');
await dbInitializer.initialize();
const status = await dbInitializer.getStatus();
test('Database initialization completed', status.healthy);
test('Migrations table exists', status.migrations.total >= 0);
// Test 4: Schema Validation
console.log('\n4. Testing schema validation...');
const validation = await dbUtils.validateSchema();
test('Schema validation passes', validation.valid);
test('Required tables exist', validation.errors.length === 0);
// Test 5: Table Operations
console.log('\n5. Testing table operations...');
const usersExist = await dbUtils.tableExists('users');
const bookmarksExist = await dbUtils.tableExists('bookmarks');
test('Users table exists', usersExist);
test('Bookmarks table exists', bookmarksExist);
// Test 6: Basic Query Operations
console.log('\n6. Testing query operations...');
const queryResult = await dbConnection.query('SELECT 1 as test');
test('Basic query execution works', queryResult.rows[0].test === 1);
// Test 7: Transaction Support
console.log('\n7. Testing transaction support...');
let transactionWorked = false;
try {
await dbConnection.transaction(async (client) => {
await client.query('SELECT 1');
transactionWorked = true;
});
} catch (error) {
console.error('Transaction test failed:', error);
}
test('Transaction support works', transactionWorked);
// Test 8: Connection Pool Stats
console.log('\n8. Testing connection pool...');
const stats = dbConnection.getStats();
test('Connection pool statistics available', stats.connected);
test('Pool configuration is correct', stats.config && stats.config.max > 0);
// Summary
console.log('\n📊 Test Results:');
console.log(`✅ Passed: ${testsPassed}/${testsTotal}`);
console.log(`❌ Failed: ${testsTotal - testsPassed}/${testsTotal}`);
if (testsPassed === testsTotal) {
console.log('\n🎉 All database tests passed! Setup is working correctly.');
} else {
console.log('\n⚠ Some tests failed. Check the output above for details.');
}
// Display diagnostics
console.log('\n🔍 Database Diagnostics:');
const diagnostics = await dbUtils.diagnostics();
console.log(JSON.stringify(diagnostics, null, 2));
} catch (error) {
console.error('\n❌ Database test failed:', error.message);
if (error.code === 'ECONNREFUSED') {
console.log('\n💡 PostgreSQL is not running. To fix this:');
console.log('1. Install PostgreSQL if not already installed');
console.log('2. Start PostgreSQL service');
console.log('3. Create database: createdb bookmark_manager');
console.log('4. Update .env file with correct credentials');
}
process.exit(1);
} finally {
await dbConnection.close();
}
}
// Run the test
testDatabaseSetup();