diff --git a/python/turbodbc/connection.py b/python/turbodbc/connection.py index 59e1879ea..19bb88e9d 100644 --- a/python/turbodbc/connection.py +++ b/python/turbodbc/connection.py @@ -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): @@ -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 diff --git a/python/turbodbc/cursor.py b/python/turbodbc/cursor.py index 1671188c0..ab122d054 100644 --- a/python/turbodbc/cursor.py +++ b/python/turbodbc/cursor.py @@ -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 @@ -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): """ @@ -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() @@ -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): """ @@ -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: