Build a Python App with CockroachDB

This tutorial shows you how build a simple Python application with CockroachDB using a PostgreSQL-compatible driver or ORM.

We have tested the Python psycopg2 driver and the SQLAlchemy ORM enough to claim beta-level support, so those are featured here. If you encounter problems, please open an issue with details to help us make progress toward full support.

Before you begin

Step 1. Install the psycopg2 driver

To install the Python psycopg2 driver, run the following command:

  1. $ pip install psycopg2

For other ways to install psycopg2, see the official documentation.

Step 2. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 3. Generate a certificate for the maxroach user

Create a certificate and key for the maxroach user by running the following command. The code samples will run as this user.

  1. $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key

Step 4. Run the Python code

Now that you have a database and a user, you'll run the code shown below to:

  • Create a table and insert some rows
  • Read and update values as an atomic transaction

Basic statements

First, use the following code to connect as the maxroach user and execute some basic SQL statements, creating a table, inserting rows, and reading and printing the rows.

Download the basic-sample.py file, or create the file yourself and copy the code into it.

  1. # Import the driver.
  2. import psycopg2
  3. # Connect to the "bank" database.
  4. conn = psycopg2.connect(
  5. database='bank',
  6. user='maxroach',
  7. sslmode='require',
  8. sslrootcert='certs/ca.crt',
  9. sslkey='certs/client.maxroach.key',
  10. sslcert='certs/client.maxroach.crt',
  11. port=26257,
  12. host='localhost'
  13. )
  14. # Make each statement commit immediately.
  15. conn.set_session(autocommit=True)
  16. # Open a cursor to perform database operations.
  17. cur = conn.cursor()
  18. # Create the "accounts" table.
  19. cur.execute("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)")
  20. # Insert two rows into the "accounts" table.
  21. cur.execute("INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)")
  22. # Print out the balances.
  23. cur.execute("SELECT id, balance FROM accounts")
  24. rows = cur.fetchall()
  25. print('Initial balances:')
  26. for row in rows:
  27. print([str(cell) for cell in row])
  28. # Close the database connection.
  29. cur.close()
  30. conn.close()

Then run the code:

  1. $ python basic-sample.py

The output should be:

  1. Initial balances:
  2. ['1', '1000']
  3. ['2', '250']

Transaction (with retry logic)

Next, use the following code to again connect as the maxroach user but this time execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted.

Download the txn-sample.py file, or create the file yourself and copy the code into it.

Note:
CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code.

  1. # Import the driver.
  2. import psycopg2
  3. import psycopg2.errorcodes
  4. # Connect to the cluster.
  5. conn = psycopg2.connect(
  6. database='bank',
  7. user='maxroach',
  8. sslmode='require',
  9. sslrootcert='certs/ca.crt',
  10. sslkey='certs/client.maxroach.key',
  11. sslcert='certs/client.maxroach.crt',
  12. port=26257,
  13. host='localhost'
  14. )
  15. def onestmt(conn, sql):
  16. with conn.cursor() as cur:
  17. cur.execute(sql)
  18. # Wrapper for a transaction.
  19. # This automatically re-calls "op" with the open transaction as an argument
  20. # as long as the database server asks for the transaction to be retried.
  21. def run_transaction(conn, op):
  22. with conn:
  23. onestmt(conn, "SAVEPOINT cockroach_restart")
  24. while True:
  25. try:
  26. # Attempt the work.
  27. op(conn)
  28. # If we reach this point, commit.
  29. onestmt(conn, "RELEASE SAVEPOINT cockroach_restart")
  30. break
  31. except psycopg2.OperationalError as e:
  32. if e.pgcode != psycopg2.errorcodes.SERIALIZATION_FAILURE:
  33. # A non-retryable error; report this up the call stack.
  34. raise e
  35. # Signal the database that we'll retry.
  36. onestmt(conn, "ROLLBACK TO SAVEPOINT cockroach_restart")
  37. # The transaction we want to run.
  38. def transfer_funds(txn, frm, to, amount):
  39. with txn.cursor() as cur:
  40. # Check the current balance.
  41. cur.execute("SELECT balance FROM accounts WHERE id = " + str(frm))
  42. from_balance = cur.fetchone()[0]
  43. if from_balance < amount:
  44. raise "Insufficient funds"
  45. # Perform the transfer.
  46. cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s",
  47. (amount, frm))
  48. cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s",
  49. (amount, to))
  50. # Execute the transaction.
  51. run_transaction(conn, lambda conn: transfer_funds(conn, 1, 2, 100))
  52. with conn:
  53. with conn.cursor() as cur:
  54. # Check account balances.
  55. cur.execute("SELECT id, balance FROM accounts")
  56. rows = cur.fetchall()
  57. print('Balances after transfer:')
  58. for row in rows:
  59. print([str(cell) for cell in row])
  60. # Close communication with the database.
  61. conn.close()

Then run the code:

  1. $ python txn-sample.py

The output should be:

  1. Balances after transfer:
  2. ['1', '900']
  3. ['2', '350']

To verify that funds were transferred from one account to another, start the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs --database=bank

To check the account balances, issue the following statement:

  1. > SELECT id, balance FROM accounts;
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

Step 2. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --insecure

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 3. Run the Python code

Now that you have a database and a user, you'll run the code shown below to:

  • Create a table and insert some rows
  • Read and update values as an atomic transaction

Basic statements

First, use the following code to connect as the maxroach user and execute some basic SQL statements, creating a table, inserting rows, and reading and printing the rows.

Download the basic-sample.py file, or create the file yourself and copy the code into it.

  1. # Import the driver.
  2. import psycopg2
  3. # Connect to the "bank" database.
  4. conn = psycopg2.connect(
  5. database='bank',
  6. user='maxroach',
  7. sslmode='disable',
  8. port=26257,
  9. host='localhost'
  10. )
  11. # Make each statement commit immediately.
  12. conn.set_session(autocommit=True)
  13. # Open a cursor to perform database operations.
  14. cur = conn.cursor()
  15. # Create the "accounts" table.
  16. cur.execute("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)")
  17. # Insert two rows into the "accounts" table.
  18. cur.execute("INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)")
  19. # Print out the balances.
  20. cur.execute("SELECT id, balance FROM accounts")
  21. rows = cur.fetchall()
  22. print('Initial balances:')
  23. for row in rows:
  24. print([str(cell) for cell in row])
  25. # Close the database connection.
  26. cur.close()
  27. conn.close()

Then run the code:

  1. $ python basic-sample.py

The output should be:

  1. Initial balances:
  2. ['1', '1000']
  3. ['2', '250']

Transaction (with retry logic)

Next, use the following code to again connect as the maxroach user but this time execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted.

Download the txn-sample.py file, or create the file yourself and copy the code into it.

Note:
CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code.

  1. # Import the driver.
  2. import psycopg2
  3. import psycopg2.errorcodes
  4. # Connect to the cluster.
  5. conn = psycopg2.connect(
  6. database='bank',
  7. user='maxroach',
  8. sslmode='disable',
  9. port=26257,
  10. host='localhost'
  11. )
  12. def onestmt(conn, sql):
  13. with conn.cursor() as cur:
  14. cur.execute(sql)
  15. # Wrapper for a transaction.
  16. # This automatically re-calls "op" with the open transaction as an argument
  17. # as long as the database server asks for the transaction to be retried.
  18. def run_transaction(conn, op):
  19. with conn:
  20. onestmt(conn, "SAVEPOINT cockroach_restart")
  21. while True:
  22. try:
  23. # Attempt the work.
  24. op(conn)
  25. # If we reach this point, commit.
  26. onestmt(conn, "RELEASE SAVEPOINT cockroach_restart")
  27. break
  28. except psycopg2.OperationalError as e:
  29. if e.pgcode != psycopg2.errorcodes.SERIALIZATION_FAILURE:
  30. # A non-retryable error; report this up the call stack.
  31. raise e
  32. # Signal the database that we'll retry.
  33. onestmt(conn, "ROLLBACK TO SAVEPOINT cockroach_restart")
  34. # The transaction we want to run.
  35. def transfer_funds(txn, frm, to, amount):
  36. with txn.cursor() as cur:
  37. # Check the current balance.
  38. cur.execute("SELECT balance FROM accounts WHERE id = " + str(frm))
  39. from_balance = cur.fetchone()[0]
  40. if from_balance < amount:
  41. raise "Insufficient funds"
  42. # Perform the transfer.
  43. cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s",
  44. (amount, frm))
  45. cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s",
  46. (amount, to))
  47. # Execute the transaction.
  48. run_transaction(conn, lambda conn: transfer_funds(conn, 1, 2, 100))
  49. with conn:
  50. with conn.cursor() as cur:
  51. # Check account balances.
  52. cur.execute("SELECT id, balance FROM accounts")
  53. rows = cur.fetchall()
  54. print('Balances after transfer:')
  55. for row in rows:
  56. print([str(cell) for cell in row])
  57. # Close communication with the database.
  58. conn.close()

Then run the code:

  1. $ python txn-sample.py

The output should be:

  1. Balances after transfer:
  2. ['1', '900']
  3. ['2', '350']

To verify that funds were transferred from one account to another, start the built-in SQL client:

  1. $ cockroach sql --insecure --database=bank

To check the account balances, issue the following statement:

  1. > SELECT id, balance FROM accounts;
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

What's next?

Read more about using the Python psycopg2 driver.

You might also be interested in using a local cluster to explore the following CockroachDB benefits:

Was this page helpful?
YesNo