Cockroach Database

CockroachDB (CRDB) is well supported bypeewee.

  1. from playhouse.cockroachdb import CockroachDatabase
  2.  
  3. db = CockroachDatabase('my_app', user='root', host='10.1.0.8')

The playhouse.cockroachdb extension module provides the following classesand helpers:

Special field-types that may be useful when using CRDB:

  • UUIDKeyField - a primary-key field implementation that usesCRDB’s UUID type with a default randomly-generated UUID.
  • RowIDField - a primary-key field implementation that uses CRDB’sINT type with a default unique_rowid().
  • JSONField - same as the Postgres BinaryJSONField, asCRDB treats JSON as JSONB.
  • ArrayField - same as the Postgres extension (but does not supportmulti-dimensional arrays).

CRDB is compatible with Postgres’ wire protocol and exposes a very similarSQL interface, so it is possible (though not recommended) to usePostgresqlDatabase with CRDB:

  • CRDB does not support nested transactions (savepoints), so theatomic() method has been implemented to enforce this whenusing CockroachDatabase. For more info CRDB Transactions.
  • CRDB may have subtle differences in field-types, date functions andintrospection from Postgres.
  • CRDB-specific features are exposed by the CockroachDatabase,such as specifying a transaction priority or the AS OF SYSTEM TIMEclause.

CRDB Transactions

CRDB does not support nested transactions (savepoints), so theatomic() method on the CockroachDatabase hasbeen modified to raise an exception if an invalid nesting is encountered. Ifyou would like to be able to nest transactional code, you can use thetransaction() method, which will ensure that the outer-mostblock will manage the transaction (e.g., exiting a nested-block will not causean early commit).

Example:

  1. @db.transaction()def create_user(username): return User.create(username=username)

  2. def some_other_function(): with db.transaction() as txn:

  3.     # do some stuff...
  4.     # This function is wrapped in a transaction, but the nested
  5.     # transaction will be ignored and folded into the outer
  6.     # transaction, as we are already in a wrapped-block (via the
  7.     # context manager).
  8.     create_user('some_user@example.com')
  9.     # do other stuff.
  10. # At this point we have exited the outer-most block and the transaction
  11. # will be committed.
  12. return

CRDB provides client-side transaction retries, which are available using aspecial run_transaction() helper. This helpermethod accepts 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.

Example of using run_transaction() to implementclient-side retries for a transaction that transfers an amount from one accountto another:

  1. from playhouse.cockroachdb import CockroachDatabase
  2.  
  3. db = CockroachDatabase('my_app')
  4.  
  5.  
  6. def transfer_funds(from_id, to_id, amt):
  7. """
  8. Returns a 3-tuple of (success?, from balance, to balance). If there are
  9. not sufficient funds, then the original balances are returned.
  10. """
  11. def thunk(db_ref):
  12. src, dest = (Account
  13. .select()
  14. .where(Account.id.in_([from_id, to_id])))
  15. if src.id != from_id:
  16. src, dest = dest, src # Swap order.
  17.  
  18. # Cannot perform transfer, insufficient funds!
  19. if src.balance < amt:
  20. return False, src.balance, dest.balance
  21.  
  22. # Update each account, returning the new balance.
  23. src, = (Account
  24. .update(balance=Account.balance - amt)
  25. .where(Account.id == from_id)
  26. .returning(Account.balance)
  27. .execute())
  28. dest, = (Account
  29. .update(balance=Account.balance + amt)
  30. .where(Account.id == to_id)
  31. .returning(Account.balance)
  32. .execute())
  33. return True, src.balance, dest.balance
  34.  
  35. # Perform the queries that comprise a logical transaction. In the
  36. # event the transaction fails due to contention, it will be auto-
  37. # matically retried (up to 10 times).
  38. return db.run_transaction(thunk, max_attempts=10)

CRDB APIs

  • class CockroachDatabase(database[, **kwargs])
  • CockroachDB implementation, based on the PostgresqlDatabase andusing the psycopg2 driver.

Additional keyword arguments are passed to the psycopg2 connectionconstructor, and may be used to specify the database user, port,etc.

  • runtransaction(_callback[, max_attempts=None[, system_time=None[, priority=None]]])

Parameters:

  1. - **callback** callable that accepts a single <code>db</code> parameter (whichwill be the database instance this method is called from).
  2. - **max_attempts** (_int_) max number of times to try before giving up.
  3. - **system_time** (_datetime_) execute the transaction <code>AS OF SYSTEM TIME</code>with respect to the given value.
  4. - **priority** (_str_) either low”, normal or high”.Returns:

returns the value returned by the callback.Raises:ExceededMaxAttempts if max_attempts is exceeded.

Run SQL in a transaction with automatic client-side retries.

User-provided callback:

  1. - **Must** accept one parameter, the <code>db</code> instance representing theconnection the transaction is running under.
  2. - **Must** not attempt to commit, rollback or otherwise manage thetransaction.
  3. - **May** be called more than one time.
  4. - **Should** ideally only contain SQL operations.

Additionally, the database must not have any open transactions at thetime this function is called, as CRDB does not support nestedtransactions. Attempting to do so will raise a NotImplementedError.

Simplest possible example:

  1. def create_user(email):
  2. def callback(db_ref):
  3. return User.create(email=email)
  4.  
  5. return db.run_transaction(callback, max_attempts=10)
  6.  
  7. user = create_user('huey@example.com')
  • class PooledCockroachDatabase(database[, **kwargs])
  • CockroachDB connection-pooling implementation, based onPooledPostgresqlDatabase. Implements the same APIs asCockroachDatabase, but will do client-side connection pooling.
  • runtransaction(_db, callback[, max_attempts=None[, system_time=None[, priority=None]]])
  • Run SQL in a transaction with automatic client-side retries. SeeCockroachDatabase.run_transaction() for details.

Parameters:

  • db (CockroachDatabase) – database instance.
  • callback – callable that accepts a single db parameter (whichwill be the same as the value passed above).

Note

This function is equivalent to the identically-named method onthe CockroachDatabase class.

  • class UUIDKeyField
  • UUID primary-key field that uses the CRDB gen_random_uuid() function toautomatically populate the initial value.
  • class RowIDField
  • Auto-incrementing integer primary-key field that uses the CRDBunique_rowid() function to automatically populate the initial value.

See also:

  • BinaryJSONField from the Postgresql extension (available in thecockroachdb extension module, and aliased to JSONField).
  • ArrayField from the Postgresql extension.