Build a Rust App with CockroachDB

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

We have tested the Rust Postgres driver enough to claim beta-level support, so that driver is 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 Rust Postgres driver

Install the Rust Postgres driver as described in the official documentation.

Step 2. Start a single-node cluster

For the purpose of this tutorial, you need only one CockroachDB node running in insecure mode:

  1. $ cockroach start \
  2. --insecure \
  3. --store=hello-1 \
  4. --listen-addr=localhost

Step 3. Create a user

In a new terminal, as the root user, use the cockroach user command to create a new user, maxroach.

  1. $ cockroach user set maxroach --insecure

Step 4. Create a database and grant privileges

As the root user, use the built-in SQL client to create a bank database.

  1. $ cockroach sql --insecure -e 'CREATE DATABASE bank'

Then grant privileges to the maxroach user.

  1. $ cockroach sql --insecure -e 'GRANT ALL ON DATABASE bank TO maxroach'

Step 5. Create a table in the new database

As the maxroach user, use the built-in SQL client to create an accounts table in the new database.

  1. $ cockroach sql --insecure \
  2. --database=bank \
  3. --user=maxroach \
  4. -e 'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)'

Step 6. Run the Rust code

Now that you have a database and a user, you'll run code to create a table and insert some rows, and then you'll run code to 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, inserting rows and reading and printing the rows.

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

  1. extern crate postgres;
  2. use postgres::{Connection, TlsMode};
  3. use postgres::tls::openssl::OpenSsl;
  4. use postgres::tls::openssl::openssl::ssl::{SslConnectorBuilder, SslMethod};
  5. use postgres::tls::openssl::openssl::x509::X509_FILETYPE_PEM;
  6. fn ssl_config() -> OpenSsl {
  7. // Warning! This API will be changing in the next version of these crates.
  8. let mut connector_builder = SslConnectorBuilder::new(SslMethod::tls()).unwrap();
  9. connector_builder.set_ca_file("certs/ca.crt").unwrap();
  10. connector_builder.set_certificate_chain_file("certs/client.maxroach.crt").unwrap();
  11. connector_builder.set_private_key_file("certs/client.maxroach.key", X509_FILETYPE_PEM).unwrap();
  12. let mut ssl = OpenSsl::new().unwrap();
  13. *ssl.connector_mut() = connector_builder.build();
  14. ssl
  15. }
  16. fn main() {
  17. let tls_mode = TlsMode::Require(&ssl_config());
  18. let conn = Connection::connect("postgresql://maxroach@localhost:26257/bank", tls_mode)
  19. .unwrap();
  20. // Insert two rows into the "accounts" table.
  21. conn.execute(
  22. "INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)",
  23. &[],
  24. ).unwrap();
  25. // Print out the balances.
  26. println!("Initial balances:");
  27. for row in &conn.query("SELECT id, balance FROM accounts", &[]).unwrap() {
  28. let id: i64 = row.get(0);
  29. let balance: i64 = row.get(1);
  30. println!("{} {}", id, balance);
  31. }
  32. }

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.rs 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. extern crate postgres;
  2. use postgres::{Connection, TlsMode, Result};
  3. use postgres::tls::openssl::OpenSsl;
  4. use postgres::tls::openssl::openssl::ssl::{SslConnectorBuilder, SslMethod};
  5. use postgres::tls::openssl::openssl::x509::X509_FILETYPE_PEM;
  6. use postgres::transaction::Transaction;
  7. use postgres::error::T_R_SERIALIZATION_FAILURE;
  8. /// Runs op inside a transaction and retries it as needed.
  9. /// On non-retryable failures, the transaction is aborted and
  10. /// rolled back; on success, the transaction is committed.
  11. fn execute_txn<T, F>(conn: &Connection, mut op: F) -> Result<T>
  12. where
  13. F: Fn(&Transaction) -> Result<T>,
  14. {
  15. let txn = conn.transaction()?;
  16. loop {
  17. let sp = txn.savepoint("cockroach_restart")?;
  18. match op(&sp).and_then(|t| sp.commit().map(|_| t)) {
  19. Err(ref err) if err.as_db()
  20. .map(|e| e.code == T_R_SERIALIZATION_FAILURE)
  21. .unwrap_or(false) => {},
  22. r => break r,
  23. }
  24. }.and_then(|t| txn.commit().map(|_| t))
  25. }
  26. fn transfer_funds(txn: &Transaction, from: i64, to: i64, amount: i64) -> Result<()> {
  27. // Read the balance.
  28. let from_balance: i64 = txn.query("SELECT balance FROM accounts WHERE id = $1", &[&from])?
  29. .get(0)
  30. .get(0);
  31. assert!(from_balance >= amount);
  32. // Perform the transfer.
  33. txn.execute(
  34. "UPDATE accounts SET balance = balance - $1 WHERE id = $2",
  35. &[&amount, &from],
  36. )?;
  37. txn.execute(
  38. "UPDATE accounts SET balance = balance + $1 WHERE id = $2",
  39. &[&amount, &to],
  40. )?;
  41. Ok(())
  42. }
  43. fn ssl_config() -> OpenSsl {
  44. // Warning! This API will be changing in the next version of these crates.
  45. let mut connector_builder = SslConnectorBuilder::new(SslMethod::tls()).unwrap();
  46. connector_builder.set_ca_file("certs/ca.crt").unwrap();
  47. connector_builder.set_certificate_chain_file("certs/client.maxroach.crt").unwrap();
  48. connector_builder.set_private_key_file("certs/client.maxroach.key", X509_FILETYPE_PEM).unwrap();
  49. let mut ssl = OpenSsl::new().unwrap();
  50. *ssl.connector_mut() = connector_builder.build();
  51. ssl
  52. }
  53. fn main() {
  54. let tls_mode = TlsMode::Require(&ssl_config());
  55. let conn = Connection::connect("postgresql://maxroach@localhost:26257/bank", tls_mode)
  56. .unwrap();
  57. // Run a transfer in a transaction.
  58. execute_txn(&conn, |txn| transfer_funds(txn, 1, 2, 100)).unwrap();
  59. // Check account balances after the transaction.
  60. for row in &conn.query("SELECT id, balance FROM accounts", &[]).unwrap() {
  61. let id: i64 = row.get(0);
  62. let balance: i64 = row.get(1);
  63. println!("{} {}", id, balance);
  64. }
  65. }

