Usage Guide
This guide covers the core concepts of using gocqlx for everyday database tasks.
Session Management
gocqlx operates by wrapping a standard gocql.Session. This wrapper adds the extended functionality (like BindStruct and Select) while still providing access to the underlying session if needed.
cluster := gocql.NewCluster("127.0.0.1")
// Create the standard session
rawSession, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
// Wrap it
session := gocqlx.NewSession(rawSession)
// Or wrap on creation:
// session, err := gocqlx.WrapSession(cluster.CreateSession())
Data Binding
gocqlx simplifies sending data to the database by allowing you to bind entire structs or maps to named parameters in your queries.
Field Mapping
By default, gocqlx maps struct fields to database columns by converting CamelCase fields to snake_case columns. You can customize this using the db struct tag.
type User struct {
ID gocql.UUID
UserName string `db:"user_name"` // Explicit mapping
Age int `db:"-"` // Skip this field
}
BindStruct
Binds named parameters in the query to fields in the struct.
u := User{ID: gocql.TimeUUID(), UserName: "scylla"}
// Query expects :id and :user_name
q := session.Query("INSERT INTO users (id, user_name) VALUES (:id, :user_name)",
[]string{"id", "user_name"})
q.BindStruct(u)
if err := q.ExecRelease(); err != nil {
log.Fatal(err)
}
BindMap
Similar to BindStruct, but uses a map[string]interface{}.
q.BindMap(map[string]interface{}{
"id": gocql.TimeUUID(),
"user_name": "scylla",
})
Scanning Results
Retrieving data is done by scanning results directly into Go types.
Get (Single Row)
Use Get when you expect exactly one result row. It scans into a struct pointer.
var u User
err := session.Query("SELECT * FROM users WHERE id=?", []string{"id"}).
Bind(id).
Get(&u)
Select (Multiple Rows)
Use Select to scan multiple rows into a slice of structs.
var users []User
err := session.Query("SELECT * FROM users", nil).Select(&users)
Iter (Row-by-Row)
For large datasets where loading everything into a slice memory is inefficient, use Iter with StructScan.
iter := session.Query("SELECT * FROM users", nil).Iter()
var u User
for iter.StructScan(&u) {
fmt.Println(u)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
Strict Mode
By default, gocqlx ignores columns in the result set that do not match fields in the struct. You can enable strict mode to return an error instead.
// Will error if the query returns columns not present in User struct
err := session.Query(stmt, names).Strict().Select(&users)
Batch Operations
gocqlx provides a Batch wrapper that supports struct binding.
batch := session.NewBatch(gocql.LoggedBatch)
// Create a reusable query
stmt, names := qb.Insert("users").Columns("id", "user_name").ToCql()
q := session.Query(stmt, names)
// Add multiple items
for _, u := range usersToInsert {
batch.BindStruct(q, u)
}
if err := session.ExecuteBatch(batch); err != nil {
log.Fatal(err)
}