Overview
Rodando Backend uses TypeORM with PostgreSQL for database management. The application supports automatic database creation, schema synchronization (dev only), and migrations.Prerequisites
Database Creation
The application can automatically create the database if it doesn’t exist, thanks to the
DatabaseInitService.Configuration
Configure database connection in your.env file:
TypeORM Configuration
The database configuration is managed byDatabaseConfigService in src/database/database-config/database-config.service.ts:
Schema Management
Development Mode
For development, you can use automatic schema synchronization:Production Mode
For production, use migrations:Migrations
Generate a Migration
After making changes to your entities, generate a migration:- Compares current entity definitions with the database schema
- Generates SQL statements to sync the schema
- Creates a timestamped migration file
Run Migrations
Apply pending migrations:Migration Files
Migrations are stored in:- Development:
src/database/migrations/*.ts - Production:
dist/migrations/*.js
migrations_history table.
Database Initialization
TheDatabaseInitService ensures the database exists before TypeORM connects:
- Connects to the default
postgresdatabase - Checks if your application database exists
- Creates it if missing
- Disconnects from the default database
Connection Testing
Database Module
The database is configured as a global module insrc/database/database.module.ts:
Validation Schema
Database environment variables are validated using Joi:Common Issues
Connection refused
Connection refused
Error:
ECONNREFUSED ::1:5432Solution:- Ensure PostgreSQL is running
- Check
DB_HOSTandDB_PORTin.env - Try
DB_HOST=127.0.0.1instead oflocalhost
Authentication failed
Authentication failed
Error:
password authentication failed for userSolution:- Verify
DB_USERandDB_PASSWORDin.env - Check PostgreSQL
pg_hba.confauthentication settings - Ensure the user has database access permissions
Database does not exist
Database does not exist
Error:
database "rodando" does not existSolution:- The
DatabaseInitServiceshould create it automatically - Or create manually:
createdb -U postgres rodando
Migration errors
Migration errors
Error: Migration fails to runSolution:
- Check the migration file for syntax errors
- Ensure the database user has appropriate permissions
- Review the
migrations_historytable for conflicts
Best Practices
Use Migrations
Always use migrations in production. Never rely on schema synchronization.
Backup Regularly
Implement regular database backups before running migrations.
Test Migrations
Test migrations in a staging environment before production.
Version Control
Commit migration files to version control.
Next Steps
Configuration
Learn about environment configuration
WebSockets
Set up real-time features
