From ffa7a62b9313b52af0c70f61b888703de1491777 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Tue, 26 Apr 2011 19:18:39 +0100 Subject: [PATCH] Fixed interaction between NamedTuple and named cursor Build the nametuple after fetching the first resutl, or else cursor.description will be empty. --- lib/extras.py | 4 ++-- tests/extras_dictcursor.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/extras.py b/lib/extras.py index 06d36572..dcbd65ed 100644 --- a/lib/extras.py +++ b/lib/extras.py @@ -290,17 +290,17 @@ class NamedTupleCursor(_cursor): return nt(*t) def fetchmany(self, size=None): + ts = _cursor.fetchmany(self, size) nt = self.Record if nt is None: nt = self.Record = self._make_nt() - ts = _cursor.fetchmany(self, size) return [nt(*t) for t in ts] def fetchall(self): + ts = _cursor.fetchall(self) nt = self.Record if nt is None: nt = self.Record = self._make_nt() - ts = _cursor.fetchall(self) return [nt(*t) for t in ts] def __iter__(self): diff --git a/tests/extras_dictcursor.py b/tests/extras_dictcursor.py index 70f51d23..a92968b1 100755 --- a/tests/extras_dictcursor.py +++ b/tests/extras_dictcursor.py @@ -261,6 +261,38 @@ class NamedTupleCursorTest(unittest.TestCase): finally: NamedTupleCursor._make_nt = f_orig + @skip_if_no_namedtuple + @skip_before_postgres(8, 0) + def test_named(self): + curs = self.conn.cursor('tmp') + curs.execute("""select i from generate_series(0,9) i""") + recs = [] + recs.extend(curs.fetchmany(5)) + recs.append(curs.fetchone()) + recs.extend(curs.fetchall()) + self.assertEqual(range(10), [t.i for t in recs]) + + @skip_if_no_namedtuple + def test_named_fetchone(self): + curs = self.conn.cursor('tmp') + curs.execute("""select 42 as i""") + t = curs.fetchone() + self.assertEqual(t.i, 42) + + @skip_if_no_namedtuple + def test_named_fetchmany(self): + curs = self.conn.cursor('tmp') + curs.execute("""select 42 as i""") + recs = curs.fetchmany(10) + self.assertEqual(recs[0].i, 42) + + @skip_if_no_namedtuple + def test_named_fetchall(self): + curs = self.conn.cursor('tmp') + curs.execute("""select 42 as i""") + recs = curs.fetchall() + self.assertEqual(recs[0].i, 42) + def test_suite(): return unittest.TestLoader().loadTestsFromName(__name__)