Automatic Transactions
Thetransaction() method provides automatic transaction management. The transaction is automatically committed if the callback succeeds, or rolled back if an exception is thrown.
Simple Transaction
This example inserts two rows in a transaction:- The exception is caught
- The transaction is rolled back
- The exception is thrown again
Setting Isolation Level
You can configure the transaction isolation level:'read uncommitted''read committed''repeatable read''serializable''snapshot'
Controlled Transactions
Controlled transactions give you manual control over commit and rollback operations, and allow you to work with savepoints.Manual Commit and Rollback
A controlled transaction allows you to commit and rollback manually:Using Savepoints
Savepoints allow you to create checkpoints within a transaction that you can roll back to:Setting Isolation Level
You can set the isolation level for controlled transactions:Connection Pooling
Theconnection() method provides a Kysely instance bound to a single database connection:
Transaction Object
The transaction object passed to the callback is of typeTransaction<DB>, which extends Kysely<DB>. This means you can use all the same query building methods:
Nested Transactions
Kysely doesn’t support true nested transactions, but you can use savepoints to achieve similar functionality:Transaction Lifecycle
Once a controlled transaction is committed or rolled back, it cannot be used anymore. All queries will throw an error:Best Practices
Keep Transactions Short
Keep transactions as short as possible to minimize lock contention:Use Appropriate Isolation Levels
Choose the lowest isolation level that meets your requirements:Handle Errors Properly
Always handle errors in controlled transactions:API Reference
Automatic Transactions
db.transaction()- Create a transaction builder.setIsolationLevel(level)- Set isolation level.execute(callback)- Execute the transaction
Controlled Transactions
db.startTransaction()- Create a controlled transaction builder.setIsolationLevel(level)- Set isolation level.execute()- Start the transactiontrx.commit()- Commit the transactiontrx.rollback()- Rollback the transactiontrx.savepoint(name)- Create a savepointtrx.releaseSavepoint(name)- Release a savepointtrx.rollbackToSavepoint(name)- Rollback to a savepoint
Connection Pooling
db.connection()- Create a connection builder.execute(callback)- Execute with a single connection