Transaction in Python
In Python, a "transaction" refers to a sequence of operations performed as a single logical unit of work, particularly in the context of database management. Transactions are essential for maintaining data integrity and ensuring that a series of operations either all succeed or have no effect, adhering to the ACID properties: Atomicity, Consistency, Isolation, and Durability. This concept is crucial for ensuring that databases remain reliable and accurate, even in the face of unexpected issues or failures during data processing.
Transactions in Python Concurrency with asyncio
Overview
A transaction in the context of databases is a sequence of operations performed as a single logical unit of work. Transactions ensure that a series of operations either all succeed or have no effect, maintaining the ACID properties. In asyncpg, transactions can be managed using asynchronous context managers, allowing for automatic commit or rollback based on the success or failure of the operations within the transaction.
Managing Transactions with asyncpg
Using Asynchronous Context Managers
In asyncpg, the easiest way to deal with transactions is to use the connection.transaction asynchronous context manager to start them. If there is an exception within the async with block, the transaction will automatically be rolled back. If everything executes successfully, it will be automatically committed.
import asyncio
import asyncpg
async def main():
connection = await asyncpg.connect(host='127.0.0.1',
port=5432,
user='postgres',
database='products',
password='password')
async with connection.transaction(): #1
await connection.execute("INSERT INTO brand "
"VALUES(DEFAULT, 'brand_1')")
await connection.execute("INSERT INTO brand "
"VALUES(DEFAULT, 'brand_2')")
query = """SELECT brand_name FROM brand
WHERE brand_name LIKE 'brand%'"""
brands = await connection.fetch(query) #2
print(brands)
await connection.close()
asyncio.run(main())
#1 Start a database transaction.
#2 Select brands to ensure that our transaction was committed.
Assuming the transaction committed successfully, the output should be [<Record brand_name='brand_1'>, <Record brand_name='brand_2'>], indicating that both INSERT operations were successful.
Handling Errors in Transactions
To demonstrate what happens when a rollback occurs, consider a scenario where a SQL error is forced by attempting to insert two brands with the same primary key. The first insert will work successfully, but the second will raise a duplicate key error.
import asyncio
import logging
import asyncpg
async def main():
connection = await asyncpg.connect(host='127.0.0.1',
port=5432,
user='postgres',
database='products',
password='password')
try:
async with connection.transaction():
insert_brand = "INSERT INTO brand VALUES(9999, 'big_brand')"
await connection.execute(insert_brand)
await connection.execute(insert_brand) #1
except Exception:
logging.exception('Error while running transaction') #2
finally:
query = """SELECT brand_name FROM brand
WHERE brand_name LIKE 'big_%'"""
brands = await connection.fetch(query) #3
print(f'Query result was: {brands}')
await connection.close()
asyncio.run(main())
#1 This insert statement will error because of a duplicate primary key.
#2 If we had an exception, log the error.
#3 Select the brands to ensure we didn’t insert anything.
The output of this code will show an error due to the duplicate key and confirm that the transaction was rolled back, as indicated by an empty result from the SELECT query.
ERROR:root:Error while running transaction
Traceback (most recent call last):
File "listing_5_10.py", line 16, in main
await connection.execute("INSERT INTO brand "
File "asyncpg/connection.py", line 272, in execute
return await self._protocol.query(query, timeout)
File "asyncpg/protocol/protocol.pyx", line 316, in query
asyncpg.exceptions.UniqueViolationError: duplicate key value violates unique constraint "brand_pkey"
DETAIL: Key (brand_id)=(9999) already exists.
Query result was: []
Manually Managing Transactions
To manually manage a transaction, you can use the transaction manager returned by connection.transaction outside of a context manager. This approach requires manually calling the start method to begin a transaction and then commit on success or rollback on failure.
import asyncio
import asyncpg
from asyncpg.transaction import Transaction
async def main():
connection = await asyncpg.connect(host='127.0.0.1',
port=5432,
user='postgres',
database='products',
password='password')
transaction: Transaction = connection.transaction() #1
await transaction.start() #2
try:
await connection.execute("INSERT INTO brand "
"VALUES(DEFAULT, 'brand_1')")
await connection.execute("INSERT INTO brand "
"VALUES(DEFAULT, 'brand_2')")
except asyncpg.PostgresError:
print('Errors, rolling back transaction!')
await transaction.rollback() #3
else:
print('No errors, committing transaction!')
await transaction.commit() #4
query = """SELECT brand_name FROM brand
WHERE brand_name LIKE 'brand%'"""
brands = await connection.fetch(query)
print(brands)
await connection.close()
asyncio.run(main())
#1 Create a transaction instance.
#2 Start the transaction.
#3 If there was an exception, roll back.
#4 If there was no exception, commit.
In this example, a Transaction instance is created and used to manage the transaction manually. The start coroutine initiates the transaction, and based on the success or failure of the operations, either commit or rollback is called.
Transactions in Practices of the Python Pro
Definition
A transaction in database management is a sequence of operations performed as a single logical unit of work. Transactions are crucial for ensuring data integrity within a database system. They allow a series of operations to be completed successfully or, in the event of an error, to be rolled back, thereby maintaining the database's consistent state. This mechanism ensures that the database remains reliable and accurate, even in the face of unexpected issues or failures during data processing.
For more detailed information, you can refer to the book Practices of the Python Pro.
| Book Title | Usage of Transaction | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|----------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python Concurrency with asyncio](https://www.manning.com/books/python-concurrency-with-asyncio) | Discusses transactions in the context of databases, focusing on ensuring operations succeed or have no effect, maintaining ACID properties. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-5/92) | Explores asynchronous context managers and manual transaction management with `asyncpg`. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-5/95) | Connects transactions to database operations and error handling. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-5/95) | Provides code examples for creating transactions, handling errors, and manual transaction management. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-5/95) | Focuses on practical implementation using `asyncpg` for database transactions. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-5/95) |
| [Practices of the Python Pro](https://www.manning.com/books/practices-of-the-python-pro) | Defines transactions as a sequence of operations ensuring data integrity in databases. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-6/48) | Provides a basic definition without deep technical exploration. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-6/48) | Emphasizes the importance of transactions for maintaining database consistency. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-6/48) | Does not provide specific examples. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-6/48) | Highlights the role of transactions in ensuring database reliability. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-6/48) |
FAQ (Frequently asked questions)
What is a transaction in the context of databases?
What properties do transactions maintain?
How are transactions managed in asyncpg?
How do you start a transaction in asyncpg?
What does the example code in Listing 5.9 demonstrate?
How can you ensure that a transaction was committed in asyncpg?
What is a transaction in database management?
How do transactions ensure data integrity?