Using CockroachDB

Connect to CockroachDB (CRDB) using the CockroachDatabase databaseclass, defined in playhouse.cockroachdb:

  1. from playhouse.cockroachdb import CockroachDatabase
  2.  
  3. 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():

  1. def create_user(email):
  2. # Callable that accepts a single argument (the database instance) and
  3. # which is responsible for executing the transactional SQL.
  4. def callback(db_ref):
  5. return User.create(email=email)
  6.  
  7. return db.run_transaction(callback, max_attempts=10)
  8.  
  9. 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: