2026-01-06 17:22:26 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""
|
|
|
|
|
Migration script to import CSV data into PostgreSQL database.
|
|
|
|
|
|
|
|
|
|
Usage:
|
|
|
|
|
python scripts/migrate_csv_to_db.py [--drop] [--geocode]
|
|
|
|
|
|
|
|
|
|
Options:
|
|
|
|
|
--drop Drop existing tables before migration
|
|
|
|
|
--geocode Geocode postcodes (requires network access)
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import os
|
2026-01-06 22:22:33 +00:00
|
|
|
import sys
|
2026-01-06 17:22:26 +00:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
# Add parent directory to path for imports
|
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
import re
|
2026-01-06 22:22:33 +00:00
|
|
|
from typing import Dict, Optional
|
|
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
import pandas as pd
|
2026-01-06 17:22:26 +00:00
|
|
|
import requests
|
|
|
|
|
|
|
|
|
|
from backend.config import settings
|
2026-01-06 22:22:33 +00:00
|
|
|
from backend.models import (
|
2026-01-06 22:31:57 +00:00
|
|
|
RESULT_FIELD_MAPPING,
|
|
|
|
|
SCHOOL_FIELD_MAPPING,
|
2026-01-06 22:22:33 +00:00
|
|
|
School,
|
|
|
|
|
SchoolResult,
|
|
|
|
|
)
|
2026-01-06 17:22:26 +00:00
|
|
|
from backend.schemas import (
|
|
|
|
|
COLUMN_MAPPINGS,
|
2026-01-06 22:31:57 +00:00
|
|
|
LA_CODE_TO_NAME,
|
|
|
|
|
NULL_VALUES,
|
2026-01-06 17:22:26 +00:00
|
|
|
NUMERIC_COLUMNS,
|
|
|
|
|
SCHOOL_TYPE_MAP,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_numeric(value) -> Optional[float]:
|
|
|
|
|
"""Parse a numeric value, handling special cases."""
|
|
|
|
|
if pd.isna(value):
|
|
|
|
|
return None
|
|
|
|
|
if isinstance(value, (int, float)):
|
|
|
|
|
return float(value) if not np.isnan(value) else None
|
|
|
|
|
str_val = str(value).strip().upper()
|
2026-01-06 22:22:33 +00:00
|
|
|
if str_val in NULL_VALUES or str_val == "":
|
2026-01-06 17:22:26 +00:00
|
|
|
return None
|
2026-01-06 22:22:33 +00:00
|
|
|
# Remove percentage signs if present
|
|
|
|
|
str_val = str_val.replace("%", "")
|
2026-01-06 17:22:26 +00:00
|
|
|
try:
|
|
|
|
|
return float(str_val)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_year_from_folder(folder_name: str) -> Optional[int]:
|
|
|
|
|
"""Extract year from folder name like '2023-2024'."""
|
2026-01-06 22:22:33 +00:00
|
|
|
match = re.search(r"(\d{4})-(\d{4})", folder_name)
|
2026-01-06 17:22:26 +00:00
|
|
|
if match:
|
|
|
|
|
return int(match.group(2))
|
2026-01-06 22:22:33 +00:00
|
|
|
match = re.search(r"(\d{4})", folder_name)
|
2026-01-06 17:22:26 +00:00
|
|
|
if match:
|
|
|
|
|
return int(match.group(1))
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def geocode_postcodes_bulk(postcodes: list) -> Dict[str, tuple]:
|
|
|
|
|
"""
|
|
|
|
|
Geocode postcodes in bulk using postcodes.io API.
|
|
|
|
|
Returns dict of postcode -> (latitude, longitude).
|
|
|
|
|
"""
|
|
|
|
|
results = {}
|
2026-01-06 22:22:33 +00:00
|
|
|
valid_postcodes = [
|
|
|
|
|
p.strip().upper()
|
|
|
|
|
for p in postcodes
|
|
|
|
|
if p and isinstance(p, str) and len(p.strip()) >= 5
|
|
|
|
|
]
|
2026-01-06 17:22:26 +00:00
|
|
|
valid_postcodes = list(set(valid_postcodes))
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if not valid_postcodes:
|
|
|
|
|
return results
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
batch_size = 100
|
|
|
|
|
total_batches = (len(valid_postcodes) + batch_size - 1) // batch_size
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
for i, batch_start in enumerate(range(0, len(valid_postcodes), batch_size)):
|
2026-01-06 22:22:33 +00:00
|
|
|
batch = valid_postcodes[batch_start : batch_start + batch_size]
|
|
|
|
|
print(
|
|
|
|
|
f" Geocoding batch {i + 1}/{total_batches} ({len(batch)} postcodes)..."
|
|
|
|
|
)
|
|
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
try:
|
|
|
|
|
response = requests.post(
|
2026-01-06 22:22:33 +00:00
|
|
|
"https://api.postcodes.io/postcodes",
|
|
|
|
|
json={"postcodes": batch},
|
|
|
|
|
timeout=30,
|
2026-01-06 17:22:26 +00:00
|
|
|
)
|
|
|
|
|
if response.status_code == 200:
|
|
|
|
|
data = response.json()
|
2026-01-06 22:22:33 +00:00
|
|
|
for item in data.get("result", []):
|
|
|
|
|
if item and item.get("result"):
|
|
|
|
|
pc = item["query"].upper()
|
|
|
|
|
lat = item["result"].get("latitude")
|
|
|
|
|
lon = item["result"].get("longitude")
|
2026-01-06 17:22:26 +00:00
|
|
|
if lat and lon:
|
|
|
|
|
results[pc] = (lat, lon)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f" Warning: Geocoding batch failed: {e}")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_csv_data(data_dir: Path) -> pd.DataFrame:
|
|
|
|
|
"""Load all CSV data from data directory."""
|
|
|
|
|
all_data = []
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
for folder in sorted(data_dir.iterdir()):
|
|
|
|
|
if not folder.is_dir():
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
year = extract_year_from_folder(folder.name)
|
|
|
|
|
if not year:
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 20:56:09 +00:00
|
|
|
# Specifically look for the KS2 results file
|
|
|
|
|
ks2_file = folder / "england_ks2final.csv"
|
|
|
|
|
if not ks2_file.exists():
|
2026-01-06 17:22:26 +00:00
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 20:56:09 +00:00
|
|
|
csv_file = ks2_file
|
2026-01-06 17:22:26 +00:00
|
|
|
print(f" Loading {csv_file.name} (year {year})...")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
try:
|
2026-01-06 22:22:33 +00:00
|
|
|
df = pd.read_csv(csv_file, encoding="latin-1", low_memory=False)
|
2026-01-06 17:22:26 +00:00
|
|
|
except Exception as e:
|
|
|
|
|
print(f" Error loading {csv_file}: {e}")
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Rename columns
|
|
|
|
|
df.rename(columns=COLUMN_MAPPINGS, inplace=True)
|
2026-01-06 22:22:33 +00:00
|
|
|
df["year"] = year
|
|
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Handle local authority name
|
2026-01-06 22:22:33 +00:00
|
|
|
la_name_cols = ["LANAME", "LA (name)", "LA_NAME", "LA NAME"]
|
2026-01-06 17:22:26 +00:00
|
|
|
la_name_col = next((c for c in la_name_cols if c in df.columns), None)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
|
|
|
|
if la_name_col and la_name_col != "local_authority":
|
|
|
|
|
df["local_authority"] = df[la_name_col]
|
|
|
|
|
elif "LEA" in df.columns:
|
|
|
|
|
df["local_authority_code"] = pd.to_numeric(df["LEA"], errors="coerce")
|
|
|
|
|
df["local_authority"] = (
|
|
|
|
|
df["local_authority_code"]
|
|
|
|
|
.map(LA_CODE_TO_NAME)
|
|
|
|
|
.fillna(df["LEA"].astype(str))
|
|
|
|
|
)
|
|
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Store LEA code
|
2026-01-06 22:22:33 +00:00
|
|
|
if "LEA" in df.columns:
|
|
|
|
|
df["local_authority_code"] = pd.to_numeric(df["LEA"], errors="coerce")
|
|
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Map school type
|
2026-01-06 22:22:33 +00:00
|
|
|
if "school_type_code" in df.columns:
|
|
|
|
|
df["school_type"] = (
|
|
|
|
|
df["school_type_code"]
|
|
|
|
|
.map(SCHOOL_TYPE_MAP)
|
|
|
|
|
.fillna(df["school_type_code"])
|
|
|
|
|
)
|
|
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Create combined address
|
2026-01-06 22:22:33 +00:00
|
|
|
addr_parts = ["address1", "address2", "town", "postcode"]
|
2026-01-06 17:22:26 +00:00
|
|
|
for col in addr_parts:
|
|
|
|
|
if col not in df.columns:
|
|
|
|
|
df[col] = None
|
2026-01-06 22:22:33 +00:00
|
|
|
|
|
|
|
|
df["address"] = df.apply(
|
|
|
|
|
lambda r: ", ".join(
|
|
|
|
|
str(v)
|
|
|
|
|
for v in [
|
|
|
|
|
r.get("address1"),
|
|
|
|
|
r.get("address2"),
|
|
|
|
|
r.get("town"),
|
|
|
|
|
r.get("postcode"),
|
|
|
|
|
]
|
|
|
|
|
if pd.notna(v) and str(v).strip()
|
|
|
|
|
),
|
|
|
|
|
axis=1,
|
2026-01-06 17:22:26 +00:00
|
|
|
)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
all_data.append(df)
|
|
|
|
|
print(f" Loaded {len(df)} records")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if all_data:
|
|
|
|
|
result = pd.concat(all_data, ignore_index=True)
|
|
|
|
|
print(f"\nTotal records loaded: {len(result)}")
|
|
|
|
|
print(f"Unique schools: {result['urn'].nunique()}")
|
|
|
|
|
print(f"Years: {sorted(result['year'].unique())}")
|
|
|
|
|
return result
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def migrate_data(df: pd.DataFrame, geocode: bool = False):
|
|
|
|
|
"""Migrate DataFrame data to database."""
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 21:12:47 +00:00
|
|
|
# Clean URN column - convert to integer, drop invalid values
|
|
|
|
|
df = df.copy()
|
2026-01-06 22:22:33 +00:00
|
|
|
df["urn"] = pd.to_numeric(df["urn"], errors="coerce")
|
|
|
|
|
df = df.dropna(subset=["urn"])
|
|
|
|
|
df["urn"] = df["urn"].astype(int)
|
|
|
|
|
|
2026-01-06 21:12:47 +00:00
|
|
|
# Group by URN to get unique schools (use latest year's data)
|
2026-01-06 22:22:33 +00:00
|
|
|
school_data = (
|
|
|
|
|
df.sort_values("year", ascending=False).groupby("urn").first().reset_index()
|
|
|
|
|
)
|
2026-01-06 17:22:26 +00:00
|
|
|
print(f"\nMigrating {len(school_data)} unique schools...")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Geocode if requested
|
|
|
|
|
geocoded = {}
|
2026-01-06 22:22:33 +00:00
|
|
|
if geocode and "postcode" in df.columns:
|
2026-01-06 17:22:26 +00:00
|
|
|
print("\nGeocoding postcodes...")
|
2026-01-06 22:22:33 +00:00
|
|
|
postcodes = df["postcode"].dropna().unique().tolist()
|
2026-01-06 17:22:26 +00:00
|
|
|
geocoded = geocode_postcodes_bulk(postcodes)
|
|
|
|
|
print(f" Successfully geocoded {len(geocoded)} postcodes")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
with get_db_session() as db:
|
|
|
|
|
# Create schools
|
|
|
|
|
urn_to_school_id = {}
|
|
|
|
|
schools_created = 0
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
for _, row in school_data.iterrows():
|
2026-01-06 21:01:49 +00:00
|
|
|
# Safely parse URN - handle None, NaN, whitespace, and invalid values
|
2026-01-06 22:22:33 +00:00
|
|
|
urn_val = row.get("urn")
|
2026-01-06 21:01:49 +00:00
|
|
|
urn = None
|
|
|
|
|
if pd.notna(urn_val):
|
|
|
|
|
try:
|
|
|
|
|
urn_str = str(urn_val).strip()
|
|
|
|
|
if urn_str:
|
|
|
|
|
urn = int(float(urn_str)) # Handle "12345.0" format
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
pass
|
2026-01-06 17:22:26 +00:00
|
|
|
if not urn:
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 21:12:47 +00:00
|
|
|
# Skip if we've already added this URN (handles duplicates in source data)
|
|
|
|
|
if urn in urn_to_school_id:
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Get geocoding data
|
2026-01-06 22:22:33 +00:00
|
|
|
postcode = row.get("postcode")
|
2026-01-06 17:22:26 +00:00
|
|
|
lat, lon = None, None
|
|
|
|
|
if postcode and pd.notna(postcode):
|
|
|
|
|
coords = geocoded.get(str(postcode).strip().upper())
|
|
|
|
|
if coords:
|
|
|
|
|
lat, lon = coords
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 21:01:49 +00:00
|
|
|
# Safely parse local_authority_code
|
|
|
|
|
la_code = None
|
2026-01-06 22:22:33 +00:00
|
|
|
la_code_val = row.get("local_authority_code")
|
2026-01-06 21:01:49 +00:00
|
|
|
if pd.notna(la_code_val):
|
|
|
|
|
try:
|
|
|
|
|
la_code_str = str(la_code_val).strip()
|
|
|
|
|
if la_code_str:
|
|
|
|
|
la_code = int(float(la_code_str))
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
pass
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
school = School(
|
|
|
|
|
urn=urn,
|
2026-01-06 22:22:33 +00:00
|
|
|
school_name=row.get("school_name")
|
|
|
|
|
if pd.notna(row.get("school_name"))
|
|
|
|
|
else "Unknown",
|
|
|
|
|
local_authority=row.get("local_authority")
|
|
|
|
|
if pd.notna(row.get("local_authority"))
|
|
|
|
|
else None,
|
2026-01-06 21:01:49 +00:00
|
|
|
local_authority_code=la_code,
|
2026-01-06 22:22:33 +00:00
|
|
|
school_type=row.get("school_type")
|
|
|
|
|
if pd.notna(row.get("school_type"))
|
|
|
|
|
else None,
|
|
|
|
|
school_type_code=row.get("school_type_code")
|
|
|
|
|
if pd.notna(row.get("school_type_code"))
|
|
|
|
|
else None,
|
|
|
|
|
religious_denomination=row.get("religious_denomination")
|
|
|
|
|
if pd.notna(row.get("religious_denomination"))
|
|
|
|
|
else None,
|
|
|
|
|
age_range=row.get("age_range")
|
|
|
|
|
if pd.notna(row.get("age_range"))
|
|
|
|
|
else None,
|
|
|
|
|
address1=row.get("address1") if pd.notna(row.get("address1")) else None,
|
|
|
|
|
address2=row.get("address2") if pd.notna(row.get("address2")) else None,
|
|
|
|
|
town=row.get("town") if pd.notna(row.get("town")) else None,
|
|
|
|
|
postcode=row.get("postcode") if pd.notna(row.get("postcode")) else None,
|
2026-01-06 17:22:26 +00:00
|
|
|
latitude=lat,
|
|
|
|
|
longitude=lon,
|
|
|
|
|
)
|
|
|
|
|
db.add(school)
|
|
|
|
|
db.flush() # Get the ID
|
|
|
|
|
urn_to_school_id[urn] = school.id
|
|
|
|
|
schools_created += 1
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if schools_created % 1000 == 0:
|
|
|
|
|
print(f" Created {schools_created} schools...")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
print(f" Created {schools_created} schools")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Create results
|
|
|
|
|
print(f"\nMigrating {len(df)} yearly results...")
|
|
|
|
|
results_created = 0
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
for _, row in df.iterrows():
|
2026-01-06 21:01:49 +00:00
|
|
|
# Safely parse URN
|
2026-01-06 22:22:33 +00:00
|
|
|
urn_val = row.get("urn")
|
2026-01-06 21:01:49 +00:00
|
|
|
urn = None
|
|
|
|
|
if pd.notna(urn_val):
|
|
|
|
|
try:
|
|
|
|
|
urn_str = str(urn_val).strip()
|
|
|
|
|
if urn_str:
|
|
|
|
|
urn = int(float(urn_str))
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
pass
|
2026-01-06 17:22:26 +00:00
|
|
|
if not urn or urn not in urn_to_school_id:
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
school_id = urn_to_school_id[urn]
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 21:01:49 +00:00
|
|
|
# Safely parse year
|
2026-01-06 22:22:33 +00:00
|
|
|
year_val = row.get("year")
|
2026-01-06 21:01:49 +00:00
|
|
|
year = None
|
|
|
|
|
if pd.notna(year_val):
|
|
|
|
|
try:
|
|
|
|
|
year = int(float(str(year_val).strip()))
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
pass
|
2026-01-06 17:22:26 +00:00
|
|
|
if not year:
|
|
|
|
|
continue
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
result = SchoolResult(
|
|
|
|
|
school_id=school_id,
|
|
|
|
|
year=year,
|
2026-01-06 22:22:33 +00:00
|
|
|
total_pupils=parse_numeric(row.get("total_pupils")),
|
|
|
|
|
eligible_pupils=parse_numeric(row.get("eligible_pupils")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Expected Standard
|
2026-01-06 22:22:33 +00:00
|
|
|
rwm_expected_pct=parse_numeric(row.get("rwm_expected_pct")),
|
|
|
|
|
reading_expected_pct=parse_numeric(row.get("reading_expected_pct")),
|
|
|
|
|
writing_expected_pct=parse_numeric(row.get("writing_expected_pct")),
|
|
|
|
|
maths_expected_pct=parse_numeric(row.get("maths_expected_pct")),
|
|
|
|
|
gps_expected_pct=parse_numeric(row.get("gps_expected_pct")),
|
|
|
|
|
science_expected_pct=parse_numeric(row.get("science_expected_pct")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Higher Standard
|
2026-01-06 22:22:33 +00:00
|
|
|
rwm_high_pct=parse_numeric(row.get("rwm_high_pct")),
|
|
|
|
|
reading_high_pct=parse_numeric(row.get("reading_high_pct")),
|
|
|
|
|
writing_high_pct=parse_numeric(row.get("writing_high_pct")),
|
|
|
|
|
maths_high_pct=parse_numeric(row.get("maths_high_pct")),
|
|
|
|
|
gps_high_pct=parse_numeric(row.get("gps_high_pct")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Progress
|
2026-01-06 22:22:33 +00:00
|
|
|
reading_progress=parse_numeric(row.get("reading_progress")),
|
|
|
|
|
writing_progress=parse_numeric(row.get("writing_progress")),
|
|
|
|
|
maths_progress=parse_numeric(row.get("maths_progress")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Averages
|
2026-01-06 22:22:33 +00:00
|
|
|
reading_avg_score=parse_numeric(row.get("reading_avg_score")),
|
|
|
|
|
maths_avg_score=parse_numeric(row.get("maths_avg_score")),
|
|
|
|
|
gps_avg_score=parse_numeric(row.get("gps_avg_score")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Context
|
2026-01-06 22:22:33 +00:00
|
|
|
disadvantaged_pct=parse_numeric(row.get("disadvantaged_pct")),
|
|
|
|
|
eal_pct=parse_numeric(row.get("eal_pct")),
|
|
|
|
|
sen_support_pct=parse_numeric(row.get("sen_support_pct")),
|
|
|
|
|
sen_ehcp_pct=parse_numeric(row.get("sen_ehcp_pct")),
|
|
|
|
|
stability_pct=parse_numeric(row.get("stability_pct")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Gender
|
2026-01-06 22:22:33 +00:00
|
|
|
rwm_expected_boys_pct=parse_numeric(row.get("rwm_expected_boys_pct")),
|
|
|
|
|
rwm_expected_girls_pct=parse_numeric(row.get("rwm_expected_girls_pct")),
|
|
|
|
|
rwm_high_boys_pct=parse_numeric(row.get("rwm_high_boys_pct")),
|
|
|
|
|
rwm_high_girls_pct=parse_numeric(row.get("rwm_high_girls_pct")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# Disadvantaged
|
2026-01-06 22:22:33 +00:00
|
|
|
rwm_expected_disadvantaged_pct=parse_numeric(
|
|
|
|
|
row.get("rwm_expected_disadvantaged_pct")
|
|
|
|
|
),
|
|
|
|
|
rwm_expected_non_disadvantaged_pct=parse_numeric(
|
|
|
|
|
row.get("rwm_expected_non_disadvantaged_pct")
|
|
|
|
|
),
|
|
|
|
|
disadvantaged_gap=parse_numeric(row.get("disadvantaged_gap")),
|
2026-01-06 17:22:26 +00:00
|
|
|
# 3-Year
|
2026-01-06 22:22:33 +00:00
|
|
|
rwm_expected_3yr_pct=parse_numeric(row.get("rwm_expected_3yr_pct")),
|
|
|
|
|
reading_avg_3yr=parse_numeric(row.get("reading_avg_3yr")),
|
|
|
|
|
maths_avg_3yr=parse_numeric(row.get("maths_avg_3yr")),
|
2026-01-06 17:22:26 +00:00
|
|
|
)
|
|
|
|
|
db.add(result)
|
|
|
|
|
results_created += 1
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if results_created % 10000 == 0:
|
|
|
|
|
print(f" Created {results_created} results...")
|
|
|
|
|
db.flush()
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
print(f" Created {results_created} results")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
# Commit all changes
|
|
|
|
|
db.commit()
|
|
|
|
|
print("\nMigration complete!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2026-01-06 22:22:33 +00:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
|
description="Migrate CSV data to PostgreSQL database"
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--drop", action="store_true", help="Drop existing tables before migration"
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument("--geocode", action="store_true", help="Geocode postcodes")
|
2026-01-06 17:22:26 +00:00
|
|
|
args = parser.parse_args()
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
print("=" * 60)
|
|
|
|
|
print("School Data Migration: CSV -> PostgreSQL")
|
|
|
|
|
print("=" * 60)
|
|
|
|
|
print(f"\nDatabase: {settings.database_url.split('@')[-1]}")
|
|
|
|
|
print(f"Data directory: {settings.data_dir}")
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if args.drop:
|
|
|
|
|
print("\n⚠️ Dropping existing tables...")
|
|
|
|
|
Base.metadata.drop_all(bind=engine)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
print("\nCreating tables...")
|
|
|
|
|
Base.metadata.create_all(bind=engine)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
print("\nLoading CSV data...")
|
|
|
|
|
df = load_csv_data(settings.data_dir)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
if df.empty:
|
|
|
|
|
print("No data found to migrate!")
|
|
|
|
|
return 1
|
2026-01-06 22:22:33 +00:00
|
|
|
|
2026-01-06 17:22:26 +00:00
|
|
|
migrate_data(df, geocode=args.geocode)
|
2026-01-06 22:22:33 +00:00
|
|
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2026-01-06 17:22:26 +00:00
|
|
|
sys.exit(main())
|