# Database Partitioning and Initialization Strategy

## Summary
Implemented automatic database initialization and time-based table partitioning to ensure system scalability and ease of deployment.

## Changes

### 1. Database Initialization (`src/db/initializer.js`)
- **Logic**:
  1. **Database Check**: Connects to the default `postgres` database to check if the target database (defined in `.env`) exists. Creates it if missing.
  2. **Schema & Table Check**: Connects to the target database and executes `scripts/init_db.sql`.
  3. **Partition Check**: Calls `PartitionManager` to ensure partition tables exist for the next 30 days.
- **Integration**: Called during application bootstrap in `src/index.js`.

### 2. Table Partitioning (`src/db/partitionManager.js`)
- **Strategy**: Partition by Range on `ts_ms` (milliseconds).
- **Partition Size**: Daily partitions (e.g., `rcu_action.rcu_action_events_20260129`).
- **Automation**:
  - `ensurePartitions(daysAhead)`: Calculates daily ranges and creates partitions if they don't exist.
  - **Scheduled Task**: `node-cron` job runs daily at 00:00 to pre-create partitions for the next 30 days.

### 3. Schema Updates (`scripts/init_db.sql`)
- Modified `rcu_action_events` table definition to use `PARTITION BY RANGE (ts_ms)`.
- **Note**: The primary key `(ts_ms, guid)` supports this partitioning strategy perfectly.

### 4. Code Structure Updates
- **Dependency**: Added `node-cron`.
- **Singleton**: Updated `src/db/databaseManager.js` to export a singleton instance for shared connection pooling.
- **Bootstrap**: Updated `src/index.js` to include initialization and cron scheduling.

## Verification
- **Startup**: Application will auto-initialize DB and partitions on first run.
- **Maintenance**: Cron job ensures future partitions are always ready.
