Showing posts with label scala. Show all posts
Showing posts with label scala. Show all posts

Monday, February 11, 2013

anorm-typed: Statically-Typed SQL Queries for Scala Play Applications

The Play framework's default persistence framework, Anorm, is a very thin wrapper around JDBC (the whole library is about 800 lines of code). Although I like the idea of a framework that treats a database as a database - instead of trying to shoehorn databases into the OO paradigm - Anorm has never really appealed to me. Since it's just a wrapper around SQL, you end up writing lots of raw SQL in your application. This is a problem, because the Scala compiler and typechecker have no opportunity to check your database interaction for errors. As flawed as ORM approaches can be, at least they can generate valid SQL for you. Consider this Anorm call from the Play! documentation:
  SQL(
    """
      select * from Country c 
      join CountryLanguage l on l.CountryCode = c.Code 
      where c.code = {countryCode};
   """
  ).on("countryCode" -> "FRA")
Here are just some of the ways this code can go wrong at runtime:
  • A typo in an SQL keyword
  • A typo in a column or table name
  • Reference to a column or table that doesn't exist
  • A typo in the "countryCode" key passed to the "on" function
  • Passing in a non-string value for "countryCode"
  • A mismatch between the parameters named in the query string and the keys passed to "on"
With Anorm's primary competitors (SLICK and Squeryl), you create mappings between columns and class fields, then use a query DSL to translate Scala Collections-like code into SQL. These frameworks are still vulnerable to some of the above problems, but they have some advantages:
  • You map each column only once, so if you get the column's name or type wrong, there's only one place to correct it, and then the rest of your program will be free of that particular bug.
  • These frameworks generate SQL themselves from a simple Scala DSL, so most syntax errors are ruled out.
Yet, these frameworks also introduce a number of issues:
  • You need to manually maintain model mappings that can drift out of sync with the database
  • The DSL's these libraries provide are necessarily limited. Some queries that would be straightforward and fast with pure SQL are simply inexpressible in these DSL's.
  • Both mappings are database-agnostic. This has obvious advantages, but if you need to take advantage of a database-specific data type, function or syntactical convenience, you're out of luck.
About a month ago, Play developer Guillaume Bort announced a proof-of-concept implementation of a statically-checked version of Anorm, Play's persistence framework (source on Github). The framework was inspired by Joni Freeman's sqltyped framework. The main API of anorm-typed is the TypedSQL macro. When you compile a Scala file that contains TypedSQL calls, these calls are expanded into type-safe code that accepts parameters for any placeholders in the SQL and returns a tuple based on the column types selected in the query. Here's a short example:

  // assume
  // CREATE TABLE users(
  //    id integer,
  //    best_friend_id integer,
  //    name varchar(256)
  // );

  val q = TypedSQL("select * from users")
  q().list() // returns List[(Int, Int, String)]

  val q2 = TypedSQL("select name from users where id = ?")
  q2(5).single() // returns String

  val q3 = TypedSQL("update users set name = ? where id = 5")
  q3("Tyrone Slothrop").execute()

The anorm-typed module will catch every one of the errors I listed above - before your application can even compile. Note that everything here is type-checked, and that the code simply will not compile if we make a mistake matching Scala types to SQL types, if the SQL has a syntax error, if we use a nonexistent column, or if we provide the wrong number of arguments to the query. Awesome. Of course, there are some drawbacks to this approach:
  • The TypedSQL macro needs to connect to your database during compilation. This can cause a number of issues:
    • CI servers or other automated builds will need to be able to access a database to finish compilation
    • IDE's have no idea what to do with the TypedSQL macro - IntelliJ highlights every call as an error, even though the code compiles fine.
Still, this is pretty close to my holy grail for database interaction. I'm planning to set aside some time to work on an alternative implementation that would suit my needs a little better: instead of a macro, I'm planning to build an SBT plugin for Play apps that would, as with the conf/routes compiler, compile a list of SQL queries into an autogenerated file.

Tuesday, November 15, 2011

I should also say, there's really nothing wrong in just coding the
imperative algorithm in Scala. It's not a sacrilege to use imperative code,
in particular if it's inside a function. Sometimes it's the clearest way to
express things. Many other times it is not.

