Skip to content

Latest commit

 

History

History
98 lines (71 loc) · 3.05 KB

build-a-go-app-with-cockroachdb-gorm.md

File metadata and controls

98 lines (71 loc) · 3.05 KB
title summary toc twitter
Build a Go App with CockroachDB
Learn how to use CockroachDB from a simple Go application with the GORM ORM.
false
false

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.

{{site.data.alerts.callout_success}}For a more realistic use of GORM with CockroachDB, see our examples-orms repository.{{site.data.alerts.end}}

Before You Begin

Make sure you have already installed CockroachDB.

Step 1. Install the GORM ORM

To install GORM, run the following command:

{% include copy-clipboard.html %}

$ go get -u github.com/jinzhu/gorm

{% include app/common-steps.md %}

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.

{% include copy-clipboard.html %}

{% include app/gorm-basic-sample.go %}

Then run the code:

{% include copy-clipboard.html %}

$ 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:

{% include copy-clipboard.html %}

$ cockroach sql --insecure -e 'SHOW TABLES' --database=bank
+----------+
|  Table   |
+----------+
| accounts |
+----------+
(1 row)

{% include copy-clipboard.html %}

$ 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.

{% include app/see-also-links.md %}