coolqlite.transactions¶
Transaction control through context managers.
We use the savepoint API because it’s the most flexible.
We don’t use standard BEGIN..COMMIT/ROLLBACK because
managing the interactions between that and savepoints would be annoying.
Basic Usage¶
At its simplest, it works the same as how the stdlib module
uses connections for transactions, but instead with a separate object.
For the following examples, let’s use a simple setup:
from coolqlite import connect
db = connect(":memory:")
db.run(t"create table Names(name TEXT NOT NULL UNIQUE) strict")
def has_name(name: str) -> bool:
return 1 == db.colquery(t"select count(*) from Names where name = {name}", int).one()
Using a Savepoint context manager
from with_savepoint()
will “commit” the data if it exits without error.
with db.with_savepoint():
db.run(t"insert into Names values ('foo')")
assert has_name("foo")
If there’s an exception, the transaction will be rolled back.
try:
with db.with_savepoint():
db.run(t"insert into Names values ('bar')")
raise Exception("something bad!")
except Exception:
pass
assert not has_name("bar")
- exception coolqlite.transactions.IncorrectTransactionControlError¶
Bases:
CoolqliteErrorSomething incorrect happened when using savepoints. This should only happen if using the savepoint context manager incorrectly, or otherwise doing something that would break a savepoint correctness guarantee.