Peewee now supports CockroachDB
source link: https://charlesleifer.com/blog/peewee-now-supports-cockroachdb/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Peewee now supports CockroachDB
December 05, 2019 19:27 / cockroachdb peewee python / 0 comments
I'm pleased to announce that Peewee now supports CockroachDB (CRDB), the distributed, horizontally-scalable SQL database. I'm excited about this release, because it's now quite easy to get up-and-running with a robust SQL database that can scale out with minimal effort (documentation).
Here is how you configure a CockroachDatabase
instance:
from playhouse.cockroachdb import CockroachDatabase db = CockroachDatabase('my_app', user='root', host='10.1.0.8', port=26257)
CRDB conveniently provides a very similar SQL dialect to Postgres, which has been
well-supported in Peewee for many years, allowing you to use features like jsonb
and arrays,
in addition to the regular complement of field-types. Additionally, CRDB speaks
the same wire-protocol as Postgres, so it works out-of-the-box using the
popular psycopg2
driver.
Example model class using jsonb
and CRDB's UUID primary-key type:
from peewee import * from playhouse.cockroachdb import JSONField from playhouse.cockroachdb import UUIDKeyField class UserProfile(Model): id = UUIDKeyField() # Auto-generated UUID primary-key. email = TextField() signup_date = DateTimeField() # Date/time with timezone. preferences = JSONField(default=dict) # Free-form JSON data.
CRDB provides a client-side transaction retry API, which Peewee supports using a helper-method. To use client-side retries with Peewee and CRDB, provide a callable that executes your transactional SQL and pass it to the run_transaction() method:
from playhouse.cockroachdb import CockroachDatabase db = CockroachDatabase('my_app') def create_user_and_token(username, timestamp): # The run_transaction() helper accepts a callable that contains your # transactional SQL statements. The transaction will be automatically # retried until it can be committed. def callback(db_ref): user = User.create(username=username, created=timestamp) token = Token.create( user=user, expires=timestamp + timedelta(days=1), code=generate_random_token()) return user, token.code # Upon success, the return-value of the callback is passed back to # the caller. If an error, such as a constraint violation, occurs, # the error is propagated back up the call-stack. return db.run_transaction(callback, max_attempts=10) user, code = create_user_and_token('huey@kitten', datetime.now())
Check out the CockroachDB installation docs for instructions on getting up-and-running.
Links
Comments (0)
Commenting has been closed, but please feel free to contact me
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK