Database Setup
The SSP Backend API uses PostgreSQL as its database and TypeORM as the Object-Relational Mapping (ORM) library. This guide covers database configuration, schema design, and entity management.PostgreSQL Requirements
Minimum Version
- PostgreSQL 12 or higher
- Recommended: PostgreSQL 14 or 15 for best performance
Installation
See the Installation Guide for detailed PostgreSQL installation instructions for your operating system.Database Configuration
Creating the Database
Create a dedicated database for the SSP API:Environment Configuration
Configure database connection in.env:
TypeORM Configuration
Application Module Setup
TypeORM is configured insrc/app.module.ts:12 using the async pattern to inject environment variables:
Configuration Options Explained
autoLoadEntities: true
autoLoadEntities: true
Automatically loads all entities registered in modules without manually adding them to the entities array. This simplifies configuration and reduces boilerplate.
synchronize: false
synchronize: false
IMPORTANT: Disables automatic schema synchronization. This is a safety feature to prevent accidental schema changes in production.
migrationsRun: true
migrationsRun: true
Automatically runs pending migrations when the application starts. This ensures the database schema is always up to date.
migrations: [...]
migrations: [...]
Specifies where TypeORM should look for migration files. Migrations are stored in
src/migrations/.Database Schema
The SSP Backend API uses four main tables:1. usuarios (Users)
Stores user accounts with authentication and role information. Entity:src/shared/users/entities/user.entity.ts:17
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO INCREMENT | User ID |
| nombre | varchar(150) | NOT NULL | Full name |
| rol | enum | NOT NULL | User role (Admin, Psicologo, TrabajoSocial, Guia) |
| nomUsuario | varchar(100) | UNIQUE, NOT NULL | Username for login |
| contrasena | text | NOT NULL | Bcrypt-hashed password |
| estatus | boolean | DEFAULT true | Active/inactive status |
| creadoEn | timestamp | DEFAULT NOW() | Account creation date |
2. beneficiarios (Beneficiaries)
Tracks individuals enrolled in service programs. Entity:src/shared/beneficiarios/beneficiario.entity.ts:14
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO INCREMENT | Beneficiary ID |
| nombre | varchar(150) | NOT NULL | Full name |
| fecha_ingreso | date | DEFAULT CURRENT_DATE | Entry date to program |
| tiempo_asignado | integer | NOT NULL | Assigned service time |
| unidad_tiempo | enum | DEFAULT ‘MESES’ | Time unit (HORAS, MESES) |
| creado_en | timestamp | DEFAULT NOW() | Record creation date |
3. actividades (Activities)
Manages community service activities. Entity:src/shared/actividades/actividad.entity.ts:13
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO INCREMENT | Activity ID |
| nombre | text | UNIQUE, NOT NULL | Activity name |
| descripcion | text | NULLABLE | Activity description |
| objetivo | text | NULLABLE | Activity objective |
| categoria | enum | NULLABLE | Category type |
| activo | boolean | DEFAULT true | Active/inactive status |
4. salud_perfil_general (Health Profiles)
Stores comprehensive health information for beneficiaries. Entity:src/shared/salud/salud.entity.ts:11
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | integer | PRIMARY KEY, AUTO INCREMENT | Health profile ID |
| beneficiario_id | integer | UNIQUE, FOREIGN KEY | Reference to beneficiario |
| esAptoFisico | boolean | DEFAULT true | Physically fit |
| padecEnfermedad | boolean | DEFAULT false | Has illness |
| nombreEnfermedad | varchar(255) | NULLABLE | Illness name |
| consumeSustancias | boolean | DEFAULT false | Consumes substances |
| tipoSustancias | text | NULLABLE | Types of substances |
| afiliadoServicioSalud | varchar(100) | NULLABLE | Health service affiliation |
| necesitaLentes | boolean | DEFAULT false | Needs glasses |
| observacionesMedicas | text | NULLABLE | Medical observations |
| fecha_actualizacion | timestamp | AUTO UPDATE | Last update timestamp |
Entity Relationships
Database Migrations
Migration Strategy
The application uses TypeORM migrations for schema management:Automatic Migration Execution
Migrations run automatically on application startup due to
migrationsRun: true configurationCreating Migrations
To create a new migration:Running Migrations Manually
Migrations run automatically on startup, but you can run them manually:If you don’t have these scripts in
package.json, you can add them or run TypeORM CLI directly.Working with Entities
Registering Entities
Entities are automatically loaded due toautoLoadEntities: true, but they must be registered in their respective modules:
Using Repositories
Inject TypeORM repositories in services:Database Best Practices
Use Transactions
Wrap related database operations in transactions to ensure data consistency
Index Frequently Queried Fields
Add database indexes on fields used in WHERE clauses (e.g.,
nomUsuario is already indexed)Validate Data
Use class-validator decorators on DTOs before saving to database
Handle Errors
Catch and handle database errors appropriately (unique constraint violations, etc.)
Database Maintenance
Backup and Restore
Monitoring
Monitor database connections and performance:Troubleshooting
Connection refused
Connection refused
Ensure PostgreSQL is running and accepting connections:Check
pg_hba.conf for authentication settings.Migration errors
Migration errors
If migrations fail:
- Check migration files for syntax errors
- Verify database user has CREATE/ALTER permissions
- Look at TypeORM logs for specific error messages
- Check if migrations table exists:
SELECT * FROM migrations; - Manually fix schema and mark migration as run if needed
Entity not found
Entity not found
If TypeORM can’t find an entity:
- Ensure entity is registered in module with
TypeOrmModule.forFeature([Entity]) - Verify
autoLoadEntities: truein app.module.ts - Check that entity file has proper decorators (
@Entity,@Column, etc.) - Restart the application after adding new entities
What’s Next?
Seeding Data
Learn how to populate the database with initial data
Environment Variables
Configure database connection settings
Testing
Set up test databases and run tests
Deployment
Deploy the database in production
