Quick Start

This guide will get you up and running with a simple example of connecting to the database, defining a schema, and performing basic insert and select operations.

1. Setup

Ensure you have a ScyllaDB or Cassandra instance running locally on port 9042.

2. The Code

Create a file named main.go:

package main

import (
    "fmt"
    "log"

    "github.com/gocql/gocql"
    "github.com/scylladb/gocqlx/v3"
    "github.com/scylladb/gocqlx/v3/qb"
    "github.com/scylladb/gocqlx/v3/table"
)

// 1. Define the Go Struct
type Person struct {
    FirstName string
    LastName  string
    Email     []string
}

// 2. Define Table Metadata
var personMetadata = table.Metadata{
    Name:    "person",
    Columns: []string{"first_name", "last_name", "email"},
    PartKey: []string{"first_name"},
    SortKey: []string{"last_name"},
}

var personTable = table.New(personMetadata)

func main() {
    // 3. Connect to the Cluster
    cluster := gocql.NewCluster("127.0.0.1")
    cluster.Keyspace = "example_keyspace"
    cluster.Consistency = gocql.Quorum

    // Wrap the session with gocqlx
    session, err := gocqlx.WrapSession(cluster.CreateSession())
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

    // Ensure table exists (for this example)
    err = session.ExecStmt(`CREATE TABLE IF NOT EXISTS person (
        first_name text,
        last_name text,
        email list<text>,
        PRIMARY KEY (first_name, last_name)
    )`)
    if err != nil {
        log.Fatal("create table:", err)
    }

    // 4. Insert Data
    p := Person{
        FirstName: "John",
        LastName:  "Doe",
        Email:     []string{"john@example.com"},
    }

    // Use the table model to create an insert query
    q := session.Query(personTable.Insert()).BindStruct(p)
    if err := q.ExecRelease(); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Inserted person")

    // 5. Query Data
    var people []Person

    // Use query builder for a custom SELECT
    stmt, names := qb.Select("person").Where(qb.Eq("first_name")).ToCql()

    q = session.Query(stmt, names).BindMap(qb.M{
        "first_name": "John",
    })

    if err := q.SelectRelease(&people); err != nil {
        log.Fatal(err)
    }

    for _, person := range people {
        fmt.Printf("Found: %+v\n", person)
    }
}

3. Run

go run main.go