- Martin Oderksy

Saturday, August 20, 2011

The Implicit Environment Pattern

In general, I'm pretty skeptical of the purported benefits of test-driven development. Nevertheless, there are cases where some unit tests can be extremely helpful. Recently, I wanted to write a simple command-line utility to analyze some sales data for me. The problem was simple and well-contained enough that I thought it would make sense to write a few unit tests.

One of the perennial problems with writing good unit tests is cleanly separating out the objects being tested from their dependencies and collaborators. Most discussions of this topic limit this to separating out references to global variables or singleton objects. They typically do this with dependency injection. Conventional dependency injection is a pretty good solution to this problem, but it's often an extralingual solution, relying on XML files that are kept separate from your source code and which fall outside the purview of the type system. Even if they avoid XML files (Guice comes to mind), they're fairly heavy systems, in that you have to bring in jar's, set up your configuration, and get familiar with the API.

And aside from simply avoiding hardcoded class references, there were some other kinds of dependencies that I wanted to isolate:

  • Environment information, such as where to find configuration files, server addresses and ports, or flags
  • Side effects, including I/O For example, println assumes the presence of a console and offers no way for you to compare what was printed to what you expected to print. Similarly, reading from the console assumes that someone is present to type in commands and provides no way for you to provide mock input.

I eventually hit on a solution I'm calling the Implicit Environment Pattern. It makes heavy use of Scala-specific features, like traits and implicits. Unlike most dependency injection solutions, this is simply a code pattern and requires no external jar's, dependencies or configuration languages.

The key principles of this pattern are:

  • Separate configuration, hardcoded class references and I/O operations into abstract traits
  • Define concrete implementations of these traits for different environments, e.g. production, testing, QA, development
  • Pass these implementations into their dependent classes via implicit parameters to the constructor
  • Dependencies are transitive - the implicit values passed into one class will be transparently passed into any other instances they create, as long as those classes declare their dependencies via implicit parameters

To start with, I'll create a number of traits to declare very fine-grained dependencies:

trait WritesOutput { 
  def println(x: Any): Unit 
}

trait ReadsSalesDirectory { 
  def salesDirectory: File 
}

trait ReadsHistoricalRecords { 
  def historicalRecordsFile: File 
}

trait NeedsConsoleInput { 
  def readLine(completionOptions: Iterable[String] = Nil): String 
}

In this example, I've made the choice to treat the sales directory as a configuration parameter, so I can simply pass in a different directory in different environments. Depending on how much I/O is going on, I could also create a trait with a readFromFiles method that abstracts the I/O completely; in that case, my test implementations could just return an in-memory list from readFiles without touching the filesystem at all. Which of these paths you choose depends on how complicated the I/O is and on whether it's easier to provide test files or just create in-memory data structures. In this case, I have easy access to sample files, I'm pretty confident that basic line-reading code will work and I'm only reading data and not changing anything, so I've made this choice in the interest of pragmatism.

Now let's write a class that makes use of these traits via implicit parameters:

class SalesReportParser(val startingDay: LocalDate)(
     implicit salesDir: ReadsSalesDirectory, writer: WritesOutput) {
  ...
  
  def parseAll(): List[SalesRecord] = {
    val result = withSource(Source.fromFile(salesDir.salesDirectory)) { source => 
      ... 
    }

    writer.println("Parsed %d files.".format(result.count))
    result
  }
}

Clients of the class will pass in its dependencies transparently via implicits. So in my main method, I simply write:

object SalesReport {
  class ProdEnv extends WritesToStdout 
        with ReadsSalesDirectory 
        with ReadsBooksAndRecords 
        with AcceptsInput {
    def println(x: Any) = Predef.println(x)
    val salesDirecotry = new File(...)
    val historicalRecordsFile = new File(...)
    def readLine(completionOptions: Iterable[String]) = {
       ...
    }    
  }

  def main(args: Array[String]) {
    implicit val env: ProdEnv = new ProdEnv

    val parser = new SalesReportParser(new LocalDate)
    parser.parseAll()

    ...
  }
}

(For convenience, one class implements all of the necessary traits. In tests, I might want to create separate implementations for individual dependencies.)

