pgtoolkit/pgmanager.py
changeset 31 c2e6e24b83d9
parent 26 7f219da7ab71
child 33 bd0beda49bcb
--- a/pgtoolkit/pgmanager.py	Mon Feb 27 15:12:40 2012 +0100
+++ b/pgtoolkit/pgmanager.py	Mon Mar 05 18:36:46 2012 +0100
@@ -2,7 +2,7 @@
 #
 # PgManager - manage database connections
 #
-# Requires: Python 2.6, psycopg2
+# Requires: Python 3.2, psycopg2
 #
 # Part of pgtoolkit
 # http://hg.devl.cz/pgtoolkit
@@ -70,6 +70,7 @@
 """
 
 from contextlib import contextmanager
+from collections import OrderedDict
 import logging
 import threading
 import multiprocessing
@@ -103,10 +104,13 @@
         self.keep_open = keep_open
 
 
-class RowDict(dict):
+class RowDict(OrderedDict):
 
     def __getattr__(self, key):
-        return self[key]
+        try:
+            return self[key]
+        except KeyError:
+            raise AttributeError(key)
 
 
 class Cursor(psycopg2.extensions.cursor):
@@ -132,17 +136,19 @@
         return RowDict(zip([adjustname(desc[0]) for desc in self.description], row))
 
     def fetchone_dict(self, lstrip=None):
+        '''Return one row as OrderedDict'''
         row = super(Cursor, self).fetchone()
         if row is None:
             return None
         return self.row_dict(row, lstrip)
 
     def fetchall_dict(self, lstrip=None):
+        '''Return all rows as OrderedDict'''
         rows = super(Cursor, self).fetchall()
         return [self.row_dict(row, lstrip) for row in rows]
 
-    def fetchone_adapted(self):
-        '''Like fetchone() but values are quoted for direct inclusion in SQL query.
+    def fetchone_adapted(self, lstrip=None):
+        '''Like fetchone_dict() but values are quoted for direct inclusion in SQL query.
         
         This is useful when you need to generate SQL script from data returned
         by the query. Use mogrify() for simple cases.
@@ -151,12 +157,12 @@
         row = super(Cursor, self).fetchone()
         if row is None:
             return None
-        return [self.mogrify('%s', [x]).decode('utf8') for x in row]
+        return self.row_dict([self.mogrify('%s', [x]).decode('utf8') for x in row], lstrip)
 
-    def fetchall_adapted(self):
-        '''Like fetchall() but values are quoted for direct inclusion in SQL query.'''
+    def fetchall_adapted(self, lstrip=None):
+        '''Like fetchall_dict() but values are quoted for direct inclusion in SQL query.'''
         rows = super(Cursor, self).fetchall()
-        return [[self.mogrify('%s', [x]).decode('utf8') for x in row] for row in rows]
+        return [self.row_dict([self.mogrify('%s', [x]).decode('utf8') for x in row], lstrip) for row in rows]
 
 
 class Connection(psycopg2.extensions.connection):