Module
pgtransaction.atomic
atomic(
using: Union[str, None] = None,
savepoint: bool = True,
durable: bool = False,
isolation_level: Union[str, None] = None,
retry: Union[int, None] = None,
)
Extends django.db.transaction.atomic
with PostgreSQL functionality.
Allows one to dynamically set the isolation level when opening a transaction, as well as specifying a retry policy for when an operation in that transaction results in a Postgres locking exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
using |
Union[str, None]
|
The database to use. |
None
|
savepoint |
bool
|
If |
True
|
durable |
bool
|
If |
False
|
isolation_level |
Union[str, None]
|
The isolation level we wish to be
used for the duration of the transaction. If passed in
as None, the current isolation level is used. Otherwise,
we must choose from |
None
|
retry |
Union[int, None]
|
An integer specifying the number of attempts
we want to retry the entire transaction upon encountering
the settings-specified psycogp2 exceptions. If passed in as
None, we default to using the settings-specified retry
policy defined by |
None
|
Example
Since pgtransaction.atomic inherits from django.db.transaction.atomic
, it
can be used in exactly the same manner. Additionally, when used as a
context manager or a decorator, one can use it to specify the
isolation level of the new transaction. For example:
import pgtransaction
with pgtransaction.atomic(isolation_level=pgtransaction.REPEATABLE_READ):
# Isolation level is now "REPEATABLE READ" for the duration of the "with" block.
...
Note that setting isolation_level
in a nested atomic block is permitted as long
as no queries have been made.
Example
When used as a decorator, one can also specify a retry
argument. This
defines the number of times the transaction will be retried upon encountering
the exceptions referenced by settings.PGTRANSACTION_RETRY_EXCEPTIONS
,
which defaults to
(psycopg.errors.SerializationFailure, psycopg.errors.DeadlockDetected)
.
For example:
@pgtransaction.atomic(retry=3)
def update():
# will retry update function up to 3 times
# whenever any exception in settings.PGTRANSACTION_RETRY_EXCEPTIONS
# is encountered. Each retry will open a new transaction (after
# rollback the previous one).
Attempting to set a non-zero value for retry
when using pgtransaction.atomic
as a context manager will result in a RuntimeError
.
Source code in pgtransaction/transaction.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
|