Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 5,314 Bytes
d15f07c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | # Database & Data Migrations
This directory contains migration scripts for schema changes and data transformations.
## Available Migrations
### migrate_state_naming.py
**Purpose:** Standardize state field naming across all database tables and parquet files
**What it does:**
- Renames `state` (2-char codes) → `state_code`
- Renames `state_name` (full names) → `state`
- Renames `state_abbr` → `state_code`
- Adds missing `state` (full name) columns where needed
- Populates full state names from codes using lookup table
**Usage:**
```bash
# Dry run (recommended first)
python scripts/migrations/migrate_state_naming.py --dry-run --all
# Migrate database tables only
python scripts/migrations/migrate_state_naming.py --tables
# Migrate parquet files only
python scripts/migrations/migrate_state_naming.py --parquets
# Migrate everything
python scripts/migrations/migrate_state_naming.py --all
```
**Safety:**
- Always runs in dry-run mode by default if no target specified
- Creates `.parquet.backup` files before modifying parquet files
- Shows all changes before applying them
- Can be run multiple times safely (idempotent)
**Affected Tables:**
- `jurisdiction`
- `contact`
- `event`
- `organization_nonprofit`
- `bills_search`
- `bill_map_aggregate`
- `jurisdictions_details_search`
- `zip_county_mapping`
- + 8 more tables with state columns
**Affected Files:**
- `data/gold/states/{STATE}/*.parquet` (all state-specific parquets)
- `data/gold/jurisdictions_details.parquet`
## Best Practices
### Before Running Migrations
1. **Backup your database:**
```bash
pg_dump -h localhost -p 5433 -U postgres open_navigator > backup_$(date +%Y%m%d).sql
```
2. **Test in dry-run mode:**
```bash
python scripts/migrations/migrate_state_naming.py --dry-run --all
```
3. **Review the changes:**
- Check the migration plan
- Verify table/file identification
- Confirm backup locations
### After Running Migrations
1. **Verify the migration:**
```sql
-- Check table structure
\d+ jurisdiction
-- Verify data
SELECT state_code, state, COUNT(*)
FROM jurisdiction
GROUP BY state_code, state
LIMIT 10;
```
2. **Test parquet files:**
```python
import pandas as pd
df = pd.read_parquet('data/gold/states/AL/contact_official.parquet')
print(df.columns.tolist())
print(df[['state_code', 'state']].drop_duplicates())
```
3. **Update dependent code:**
- Search for: `WHERE state =`
- Update API endpoints
- Update frontend filters
- Update data loading scripts
## Creating New Migrations
### Template
```python
#!/usr/bin/env python3
"""
Migration: [Brief description]
Changes:
- [Change 1]
- [Change 2]
Usage:
python scripts/migrations/migrate_xxx.py --dry-run
python scripts/migrations/migrate_xxx.py --apply
"""
import os
import sys
from pathlib import Path
import psycopg2
from loguru import logger
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv('NEON_DATABASE_URL_DEV',
'postgresql://postgres:password@localhost:5433/open_navigator')
class XXXMigrator:
def __init__(self, dry_run: bool = True):
self.dry_run = dry_run
def migrate(self):
logger.info("Starting migration...")
conn = psycopg2.connect(DATABASE_URL)
cursor = conn.cursor()
try:
# Migration logic here
if not self.dry_run:
conn.commit()
else:
conn.rollback()
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dry-run', action='store_true', default=True)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
migrator = XXXMigrator(dry_run=not args.apply)
migrator.migrate()
```
### Naming Convention
- Use descriptive names: `migrate_{what}_{when}.py`
- Include date for tracking: `migrate_state_naming_20260503.py`
- Keep migrations in order: `001_`, `002_`, etc.
## Migration History
| Date | Script | Description | Status |
|------|--------|-------------|--------|
| 2026-05-03 | `migrate_state_naming.py` | Standardize state field naming | ✅ Ready |
## Troubleshooting
### Migration failed mid-way
1. Check the error message
2. Restore from backup:
```bash
psql -h localhost -p 5433 -U postgres open_navigator < backup_20260503.sql
```
3. Fix the issue
4. Run migration again
### Parquet file corruption
1. Backups are created as `.parquet.backup`
2. Restore:
```bash
mv file.parquet file.parquet.failed
mv file.parquet.backup file.parquet
```
### Dependent code breaking
1. Search for state field references:
```bash
grep -r "WHERE state = " api/ scripts/ neon/
```
2. Update to use `state_code`:
```python
# Before
query = "SELECT * FROM jurisdictions WHERE state = 'AL'"
# After
query = "SELECT * FROM jurisdictions WHERE state_code = 'AL'"
```
## See Also
- [State Field Naming Standard](../../website/docs/development/state-field-naming-standard.md)
- [GitHub Copilot Instructions](../../.github/copilot-instructions.md)
- [Database Schema](../../packages/hosting/src/hosting/neon/schema.sql)
|