This commit was generated by cvs2svn to compensate for changes in r431,
[plcapi.git] / psycopg2 / doc / async.txt
1 psycopg asynchronous API
2 ************************
3
4 ** Important: async quaeries are not enabled for 2.0 **
5
6 Program code can initiate an asynchronous query by passing an 'async=1' flag
7 to the .execute() method. A very simple example, from the connection to the
8 query:
9
10     conn = psycopg.connect(database='test')
11     curs = conn.cursor()
12     curs.execute("SEECT * from test WHERE fielda > %s", (1971,), async=1)
13     
14 From then on any query on other cursors derived from the same connection is
15 doomed to fail (and raise an exception) until the original cursor (the one
16 executing the query) complete the asynchronous operation. This can happen in
17 a number of different ways:
18
19     1) one of the .fetchXXX() methods is called, effectively blocking untill
20        data has been sent from the backend to the client, terminating the
21        query.
22        
23     2) .cancel() is called. This method tries to abort the current query and
24        will block until the query is aborted or fully executed. The return
25        value is True if the query was successfully aborted or False if it
26        was executed. Query result are discarded in both cases.
27        
28     3) .execute() is called again on the same cursor (.execute() on a
29        different cursor will simply raise an exception.) This waits for the
30        complete execution of the current query, discard any data and execute
31        the new one.
32
33 Note that calling .execute() two times in a row will not abort the former
34 query and will temporarily go to synchronous mode until the first of the two
35 queries is executed.
36
37 Cursors now have some extra methods that make them usefull during
38 asynchronous queries:
39
40     .fileno()
41       Returns the file descriptor associated with the current connection and
42       make possible to use a cursor in a context where a file object would be
43       expected (like in a select() call.)
44
45     .isbusy()
46       Returns True if the backend is still processing the query or false if
47       data is ready to be fetched (by one of the .fetchXXX() methods.)
48       
49 A code snippet that shows how to use the cursor object in a select() call:
50
51     import psycopg
52     import select
53         
54     conn = psycopg.connect(database='test')
55     curs = conn.cursor()
56     curs.execute("SEECT * from test WHERE fielda > %s", (1971,), async=1)
57
58     # wait for input with a maximum timeout of 5 seconds
59     query_ended = False
60     while not query_ended:
61         rread, rwrite, rspec = select([cursor, another_file], [], [], 5)
62         if not cursor.isbusy():
63            query_ended = True
64         # manage input from other sources like other_file, etc.
65     print "Query Results:"
66     for row in cursor:
67         print row