After running the code, use the built-in SQL client to verify that funds were transferred from one account to another:

  1. $ cockroach sql --insecure -e 'SELECT id, balance FROM accounts' --database=bank
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

Step 1. Install the Rust Postgres driver

Install the Rust Postgres driver as described in the official documentation.

Step 2. Start a single-node cluster

For the purpose of this tutorial, you need only one CockroachDB node running in insecure mode:

  1. $ cockroach start \
  2. --insecure \
  3. --store=hello-1 \
  4. --listen-addr=localhost

Step 3. Create a user

In a new terminal, as the root user, use the cockroach user command to create a new user, maxroach.

  1. $ cockroach user set maxroach --insecure

Step 4. Create a database and grant privileges

As the root user, use the built-in SQL client to create a bank database.

  1. $ cockroach sql --insecure -e 'CREATE DATABASE bank'

Then grant privileges to the maxroach user.

  1. $ cockroach sql --insecure -e 'GRANT ALL ON DATABASE bank TO maxroach'

Step 5. Create a table in the new database

As the maxroach user, use the built-in SQL client to create an accounts table in the new database.

  1. $ cockroach sql --insecure \
  2. --database=bank \
  3. --user=maxroach \
  4. -e 'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)'

Step 6. Run the Rust code

Now that you have a database and a user, you'll run code to create a table and insert some rows, and then you'll run code to 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, inserting rows and reading and printing the rows.

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

  1. extern crate postgres;
  2. use postgres::{Connection, TlsMode};
  3. fn main() {
  4. let conn = Connection::connect("postgresql://maxroach@localhost:26257/bank", TlsMode::None)
  5. .unwrap();
  6. // Insert two rows into the "accounts" table.
  7. conn.execute(
  8. "INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)",
  9. &[],
  10. ).unwrap();
  11. // Print out the balances.
  12. println!("Initial balances:");
  13. for row in &conn.query("SELECT id, balance FROM accounts", &[]).unwrap() {
  14. let id: i64 = row.get(0);
  15. let balance: i64 = row.get(1);
  16. println!("{} {}", id, balance);
  17. }
  18. }

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.rs 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. extern crate postgres;
  2. use postgres::{Connection, TlsMode, Result};
  3. use postgres::transaction::Transaction;
  4. use postgres::error::T_R_SERIALIZATION_FAILURE;
  5. /// Runs op inside a transaction and retries it as needed.
  6. /// On non-retryable failures, the transaction is aborted and
  7. /// rolled back; on success, the transaction is committed.
  8. fn execute_txn<T, F>(conn: &Connection, mut op: F) -> Result<T>
  9. where
  10. F: Fn(&Transaction) -> Result<T>,
  11. {
  12. let txn = conn.transaction()?;
  13. loop {
  14. let sp = txn.savepoint("cockroach_restart")?;
  15. match op(&sp).and_then(|t| sp.commit().map(|_| t)) {
  16. Err(ref err) if err.as_db()
  17. .map(|e| e.code == T_R_SERIALIZATION_FAILURE)
  18. .unwrap_or(false) => {},
  19. r => break r,
  20. }
  21. }.and_then(|t| txn.commit().map(|_| t))
  22. }
  23. fn transfer_funds(txn: &Transaction, from: i64, to: i64, amount: i64) -> Result<()> {
  24. // Read the balance.
  25. let from_balance: i64 = txn.query("SELECT balance FROM accounts WHERE id = $1", &[&from])?
  26. .get(0)
  27. .get(0);
  28. assert!(from_balance >= amount);
  29. // Perform the transfer.
  30. txn.execute(
  31. "UPDATE accounts SET balance = balance - $1 WHERE id = $2",
  32. &[&amount, &from],
  33. )?;
  34. txn.execute(
  35. "UPDATE accounts SET balance = balance + $1 WHERE id = $2",
  36. &[&amount, &to],
  37. )?;
  38. Ok(())
  39. }
  40. fn main() {
  41. let conn = Connection::connect("postgresql://maxroach@localhost:26257/bank", TlsMode::None)
  42. .unwrap();
  43. // Run a transfer in a transaction.
  44. execute_txn(&conn, |txn| transfer_funds(txn, 1, 2, 100)).unwrap();
  45. // Check account balances after the transaction.
  46. for row in &conn.query("SELECT id, balance FROM accounts", &[]).unwrap() {
  47. let id: i64 = row.get(0);
  48. let balance: i64 = row.get(1);
  49. println!("{} {}", id, balance);
  50. }
  51. }

After running the code, use the built-in SQL client to verify that funds were transferred from one account to another:

  1. $ cockroach sql --insecure -e 'SELECT id, balance FROM accounts' --database=bank
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

What's next?

Read more about using the Rust Postgres driver.

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

Was this page helpful?
YesNo