Transactions Guide
NyanSQLite provides a safe and easy-to-use API for utilizing SQLite's transaction features.
Transactions in NyanSQLite
Bulk processing methods such as insert_many in NyanSQLite automatically use transactions internally. This allows you to process large amounts of data quickly and atomically (either all succeed or all fail).
Internal Behavior
NyanSQLite performs the following steps during bulk operations:
- Issues
BEGIN(orBEGIN IMMEDIATE). - Processes data in chunks.
- Issues
COMMITif all operations succeed. - Issues
ROLLBACKif an error occurs.
Manual Transaction Management (atomic)
The atomic() context manager allows you to explicitly group multiple operations into a single transaction.
Synchronous Version (NyanSQLite)
from nyansqlite import NyanSQLite
db = NyanSQLite("app.db")
with db.atomic():
db.insert(item1)
db.insert(item2)
# Automatically rolled back if an exception occursAsynchronous Version (NyanSQLiteAIO)
from nyansqlite import NyanSQLiteAIO
db = NyanSQLiteAIO("app.db")
async with db.atomic():
await db.insert(item1)
await db.insert(item2)
# Automatically rolled back if an exception occursNested Transactions
atomic() can be nested. The transaction is committed only when the outermost atomic block finishes. If an exception occurs in an inner block, the entire transaction is rolled back.
with db.atomic():
db.insert(item1)
with db.atomic(): # Inner transaction
db.insert(item2)
# Committed herePerformance Optimization
Using transactions drastically improves SQLite's write performance by reducing the number of disk synchronizations (fsync).
Best Practices
- Use
insert_manyfor Bulk Inserts: It is much faster than callinginsertin a loop manually. - Wrap Related Operations with
atomic(): Grouping multiple related update operations into a singleatomic()block ensures data consistency and improves performance. - Leverage WAL Mode: NyanSQLite enables WAL (Write-Ahead Logging) mode by default, which allows high concurrency by not blocking reads during writes.