"Igor Tandetnik" <itandet...@mvps.org> writes:
> Nikolaus Rath wrote:
>> "Igor Tandetnik" <itandet...@mvps.org> writes:
>>> Nikolaus Rath <nikol...@rath.org> wrote:
>>>> How can I determine the rowid of the last insert if I am accessing
>>>> the db from different threads? If I understand correctly,
>>>> last_insert_rowid() won't work reliably in this case.
>>>
>>> Last inserted rowid is maintained per connection. Do your threads use
>>> the same connection, or each create their own?
>>
>> Same connection, just different cursors.
>>
>>> If all threads share the same connection, it is your responsibility
>>> to make "insert then retrieve last rowid" an atomic operation, using
>>> thread synchronization mechanism of your choice. Just as with any
>>> access to shared data.
>>
>> Is BEGIN ... COMMIT sufficient for that?
>
> No. Transaction is also maintained per connection. Starting a 
> transaction would prevent other connections from making concurrent 
> changes, but wouldn't block other threads using the same connection.

Actually it seems to do exactly that:

,----
| $ cat test.py 
| import apsw
| import threading
| import time
| 
| conn = apsw.Connection('test.db')
| 
| def thread1():
|     cur = conn.cursor()
|     cur.execute("BEGIN")
|     print "Thread 1 in transaction"
|     time.sleep(5)
|     print "Thread 1 finished."
| 
| def thread2():
|     cur = conn.cursor()
|     time.sleep(2)
|     cur.execute("BEGIN")
|     print "Thread 2 in transaction"
|     time.sleep(5)
|     print "Thread 2 finished."
| 
| 
| threading.Thread(target=thread1).start()
| threading.Thread(target=thread2).start()
`----

,----
| $ python test.py 
| Thread 1 in transaction
| Exception in thread Thread-2:
| Traceback (most recent call last):
|   File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
|     self.run()
|   File "/usr/lib/python2.6/threading.py", line 477, in run
|     self.__target(*self.__args, **self.__kwargs)
|   File "test.py", line 17, in thread2
|     cur.execute("BEGIN")
|   File "apsw.c", line 4238, in resetcursor
| SQLError: SQLError: cannot start a transaction within a transaction
| 
| Thread 1 finished.
`----


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C

_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to