Skip to content

Commit 7eea2ce

Browse files
committed
added support for cmd specific env vars and auth
1 parent bacc52d commit 7eea2ce

File tree

8 files changed

+68
-181
lines changed

8 files changed

+68
-181
lines changed

.github/workflows/async_server_tests.yaml.disabled

Lines changed: 0 additions & 82 deletions
This file was deleted.

.github/workflows/test.yaml

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@ jobs:
4646
pip install -r requirements.txt
4747
4848
# Windows
49-
- name: Install psycopg2-binary for Windows
49+
- name: Install psycopg
5050
if: matrix.os == 'windows-latest'
5151
run: |
52-
pip install psycopg
52+
pip install psycopg[binary]
5353
shell: powershell
5454
# End Windows
5555

@@ -58,16 +58,14 @@ jobs:
5858
if: matrix.os == 'ubuntu-latest'
5959
run: |
6060
sudo apt-get update
61-
sudo apt-get install -y libpq-dev
62-
pip install psycopg2
61+
pip install psycopg
6362
# End Linux
6463

6564
# macOS
6665
- name: Install PostgreSQL dev libraries on macOS
6766
if: matrix.os == 'macos-latest'
6867
run: |
69-
brew install postgresql@14
70-
pip install psycopg2
68+
pip install psycopg
7169
# End macOS
7270

7371
- name: Install pystackql
@@ -92,15 +90,15 @@ jobs:
9290
shell: bash
9391
if: matrix.os != 'windows-latest'
9492

95-
- name: Debug Shell Information
96-
if: matrix.os == 'windows-latest'
97-
shell: pwsh
98-
run: |
99-
Write-Host "Checking PowerShell version and environment variables:"
100-
$PSVersionTable
101-
Write-Host "Environment variables:"
102-
Get-ChildItem Env:
103-
Write-Host "Current Shell: $SHELL"
93+
# - name: Debug Shell Information
94+
# if: matrix.os == 'windows-latest'
95+
# shell: pwsh
96+
# run: |
97+
# Write-Host "Checking PowerShell version and environment variables:"
98+
# $PSVersionTable
99+
# Write-Host "Environment variables:"
100+
# Get-ChildItem Env:
101+
# Write-Host "Current Shell: $SHELL"
104102

105103
- name: Run tests on Windows
106104
env:

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ Before testing, ensure you have all the required packages installed:
166166
::
167167

168168
pip install -r requirements.txt
169-
pip install psycopg2-binary
169+
pip install psycopg
170170

171171
Once the dependencies are installed, you can run the tests using the provided script:
172172

docs/requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
sphinx_rtd_theme
2-
psycopg2
32
pandas
43
requests
54
IPython

pystackql/_util.py

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -79,30 +79,6 @@ def _download_file(url, path, showprogress=True):
7979
print("ERROR: [_download_file] %s" % (str(e)))
8080
exit(1)
8181

82-
# def _setup(download_dir, platform, showprogress=False):
83-
# try:
84-
# print('installing stackql...')
85-
# binary_name = _get_binary_name(platform)
86-
# url = _get_url()
87-
# print("downloading latest version of stackql from %s to %s" % (url, download_dir))
88-
# archive_file_name = os.path.join(download_dir, os.path.basename(url))
89-
# _download_file(url, archive_file_name, showprogress)
90-
# # if Platform is starting with Darwin, then it is a MacOS
91-
# if platform.startswith('Darwin'):
92-
# unpacked_file_name = os.path.join(download_dir, 'stackql')
93-
# command = 'pkgutil --expand-full {} {}'.format(archive_file_name, unpacked_file_name)
94-
# # if there are files in unpacked_file_name, then remove them
95-
# if os.path.exists(unpacked_file_name):
96-
# os.system('rm -rf {}'.format(unpacked_file_name))
97-
# os.system(command)
98-
# else:
99-
# with zipfile.ZipFile(archive_file_name, 'r') as zip_ref:
100-
# zip_ref.extractall(download_dir)
101-
# os.chmod(os.path.join(download_dir, binary_name), 0o755)
102-
# except Exception as e:
103-
# print("ERROR: [_setup] %s" % (str(e)))
104-
# exit(1)
105-
10682
def _setup(download_dir, platform, showprogress=False):
10783
try:
10884
print('installing stackql...')

pystackql/stackql.py

