Source code for ds_provider_postgresql_py_lib.utils.dataset_rows
"""
**File:** ``dataset_rows.py``
**Region:** ``ds_provider_postgresql_py_lib/utils/dataset_rows``
Dataset Row Helpers
This module contains row execution and dataframe materialization helpers.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pandas as pd
if TYPE_CHECKING:
from sqlalchemy import Table
from sqlalchemy.engine import Connection
from sqlalchemy.sql import Executable
[docs]
def execute_returning_rows(conn: Connection, stmt: Executable) -> list[dict[str, Any]]:
"""
Execute a statement with RETURNING and convert rows to dicts.
Args:
conn: SQLAlchemy connection.
stmt: SQL statement to execute.
Returns:
list[dict[str, Any]]: Returned rows as dictionaries.
"""
return [dict(row) for row in conn.execute(stmt).mappings().all()]
[docs]
def output_from_rows(table: Table, rows: list[dict[str, Any]]) -> pd.DataFrame:
"""
Build output DataFrame using a stable table-column order.
Args:
table: Reflected SQLAlchemy table.
rows: Row dictionaries to materialize.
Returns:
pd.DataFrame: Output DataFrame aligned to table column order.
"""
return pd.DataFrame(rows, columns=list(table.c.keys()))