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

What if I told you, Scala compiler can understand SQL queries?

Posted by Tamer M AbdulRadi on Fri, Jun 16, 2017

What if I told you, the Scala compiler can understand SQL queries? In fact .. let me show you!

toy-troy-macro

 

In the GIF above, we managed to get a compiler error when the SQL query selected a non-existing column "blah". But, how this is possible?

Obviously there is a little bit of macros involved, but under the hood, it all boils down to "type-level programming", in fact you can achieve the same without macros albeit not as prettily as above. Let's see...

toy-troy-typelevel

 

The GIF above achieves the same as the first one. The compiler knows about our schema that is encoded as "facts"! Basically I've written a prologue-like program disguised as Scala code that gets executed at the compile-time, allowing me to proof that my queries matches the schema, as well as generating encoding/decoding boilerplate for me.

The code here is using Troy, the Schemasafe Cassandra driver. If you want to learn how it was built, I recommend checking Toy-Troy, a stripped down version of Troy for the educational purpose. Also keep an eye on a series of blog posts I am writing here called "Introduction to type-level programming".

Finally, I'll be explaining step-by-step how to build a similar program in my upcoming talk "How to program the type system" in Scala Swarm on the 22nd of this month in Porto, so see you there!

 

Posts by Topic

see all

Subscribe to Email Updates