Using CockroachDB
Connect to CockroachDB (CRDB) using the CockroachDatabase
database class, defined in playhouse.cockroachdb
:
from playhouse.cockroachdb import CockroachDatabase
db = CockroachDatabase('my_app', user='root', port=26257, host='localhost')
CRDB provides client-side transaction retries, which are available using a special CockroachDatabase.run_transaction()
helper-method. This method accepts a callable, which is responsible for executing any transactional statements that may need to be retried.
Simplest possible example of run_transaction()
:
def create_user(email):
# Callable that accepts a single argument (the database instance) and
# which is responsible for executing the transactional SQL.
def callback(db_ref):
return User.create(email=email)
return db.run_transaction(callback, max_attempts=10)
huey = create_user('huey@example.com')
Note
The cockroachdb.ExceededMaxAttempts
exception will be raised if the transaction cannot be committed after the given number of attempts. If the SQL is mal-formed, violates a constraint, etc., then the function will raise the exception to the caller.
For more information, see:
- CRDB extension documentation
- Arrays (postgres-specific, but applies to CRDB)
- JSON (postgres-specific, but applies to CRDB)