Build a Ruby App with CockroachDB

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

We have tested the Ruby pg driver and the ActiveRecord 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 Ruby pg driver

To install the Ruby pg driver, run the following command:

  1. $ gem install pg

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 Ruby 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

The following code connects as the maxroach user and executes some basic SQL statements: creating a table, inserting rows, and reading and printing the rows.

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

  1. # Import the driver.
  2. require 'pg'
  3. # Connect to the "bank" database.
  4. conn = PG.connect(
  5. user: 'maxroach',
  6. dbname: 'bank',
  7. host: 'localhost',
  8. port: 26257,
  9. sslmode: 'require',
  10. sslrootcert: 'certs/ca.crt',
  11. sslkey:'certs/client.maxroach.key',
  12. sslcert:'certs/client.maxroach.crt'
  13. )
  14. # Create the "accounts" table.
  15. conn.exec('CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)')
  16. # Insert two rows into the "accounts" table.
  17. conn.exec('INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)')
  18. # Print out the balances.
  19. puts 'Initial balances:'
  20. conn.exec('SELECT id, balance FROM accounts') do |res|
  21. res.each do |row|
  22. puts row
  23. end
  24. end
  25. # Close communication with the database.
  26. conn.close()

Then run the code:

  1. $ ruby basic-sample.rb

The output should be:

  1. Initial balances:
  2. {"id"=>"1", "balance"=>"1000"}
  3. {"id"=>"2", "balance"=>"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.rb file, or create the file yourself and copy the code into it.

Note:

With the default SERIALIZABLE isolation level, 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. The code sample below shows how it is used.

  1. # Import the driver.
  2. require 'pg'
  3. # Wrapper for a transaction.
  4. # This automatically re-calls "op" with the open transaction as an argument
  5. # as long as the database server asks for the transaction to be retried.
  6. def run_transaction(conn)
  7. conn.transaction do |txn|
  8. txn.exec('SAVEPOINT cockroach_restart')
  9. while
  10. begin
  11. # Attempt the work.
  12. yield txn
  13. # If we reach this point, commit.
  14. txn.exec('RELEASE SAVEPOINT cockroach_restart')
  15. break
  16. rescue PG::TRSerializationFailure
  17. txn.exec('ROLLBACK TO SAVEPOINT cockroach_restart')
  18. end
  19. end
  20. end
  21. end
  22. def transfer_funds(txn, from, to, amount)
  23. txn.exec_params('SELECT balance FROM accounts WHERE id = $1', [from]) do |res|
  24. res.each do |row|
  25. raise 'insufficient funds' if Integer(row['balance']) < amount
  26. end
  27. end
  28. txn.exec_params('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from])
  29. txn.exec_params('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to])
  30. end
  31. # Connect to the "bank" database.
  32. conn = PG.connect(
  33. user: 'maxroach',
  34. dbname: 'bank',
  35. host: 'localhost',
  36. port: 26257,
  37. sslmode: 'require',
  38. sslrootcert: 'certs/ca.crt',
  39. sslkey:'certs/client.maxroach.key',
  40. sslcert:'certs/client.maxroach.crt'
  41. )
  42. run_transaction(conn) do |txn|
  43. transfer_funds(txn, 1, 2, 100)
  44. end
  45. # Close communication with the database.
  46. conn.close()

Then run the code:

  1. $ ruby txn-sample.rb

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 Ruby 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

The following code connects as the maxroach user and executes some basic SQL statements: creating a table, inserting rows, and reading and printing the rows.

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

  1. # Import the driver.
  2. require 'pg'
  3. # Connect to the "bank" database.
  4. conn = PG.connect(
  5. user: 'maxroach',
  6. dbname: 'bank',
  7. host: 'localhost',
  8. port: 26257,
  9. sslmode: 'disable'
  10. )
  11. # Create the "accounts" table.
  12. conn.exec('CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)')
  13. # Insert two rows into the "accounts" table.
  14. conn.exec('INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)')
  15. # Print out the balances.
  16. puts 'Initial balances:'
  17. conn.exec('SELECT id, balance FROM accounts') do |res|
  18. res.each do |row|
  19. puts row
  20. end
  21. end
  22. # Close communication with the database.
  23. conn.close()

Then run the code:

  1. $ ruby basic-sample.rb

The output should be:

  1. Initial balances:
  2. {"id"=>"1", "balance"=>"1000"}
  3. {"id"=>"2", "balance"=>"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.rb file, or create the file yourself and copy the code into it.

Note:

With the default SERIALIZABLE isolation level, 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. The code sample below shows how it is used.

  1. # Import the driver.
  2. require 'pg'
  3. # Wrapper for a transaction.
  4. # This automatically re-calls "op" with the open transaction as an argument
  5. # as long as the database server asks for the transaction to be retried.
  6. def run_transaction(conn)
  7. conn.transaction do |txn|
  8. txn.exec('SAVEPOINT cockroach_restart')
  9. while
  10. begin
  11. # Attempt the work.
  12. yield txn
  13. # If we reach this point, commit.
  14. txn.exec('RELEASE SAVEPOINT cockroach_restart')
  15. break
  16. rescue PG::TRSerializationFailure
  17. txn.exec('ROLLBACK TO SAVEPOINT cockroach_restart')
  18. end
  19. end
  20. end
  21. end
  22. def transfer_funds(txn, from, to, amount)
  23. txn.exec_params('SELECT balance FROM accounts WHERE id = $1', [from]) do |res|
  24. res.each do |row|
  25. raise 'insufficient funds' if Integer(row['balance']) < amount
  26. end
  27. end
  28. txn.exec_params('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from])
  29. txn.exec_params('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to])
  30. end
  31. # Connect to the "bank" database.
  32. conn = PG.connect(
  33. user: 'maxroach',
  34. dbname: 'bank',
  35. host: 'localhost',
  36. port: 26257,
  37. sslmode: 'disable'
  38. )
  39. run_transaction(conn) do |txn|
  40. transfer_funds(txn, 1, 2, 100)
  41. end
  42. # Close communication with the database.
  43. conn.close()

Then run the code:

  1. $ ruby txn-sample.rb

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 Ruby pg driver.

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

Was this page helpful?
YesNo