Connect the Go driver to your database
This driver doesn’t support the vector data type. DataStax recommends the Data API and clients for Serverless (Vector) databases. You can use the Data API to perform CQL operations on your table data in Serverless (Vector) databases. DataStax recommends drivers only for Serverless (Non-Vector) databases, existing applications that previously used a CQL-based driver, or applications that require CQL functions that aren’t supported by the Data API. For more information, see Connection methods comparison. |
To use the Apache Cassandra® GoCQL driver (gocql
) with Astra DB, use the gocql-astra
package, which includes gocql
and additional support for connections to Astra DB.
Because gocql
doesn’t directly support connections to Astra DB, the gocql-astra
package provides a custom gocql.HostDialer
that facilitates gocql
connections to Astra DB.
Prerequisites
-
An active Astra account.
-
An active Astra DB Serverless database.
-
Install Go version 1.18 or later.
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
dependency.
Connect to your database
gocql-astra
provides support to connect gocql
to Astra DB.
-
Connect with an application token
-
Connect with an SCB
-
Set the following environment variables:
-
ASTRA_DB_ID
: The database ID -
ASTRA_DB_REGION
: A region where your database is deployed and where you want to connect to the database, such asus-east-2
-
ASTRA_DB_KEYSPACE
: A keyspace in your database, such asdefault_keyspace
-
ASTRA_DB_APPLICATION_TOKEN
: An application token with the Database Administrator role.
-
-
Run a script such as the following to connect to your database. This code imports the necessary classes, sets up a session, authenticates with an application token, and specifies a default keyspace.
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("ASTRA_DB_APPLICATION_TOKEN")) > 0 { if len(os.Getenv("ASTRA_DB_ID")) == 0 { panic("database ID is required when using a token") } } cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("ASTRA_DB_ID"), os.Getenv("ASTRA_DB_APPLICATION_TOKEN"), 10*time.Second) if err != nil { log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("ASTRA_DB_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) } }
-
Download your database’s Secure Connect Bundle (SCB).
-
Set the following environment variables:
-
ASTRA_DB_SECURE_BUNDLE_PATH
: The path your database’s SCB ZIP file. -
ASTRA_DB_APPLICATION_TOKEN
: An application token with the Database Administrator role.
-
-
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.
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("ASTRA_DB_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
Book
object -
Create a
books
table -
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("ASTRA_DB_APPLICATION_TOKEN")) > 0 {
if len(os.Getenv("ASTRA_DB_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("ASTRA_DB_ID"), os.Getenv("ASTRA_DB_APPLICATION_TOKEN"), 20*time.Second)
if err != nil {
log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("ASTRA_DB_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:
-
In your Go project directory, create a
main.go
file. -
Copy the sample script to
main.go
, and then save the file. -
Run
main.go
.Be aware that the sample script creates and deletes a table. If you run it as is, the
books
table won’t exist in your database after the script ends. Consider breaking the sample script into smaller scripts or commenting out theDELETE
commands if you want to preserve thebooks
table for additional testing.go run main.go