from datetime import datetime from typing import List, Dict, Any, Optional from sqlalchemy import ( Table, MetaData, select, func, and_, or_, text, Column ) from sqlalchemy.orm import Session from app.models.user import User from app.models.dataset import Dataset, DatasetColumn from app.schemas.chart import ChartSpec, ChartResult, ChartFilter from app.services.permission_service import get_effective_permissions from app.core.exceptions import NotFoundException, ForbiddenException, ValidationException def get_column_expression(table: Table, col_name: str, time_bucket: Optional[str] = None, dialect_name: str = "sqlite") -> Any: """Returns a safe SQLAlchemy Core column expression with optional time bucketing.""" if col_name not in table.c: raise ValidationException(f"Column '{col_name}' does not exist on table") col = table.c[col_name] if time_bucket: if dialect_name == "postgresql": if time_bucket == "month": return func.to_char(col, "YYYY-MM").label("time_bucket") elif time_bucket == "day": return func.to_char(col, "YYYY-MM-DD").label("time_bucket") elif time_bucket == "year": return func.to_char(col, "YYYY").label("time_bucket") else: # SQLite fallback if time_bucket == "month": return func.strftime("%Y-%m", col).label("time_bucket") elif time_bucket == "day": return func.strftime("%Y-%m-%d", col).label("time_bucket") elif time_bucket == "year": return func.strftime("%Y", col).label("time_bucket") return col def build_filter_clause(table: Table, filt: ChartFilter) -> Any: """Builds a parameterized filter condition using SQLAlchemy Core whitelisted columns.""" if filt.column not in table.c: raise ValidationException(f"Filter column '{filt.column}' is not a valid dataset column") col = table.c[filt.column] op = filt.operator.lower() val = filt.value if op == "eq": return col == val elif op == "ne": return col != val elif op == "gt": return col > val elif op == "gte": return col >= val elif op == "lt": return col < val elif op == "lte": return col <= val elif op == "in": if isinstance(val, list): return col.in_(val) else: return col.in_([v.strip() for v in str(val).split(",") if v.strip()]) elif op == "between" and isinstance(val, list) and len(val) == 2: return and_(col >= val[0], col <= val[1]) else: return col == val def execute_chart_query( db: Session, user: User, spec: ChartSpec, preview_user_id: Optional[int] = None, preview_role: Optional[str] = None ) -> ChartResult: """ Validates permissions, whitelists columns, injects row rules, and executes an aggregated query using SQLAlchemy Core with bound parameters. """ # 1. Dataset verification dataset = db.query(Dataset).filter(Dataset.id == spec.dataset_id).first() if not dataset: raise NotFoundException(f"Dataset with ID {spec.dataset_id} not found") # 2. Permission Evaluation eff_perms = get_effective_permissions( db=db, user=user, dataset_id=spec.dataset_id, preview_user_id=preview_user_id, preview_role=preview_role ) if not eff_perms.can_view: raise ForbiddenException("Access denied: You do not have permission to view this dataset") # 3. Whitelist column checks allowed_cols = set(eff_perms.allowed_columns) if spec.dimension and spec.dimension not in allowed_cols: raise ForbiddenException(f"Access to dimension column '{spec.dimension}' is restricted") if spec.measure and spec.measure != "*" and spec.measure not in allowed_cols: raise ForbiddenException(f"Access to measure column '{spec.measure}' is restricted") if spec.secondary_dimension and spec.secondary_dimension not in allowed_cols: raise ForbiddenException(f"Access to secondary dimension '{spec.secondary_dimension}' is restricted") for f in spec.filters: if f.column not in allowed_cols: raise ForbiddenException(f"Filtering on restricted column '{f.column}' is forbidden") # 4. Reflect dynamic table bind = db.get_bind() dialect_name = bind.dialect.name meta = MetaData() table = Table(dataset.table_name, meta, autoload_with=bind) # 5. Build WHERE conditions (Row rules + User filters) where_conditions = [] # Inject enforced row rules (AND intersection) for rule in eff_perms.row_rules: if rule.column_name in table.c: rule_filt = ChartFilter( column=rule.column_name, operator=rule.operator, value=rule.rule_value ) where_conditions.append(build_filter_clause(table, rule_filt)) # Inject client filters for f in spec.filters: where_conditions.append(build_filter_clause(table, f)) where_clause = and_(*where_conditions) if where_conditions else None # 6. Aggregation function agg_op = spec.aggregation.lower() if agg_op == "sum" and spec.measure and spec.measure != "*": agg_metric = func.sum(table.c[spec.measure]).label("metric_value") elif agg_op == "avg" and spec.measure and spec.measure != "*": agg_metric = func.avg(table.c[spec.measure]).label("metric_value") elif agg_op == "min" and spec.measure and spec.measure != "*": agg_metric = func.min(table.c[spec.measure]).label("metric_value") elif agg_op == "max" and spec.measure and spec.measure != "*": agg_metric = func.max(table.c[spec.measure]).label("metric_value") else: agg_metric = func.count().label("metric_value") # 7. Chart-specific query building if spec.chart_type == "kpi": # Total metric query q = select(agg_metric).select_from(table) if where_clause is not None: q = q.where(where_clause) scalar_val = db.execute(q).scalar() or 0 formatted_val = round(float(scalar_val), 1) if isinstance(scalar_val, float) else scalar_val return ChartResult( chart_type="kpi", title=spec.dimension or "Total", kpi_value=formatted_val, kpi_subtext=f"Aggregated {agg_op.upper()} on {dataset.name}", total_records=int(scalar_val) if isinstance(scalar_val, (int, float)) else 0, applied_rules_count=len(eff_perms.row_rules) ) # Dimensional Query dim_expr = get_column_expression(table, spec.dimension, spec.time_bucket, dialect_name) select_items = [dim_expr.label("dim_label"), agg_metric] group_items = [dim_expr] if spec.secondary_dimension: sec_dim = table.c[spec.secondary_dimension].label("sec_dim_label") select_items.append(sec_dim) group_items.append(sec_dim) query = select(*select_items).group_by(*group_items) if where_clause is not None: query = query.where(where_clause) # Ordering if spec.order == "asc": query = query.order_by(agg_metric.asc()) else: query = query.order_by(agg_metric.desc()) if spec.limit: query = query.limit(spec.limit) rows = db.execute(query).fetchall() # 8. Shape Data for ECharts categories: List[str] = [] series_data: List[Dict[str, Any]] = [] raw_aggregated: List[Dict[str, Any]] = [] total_recs = 0 if not spec.secondary_dimension: values = [] for r in rows: label = str(r[0]) if r[0] is not None else "(Blank)" val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0) categories.append(label) values.append(val) raw_aggregated.append({"name": label, "value": val}) total_recs += (val if isinstance(val, int) else 1) series_data.append({ "name": spec.dimension or "Count", "type": "pie" if spec.chart_type in ("pie", "donut") else ("line" if spec.chart_type in ("line", "area") else "bar"), "data": values }) else: # Grouped / Stacked query distinct_categories = [] distinct_sec = [] matrix: Dict[str, Dict[str, Any]] = {} for r in rows: dim_lbl = str(r[0]) if r[0] is not None else "(Blank)" sec_lbl = str(r[2]) if r[2] is not None else "(Blank)" val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0) if dim_lbl not in distinct_categories: distinct_categories.append(dim_lbl) if sec_lbl not in distinct_sec: distinct_sec.append(sec_lbl) if sec_lbl not in matrix: matrix[sec_lbl] = {} matrix[sec_lbl][dim_lbl] = val raw_aggregated.append({"dimension": dim_lbl, "secondary": sec_lbl, "value": val}) categories = distinct_categories for s in distinct_sec: s_data = [matrix.get(s, {}).get(cat, 0) for cat in categories] series_data.append({ "name": s, "type": "bar", "stack": "total" if spec.chart_type == "stacked_bar" else None, "data": s_data }) return ChartResult( chart_type=spec.chart_type, title=f"{dataset.name} by {spec.dimension}", categories=categories, series=series_data, data=raw_aggregated, total_records=total_recs, applied_rules_count=len(eff_perms.row_rules) )