Skip to main content

Overview

Rodando Backend uses TypeORM with PostgreSQL for database management. The application supports automatic database creation, schema synchronization (dev only), and migrations.

Prerequisites

1

Install PostgreSQL

Ensure PostgreSQL 12 or higher is installed and running:
# Check PostgreSQL version
psql --version
2

Start PostgreSQL service

# On Linux/macOS
sudo service postgresql start

# Or using systemctl
sudo systemctl start postgresql

Database Creation

1

Create the database

Connect to PostgreSQL and create the database:
CREATE DATABASE rodando;
Or using the command line:
createdb -U postgres rodando
2

Verify database exists

\l rodando
The application can automatically create the database if it doesn’t exist, thanks to the DatabaseInitService.

Configuration

Configure database connection in your .env file:
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_secure_password
DB_NAME=rodando

TypeORM Configuration

The database configuration is managed by DatabaseConfigService in src/database/database-config/database-config.service.ts:
{
  type: 'postgres',
  host: process.env.DB_HOST,
  port: +process.env.DB_PORT || 5432,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  synchronize: !isProd && DB_SYNCHRONIZE,
  logging: DB_LOGGING,
  autoLoadEntities: true,
  migrationsRun: RUN_MIGRATIONS,
  migrationsTableName: 'migrations_history'
}

Schema Management

Development Mode

For development, you can use automatic schema synchronization:
DB_SYNCHRONIZE=true
DB_LOGGING=true
NODE_ENV=development
Never use DB_SYNCHRONIZE=true in production! It can cause data loss by automatically dropping and recreating tables.

Production Mode

For production, use migrations:
DB_SYNCHRONIZE=false
RUN_MIGRATIONS=true
NODE_ENV=production

Migrations

Generate a Migration

After making changes to your entities, generate a migration:
npm run typeorm:generate -- src/database/migrations/MigrationName
This command:
  1. Compares current entity definitions with the database schema
  2. Generates SQL statements to sync the schema
  3. Creates a timestamped migration file

Run Migrations

Apply pending migrations:
npm run typeorm:run
Or enable automatic migration on startup:
RUN_MIGRATIONS=true

Migration Files

Migrations are stored in:
  • Development: src/database/migrations/*.ts
  • Production: dist/migrations/*.js
All migrations are tracked in the migrations_history table.

Database Initialization

The DatabaseInitService ensures the database exists before TypeORM connects:
// src/database/database-init/database-init.service.ts
await initService.ensureDatabaseExists();
This service:
  1. Connects to the default postgres database
  2. Checks if your application database exists
  3. Creates it if missing
  4. Disconnects from the default database

Connection Testing

1

Test database connection

Start the application and check the logs:
npm run start:dev
You should see:
[TypeORM] Connected to database
2

Enable SQL logging

To see all SQL queries:
DB_LOGGING=true

Database Module

The database is configured as a global module in src/database/database.module.ts:
@Global()
@Module({})
export class DatabaseModule {
  static forRoot(): DynamicModule {
    return {
      module: DatabaseModule,
      imports: [
        ConfigModule.forRoot({ /* ... */ }),
        TypeOrmModule.forRootAsync({ /* ... */ })
      ],
      providers: [DatabaseConfigService, DatabaseInitService],
      exports: [TypeOrmModule, DatabaseInitService]
    };
  }
}

Validation Schema

Database environment variables are validated using Joi:
validationSchema: Joi.object({
  DB_HOST: Joi.string().required(),
  DB_PORT: Joi.number().default(5432),
  DB_USER: Joi.string().required(),
  DB_PASSWORD: Joi.string().required(),
  DB_NAME: Joi.string().required(),
  DB_SYNCHRONIZE: Joi.boolean().default(false),
  DB_LOGGING: Joi.boolean().default(false),
})

Common Issues

Error: ECONNREFUSED ::1:5432Solution:
  • Ensure PostgreSQL is running
  • Check DB_HOST and DB_PORT in .env
  • Try DB_HOST=127.0.0.1 instead of localhost
Error: password authentication failed for userSolution:
  • Verify DB_USER and DB_PASSWORD in .env
  • Check PostgreSQL pg_hba.conf authentication settings
  • Ensure the user has database access permissions
Error: database "rodando" does not existSolution:
  • The DatabaseInitService should create it automatically
  • Or create manually: createdb -U postgres rodando
Error: Migration fails to runSolution:
  • Check the migration file for syntax errors
  • Ensure the database user has appropriate permissions
  • Review the migrations_history table 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

Build docs developers (and LLMs) love