Using CockroachDB

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

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

  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. return db.run_transaction(callback, max_attempts=10)
  7. 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: