# Migration Quick Start Guide

## Pre-Migration Checklist

- [ ] **Backup database** (CRITICAL!)
  ```bash
  turso db shell <database-name> ".backup backup-$(date +%Y%m%d-%H%M%S).db"
  ```

- [ ] **Verify environment variables**
  ```bash
  npm run verify:env
  ```

- [ ] **Review current database state**
  ```bash
  npm run migrate:schema:stats
  npm run migrate:schema:test
  ```

- [ ] **Test dry-run**
  ```bash
  npm run migrate:schema:dry-run
  ```

## Migration Execution

### Option 1: Run All Migrations (Recommended)
```bash
npm run migrate:schema
```

### Option 2: Run Phase by Phase (Conservative)

**Step 1: Phase 1 (Low-Risk Optimizations)**
```bash
npm run migrate:schema:phase1
```

**Step 2: Verify Phase 1**
```bash
npm run migrate:schema:stats
npm run migrate:schema:test
```

**Step 3: Phase 2 (Schema Consistency)**
```bash
npm run migrate:schema:phase2
```

**Step 4: Final Verification**
```bash
npm run verify:schema
```

## Post-Migration Verification

### 1. Check Database Statistics
```bash
npm run migrate:schema:stats
```

Expected output:
- Tables: 9-10
- Indexes: ~40
- Triggers: ~6

### 2. Verify Indexes Created
```bash
npm run migrate:schema:test
```

Expected:
- ✅ idx_memories_user_type: Found
- ✅ idx_memories_user_importance: Found
- ✅ api_key_hash column exists

### 3. Run Schema Verification
```bash
npm run verify:schema
```

All checks should pass.

## Rollback (If Needed)

### Rollback Phase 2 Only
```bash
npm run migrate:schema:rollback --phase="Phase 2"
```

### Rollback Phase 1 Only
```bash
npm run migrate:schema:rollback --phase="Phase 1"
```

### Rollback All
```bash
npm run migrate:schema:rollback
```

⚠️ Wait 5 seconds before rollback executes (safety delay)

### Restore from Backup
```bash
turso db shell <database-name> ".restore backup-YYYYMMDD-HHMMSS.db"
```

## Troubleshooting

### Issue: "Column already exists"
**Solution:** Migration is idempotent. The script detects existing columns and skips them.

### Issue: "Index already exists"
**Solution:** All index creation uses `IF NOT EXISTS` - safe to re-run.

### Issue: "Verification failed"
**Solution:**
1. Check error message
2. Run `npm run migrate:schema:stats` to see current state
3. Re-run specific phase if needed

### Issue: Migration step fails mid-execution
**Solution:**
1. Note which step failed
2. Fix the underlying issue
3. Re-run migration (idempotent - safe to retry)

## Performance Impact

### Expected Results (Phase 1)
- **Index count:** Reduced from ~45 to ~40
- **Query performance:** 10-30% improvement on filtered queries
- **Storage:** Minimal reduction (~1-5%)

### Expected Results (Phase 2)
- **Schema consistency:** 100% aligned with code
- **No performance impact:** Column rename is metadata only

## Monitoring

### During Migration
Watch for:
- Execution time (should be < 1 minute total)
- Any error messages
- Verification failures

### After Migration
Monitor:
- Query performance metrics
- Application error logs
- Database connection stability

## Success Criteria

- [x] All migration steps completed
- [x] Verification passes
- [x] No application errors
- [x] Query performance stable or improved

## Common Commands Reference

| Command | Purpose |
|---------|---------|
| `npm run migrate:schema:dry-run` | Preview changes without applying |
| `npm run migrate:schema:stats` | Show current database state |
| `npm run migrate:schema:test` | Validate migration readiness |
| `npm run migrate:schema` | Run all migrations |
| `npm run migrate:schema:phase1` | Run Phase 1 only |
| `npm run migrate:schema:phase2` | Run Phase 2 only |
| `npm run verify:schema` | Comprehensive schema verification |
| `npm run migrate:schema:rollback` | Rollback all changes |

## Support

If issues arise:
1. Check `MIGRATION-FIXES-SUMMARY.md` for detailed documentation
2. Review error logs
3. Restore from backup if critical
4. Contact database administrator

---

**Last Updated:** 2025-10-02
**Migration Script:** `scripts/migrate-schema-optimization.ts`
**Test Script:** `scripts/test-migration-fixes.ts`
