Database Setup
Dharini uses PostgreSQL with the PostGIS extension for geospatial capabilities.
Local Development
Section titled “Local Development”For local development, PostgreSQL runs in Docker via docker-compose.yml.
Start PostgreSQL
Section titled “Start PostgreSQL”docker compose --profile development up -d postgresConnect to Local Database
Section titled “Connect to Local Database”docker exec -it postgres16-postgis psql -U postgres -d dhariniUseful Commands
Section titled “Useful Commands”-- List all tables\dt
-- Describe table structure\d table_name
-- List all databases\l
-- Connect to different database\c database_name
-- Quit\qProduction with AWS RDS
Section titled “Production with AWS RDS”Create RDS Instance
Section titled “Create RDS Instance”See Production Setup for detailed RDS creation steps.
Connect to RDS
Section titled “Connect to RDS”RDS requires SSL connections in production:
PGSSLMODE=require psql \ -h your-database-instance.xxxxxxxxx.region.rds.amazonaws.com \ -U postgres \ -d postgresInstall Required Extensions
Section titled “Install Required Extensions”After creating the RDS instance, install required PostgreSQL extensions:
-- PostGIS for spatial dataCREATE EXTENSION IF NOT EXISTS postgis;CREATE EXTENSION IF NOT EXISTS postgis_topology;
-- UUID generationCREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Additional extensions (optional)CREATE EXTENSION IF NOT EXISTS pg_trgm; -- For similarity searchesCREATE EXTENSION IF NOT EXISTS btree_gist; -- For specialized indexesVerify extensions:
SELECT * FROM pg_extension;Database Migrations
Section titled “Database Migrations”Dharini uses TypeORM for database migrations.
Run Migrations
Section titled “Run Migrations”On first deployment or after pulling new code:
docker exec -it backend npm run migration:runGenerate New Migration
Section titled “Generate New Migration”After modifying entity files:
docker exec -it backend npm run migration:generate -- -n MigrationNameRevert Last Migration
Section titled “Revert Last Migration”docker exec -it backend npm run migration:revertView Migration Status
Section titled “View Migration Status”Check which migrations have been applied:
SELECT * FROM migrations;Database Schema
Section titled “Database Schema”Dharini’s main tables include:
users- User accounts and authenticationprojects- Surveillance projectsteams- Team organizationroles- User roles and permissionssites- Surveillance sites with geospatial datavisits- Scheduled and completed site visitssamples- Sample collection recordslab_tests- Laboratory test resultsdiseases- Disease definitionssurveillance_types- Types of surveillance activitiesregions- Geographical regionsmedia- Uploaded files and images
Initial Data Setup
Section titled “Initial Data Setup”Create Super Admin User
Section titled “Create Super Admin User”A super admin user is automatically created during migrations:
- Email:
sneha+superadmin@artpark.in - Phone:
99988888665 - Designation:
super-admin
You can modify this in the wipedata script or create additional users via the application.
Wipe and Reinitialize Database
Section titled “Wipe and Reinitialize Database”Warning: This will delete all data!
The repository includes a script for wiping data and recreating the super admin:
# For Docker development setup./jobs/db/wipedata.sh
# For RDS (requires modification of script)# See script comments for RDS usageBackup and Restore
Section titled “Backup and Restore”Backup Database
Section titled “Backup Database”Local (Docker)
Section titled “Local (Docker)”docker exec -it postgres16-postgis pg_dump -U postgres dharini > backup.sqlPGSSLMODE=require pg_dump \ -h your-database-instance.xxxxxxxxx.region.rds.amazonaws.com \ -U postgres \ -d postgres \ > backup.sqlRestore Database
Section titled “Restore Database”Local (Docker)
Section titled “Local (Docker)”docker exec -i postgres16-postgis psql -U postgres dharini < backup.sqlPGSSLMODE=require psql \ -h your-database-instance.xxxxxxxxx.region.rds.amazonaws.com \ -U postgres \ -d postgres \ < backup.sqlAutomated Backups (RDS)
Section titled “Automated Backups (RDS)”RDS provides automated backups:
- Configure retention period (default: 7 days)
- Set backup window (time when backups occur)
- Enable point-in-time recovery for granular restore
Access backups in RDS Console → Your instance → Maintenance & backups
Performance Optimization
Section titled “Performance Optimization”Indexes
Section titled “Indexes”Ensure critical indexes are created:
-- Spatial index on site locationsCREATE INDEX idx_sites_location ON sites USING GIST (location);
-- User lookupsCREATE INDEX idx_users_email ON users(email);CREATE INDEX idx_users_phone ON users("contactNumber");
-- Visit queriesCREATE INDEX idx_visits_site ON visits("siteId");CREATE INDEX idx_visits_date ON visits("visitDate");
-- Sample trackingCREATE INDEX idx_samples_visit ON samples("visitId");CREATE INDEX idx_samples_barcode ON samples("barcode");Connection Pooling
Section titled “Connection Pooling”TypeORM handles connection pooling automatically. Configuration in app.module.ts:
{ type: 'postgres', // ... other config // Connection pool settings (TypeORM defaults) extra: { max: 10, // Maximum pool size idleTimeoutMillis: 30000, }}Query Optimization
Section titled “Query Optimization”Monitor slow queries:
-- Enable slow query logging (RDS)-- Set parameter group: log_min_duration_statement = 1000 (ms)
-- View slow queriesSELECT query, calls, total_time, mean_timeFROM pg_stat_statementsORDER BY mean_time DESCLIMIT 10;Security
Section titled “Security”RDS Security
Section titled “RDS Security”-
Network Isolation:
- Place RDS in private subnet
- Only allow access from EC2 security group
-
Encryption:
- Enable encryption at rest
- Force SSL connections
-
Credentials:
- Use strong passwords
- Rotate credentials regularly
- Store in AWS Secrets Manager (optional)
Security Group Rules
Section titled “Security Group Rules”RDS security group inbound rules:
| Type | Port | Source | Description |
|---|---|---|---|
| PostgreSQL | 5432 | EC2 security group | Application access |
Monitoring
Section titled “Monitoring”RDS CloudWatch Metrics
Section titled “RDS CloudWatch Metrics”Monitor key metrics:
- CPUUtilization - Should stay below 80%
- FreeableMemory - Watch for memory pressure
- DatabaseConnections - Monitor connection usage
- ReadLatency / WriteLatency - Query performance
Query Performance
Section titled “Query Performance”Enable Performance Insights in RDS for detailed query analysis.
Connection Count
Section titled “Connection Count”Check active connections:
SELECT count(*) FROM pg_stat_activity;View connection details:
SELECT datname, usename, application_name, client_addr, state, queryFROM pg_stat_activityWHERE datname = 'postgres';Troubleshooting
Section titled “Troubleshooting”Cannot Connect to RDS
Section titled “Cannot Connect to RDS”- Check security group - Ensure EC2 instance can reach RDS
- Verify endpoint - Confirm RDS endpoint is correct
- Test SSL connection:
Terminal window PGSSLMODE=require psql -h your-endpoint -U postgres -d postgres
SSL Connection Errors
Section titled “SSL Connection Errors”If you see “no pg_hba.conf entry for host” errors:
# Always use SSL mode for RDSPGSSLMODE=require psql -h your-rds-endpoint -U postgres -d postgresThe application automatically enables SSL when:
NODE_ENV=productionNODE_ENV=stagingDB_HOSTcontainsrds.amazonaws.com
Migration Failures
Section titled “Migration Failures”Check backend logs:
docker logs backend --tail 100Common issues:
- PostGIS extension not installed
- Insufficient permissions
- Network connectivity to RDS
Database Performance Issues
Section titled “Database Performance Issues”- Check connection count
- Review slow query log
- Analyze explain plans for slow queries:
EXPLAIN ANALYZE SELECT ...;
- Rebuild indexes if needed
- Scale RDS instance if consistently high CPU/memory
Next Steps
Section titled “Next Steps”- Troubleshooting - Common issues and solutions
- Production Setup - Complete deployment guide