Skip to content

Instantly share code, notes, and snippets.

@szeiger
Created May 20, 2011 21:39
Show Gist options
  • Save szeiger/983883 to your computer and use it in GitHub Desktop.
Save szeiger/983883 to your computer and use it in GitHub Desktop.
Using the new higher-kinded collection magic in ScalaQuery
// A simple table with keys and values
val T = new Table[(Int, String)]("T") {
def k = column[Int]("KEY", O.PrimaryKey)
def v = column[String]("VALUE")
def * = k ~ v
}
// Create the table and insert some data
T.ddl.create
T.insertAll(1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", 5 -> "e")
// Define a QueryTemplate for reading all key/value pairs up to a given key.
val upTo = for {
k <- Parameters[Int]
t <- T if t.k <= k
_ <- Query orderBy t.k
} yield t
// Print a list of k/v pairs up to 3 the way we had to do it in the dark
// ages before higher-kinds and collection builders, by using the special
// .list method whose only purpose is building Lists from query results
println(upTo.list(3))
// And here's the fancy new way with .to
println(upTo.to[List](3))
// It can build any kind of collection for which a CanBuildFrom object is
// defined. Let's try it with a Set, an IndexedSeq (which really builds a
// Vector as IndexedSeq's default implementation) and a mutable ArrayBuffer
println(upTo.to[Set](3))
println(upTo.to[IndexedSeq](3))
println(upTo.to[ArrayBuffer](3))
// Let's read all keys into a real unboxed Array[Int]
val allKeys = T.map(_.k)
println(allKeys.to[Array]())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment