Struct Binding In CQLC

One of the major design goals of cqlc is to reduce the amount of boilerplate code required to maintain non-trivial Cassandra based applications. I’ve been thinking for a while that the cqlc fluent API would be more convenient if it offered a convenience method to store an entire Go struct to a row in Cassandra.

That said, cqlc is not an ORM and as such, it should not attempt to anything too clever, lest it turn into a leaky abstraction. In addition to not hiding anything from the developer, it should retain the type safety that underpins the cqlc concept, so that when you upgrade your schema, the compiler will tell you when your code is out of sync.

So as a compromise between the full convenience of an object mapping layer and the bare bones simplicity approach of cqlc, I’ve modified the cqlc schema compiler to generate a Bind() method for each column family it visits. The Bind() method takes an instance of the generated struct that corresponds to a particular column family. In the future this binding might be made more flexible and configurable, but I wanted to run with something simple for now.


The following example shows how cqlc generates struct bindings from an example table in Cassandra. If you don’t know how cqlc works in general, your can read the introduction here.

Using the following example events table:

    sensor bigint,
    timestamp timeuuid,
    temperature float,
    pressure int,
    PRIMARY KEY (sensor, timestamp)

cqlc will generate the following struct in Go:

type Events struct {
    Pressure    int32
    Temperature float32
    Sensor      int64
    Timestamp   gocql.UUID

At runtime you can create an instance of this generated struct and use it in conjunction with the fluent API:

events := Events{
    Pressure:    74,
    Temparature: 24.36,
    Sensor:      23083458901980,
    Timestamp:   gocql.TimeUUID(),

err := ctx.Store(EVENTS.Bind(events)).Exec(session)

The call to EVENTS.Bind(events) is type safe in the sense that the generted Bind() method only accepts instances of the Events struct.


The documentation on struct binding in cqlc is available here.

comments powered by Disqus