new method next_id(...) returns next primary key id
[plcapi.git] / PLC / PostgreSQL.py
index f15ebf9..5c12257 100644 (file)
@@ -5,7 +5,7 @@
 # Mark Huang <mlhuang@cs.princeton.edu>
 # Copyright (C) 2006 The Trustees of Princeton University
 #
-# $Id: PostgreSQL.py,v 1.13 2007/02/11 04:53:40 mlhuang Exp $
+# $Id$
 #
 
 import psycopg2
@@ -130,9 +130,19 @@ class PostgreSQL:
         self.connection.rollback()
 
     def do(self, query, params = None):
-        self.execute(query, params)
+        cursor = self.execute(query, params)
+        cursor.close()
         return self.rowcount
 
+    def next_id(self, table_name, primary_key):
+       sequence = "%(table_name)s_%(primary_key)s_seq" % locals()      
+       sql = "SELECT nextval('%(sequence)s')" % locals()
+       rows = self.selectall(sql, hashref = False)
+       if rows: 
+           return rows[0][0]
+               
+       return None 
+
     def last_insert_id(self, table_name, primary_key):
         if isinstance(self.lastrowid, int):
             sql = "SELECT %s FROM %s WHERE oid = %d" % \
@@ -194,7 +204,9 @@ class PostgreSQL:
         to the query.
         """
 
-        rows = self.execute(query, params).fetchall()
+        cursor = self.execute(query, params)
+        rows = cursor.fetchall()
+        cursor.close()
 
         if hashref or key_field is not None:
             # Return each row as a dictionary keyed on field name