# Chat Database Migration Guide

This guide will help you migrate your chat database from the current server to a new PostgreSQL server.

## Overview
Your chat system uses:
- Database: `rocketchat_converted` (PostgreSQL)
- Main tables: users, message, room, uploads, avatars, subscription
- File storage: db-convert/db/files/ directory with uploads and avatars
- Environment configuration for database connection

## Migration Steps

### 1. Pre-Migration Setup

On your **new server**, ensure PostgreSQL is installed and running:
```bash
# Install PostgreSQL (if not already done)
sudo apt update
sudo apt install postgresql postgresql-contrib

# Start PostgreSQL service
sudo systemctl start postgresql
sudo systemctl enable postgresql
```

### 2. Create Database Schema on New Server

Run the provided migration script:
```bash
# On new server
sudo -u postgres psql -f create-new-database.sql
```

### 3. Export Data from Current Server

Run the export script:
```bash
# On current server
./export-chat-data.sh
```

This will create:
- `chat-schema.sql` - Database schema
- `chat-data.sql` - All table data
- `chat-files.tar.gz` - All uploaded files and avatars

### 4. Transfer Data to New Server

```bash
# Copy files to new server
scp chat-schema.sql chat-data.sql chat-files.tar.gz user@new-server:/tmp/
```

### 5. Import Data on New Server

```bash
# On new server
./import-chat-data.sh
```

### 6. Update Configuration

Update your environment variables to point to the new database server.

### 7. Verify Migration

Run the verification script to ensure everything transferred correctly:
```bash
node verify-migration.js
```

## Files Provided

1. `create-new-database.sql` - Creates database and user on new server
2. `export-chat-data.sh` - Exports data from current server
3. `import-chat-data.sh` - Imports data to new server  
4. `verify-migration.js` - Verifies data integrity
5. `update-config-template.env` - Template for new configuration

## Important Notes

- **Backup first**: Always backup your current database before migration
- **Downtime**: Plan for application downtime during migration
- **File permissions**: Ensure file permissions are preserved during transfer
- **Network access**: Ensure new server can accept connections from your application
