virtual-data-analyst / functions /sqlite_functions.py
nolanzandi's picture
Table generation and download
e7b4bfb verified
raw
history blame
1.34 kB
from typing import List
from haystack import component
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)
import sqlite3
from utils import TEMP_DIR
@component
class SQLiteQuery:
def __init__(self, sql_database: str):
self.connection = sqlite3.connect(sql_database, check_same_thread=False)
@component.output_types(results=List[str], queries=List[str])
def run(self, queries: List[str]):
print("ATTEMPTING TO RUN QUERY")
results = []
for query in queries:
result = pd.read_sql(query, self.connection)
results.append(f"{result}")
self.connection.close()
return {"results": results, "queries": queries}
def sqlite_query_func(queries: List[str], session_hash):
dir_path = TEMP_DIR / str(session_hash)
sql_query = SQLiteQuery(f'{dir_path}/data_source.db')
try:
result = sql_query.run(queries)
return {"reply": result["results"][0]}
except Exception as e:
reply = f"""There was an error running the SQL Query = {queries}
The error is {e},
You should probably try again.
"""
return {"reply": reply}