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

Cursors to optionally return dict with column names #235

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions python/turbodbc/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ def _assert_valid(self):
def __init__(self, impl):
self.impl = impl
self.cursors = WeakSet([])
self._as_dict = False

@property
def as_dict(self):
return self._as_dict

@as_dict.setter
def as_dict(self, value):
self._as_dict = True if value is True else False

@translate_exceptions
def cursor(self):
Expand All @@ -24,6 +33,7 @@ def cursor(self):
"""
self._assert_valid()
c = Cursor(self.impl.cursor())
c.as_dict = self._as_dict
self.cursors.add(c)
return c

Expand Down
28 changes: 28 additions & 0 deletions python/turbodbc/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ def __init__(self, impl):
self.result_set = None
self.rowcount = -1
self.arraysize = 1
self._column_names = None
self._as_dict = False

def __iter__(self):
return self
Expand All @@ -92,6 +94,14 @@ def _assert_valid_result_set(self):
if self.result_set is None:
raise InterfaceError("No active result set")

@property
def as_dict(self):
return self._as_dict

@as_dict.setter
def as_dict(self, value):
self._as_dict = True if value is True else False

@property
def description(self):
"""
Expand All @@ -109,6 +119,7 @@ def description(self):
return None

def _execute(self):
self._column_names = None
self.impl.execute()
self.rowcount = self.impl.get_row_count()
cpp_result_set = self.impl.get_result_set()
Expand Down Expand Up @@ -228,6 +239,21 @@ def _num_chunks(c):

return self._execute()


def _to_dict(self, result):
if not self.result_set or len(result) == 0:
return dict()

if self._column_names is None:
info = self.result_set.get_column_info()
self._column_names = [c.name for c in info]

data = dict()
for i in range(len(self._column_names)):
data[self._column_names[i]] = result[i]
return data


@translate_exceptions
def fetchone(self):
"""
Expand All @@ -238,6 +264,8 @@ def fetchone(self):
"""
self._assert_valid_result_set()
result = self.result_set.fetch_row()
if self._as_dict:
return self._to_dict(result)
if len(result) == 0:
return None
else:
Expand Down