# Database Migrations

This directory contains SQL migration scripts for the User Service database schema.

## Migration Files

### 20260126_add_multi_tenancy_support.sql
Adds multi-tenancy support by adding `tenant_id` column to all user-related tables:
- users
- user_profiles
- user_contacts
- verification_codes

**Rollback**: Use `20260126_add_multi_tenancy_support_rollback.sql`

## How to Run Migrations

### Using Docker

```bash
# Run migration
docker exec iconsulting-postgres psql -U postgres -d iconsulting -f /path/to/migration.sql

# Or copy file and run
docker cp migration.sql iconsulting-postgres:/tmp/
docker exec iconsulting-postgres psql -U postgres -d iconsulting -f /tmp/migration.sql
```

### Using psql directly

```bash
psql -U postgres -d iconsulting -f migration.sql
```

### From the project root

```bash
# Run migration on server
ssh user@server "docker exec iconsulting-postgres psql -U postgres -d iconsulting" < migration.sql
```

## Rollback Migrations

To rollback a migration, use the corresponding `*_rollback.sql` file:

```bash
docker exec iconsulting-postgres psql -U postgres -d iconsulting -f rollback_migration.sql
```

## Migration History

| Date | Migration | Description | Status |
|------|-----------|-------------|--------|
| 2026-01-26 | add_multi_tenancy_support | Added tenant_id to user tables | ✅ Applied |

## Best Practices

1. **Always backup before running migrations in production**
2. **Test migrations in development first**
3. **Keep rollback scripts updated**
4. **Document all schema changes**
5. **Use transactions when possible**

## Verification

After running a migration, verify the changes:

```bash
# Check if column was added
docker exec iconsulting-postgres psql -U postgres -d iconsulting -c "\d users"

# Check indexes
docker exec iconsulting-postgres psql -U postgres -d iconsulting -c "\di idx_users_tenant*"
```
