<img height="1" width="1" src="https://www.facebook.com/tr?id=1076094119157733&amp;ev=PageView &amp;noscript=1">

Introducing a schema-safe Scala Cassandra driver (Scala eXchange sneak-peak)

Posted by Tamer M AbdulRadi on Wed, Nov 16, 2016

Troy is an open source macro-based Cassandra driver, provides type-safe & compile-time checking for database queries, without imposing a DSL to express the queries in Scala. Instead, it allows developers to write plain Cassandra-query-language (CQL) queries within Scala code, complete with schema validation.

As a Datastax certified Cassandra developer I have learned a set of techniques and patterns for designing Cassandra schemas, which requires you to "know your queries" from the beginning. Based on those queries you might need to tweak the schema, add tables, or duplicate data. Therefore, to be able to verify that the schema actually fulfils the required queries, you have to test with tools like CQL shell. Once we got our queries validated and peer-reviewed, we are good to write some Scala code.

On one hand, If I chose to use Phantom or Quill, I'll find myself in a situation where I have to translate the CQL queries into some DSL, a collection-API like in the case of Quill, and proprietary custom syntax in case of Phantom. Later, these DSLs would generate/compile back into CQL. The same CQL I already wrote myself! But on the other hand, using Datastax Java driver directly allows me to copy-paste my queries directly from CQLsh into my editor, giving me maximum convenience, but very little type safety.

That's why Troy was implemented to give the same flexibility and copy-paste convenience of the Java driver, without sacrificing type safety.

For example:

val listByAuthor = withSchema {
  (authorId: String) =>
    
    cql"""
      
      SELECT post_id, post_title
      
      FROM test.posts
      
      WHERE author_id = $authorId;

    """
}

The example above compiles fine, but what if we made a mistake, for example, selecting a non existing column...

val listByAuthor = withSchema {
  (authorId: String) =>
    
    cql"""
      
      SELECT post_id, blaaa
      FROM test.posts
      WHERE author_id = $authorId;

    """

}

This won't compile, showing the following error message

Column 'blaaa' not found in table 'test.posts'

To know more about Troy, please check more examples and source in Github repo. Also attend my talk at Scala eXchange 2016, I'll answer questions and present how Troy works under-the-hood, like: how it knows about the schema (no, it doesn't connect to Cassandra at compile time, it is a terrible idea).

Topics: Scala, Cassandra

Recent Posts

Posts by Topic

see all

Subscribe to Email Updates