The implicit value env in main is transparently passed into SalesReportParser's constructor. Importantly, if SalesReportParser instantiates any classes that have their own dependencies declared as implicits, they'll be automatically passed in from the SalesReportParser instance.

If I fail to provide any of the parser's dependencies, the bug will be caught at compile time, since implicit resolution will fail when SalesReportParser's constructor is called. This is what I want: it's a beautiful thing when you're able to structure your code such that certain bugs are "inexpressible," i.e. the compiler will reject them outright before they can even become bugs.

So now I've isolated the console output dependency and sales directory path from my sales report parsing logic. Further, each class specifies exactly what dependencies it needs - the SalesReportParser can't read the historical records without explicitly adding ReadsHistoricalRecords as an implicit parameter, so readers of this code can immediately determine how a given class depends on and affects the world around it. In effect, the SalesReportParser class acts like a function in the functional programming sense - since I provide the class with the objects that will accept its input and emit its output, it need not affect the real world unless I provide it dependencies that do so.

But the other benefit is that my unit tests become extremely straightforward:

class TestTheParser extends TestCase {
  class TestEnv extends ReadsSalesDirectory with WritesToStdout {
    var writtenData: List[String] = Nil

    def salesDirectory = new File("test/testSalesData")
    def println(x: Any) = {
      writtenData ::= x
 }
  }

  val testDate = ...

  def testMe = {
    implicit val env = new TestEnv
    val parser = new SalesReportParser(testDate)
    parser.parseAll()

    env.writtenData should_== List("Parsed 10 files.")
  }
}

The Implicit Environment pattern also allows us to create a single TestEnv class to be used throughout all test cases and override its behavior only when necessary. For example, our TestEnv class will by default accumulate output into the writtenData array, but we may want to override this in certain cases:

class MyTest extends TestCase {
  def testMe = {
    implicit val testEnvCatchesPrinting = new TestEnv {
      override def println(x) = fail("should not print to stdout")
    }

    val parser = new SalesReportParser
    parser.parseAll() // any output here will cause the test to fail
  }
}

Another advantage of this architecture - with strict separation of I/O into explicitly specified dependencies - is that it's less likely that test code will accidentally perform operations on production data. By isolating as much I/O as is practical into dependency traits, the only way the the two could intermingle would be by intentionally passing in a production implementation into test code, or vice-versa.

Saturday, July 9, 2011

Prefer recursion to var's and while loops

A while back, when I was first picking up Scala, I needed to prompt the user for a line of text and keep prompting until I got a non-blank line.

Apparently, I threw the following together:

def readCompleteLine(prompt: String) = {
  val reader = new jline.ConsoleReader()
  reader.setDefaultPrompt(prompt)

  var line: String = null

  do {
    line = reader.readLine()
  } while( line != null && line.length == 0 )

  line
}

I came across this function yesterday and involuntarily made a gross-out sound. var's, mutability, a while loop (a do-while loop, no less!) and even the dread null. There had to be a better way.

Using higher-order functions and recursion, I rewrote this to be less imperative, more readable and more general:

def readUntil[X](prompt: String, transform: String => X, pred: X => Boolean): X =  {
  val reader = new jline.ConsoleReader() { setDefaultPrompt(prompt)}

  @tailrec def ruHelper: X = Option(reader.readLine()).map(transform(_)) match {
    case Some(x) if pred(x) => x
    case _ => ruHelper
  }

  ruHelper
}

/* simple, string-only version */
def readUntil(prompt: String, pred: String => Boolean): String =  {
  readUntil(prompt, x => x, pred)
}

Using this as a primitive, it's easy to write a method that repeatedly prompts the user for a string until it's non-empty.

def readUntilNonBlankLine(prompt: String) = readUntil(prompt, _.length > 0)

But it's also easy to create a method that only allows input from a list of accepted strings:

def readOneOf(prompt: String, acceptableValues: List[String]): String = 
    readUntil(prompt, acceptableValues.contains(_))

Or even a function that reads until the value is a properly-formed floating-point number:

import util.control.Exception._

def tryToReadDouble(s: String) = 
  catching(classOf[NumberFormatException]) opt (s.toDouble)

