Fixed interaction between NamedTuple and named cursor

Build the nametuple after fetching the first resutl, or else
cursor.description will be empty.
This commit is contained in:
Daniele Varrazzo 2011-04-26 19:18:39 +01:00
parent 80891e64b3
commit ffa7a62b93
2 changed files with 34 additions and 2 deletions

View File

@ -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):

View File

@ -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__)