[PyGreSQL] Aborting cursor.execute statement

Christoph Zwerschke cito at online.de
Sat Feb 11 05:17:57 EST 2006


> I've tried to close the cursor and even the connection while the execute
> statement is running but it always waits for the cursor.execute() statement
> to return before raising an exception.
> Is there a way of aborting the execution of an SQL statement ?

I've just checked in a patch that allows calling cancel() on a pg 
connection. The example below shows that it works.

Currently you can only use it with the classic pg interface. There is no 
such functionality in the DBAPI. If you really want to do it, it is 
possible to get the connection object from a pgdb connection and call 
the cancel method(). However, the connection object is a private 
attribute and is not easy to access (purposfully so).

This raises the question whether the __ctx and __source attributes of 
pgdb connections should be renamed to _ctx and _source to make them 
accessible if you want to do such things that are not in the DBAPI.
Opinions?

-- Christoph

----------- testing the cancel() method ---------

import threading, time
import pg

db = pg.DB('test')

class LongQuery(threading.Thread):

     def run(self):
         global db
         print "Subthread starts..."
         print "Creating test table..."
         try:
             db.query("drop table t")
         except pg.ProgrammingError:
             pass
         db.query("create table t as"
             " (select 0 union select 1 union select 2"
             " union select 3 union select 4 union select 5"
             " union select 6 union select 7 union select 8"
             " union select 9 union select 10)")
         print "Starting long query..."
         try:
             db.query("select sum(sin(0.2)+cos(0.3)+tan(0.4))"
                 " from t cross join t as t1 cross join t as t2"
                 " cross join t as t3 cross join t as t4"
                 " cross join t as t5 cross join t as t6"
                 " cross join t as t7 cross join t as t8"
                 " cross join t as t9 cross join t as t10")
         except pg.ProgrammingError, e:
             print "Query has been cancelled."
             print str(e).strip()
         else:
             print "Long query finished."
         print "Subthread ends..."

LongQuery().start()
time.sleep(3)
print "3 seconds over..."
time.sleep(3)
print "another 3 seconds over, aborting query..."
db.cancel()
print "cancelled query."



More information about the PyGreSQL mailing list