Source code for mcp_ohmy_sql.aws.aws_redshift.query
# -*- coding: utf-8 -*-importtypingasTfromtabulateimporttabulatefrom...lazy_importimportredshift_connectorfrom.utilsimportSessiontry:# pragma: no coverfromrichimportprintasrprintexceptImportError:# pragma: no coverpass
[docs]defformat_result(columns:list[str],records:list[tuple],)->str:""" Format SQL query result into a Markdown table. """rows=list()rows.append(columns)rows.extend(records)text=tabulate(rows,headers="firstrow",tablefmt="pipe",floatfmt=".4f",)returntext
[docs]defensure_valid_select_query(query:str):""" Ensure the query is a valid SELECT statement. """ifquery.upper().strip().startswith("SELECT ")isFalse:raiseValueError("Invalid query: must start with 'SELECT '")
[docs]defexecute_select_query(conn:"redshift_connector.Connection",query:str,params:T.Optional[dict[str,T.Any]]=None,)->str:""" Executes a SQL SELECT query and returns the result formatted as a Markdown table. """try:ensure_valid_select_query(query)exceptValueErrorase:# pragma: no coverreturnf"Error: {e}"withSession(conn)ascursor:try:cursor.execute(query,params)columns=[desc[0]fordescincursor.description]rows=cursor.fetchall()exceptExceptionase:# pragma: no coverreturnf"Error executing query: {e}"try:text=format_result(columns,rows)exceptExceptionase:# pragma: no coverreturnf"Error formatting result: {e}"returntext