To use GocqlX, you first wrap a standard gocql.Session using gocqlx.WrapSession.
Then, define your table metadata using table.Metadata and create a table object with table.New. For your data structures (structs), GocqlX automatically maps field names to snake_case in the database. You can skip fields by using the db:"-" tag or by making the field unexported.
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. Wrap gocql Session
cluster := gocql.NewCluster(hosts...)
session, err := gocqlx.WrapSession(cluster.CreateSession())
if err != nil {
log.Fatal(err)
}
defer session.Close()
// 2. Specify table model
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)
type Person struct {
FirstName string
LastName string
Email []string
HairColor string `db:"-"` // exported and skipped
eyeColor string // unexported also skipped
}