Understanding Database Connections
Database connections are how your application communicates with databases. IlanaORM can manage multiple connections simultaneously, allowing you to work with different databases for different purposes.Database Drivers: IlanaORM requires you to install database drivers separately:
- PostgreSQL:
npm install pg - MySQL:
npm install mysql2 - SQLite:
npm install sqlite3
Real-world analogy: Think of database connections like phone lines to
different offices. You might have one line to your main office (primary
database), another to your analytics department (reporting database), and a
third to your testing facility (test database).
Single Database Setup
Basic Configuration
Using the Connection
Multiple Database Connections
Configuration
Using Specific Connections
In Models
In Queries
Runtime Connection Switching
Connection Patterns
Read/Write Splitting
Microservices Pattern
Environment-Based Connections
Connection Management
Connection Pooling
Connection Health Checks
Connection Retry Logic
Migrations with Multiple Connections
Connection-Specific Migrations
Migration Configuration
Cross-Connection Data Migration
Testing with Multiple Connections
Test Configuration
Test Helpers
Performance Optimization
Connection Monitoring
Query Distribution
Best Practices
1. Use Descriptive Connection Names
2. Configure Appropriate Pool Sizes
3. Handle Connection Failures Gracefully
4. Document Connection Usage
Troubleshooting
Connection Pool Exhausted
Connection Pool Exhausted
Problem: “Pool exhausted” or “Connection timeout” errorsSolutions:
- Increase pool size:
pool: { max: 20 } - Check for connection leaks (unclosed connections)
- Reduce connection timeout:
acquireTimeoutMillis: 10000 - Monitor slow queries that hold connections
Connection Refused
Connection Refused
Problem: Cannot connect to databaseSolutions:
- Verify host, port, username, password
- Check network connectivity and firewall rules
- Ensure database server is running
- Test connection with database client tools
Wrong Database Used
Wrong Database Used
Problem: Query executed on wrong databaseSolutions:
- Explicitly specify connection:
Model.connection('specific') - Check model’s static connection property
- Verify default connection in config
- Use connection-specific queries:
Model.on('connection_name')
Next Steps
Advanced Events
Learn about model events and lifecycle hooks
Model Observers
Organize event handling with observer classes
