Connect with the Go driver
|
DataStax recommends the Data API and clients for Serverless (vector) databases. You can use the Data API to run CQL statements on tables in Serverless (vector) databases. DataStax recommends drivers only for Serverless (non-vector) databases, legacy applications that rely on a driver, or CQL functions that aren’t supported by the Data API. For more information, see Connect to Astra DB Serverless databases. |
Because Astra DB is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra DB Serverless databases.
To use the Apache Cassandra GoCQL driver (gocql) with Astra DB Serverless databases, use the gocql-astra package.
This package includes GoCQL and additional support for connections to Astra DB.
The gocql-astra package provides a custom gocql.HostDialer that facilitates GoCQL connections to Astra DB because GoCQL doesn’t directly support connections to Astra DB.
This quickstart explains how to use gocql-astra to connect gocql to your database, create a table, read and write data, and then delete the rows and table.
|
gocql-astra doesn’t support gocql 2.x or the vector type
Until |
Prerequisites
-
Install Go version 1.22 or later.
-
Download your database’s Secure Connect Bundle (SCB).
For multi-region databases, download the SCB for a region that is geographically close to your application to reduce latency.
If you need to connect to multiple regions in the same application, you need the SCB for each region, and your driver code must instantiate one root object (
session) for each region. For more information, see Best practices for Cassandra drivers. -
Set the following environment variables:
-
DATABASE_ID: The database ID. -
APPLICATION_TOKEN: An application token with the Database Administrator role.
-
Install gocql-astra
In the root of your Go project directory, add gocql-astra:
go get github.com/datastax/gocql-astra
gocql-astra includes the gocql package.
Connect to your database
gocql-astra provides support to connect gocql to Astra DB Serverless databases.
Connect with an application token only
Write a script to connect gocql to your database using the APPLICATION_TOKEN and DATABASE_ID environment variables.
The following example imports the necessary classes, sets up a session, authenticates with an application token, and runs a SELECT statement on the system.local table.
You can replace the example SELECT statement with any CQL statement that you want to run against a keyspace and table in your database.
package main
import (
"fmt"
"log"
"os"
"time"
gocqlastra "github.com/datastax/gocql-astra"
"github.com/gocql/gocql"
)
func main() {
var err error
var cluster *gocql.ClusterConfig
if len(os.Getenv("APPLICATION_TOKEN")) > 0 {
if len(os.Getenv("DATABASE_ID")) == 0 {
panic("database ID is required when using a token")
}
}
cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 10*time.Second)
if err != nil {
log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
}
cluster.Timeout = 30 * time.Second
start := time.Now()
session, err := gocql.NewSession(*cluster)
elapsed := time.Now().Sub(start)
if err != nil {
log.Fatalf("unable to connect session: %v", err)
}
fmt.Println("Making the query now")
iter := session.Query("SELECT release_version FROM system.local").Iter()
var version string
for iter.Scan(&version) {
fmt.Println(version)
}
if err = iter.Close(); err != nil {
log.Printf("error running query: %v", err)
}
fmt.Printf("Connection process took %s
", elapsed)
if err != nil {
log.Fatalf("unable to connect session: %v", err)
}
}
Enable SSL encryption with an SCB
To connect with SSL encryption, use the gocql-astra method that accepts an SCB path and application token:
-
Set an environment variable for your database’s SCB zip file, such as
ASTRA_DB_SECURE_BUNDLE_PATH. For more information, see Prerequisites. -
Run a script such as the following to connect to your database. This code imports the necessary classes, sets up a session, and authenticates with an SCB.
In the authentication credentials, the literal string
tokenis required for successful authentication. For more information, see Token details.package main import ( "fmt" "log" "os" "time" gocqlastra "github.com/datastax/gocql-astra" "github.com/gocql/gocql" ) func main() { var cluster *gocql.ClusterConfig cluster, err := gocqlastra.NewClusterFromBundle(os.Getenv("ASTRA_DB_SECURE_BUNDLE_PATH"), "token", os.Getenv("APPLICATION_TOKEN"), 30*time.Second) if err != nil { panic("unable to load the bundle") } cluster.Timeout = 30 * time.Second session, err := gocql.NewSession(*cluster) if err != nil || session == nil { log.Fatalf("unable to connect session: %v", err) } else { fmt.Println("Success!") } }
Run commands
With gocql-astra, your scripts can use gocql commands to perform operations on your database.
For example, the following sample script performs these operations:
-
Defines the
Bookobject -
Connects to the database with an application token
-
Create a
bookstable -
Inserts two rows into the table
-
Retries the inserted rows
-
Updates one row
-
Deletes one row
-
Deletes the table
package main
import (
"fmt"
"log"
"os"
"time"
gocqlastra "github.com/datastax/gocql-astra"
"github.com/gocql/gocql"
)
type Book struct {
ID gocql.UUID
Title string
Author string
Year int
}
func main() {
var err error
var cluster *gocql.ClusterConfig
if len(os.Getenv("APPLICATION_TOKEN")) > 0 {
if len(os.Getenv("DATABASE_ID")) == 0 {
panic("database ID is required when using a token")
}
}
fmt.Println("Creating the cluster now")
cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 20*time.Second)
if err != nil {
log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
}
cluster.Timeout = 30 * time.Second
session, err := gocql.NewSession(*cluster)
if err != nil {
log.Fatalf("unable to connect session: %v", err)
}
defer session.Close()
// Delete the table
if err := session.Query(`DROP TABLE IF EXISTS library.books`).Exec(); err != nil {
fmt.Println("Dropping table to clean for examples.")
}
// Create the table
fmt.Println("Creating the table now")
if err := session.Query(`CREATE TABLE library.books ( id uuid PRIMARY KEY, title text, author text, year int );`).Exec(); err != nil {
log.Fatal(err)
}
// Create Rows
newBook := Book{
ID: gocql.TimeUUID(),
Title: "Go Programming",
Author: "John Doe",
Year: 2023,
}
secondBook := Book{
ID: gocql.TimeUUID(),
Title: "Zen and the Art of Go",
Author: "Jane Doe",
Year: 2023,
}
fmt.Println("Adding the books now:")
if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
newBook.ID, newBook.Title, newBook.Author, newBook.Year).Exec(); err != nil {
log.Fatal(err)
}
if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
secondBook.ID, secondBook.Title, secondBook.Author, secondBook.Year).Exec(); err != nil {
log.Fatal(err)
}
fmt.Println("Querying the books now:")
iter := session.Query(`SELECT id, title, author, year FROM library.books`).Iter()
var books []Book
var book Book
for iter.Scan(&book.ID, &book.Title, &book.Author, &book.Year) {
books = append(books, book)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
// Print all books
for _, book := range books {
fmt.Println("Book:", book)
}
// Update
updatedBook := Book{
ID: newBook.ID,
Title: "Advanced Go Programming",
Author: "John Doe",
Year: 2024,
}
if err := session.Query(`UPDATE library.books SET title = ?, author = ?, year = ? WHERE id = ?`,
updatedBook.Title, updatedBook.Author, updatedBook.Year, updatedBook.ID).Exec(); err != nil {
log.Fatal(err)
}
// Delete
if err := session.Query(`DELETE FROM library.books WHERE id = ?`, newBook.ID).Exec(); err != nil {
log.Fatal(err)
}
}
To run the sample script, do the following:
-
In your Go project directory, create a
main.gofile. -
Copy the sample script to
main.go, and then save the file.The sample script creates and deletes a table. If you run it as is, the
bookstable won’t exist in your database after the script ends. Consider breaking the sample script into smaller scripts, or comment out theDELETEcommands, if you want to preserve thebookstable for additional testing. -
Run
main.go:go run main.go
Next steps
Next, extend or modify this script to run other commands against your database or connect to other databases. For more information, see the following: