Last active
May 13, 2018 23:02
-
-
Save jaredLunde/7ef56880f79d1c48d887 to your computer and use it in GitHub Desktop.
OrderedDict cursor for psycopg2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
from psycopg2.extensions import cursor as _cursor | |
class OrderedDictCursor(_cursor): | |
def _to_od(self, tup): | |
return OrderedDict((k[0], v) for k, v in zip(self.description, tup)) | |
def execute(self, query, vars=None): | |
return super().execute(query, vars) | |
def executemany(self, query, vars): | |
return super().executemany(query, vars) | |
def callproc(self, procname, vars=None): | |
return super().callproc(procname, vars) | |
def fetchone(self): | |
t = super().fetchone() | |
if t is not None: | |
return self._to_od(t) | |
def fetchmany(self, size=None): | |
ts = super().fetchmany(size) | |
return list(map(self._to_od, ts)) | |
def fetchall(self): | |
ts = super().fetchall() | |
return list(map(self._to_od, ts)) | |
def __iter__(self): | |
it = super().__iter__() | |
t = next(it) | |
yield self._to_od(t) | |
while 1: | |
yield self._to_od(next(it)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment