Note:
Cockroach Labs supports the current stable release and two releases prior. Therefore, this version will no longer be supported after the Spring 2019 release.

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.

Tip:
For a more realistic use of GORM with CockroachDB, see our examples-orms repository.

Before You Begin

Make sure you have already installed CockroachDB.

Step 1. Install the GORM ORM

To install GORM, run the following command:

copy
icon/buttons/copy
$ go get -u github.com/jinzhu/gorm

Step 2. Start a single-node cluster

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

copy
icon/buttons/copy
$ cockroach start \
--insecure \
--store=hello-1 \
--host=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.

copy
icon/buttons/copy
$ 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.

copy
icon/buttons/copy
$ cockroach sql --insecure -e 'CREATE DATABASE bank'

Then grant privileges to the maxroach user.

copy
icon/buttons/copy
$ cockroach sql --insecure -e 'GRANT ALL ON DATABASE bank TO maxroach'

Step 5. Run the Go code

The following code uses the GORM ORM to map Go-specific objects to SQL operations. Specifically, db.AutoMigrate(&Account{}) creates an accounts table based on the Account model, db.Create(&Account{}) inserts rows into the table, and db.Find(&accounts) selects from the table so that balances can be printed.

Copy the code or download it directly.

copy
icon/buttons/copy
package main

import (
    "fmt"
    "log"

    // Import GORM-related packages.
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

// Account is our model, which corresponds to the "accounts" database table.
type Account struct {
    ID      int `gorm:"primary_key"`
    Balance int
}

func main() {
    // Connect to the "bank" database as the "maxroach" user.
    const addr = "postgresql://maxroach@localhost:26257/bank?sslmode=disable"
    db, err := gorm.Open("postgres", addr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Automatically create the "accounts" table based on the Account model.
    db.AutoMigrate(&Account{})

    // Insert two rows into the "accounts" table.
    db.Create(&Account{ID: 1, Balance: 1000})
    db.Create(&Account{ID: 2, Balance: 250})

    // Print out the balances.
    var accounts []Account
    db.Find(&accounts)
    fmt.Println("Initial balances:")
    for _, account := range accounts {
        fmt.Printf("%d %d\n", account.ID, account.Balance)
    }
}

Then run the code:

copy
icon/buttons/copy
$ go run gorm-basic-sample.go

The output should be:

Initial balances:
1 1000
2 250

To verify that the table and rows were created successfully, you can again use the built-in SQL client:

copy
icon/buttons/copy
$ cockroach sql --insecure -e 'SHOW TABLES' --database=bank
+----------+
|  Table   |
+----------+
| accounts |
+----------+
(1 row)
copy
icon/buttons/copy
$ cockroach sql --insecure -e 'SELECT id, balance FROM accounts' --database=bank
+----+---------+
| id | balance |
+----+---------+
|  1 |    1000 |
|  2 |     250 |
+----+---------+
(2 rows)

What's Next?

Read more about using the GORM ORM, or check out a more realistic implementation of GORM with CockroachDB in our examples-orms repository.

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



Yes No