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

Make DBAPI implementation use session, fix execute for none-returning queries #169

Merged
merged 3 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
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
11 changes: 9 additions & 2 deletions chdb/dbapi/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Connection(object):
"""

_closed = False
_session = None

def __init__(self, cursorclass=Cursor):

Expand All @@ -39,6 +40,8 @@ def __init__(self, cursorclass=Cursor):
self.connect()

def connect(self):
from chdb import session as chs
self._session = chs.Session()
self._closed = False
self._execute_command("select 1;")
self._read_query_result()
Expand All @@ -55,6 +58,7 @@ def close(self):
if self._closed:
raise err.Error("Already closed")
self._closed = True
self._session = None

@property
def open(self):
Expand Down Expand Up @@ -119,8 +123,7 @@ def _execute_command(self, sql):
if DEBUG:
print("DEBUG: query:", sql)
try:
import chdb
self._resp = chdb.query(sql, output_format="JSON").data()
self._resp = self._session.query(sql, fmt="JSON").data()
except Exception as error:
raise err.InterfaceError("query err: %s" % error)

Expand Down Expand Up @@ -181,6 +184,10 @@ def __init__(self, connection):
self.has_next = None

def read(self):
# Handle empty responses (for instance from CREATE TABLE)
if self.connection.resp is None:
return

try:
data = json.loads(self.connection.resp)
except Exception as error:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,26 @@ def test_select_version(self):
print(data)
self.assertRegex(data[0], expected_clickhouse_version_pattern)

def test_insert_and_read_data(self):
conn = dbapi.connect()
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS test_db ENGINE = Atomic")
cur.execute("USE test_db")
cur.execute("""
CREATE TABLE rate (
day Date,
value Int32
) ENGINE = Log""")

# Insert values
cur.execute("INSERT INTO rate VALUES ('2024-01-01', 24)")
cur.execute("INSERT INTO rate VALUES ('2024-01-02', 72)")

# Read values
cur.execute("SELECT value FROM rate ORDER BY day DESC")
rows = cur.fetchall()
self.assertEqual(rows, ((72,), (24,)))

def test_select_chdb_version(self):
ver = dbapi.get_client_info() # chDB version liek '0.12.0'
ver_tuple = dbapi.chdb_version # chDB version tuple like ('0', '12', '0')
Expand Down