Build a Go App with CockroachDB

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

We have tested the Go pq driver and the GORM 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 Go pq driver

To install the Go pq driver, run the following command:

  1. $ go get -u github.com/lib/pq

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 Go 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, creating a table, inserting rows, and reading and printing the rows.

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

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/lib/pq"
  7. )
  8. func main() {
  9. // Connect to the "bank" database.
  10. db, err := sql.Open("postgres",
  11. "postgresql://maxroach@localhost:26257/bank?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.maxroach.key&sslcert=certs/client.maxroach.crt")
  12. if err != nil {
  13. log.Fatal("error connecting to the database: ", err)
  14. }
  15. defer db.Close()
  16. // Create the "accounts" table.
  17. if _, err := db.Exec(
  18. "CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)"); err != nil {
  19. log.Fatal(err)
  20. }
  21. // Insert two rows into the "accounts" table.
  22. if _, err := db.Exec(
  23. "INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)"); err != nil {
  24. log.Fatal(err)
  25. }
  26. // Print out the balances.
  27. rows, err := db.Query("SELECT id, balance FROM accounts")
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. defer rows.Close()
  32. fmt.Println("Initial balances:")
  33. for rows.Next() {
  34. var id, balance int
  35. if err := rows.Scan(&id, &balance); err != nil {
  36. log.Fatal(err)
  37. }
  38. fmt.Printf("%d %d\n", id, balance)
  39. }
  40. }

Then run the code:

  1. $ go run basic-sample.go

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 will 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.go file, or create the file yourself and copy the code into it.

  1. package main
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "log"
  7. "github.com/cockroachdb/cockroach-go/crdb"
  8. )
  9. func transferFunds(tx *sql.Tx, from int, to int, amount int) error {
  10. // Read the balance.
  11. var fromBalance int
  12. if err := tx.QueryRow(
  13. "SELECT balance FROM accounts WHERE id = $1", from).Scan(&fromBalance); err != nil {
  14. return err
  15. }
  16. if fromBalance < amount {
  17. return fmt.Errorf("insufficient funds")
  18. }
  19. // Perform the transfer.
  20. if _, err := tx.Exec(
  21. "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, from); err != nil {
  22. return err
  23. }
  24. if _, err := tx.Exec(
  25. "UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, to); err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. func main() {
  31. db, err := sql.Open("postgres",
  32. "postgresql://maxroach@localhost:26257/bank?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.maxroach.key&sslcert=certs/client.maxroach.crt")
  33. if err != nil {
  34. log.Fatal("error connecting to the database: ", err)
  35. }
  36. defer db.Close()
  37. // Run a transfer in a transaction.
  38. err = crdb.ExecuteTx(context.Background(), db, nil, func(tx *sql.Tx) error {
  39. return transferFunds(tx, 1 /* from acct# */, 2 /* to acct# */, 100 /* amount */)
  40. })
  41. if err == nil {
  42. fmt.Println("Success")
  43. } else {
  44. log.Fatal("error: ", err)
  45. }
  46. }

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. For Go, the CockroachDB retry function is in the crdb package of the CockroachDB Go client. To install Clone the library into your $GOPATH as follows:

  1. $ mkdir -p $GOPATH/src/github.com/cockroachdb
  1. $ cd $GOPATH/src/github.com/cockroachdb
  1. $ git clone git@github.com:cockroachdb/cockroach-go.git

Then run the code:

  1. $ go run txn-sample.go

The output should be:

  1. Success

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

  1. $ cockroach sql --certs-dir=certs -e 'SELECT id, balance FROM accounts' --database=bank
  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 Go 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, creating a table, inserting rows, and reading and printing the rows.

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

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/lib/pq"
  7. )
  8. func main() {
  9. // Connect to the "bank" database.
  10. db, err := sql.Open("postgres", "postgresql://maxroach@localhost:26257/bank?sslmode=disable")
  11. if err != nil {
  12. log.Fatal("error connecting to the database: ", err)
  13. }
  14. // Create the "accounts" table.
  15. if _, err := db.Exec(
  16. "CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)"); err != nil {
  17. log.Fatal(err)
  18. }
  19. // Insert two rows into the "accounts" table.
  20. if _, err := db.Exec(
  21. "INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)"); err != nil {
  22. log.Fatal(err)
  23. }
  24. // Print out the balances.
  25. rows, err := db.Query("SELECT id, balance FROM accounts")
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer rows.Close()
  30. fmt.Println("Initial balances:")
  31. for rows.Next() {
  32. var id, balance int
  33. if err := rows.Scan(&id, &balance); err != nil {
  34. log.Fatal(err)
  35. }
  36. fmt.Printf("%d %d\n", id, balance)
  37. }
  38. }

Then run the code:

  1. $ go run basic-sample.go

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 will 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.go file, or create the file yourself and copy the code into it.

  1. package main
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "log"
  7. "github.com/cockroachdb/cockroach-go/crdb"
  8. )
  9. func transferFunds(tx *sql.Tx, from int, to int, amount int) error {
  10. // Read the balance.
  11. var fromBalance int
  12. if err := tx.QueryRow(
  13. "SELECT balance FROM accounts WHERE id = $1", from).Scan(&fromBalance); err != nil {
  14. return err
  15. }
  16. if fromBalance < amount {
  17. return fmt.Errorf("insufficient funds")
  18. }
  19. // Perform the transfer.
  20. if _, err := tx.Exec(
  21. "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, from); err != nil {
  22. return err
  23. }
  24. if _, err := tx.Exec(
  25. "UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, to); err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. func main() {
  31. db, err := sql.Open("postgres", "postgresql://maxroach@localhost:26257/bank?sslmode=disable")
  32. if err != nil {
  33. log.Fatal("error connecting to the database: ", err)
  34. }
  35. // Run a transfer in a transaction.
  36. err = crdb.ExecuteTx(context.Background(), db, nil, func(tx *sql.Tx) error {
  37. return transferFunds(tx, 1 /* from acct# */, 2 /* to acct# */, 100 /* amount */)
  38. })
  39. if err == nil {
  40. fmt.Println("Success")
  41. } else {
  42. log.Fatal("error: ", err)
  43. }
  44. }

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. For Go, the CockroachDB retry function is in the crdb package of the CockroachDB Go client.

To install the CockroachDB Go client, run the following command:

  1. $ go get -d github.com/cockroachdb/cockroach-go

Then run the code:

  1. $ go run txn-sample.go

The output should be:

  1. Success

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

  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 Go pq driver.

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

Was this page helpful?
YesNo