Go driver

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.

This guide 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.

Prerequisites

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

  1. 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 as us-east-2

    • ASTRA_DB_KEYSPACE: A keyspace in your database, such as default_keyspace

    • ASTRA_DB_APPLICATION_TOKEN: An application token with the Database Administrator role.

  2. 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)
        }
    
    }
  1. Download your database’s Secure Connect Bundle (SCB).

  2. Set the following environment variables:

  3. 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:

main.go
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:

  1. In your Go project directory, create a main.go file.

  2. Copy the sample script to main.go, and then save the file.

  3. 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 the DELETE commands if you want to preserve the books table for additional testing.

    go run main.go

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com