224 lines
6.8 KiB
Python
224 lines
6.8 KiB
Python
import csv
|
|
import io
|
|
import re
|
|
from datetime import datetime
|
|
from typing import List, Dict, Any, Tuple
|
|
from sqlalchemy import (
|
|
Table, Column, Integer, String, DateTime, MetaData, select, func, inspect, text
|
|
)
|
|
from sqlalchemy.orm import Session
|
|
from app.models.dataset import Dataset, DatasetColumn
|
|
from app.core.exceptions import ConflictException, NotFoundException, ValidationException
|
|
|
|
|
|
SENSITIVE_FIELD_NAMES = {"mrdnumber", "admittingdoctorname", "doctorname", "patientname"}
|
|
IDENTIFIER_FIELD_NAMES = {"srno", "mrdnumber", "patientid", "id"}
|
|
|
|
|
|
def clean_table_name(name: str) -> str:
|
|
"""Generates a safe SQL table name."""
|
|
clean = re.sub(r"[^a-zA-Z0-9_]", "_", name.lower()).strip("_")
|
|
return f"ds_{clean}"
|
|
|
|
|
|
def parse_datetime_value(val: str) -> Any:
|
|
"""Parses DD-MM-YYYY HH:MM into a Python datetime object."""
|
|
if not val or not val.strip():
|
|
return None
|
|
val = val.strip()
|
|
# Primary format: DD-MM-YYYY HH:MM
|
|
for fmt in ("%d-%m-%Y %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%d/%m/%Y %H:%M"):
|
|
try:
|
|
return datetime.strptime(val, fmt)
|
|
except ValueError:
|
|
continue
|
|
return None
|
|
|
|
|
|
def parse_int_value(val: str) -> Any:
|
|
"""Parses integer or returns None."""
|
|
if not val or not val.strip():
|
|
return None
|
|
try:
|
|
return int(val.strip())
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def register_dataset_from_csv(
|
|
db: Session,
|
|
file_content: bytes,
|
|
dataset_name: str,
|
|
description: str = ""
|
|
) -> Dataset:
|
|
"""
|
|
Ingests CSV data (specifically tuned for hospital admission data),
|
|
creates a dedicated table via SQLAlchemy Core, inserts data in chunks,
|
|
and registers dataset and column metadata.
|
|
"""
|
|
bind = db.get_bind()
|
|
|
|
# Decode CSV content
|
|
text_data = file_content.decode("utf-8-sig", errors="replace")
|
|
csv_reader = csv.DictReader(io.StringIO(text_data))
|
|
fieldnames = csv_reader.fieldnames or []
|
|
|
|
if not fieldnames:
|
|
raise ValidationException("CSV file contains no headers or columns")
|
|
|
|
table_name = clean_table_name(dataset_name)
|
|
|
|
# Check if dataset name already exists
|
|
existing_ds = db.query(Dataset).filter(
|
|
(Dataset.name == dataset_name) | (Dataset.table_name == table_name)
|
|
).first()
|
|
if existing_ds:
|
|
db.delete(existing_ds)
|
|
db.commit()
|
|
|
|
# Drop table if exists on this bind
|
|
try:
|
|
db.execute(text(f'DROP TABLE IF EXISTS "{table_name}"'))
|
|
db.commit()
|
|
except Exception:
|
|
pass
|
|
|
|
# Read rows and infer schema
|
|
rows = list(csv_reader)
|
|
total_rows = len(rows)
|
|
|
|
# Define columns using SQLAlchemy Core with fresh MetaData
|
|
table_meta = MetaData()
|
|
cols = []
|
|
col_metadata = []
|
|
|
|
for f in fieldnames:
|
|
col_lower = f.lower()
|
|
is_sensitive = col_lower in SENSITIVE_FIELD_NAMES
|
|
is_identifier = col_lower in IDENTIFIER_FIELD_NAMES
|
|
|
|
# Determine column data type
|
|
if col_lower == "srno":
|
|
data_type = "integer"
|
|
sa_col = Column(f, Integer, primary_key=True)
|
|
elif "date" in col_lower:
|
|
data_type = "datetime"
|
|
sa_col = Column(f, DateTime, nullable=True)
|
|
elif col_lower == "age":
|
|
data_type = "integer"
|
|
sa_col = Column(f, Integer, nullable=True)
|
|
else:
|
|
data_type = "string"
|
|
sa_col = Column(f, String(255), nullable=True)
|
|
|
|
cols.append(sa_col)
|
|
col_metadata.append({
|
|
"column_name": f,
|
|
"display_name": f.replace("_", " ").title() if "_" in f else f,
|
|
"data_type": data_type,
|
|
"is_sensitive": is_sensitive,
|
|
"is_identifier": is_identifier
|
|
})
|
|
|
|
# Dynamically create table with SQLAlchemy Core
|
|
dynamic_table = Table(table_name, table_meta, *cols, extend_existing=True)
|
|
dynamic_table.create(bind=bind, checkfirst=True)
|
|
|
|
# Prepare batch records
|
|
prepared_records = []
|
|
for r in rows:
|
|
row_dict = {}
|
|
for f in fieldnames:
|
|
col_lower = f.lower()
|
|
val = r.get(f)
|
|
if val is not None:
|
|
val = val.strip()
|
|
if val == "":
|
|
val = None
|
|
|
|
if col_lower == "srno":
|
|
row_dict[f] = parse_int_value(val)
|
|
elif "date" in col_lower:
|
|
row_dict[f] = parse_datetime_value(val)
|
|
elif col_lower == "age":
|
|
row_dict[f] = parse_int_value(val)
|
|
else:
|
|
row_dict[f] = val
|
|
prepared_records.append(row_dict)
|
|
|
|
# Bulk insert in batches of 5000 using SQLAlchemy Core
|
|
batch_size = 5000
|
|
for i in range(0, len(prepared_records), batch_size):
|
|
batch = prepared_records[i : i + batch_size]
|
|
db.execute(dynamic_table.insert(), batch)
|
|
db.commit()
|
|
|
|
# Save Dataset record
|
|
dataset = Dataset(
|
|
name=dataset_name,
|
|
description=description,
|
|
source_type="file",
|
|
table_name=table_name,
|
|
row_count=total_rows,
|
|
column_count=len(fieldnames)
|
|
)
|
|
db.add(dataset)
|
|
db.flush()
|
|
|
|
# Save DatasetColumn records
|
|
for cm in col_metadata:
|
|
db_col = DatasetColumn(
|
|
dataset_id=dataset.id,
|
|
column_name=cm["column_name"],
|
|
display_name=cm["display_name"],
|
|
data_type=cm["data_type"],
|
|
is_sensitive=cm["is_sensitive"],
|
|
is_identifier=cm["is_identifier"]
|
|
)
|
|
db.add(db_col)
|
|
|
|
db.commit()
|
|
db.refresh(dataset)
|
|
return dataset
|
|
|
|
|
|
def get_all_datasets(db: Session) -> List[Dataset]:
|
|
"""Returns all registered datasets with columns."""
|
|
return db.query(Dataset).order_by(Dataset.created_at.desc()).all()
|
|
|
|
|
|
def get_dataset_by_id(db: Session, dataset_id: int) -> Dataset:
|
|
"""Gets dataset details or raises 404."""
|
|
ds = db.query(Dataset).filter(Dataset.id == dataset_id).first()
|
|
if not ds:
|
|
raise NotFoundException(f"Dataset with ID {dataset_id} not found")
|
|
return ds
|
|
|
|
|
|
def update_column_metadata(
|
|
db: Session,
|
|
dataset_id: int,
|
|
column_id: int,
|
|
display_name: str = None,
|
|
is_sensitive: bool = None,
|
|
is_identifier: bool = None
|
|
) -> DatasetColumn:
|
|
"""Updates display name, sensitivity, and identifier flags for a column."""
|
|
col = db.query(DatasetColumn).filter(
|
|
DatasetColumn.id == column_id,
|
|
DatasetColumn.dataset_id == dataset_id
|
|
).first()
|
|
if not col:
|
|
raise NotFoundException(f"Column ID {column_id} for Dataset ID {dataset_id} not found")
|
|
|
|
if display_name is not None:
|
|
col.display_name = display_name
|
|
if is_sensitive is not None:
|
|
col.is_sensitive = is_sensitive
|
|
if is_identifier is not None:
|
|
col.is_identifier = is_identifier
|
|
|
|
db.commit()
|
|
db.refresh(col)
|
|
return col
|