def readUntilValidDouble(prompt: String) = ReadingUtils.readUntil(prompt,
      tryToReadDouble(_), (s: Option[Double]) => s.isDefined).get

Higher-order functions and genericity can really pay off - the base readUntil
is now a nicely abstracted primitive that I can test in isolation and then plug in elsewhere in my program, without having to write and rewrite error-prone imperative code.

Wednesday, June 8, 2011

Migrating to sbt 0.10: sbt-idea-plugin

In pre-0.10 versions of sbt, you could use sbt-idea-plugin to generate IDEA projects from your SBT files. That plugin doesn't work in 0.10, but here's how to make it happen:

Create a new file ~/.sbt/plugins/project/Build.scala and put the following code in it:

import sbt._

object MyPlugins extends Build {
  lazy val root = Project("root", file(".")) 
                    dependsOn (uri("git://github.com/ijuma/sbt-idea.git#sbt-0.10"))
}

Now restart SBT and type gen-idea (this command replaces the old idea). SBT 0.10 includes any code in this directory in all projects, so any other sbt-0.10 project will immediately get this functionality.

The initial project created by idea-gen will have a separate IDEA module for the project folder. I haven't been able to get IDEA to compile anything while this module is there, so I remove the module and then mark the project as excluded in the main module.

Note that if you later make a change to your .sbt file (e.g. adding a new dependency), you need to bring the IDEA project up-to-date. To do this, open the SBT Console in IDEA, run "update" and then run "gen-idea". Your IDEA project will be brought up to date and IDEA will prompt you to reload the project. Choose 'OK' and you're good to go.

(thanks to Graham Tackley for figuring out the proper way to do this)

Update: Updated the path to ~/.sbt/plugins/project/Build.scala, as it's not necessary to configure the IDEA plugin on a per-project basis.

Migrating to sbt 0.10: Lift

The latest release of sbt (version 0.10) is utterly incompatible with build scripts from older versions of SBT. Here's how to migrate a Lift project to SBT 0.10 (these instructions work with 2.4-M1; I believe you can use earlier versions of lift, as long as you downgrade scalaVersion to 2.8.1):

  1. Rename project/ to project-old/
  2. Create a new build.sbt file in the root of your project

    name := "projname"
    
    scalaVersion := "2.9.0"
    
    seq(WebPlugin.webSettings: _*)
    
    libraryDependencies ++= Seq(
      "net.liftweb" %% "lift-webkit" % "2.4-M1" % "compile->default",
      "net.liftweb" %% "lift-mapper" % "2.4-M1" % "compile->default",
      "net.liftweb" %% "lift-wizard" % "2.4-M1" % "compile->default")
    
    
    libraryDependencies ++= Seq(
      "junit" % "junit" % "4.5" % "test->default",
      "org.mortbay.jetty" % "jetty" % "6.1.22" % "jetty",
      "javax.servlet" % "servlet-api" % "2.5" % "provided->default",
      "com.h2database" % "h2" % "1.2.138",
      "ch.qos.logback" % "logback-classic" % "0.9.26" % "compile->default"
    )
  3. mkdir -p project/plugins
  4. Create a new file project/plugins/build.sbt and put the following in it:
    resolvers += "Web plugin repo" at "http://siasia.github.com/maven2"
    
    libraryDependencies <+= sbtVersion("com.github.siasia" %% "xsbt-web-plugin" % _)

Now you're good to go.

Note that the Jetty dependency has changed. If you execute jetty-run and no output appears, make sure you changed the scope for the Jetty dependency from "test" (the correct value in older SBT's) to "jetty".

Also note that the new SBT parser appears to be newline-sensitive; make sure you keep blank lines between each setting, as in the example above.

Wednesday, February 23, 2011

I want to go to there

From the excellent Deprecating the Observer Pattern by Odersky et al:

// step 1:
val path = new Path((self next mouseDown).position) 

// step 2: 
self loopUntil mouseUp {
 val m = self next mouseMove 
 path.lineTo(m.position) 
 draw(path)
}

// step 3:
path.close()
draw(path)

This is a complete implementation of a sketching application using scala-react.