Using CockroachDB
Connect to CockroachDB (CRDB) using the CockroachDatabase
databaseclass, 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 aspecial CockroachDatabase.run_transaction()
helper-method. This methodaccepts a callable, which is responsible for executing any transactionalstatements 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 thetransaction cannot be committed after the given number of attempts. If theSQL is mal-formed, violates a constraint, etc., then the function willraise 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)