Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix transaction handling in run_sql_postgres and improve cursor management #129

Merged
merged 3 commits into from
Jan 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/vanna/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2013,19 +2013,19 @@ def connect_to_postgres(
raise ValidationError(e)

def run_sql_postgres(sql: str) -> Union[pd.DataFrame, None]:
if conn:
try:
cs = conn.cursor()
try:
with conn.cursor() as cs: # Using a with statement to manage the cursor lifecycle
cs.execute(sql)
results = cs.fetchall()

# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=[desc[0] for desc in cs.description])
return df

except psycopg2.Error as e:
conn.rollback()
raise ValidationError(e)
conn.commit()
return df
except psycopg2.Error as e:
conn.rollback()
raise ValidationError(e)
except Exception as e:
conn.rollback()
raise e

global run_sql
run_sql = run_sql_postgres
Expand Down