Lines changed: 52 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -126,51 +126,51 @@ def _connect_to_server(self):
126126
127127
:return: Connection object if successful, or `None` if an error occurred.
128128
:rtype: Connection or None
129-
...
130-
:raises `psycopg2.OperationalError`: Failed to connect to the server.
129+
:raises `psycopg.OperationalError`: Failed to connect to the server.
131130
"""
132131
try:
133-
conn = psycopg2.connect(
132+
conn = psycopg.connect(
134133
dbname='stackql',
135134
user='stackql',
136135
host=self.server_address,
137-
port=self.server_port
136+
port=self.server_port,
137+
autocommit=True,
138+
row_factory=dict_row # Use dict_row to get rows as dictionaries
138139
)
139140
return conn
140-
except psycopg2.OperationalError as oe:
141+
except psycopg.OperationalError as oe:
141142
print(f"OperationalError while connecting to the server: {oe}")
142143
except Exception as e:
143-
# Catching all other possible psycopg2 exceptions (and possibly other unexpected exceptions).
144-
# You might want to log this or handle it differently in a real-world scenario.
145144
print(f"Unexpected error while connecting to the server: {e}")
146145
return None
147146

148147
def _run_server_query(self, query, is_statement=False):
149-
"""Runs a query against the server using psycopg2.
150-
151-
:param query: SQL query to be executed on the server.
152-
:type query: str
153-
:return: List of result rows if the query fetches results; empty list if there are no results.
154-
:rtype: list of dict objects
155-
:raises: psycopg2.ProgrammingError for issues related to the SQL query,
156-
unless the error is "no results to fetch", in which case an empty list is returned.
157-
"""
148+
"""Run a query against the server using the existing connection in server mode."""
149+
if not self._conn:
150+
raise ConnectionError("No active connection found. Ensure _connect_to_server is called.")
151+
158152
try:
159-
cur = self._conn.cursor(cursor_factory=RealDictCursor)
160-
cur.execute(query)
161-
if is_statement:
162-
# If the query is a statement, there are no results to fetch.
163-
result_msg = cur.statusmessage
164-
cur.close()
165-
return [{'message': result_msg}]
166-
rows = cur.fetchall()
167-
cur.close()
168-
return rows
169-
except psycopg2.ProgrammingError as e:
170-
if str(e) == "no results to fetch":
171-
return []
172-
else:
173-
raise
153+
with self._conn.cursor() as cur:
154+
cur.execute(query)
155+
if is_statement:
156+
# Return status message for non-SELECT statements
157+
result_msg = cur.statusmessage
158+
return [{'message': result_msg}]
159+
try:
160+
# Fetch results for SELECT queries
161+
rows = cur.fetchall()
162+
return rows
163+
except psycopg.ProgrammingError as e:
164+
# Handle cases with no results
165+
if "no results to fetch" in str(e):
166+
return []
167+
else:
168+
raise
169+
except psycopg.OperationalError as oe:
170+
print(f"OperationalError during query execution: {oe}")
171+
except Exception as e:
172+
print(f"Unexpected error during query execution: {e}")
173+
174174

175175
def _run_query(self, query, custom_auth=None, env_vars=None):
176176
"""Internal method to execute a StackQL query using a subprocess.
@@ -330,13 +330,13 @@ def __init__(self,
330330

331331
if self.server_mode:
332332
# server mode, connect to a server via the postgres wire protocol
333-
# Attempt to import psycopg2 only if server_mode is True
334-
global psycopg2, RealDictCursor
333+
# Attempt to import psycopg only if server_mode is True
334+
global psycopg, dict_row
335335
try:
336-
import psycopg2
337-
from psycopg2.extras import RealDictCursor
336+
import psycopg
337+
from psycopg.rows import dict_row # For returning results as dictionaries
338338
except ImportError:
339-
raise ImportError("psycopg2 is required in server mode but is not installed. Please install psycopg2 and try again.")
339+
raise ImportError("psycopg is required in server mode but is not installed. Please install psycopg and try again.")
340340

341341
self.server_address = server_address
342342
self.server_port = server_port
@@ -670,34 +670,30 @@ def execute(self, query, suppress_errors=True, custom_auth=None, env_vars=None):
670670
def _run_server_query_with_new_connection(self, query):
671671
"""Run a query against a StackQL postgres wire protocol server with a new connection.
672672
"""
673-
conn = None
674673
try:
675674
# Establish a new connection using credentials and configurations
676-
conn = psycopg2.connect(
675+
with psycopg.connect(
677676
dbname='stackql',
678677
user='stackql',
679678
host=self.server_address,
680-
port=self.server_port
681-
)
682-
# Create a new cursor and execute the query
683-
with conn.cursor(cursor_factory=RealDictCursor) as cur:
684-
cur.execute(query)
685-
try:
686-
rows = cur.fetchall()
687-
except psycopg2.ProgrammingError as e:
688-
if str(e) == "no results to fetch":
689-
rows = []
690-
else:
691-
raise
692-
return rows
693-
except psycopg2.OperationalError as oe:
679+
port=self.server_port,
680+
row_factory=dict_row
681+
) as conn:
682+
# Execute the query with a new cursor
683+
with conn.cursor() as cur:
684+
cur.execute(query)
685+
try:
686+
rows = cur.fetchall()
687+
except psycopg.ProgrammingError as e:
688+
if str(e) == "no results to fetch":
689+
rows = []
690+
else:
691+
raise
692+
return rows
693+
except psycopg.OperationalError as oe:
694694
print(f"OperationalError while connecting to the server: {oe}")
695695
except Exception as e:
696696
print(f"Unexpected error while connecting to the server: {e}")
697-
finally:
698-
# Ensure the connection is always closed, even if an error occurs
699-
if conn is not None:
700-
conn.close()
701697

702698
def _sync_query(self, query, new_connection=False):
703699
"""Synchronous function to perform the query.

run_tests

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
# Install packages if they aren't already installed
44
# pip3 install -r requirements.txt --user
5-
# pip3 install psycopg2-binary --user
5+
# pip3 install psycopg --user
66

77
# Load environment variables
88
source ./tests/creds/env_vars/test.env.sh

run_tests.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# install packages
22
# pip.exe install -r requirements.txt --user
3-
# pip install psycopg2-binary --user
3+
# pip install psycopg[binary]
44

55
# Load environment variables
66
. .\tests\creds\env_vars\test.env.ps1

0 commit comments

Comments
 (0)