Skip to main content

Build a Go App with upper/db and CockroachDB

Today's blog is a guest post by José Nieto, creator of upper/db. upper/db gives you tools for the most common operations with databases, and is now compatible with CockroachDB.

upper/db is a data access layer written in Go with ORM-like features. It's compatible with PostgreSQL, MySQL, SQLite, MongoDB, and now, CockroachDB! I am very pleased to announce that our CockroachDB adapter is now in beta and ready to be used!

Get the adapter the usual way:

go get

CockroachDB has two installation modes: secure and insecure. Secure mode has good defaults for production usage whilst insecure mode is more suited for local development and testing.

Here's an example on how to connect to a local insecure node using the cockroachdb adapter:

package main

import (


var settings = cockroachdb.ConnectionURL{
Host:  "localhost",
Database: "bank",
User:  "maxroach",
Options: map[string]string{
"sslmode": "disable",

func main() {
sess, err := cockroachdb.Open(settings)
if err != nil {
log.Fatal("cockroachdb.Open: ", err)
defer sess.Close()

fmt.Printf("connected to database %q\n", sess.Name())


Transactions are essential when working with SQL databases as they allow you to represent several database-altering operations as a single unit.

upper/db comes with client-side retry handling logic, whenever a transaction fails with a retryable error, upper/db will wait a few milliseconds and try again until succeeding:

err = sess.Tx(func(tx db.Session) error {
// If a retryable error happens here, the transaction will be retried a few
// times (with exponential back-off).
return nil
if err != nil {
log.Fatal("Could not commit transaction: ", err)

If you want to configure the maximum number of transaction retries you can use the SetMaxTransactionRetries method:


Build a Go App: Hello World Example

See the official Hello World repo for a tutorial on how to build a Go app with CockroachDB and upper/db, or check out all methods for building Go apps with CockroachDB.

The post Build a Go App with upper/db and CockroachDB appeared first on Cockroach Labs.