<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>szeiger.de &#187; ScalaQuery</title>
	<atom:link href="http://szeiger.de/blog/category/scala/scala-query/feed/" rel="self" type="application/rss+xml" />
	<link>http://szeiger.de</link>
	<description>Stefan Zeiger's Software Development Weblog</description>
	<lastBuildDate>Tue, 29 Jun 2010 21:33:20 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>New ScalaQuery Features</title>
		<link>http://szeiger.de/blog/2009/12/21/new-scala-query-features/</link>
		<comments>http://szeiger.de/blog/2009/12/21/new-scala-query-features/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 20:15:03 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=41</guid>
		<description><![CDATA[It&#8217;s been almost 3 months since my last summary of new features in ScalaQuery. I implemented some important changes in the following weeks but I only had little time to work on ScalaQuery after my extended one-month vacation ended in October.
Build system
Builds against newer versions of Scala 2.8 have been going well thanks to sbt [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been almost 3 months since my last <a href="http://szeiger.de/blog/2009/09/27/a-scala-query-update/">summary of new features in ScalaQuery</a>. I implemented some important changes in the following weeks but I only had little time to work on ScalaQuery after my extended one-month vacation ended in October.</p>
<h3>Build system</h3>
<p>Builds against newer versions of Scala 2.8 have been going well thanks to <a href="http://code.google.com/p/simple-build-tool/wiki/0_6_Summary">sbt 0.6</a> which separates the Scala version used by the build system from the version used by the project being built. You need to use at least version 0.6.7 of the new xsbt launcher to build ScalaQuery. Other dependencies are downloaded automatically by sbt. I wrote an implementation of sbt&#8217;s test interface for <a href="http://www.junit.org/">JUnit</a> which you can find <a href="http://github.com/szeiger/junit-interface">here</a> (binaries are <a href="http://scala-tools.org/repo-releases/com/novocode/junit-interface/">here</a> on scala-tools.org). It allows you to run ScalaQuery&#8217;s JUnit test cases from sbt with the <code>test</code> command.</p>
<p>All published artifacts now contain the Scala version in the artifact ID. You can find the latest ScalaQuery snapshot in scala-tools.org&#8217;s <a href="http://scala-tools.org/repo-snapshots/">snapshots repository</a> as:</p>
<dl>
<dt>groupId:</dt>
<dd>com.novocode</dd>
<dt>artifactId:</dt>
<dd>scala-query_2.8.0.Beta1-RC4</dd>
<dt>version:</dt>
<dd>1.0.0-SNAPSHOT</dd>
<dl>
<h3>JDBC escape syntax</h3>
<p>ScalaQuery now uses <a href="http://java.sun.com/javase/6/docs/technotes/guides/jdbc/getstart/statement.html#1006519">JDBC escape syntax</a> and scalar functions where possible for better portability between DB engines:</p>
<ul>
<li>String column concatenation (with the <code>++</code> operator) and the <code>startsWith</code> and <code>endsWith</code> methods on String columns have been moved up to <code>BasicProfile</code>.</li>
<li>Escape characters for LIKE expressions are added to the queries.</li>
<li>You can add other functions to be called with the <code>{fn ...}</code> syntax through <code>SimpleScalarFunction()</code> and <code>SimpleScalarFunction.nullary()</code>.</li>
<li>Various scalar functions are supported: <code>CONVERT</code>, <code>USER</code>, <code>DATABASE</code>, <code>CURDATE</code>, <code>CURTIME</code>, <code>PI</code>, <code>MOD</code>, <code>ABS</code>, <code>CEILING</code>, <code>FLOOR</code>, <code>SIGN</code>, <code>DEGREES</code>, <code>RADIANS</code>, <code>IFNULL</code>, <code>UCASE</code>, <code>LCASE</code>, <code>LTRIM</code>, <code>RTRIM</code>.</li>
<li>Literals for <code>Date</code>, <code>Time</code> and <code>Timestamp</code> values use the JDBC escape syntax.</li>
<li>Explicit inner, left outer, right outer and full outer joins are supported. For example:</li>
</ul>
<div class="wp_syntax">
<div class="code">
<pre>  val q = for {
    Join(c,p) &lt;- Categories innerJoin Posts on (_.id is _.category)
    _ &lt;- Query orderBy p.id
  } yield p.id ~ c.id ~ c.name ~ p.title
</pre>
</div>
</div>
<h3>Complex inserts</h3>
<p>Queries and columns can now be inserted into tables (using SQL&#8217;s <code>INSERT...SELECT</code> syntax). This allows you to use scalar functions when inserting individual records and to copy data produced by a query. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre>  val q2 = for(s &lt;- Src1 if s.id &lt;= 2) yield s
  Dst2.insert(q2)
</pre>
</div>
</div>
<h3>Various changes</h3>
<ul>
<li>String columns are created as VARCHAR(254) by default (except in H2 where no size is needed).</li>
<li>The operators <code>===</code> and <code>!=</code> can be used instead of is and isNot. They have the proper precedence when used with other operators like <code>&#038;&</code> and <code>||</code>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/12/21/new-scala-query-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A ScalaQuery Update</title>
		<link>http://szeiger.de/blog/2009/09/27/a-scala-query-update/</link>
		<comments>http://szeiger.de/blog/2009/09/27/a-scala-query-update/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 00:03:30 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=35</guid>
		<description><![CDATA[Since my last post about ScalaQuery one month ago I have wasted quite some time trying to implement the OptionMapper type (which is used to make operations on columns interoperable between base types and Option types) in a way which does not require 2^n implicit functions and 2*n+2 type parameters for operations with n operands. [...]]]></description>
			<content:encoded><![CDATA[<p>Since my <a href="http://szeiger.de/blog/2009/08/27/profiles-drivers-and-more/">last post</a> about <a href="http://github.com/szeiger/scala-query">ScalaQuery</a> one month ago I have wasted quite some time trying to implement the <code>OptionMapper</code> type (which is used to make operations on columns interoperable between base types and <code>Option</code> types) in a way which does not require 2^n implicit functions and 2*n+2 type parameters for operations with n operands. The composable <code>OptionMapper</code> itself is not hard to write (see <code>NewOptionMapper</code> <a href="http://github.com/szeiger/scala-query/blob/new-option-mapper/src/main/scala/com/novocode/squery/combinator/TypeMapper.scala">here</a>) but it requires more type fidelity than ScalaQuery offers at the moment: Either <code>Projection</code>s need to preserve the subtypes of <code>Column</code>s they are storing, or the required types have to be reconstructed from implicit values where they are needed. You can find my failed attempts in the <a href="http://github.com/szeiger/scala-query/tree/projection-types">projection-types</a> and <a href="http://github.com/szeiger/scala-query/tree/new-option-mapper">new-option-mapper</a> branches. The first one might actually work once <a href="https://lampsvn.epfl.ch/trac/scala/ticket/2346">Scala bug #2346</a> is resolved. The second one would require a much more powerful type inferencer. For now, I just added an <code>OptionMapper3</code> for 3 parameters (which is needed by the <code>BETWEEN</code> operator).</p>
<p>There are also some interesting new features in ScalaQuery:</p>
<h3>Mapped Projections</h3>
<p>You can now create a bidirectional mapping of a <code>Projection</code> with the &lt;> operator. This is especially useful for a table&#8217;s &#8220;*&#8221; projection. The &lt;> operator takes a function from the projection tuple type <em>T</em> (either as a tuple or as multiple parameters) to the mapped type <em>R</em>, and a function from <em>R</em> back to <em>Some[T]</em>. The asymmetry with the unnecessary <em>Some</em> wrapper is deliberate, matching exactly the <code>apply</code> und <code>unapply</code> methods of a <em>case class</em>. For example, here is a simple <em>User</em> class and table:</p>
<div class="wp_syntax">
<div class="code">
<pre>  case class User(first: String, last: String)

  object Users extends Table[<b>User</b>]("users") {
    def first = column[String]("first", O NotNull)
    def last = column[String]("last", O NotNull)
    def * = first ~ last <b>&lt;> (User, User.unapply _)</b>
  }
</pre>
</div>
</div>
<p>Whenever you perform an insert, update or query directly on such a table (instead of a projection of individual columns), you can use the mapped type:</p>
<div class="wp_syntax">
<div class="code">
<pre>  Users.insert(User("Stefan", "Zeiger"))
  val someUsers: List[User] = Users.where(_.first startsWith "S").list
</pre>
</div>
</div>
<h3>Finders</h3>
<p>The new convenience method <code>Table.createFinderBy</code> allows you to create a simple <em>finder</em> query template which selects values from a table by matching on a single column, e.g.:</p>
<div class="wp_syntax">
<div class="code">
<pre>  val findUserByFirstName = Users.createFinderBy(_.first)
</pre>
</div>
</div>
<p>This is equivalent to:</p>
<div class="wp_syntax">
<div class="code">
<pre>  val findUserByFirstName = for {
    first <- Parameters[String]
    u <- Users if u.first is first
  } yield u
</pre>
</div>
</div>
<h3>Updatable ResultSets</h3>
<p>JDBC allows you to modify a <code>ResultSet</code> which was created with the <code>CONCUR_UPDATABLE</code> result set concurrency. ScalaQuery now offers a high-level interface to this functionality with the <code>mutate</code> method, e.g.:</p>
<div class="wp_syntax">
<div class="code">
<pre>  val q1 = for(u <- Users if u.last.is("Simpson") || u.last.is("Bouvier")) yield u
  q1.mutate { m =>
    if(m()._3 == "Bouvier") m() = m().copy(_3 = "Simpson")
    else if(m()._2 == "Homer") m.delete()
    else if(m()._2 == "Bart") m.insert((None, "Lisa", "Simpson"))
  }
</pre>
</div>
</div>
<h3>Statement Options</h3>
<p>The new <code>ResultSetType</code>, <code>ResultSetConcurrency</code> and <code>ResultSetHoldability</code> classes allow you to request the corresponding JDBC options when ScalaQuery creates a <code>PreparedStatement</code>, e.g.:</p>
<div class="wp_syntax">
<div class="code">
<pre>  myDB withSession {
    ResultSetType.ScrollInsensitive {
      <em>// All database calls in this block use TYPE_SCROLL_INSENSITIVE</em>
    }
  }
</pre>
</div>
</div>
<p>Or if you don't want to use the implicit <code>threadLocalSession</code>:</p>
<div class="wp_syntax">
<div class="code">
<pre>  myDB withSession { s1 =>
    ResultSetType.ScrollInsensitive(s1) { s2 =>
      <em>// All database calls on s2 use TYPE_SCROLL_INSENSITIVE</em>
    }
  }
</pre>
</div>
</div>
<p>The default for all three options is <code>Auto</code> which gives you values suitable for the invoker method you are calling (e.g. <code>ResultSetConcurrency.Updatable</code> for <code>mutate</code> and <code>ResultSetConcurrency.ReadOnly</code> for all other methods).</p>
<h3>Build System</h3>
<p>I have rewritten most of the test classes as proper unit tests (using <a href="http://junit.org/">JUnit</a> 4) with assertions. I'd like to investigate <a href="http://www.artima.com/scalatest/">ScalaTest</a> and <a href="http://code.google.com/p/specs/">specs</a> further (possibly together with <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a>) in the future to replace JUnit but the binary incompatibilities between different <a href="http://www.scala-lang.org/node/212/">Scala 2.8 snapshot builds</a> would only complicate the build process right now. If you build with <a href="http://code.google.com/p/simple-build-tool/">sbt</a>, you still need to download a suitable Scala 2.8 snapshot yourself and set the paths in the properties because the build is done in forking mode. This also means that you cannot use the "test" command to run the unit tests from sbt at the moment.</p>
<p><a href="http://www.h2database.com/">H2</a> and JUnit are declared as test dependencies in the sbt project definition and the Eclipse build path refers to the local copies in <em>lib_managed</em>. If you want to build ScalaQuery with Eclipse (as I usually do), just run "<code>sbt update</code>" once to pull in the required JARs.</p>
<p>I am using <a href="http://freemarker.org/">FreeMarker</a> templates and the <a href="http://fmpp.sourceforge.net/">FMPP</a> tool to create repetitive code for the <code>Projection</code> and <code>Parameters</code> classes. This is not yet integrated into the sbt build process. You can use the supplied Eclipse launcher instead (after downloading FMPP and pointing the launcher to the correct path). The generated sources are checked in, so you only need to do this if you want to change the templates and rebuild the Scala sources.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/09/27/a-scala-query-update/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Profiles, Drivers &amp; More</title>
		<link>http://szeiger.de/blog/2009/08/27/profiles-drivers-and-more/</link>
		<comments>http://szeiger.de/blog/2009/08/27/profiles-drivers-and-more/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 15:07:47 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=34</guid>
		<description><![CDATA[It&#8217;s been three weeks already since my last post about ScalaQuery so I&#8217;d like to provide an update on some recent changes.
Profiles &#038; Drivers
The biggest news is that ScalaQuery now supports database engine-specific features. Feature sets can be bundled in profiles which are then implemented by drivers (Of course, a driver can also add driver-specific [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been three weeks already since my <a href="http://szeiger.de/blog/2009/08/06/efficient-parameterized-queries-in-scala-query/">last</a> post about <a href="http://github.com/szeiger/scala-query/tree/master">ScalaQuery</a> so I&#8217;d like to provide an update on some recent changes.</p>
<h3>Profiles &#038; Drivers</h3>
<p>The biggest news is that ScalaQuery now supports database engine-specific features. Feature sets can be bundled in <em>profiles</em> which are then implemented by <em>drivers</em> (Of course, a driver can also add driver-specific features which are not part of a profile). All previously existing features are now part of the <code>BasicProfile</code> which should work on all SQL databases with little or no customization. The <code>BasicProfile</code> provides:</p>
<ul>
<li>An object called <code>Implicit</code> with all implicit conversions which are required to use the profile&#8217;s features (including an implicit value of type <code>BasicProfile</code> which points to the driver implementing the profile).</li>
<li>Some methods for creating various statements and query templates. They have default implementations provided by the profile but can be overridden by other profiles or drivers. You do not usually call them directly.</li>
<li>A number of <code>TypeMapperDelegate</code> objects for the basic types supported by the profile. You still use <code>TypeMapper</code>s defined outside the profile but they do not implement the actual type mapping any more. Instead they ask the profile for a delegate implementation. (Alternatively, I could have moved the existing <code>TypeMapper</code> objects entirely into the profile but mappers for some basic types like <code>Int</code> and <code>Boolean</code> are used internally at many places. They would need to be threaded through several methods and constructors, thus complicating the implementation unnecessarily.)</li>
</ul>
<p>The <code>BasicProfile</code> is implemented by the <code>BasicDriver</code>.</p>
<p>There is also a new <code>ExtendedProfile</code> for features which are expected to be available in every commonly used SQL database system, albeit with a non-standard syntax. It currently provides string concatenation with the <code>++</code> operator (plus <code>startsWith</code> and <code>endsWith</code> methods which can be implemented with <code>LIKE</code> and string concatenation) and the <code>take</code> and <code>drop</code> methods needed for pagination.</p>
<p>If you only need to support a single database engine in your application, you can forget about profiles and just import a specific driver&#8217;s implicit conversions. Supporting multiple drivers is almost as simple: Give your DAO class (or whatever you have in your application design) a parameter of the required profile type and import this profile&#8217;s implicits. You can then call it with any driver which implements the profile. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre>  def test(profile: ExtendedProfile) {
    import profile.Implicit._
    println("Using driver: "+profile.getClass.getName)
    val q1 = Users.where(_.name startsWith "quote ' and backslash \\").take(5)
    println(q1.selectStatement)
    val q2 = Users.where(_.name startsWith "St".bind).drop(10).take(5)
    println(q2.selectStatement)
    val q3 = Query(42 ~ "foo")
    println(q3.selectStatement)
    println
  }

  def main(args: Array[String]) {
    test(H2Driver)
    test(OracleDriver)
    test(MySQLDriver)
  }
</pre>
</div>
</div>
<p>This prints the different statements required for <a href="http://www.h2database.com/">H2</a>, <a href="http://www.oracle.com/database/index.html">Oracle</a> and <a href="http://www.mysql.com/">MySQL</a>:</p>
<div class="wp_syntax">
<div class="code">
<pre>Using driver: com.novocode.squery.combinator.extended.H2Driver$
SELECT t1.name FROM users t1 WHERE (t1.name like 'quote '' and backslash \%') LIMIT 5
SELECT t1.name FROM users t1 WHERE (t1.name like (? || '%')) LIMIT 5 OFFSET 10
SELECT 42,'foo'

Using driver: com.novocode.squery.combinator.extended.OracleDriver$
SELECT * FROM (SELECT t1.name FROM users t1 WHERE (t1.name like 'quote '' and backslash \%')) WHERE ROWNUM &lt;= 5
SELECT * FROM (SELECT t0.*, ROWNUM ROWNUM_O FROM (t1.name,ROWNUM ROWNUM_I FROM users t1 WHERE (t1.name like (? || '%'))) t0) WHERE ROWNUM_O BETWEEN (1+10) AND (10+5) ORDER BY ROWNUM_I
SELECT 42,'foo' FROM DUAL

Using driver: com.novocode.squery.combinator.extended.MySQLDriver$
SELECT t1.name FROM users t1 WHERE (t1.name like 'quote \' and backslash \\%') LIMIT 5
SELECT t1.name FROM users t1 WHERE (t1.name like concat(?,'%')) LIMIT 10,5
SELECT 42,'foo' FROM DUAL
</pre>
</div>
</div>
<h3>Updates</h3>
<p>You can now take a simple query (returning only named columns from a single table; no modifiers except <code>WHERE</code> restrictions) and call it as an <code>UPDATE</code> statement:</p>
<div class="wp_syntax">
<div class="code">
<pre>  val q = for(u &lt;- Users if u.id is 42) yield u.first ~ u.last
  q.update("foo", "bar")
</pre>
</div>
</div>
<h3>Filtering</h3>
<p>You may already have noticed in my previous post that the <code>Query</code> class now has a <code>filter</code> method which works like <code>where</code> for functions returning a <code>Column[Boolean]</code> or <code>Column[Option[Boolean]]</code>, so you can use Scala&#8217;s standard <em>if</em> clauses in for-comprehensions on queries. Unlike <code>where</code>, <code>filter</code> also accepts functions returning a plain <code>Boolean</code> value to enable the use of refutable patterns in queries (e.g. when destructuring a <code>Join</code>).</p>
<h3>Invokers</h3>
<p>Result type remapping and parameter application are now available for all <code>Invoker</code>s. These features were pushed down from the statement invokers for monadic queries into the invoker framework. Query templates are parameterized invokers now. They can be applied like any other invoker.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/08/27/profiles-drivers-and-more/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Efficient Parameterized Queries in ScalaQuery</title>
		<link>http://szeiger.de/blog/2009/08/06/efficient-parameterized-queries-in-scala-query/</link>
		<comments>http://szeiger.de/blog/2009/08/06/efficient-parameterized-queries-in-scala-query/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 17:22:04 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=32</guid>
		<description><![CDATA[One question about ScalaQuery which keeps coming up is that of perfomance. The question is usually in the form &#8220;How does it compare to JDBC?&#8221; but that&#8217;s like comparing apples and, well, apple trees. After all, ScalaQuery is a layer on top of JDBC which provides mainly two things:

A nicer, more Scala-like way of handling [...]]]></description>
			<content:encoded><![CDATA[<p>One question about <a href="http://github.com/szeiger/scala-query/tree/master">ScalaQuery</a> which keeps coming up is that of perfomance. The question is usually in the form &#8220;How does it compare to <a href="http://java.sun.com/javase/technologies/database/">JDBC</a>?&#8221; but that&#8217;s like comparing apples and, well, apple trees. After all, ScalaQuery is a layer on top of JDBC which provides mainly two things:</p>
<ul>
<li>A nicer, more Scala-like way of handling database connections, performing queries and reading result sets. This is not optional when you access a database in your application. You will wrap SQL statement execution and result set reading in some way or another to abstract from the low-level JDBC API. Anyway, the overhead here is quite low.</li>
<li>A way of composing queries with an internal DSL based on a query monad and combinators. That&#8217;s the part I want to talk about in this post.</li>
</ul>
<p>If you want to optimize the query generation away, you can always fall back to the <code>StaticQuery</code> and <code>DynamicQuery</code> classes. These work a bit like <a href="http://ibatis.apache.org/">iBATIS</a>, except your SQL code is embedded directly in your Scala code and not in some XML files. But you&#8217;re still writing SQL! That&#8217;s nice for the special cases which are not covered by the combinator queries and which do not need to be composable but it&#8217;s probably not the reason why you want to use ScalaQuery in the first place.</p>
<p>When you&#8217;re constructing a query in the query monad, you normally have some variables which are used in the query like this:</p>
<div class="wp_syntax">
<div class="code">
<pre>def userNameByID(id: Int) =
  for(u &lt;- Users if u.id is id) yield u.first
</pre>
</div>
</div>
<p>This would insert the user ID directly into the SQL statement, thus requiring a new statement to be generated by ScalaQuery and parsed and optimized by the database server (which can be very expensive) for every invocation of the query. We can improve this by using a <em>bind variable</em> for the user ID:</p>
<div class="wp_syntax">
<div class="code">
<pre>def userNameByID(id: Int) =
  for(u &lt;- Users if u.id is id.bind) yield u.first
</pre>
</div>
</div>
<p>Now the generated SQL statement is always the same (e.g. &#8220;<code>SELECT t1.first FROM users t1 WHERE (t1.id=?)</code>&#8220;), so the database server needs to calculate an execution plan for it only once and can reuse it on subsequent invocations. But the query is still constructed as a tree of dozens of objects and compiled to the same SQL statement every time you call <code>userNameByID</code>.</p>
<p>This can be remedied with <em>query templates</em>, a recent addition to ScalaQuery:</p>
<div class="wp_syntax">
<div class="code">
<pre>val userNameByID = for {
  id &lt;- Parameters[Int]
  u &lt;- Users if u.id is id
} yield u.first
</pre>
</div>
</div>
<p>If you recall how for-comprehensions are desugared, this gets translated to <code>Parameters[Int].apply(...).flatMap(id => ...)</code>. The <code>apply</code> method on the <code>Parameters</code> object takes an implicit <code>TypeMapper</code> for each parameter type you specify and creates a <code>Parameters</code> instance. The <code>flatMap</code> method on <code>Parameters</code> takes a function which creates a <code>Query</code> and returns a <code>QueryTemplate</code> for it:</p>
<div class="wp_syntax">
<div class="code">
<pre>final class QueryTemplate[P, R](query: Query[ColumnBase[R]]) {
  def apply(param: P) = new AppliedQueryTemplate(built, param, query.value)
  lazy val built = QueryBuilder.buildSelect(query, NamingContext())
}

final class Parameters[P, C](c: C) {
  def flatMap[F](f: C => Query[ColumnBase[F]]): QueryTemplate[P, F] =
    new QueryTemplate[P, F](f(c))
  ...
}

object Parameters {
  def apply[P1](implicit tm1: TypeMapper[P1]) =
    new Parameters[P1, Column[P1]](new ParameterColumn(-1, tm1))
  ...
}
</pre>
</div>
</div>
<p>Note that, unlike <code>Query</code>, neither <code>Parameters</code> nor <code>QueryTemplate</code> is a monad. You cannot compose multiple parameter lists or query templates this way but by providing a suitable <code>flatMap</code> method, the parameters can be used as the first generator in a for-comprehension which otherwise operates in the <code>Query</code> monad.</p>
<p>Either one of the <code>userNameByID</code> functions/methods defined above can be used in the same way:</p>
<div class="wp_syntax">
<div class="code">
<pre>for(t &lt;- userNameByID(3)) println(t)
</pre>
</div>
</div>
<p>When you apply the parameters to a <code>QueryTemplate</code>, you get an <code>AppliedQueryTemplate</code> which can be lifted to a suitable <code>Invoker</code> by an implicit conversion (just like a <code>Query</code>). The first time you do this, the SQL code gets generated and then cached in the <code>QueryTemplate</code> for further applications.</p>
<p>If you specify more than one type parameter, the <code>Parameters</code> generator gives you a <code>Projection</code> instead of a single <code>Column</code>. It can be unpacked either with the extractor on the &#8220;<code>~</code>&#8221; object:</p>
<div class="wp_syntax">
<div class="code">
<pre>val userNameByIDRangeAndProduct = for {
  min ~ max ~ product &lt;- Parameters[Int, Int, String]
  u &lt;- Users if u.id >= min &#038;&#038;
    u.id &lt;= max &#038;&#038;
    Orders.where(o => (u.id is o.userID) &#038;&#038; (o.product is product)).exists
} yield u.first
</pre>
</div>
</div>
<p>&#8230;or with the <code>Projection</code> extractor (which is slightly more efficient but not as nice to read):</p>
<div class="wp_syntax">
<div class="code">
<pre>val userNameByIDRangeAndProduct = for {
  Projection(min, max, product) &lt;- Parameters[Int, Int, String]
  u &lt;- Users if u.id >= min &#038;&#038;
    u.id &lt;= max &#038;&#038;
    Orders.where(o => (u.id is o.userID) &#038;&#038; (o.product is product)).exists
} yield u.first
</pre>
</div>
</div>
<p>ScalaQuery&#8217;s invoker framework provides methods for invoking queries with parameters but these are currently used by the simple queries only. I expect to integrate query templates with this system in the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/08/06/efficient-parameterized-queries-in-scala-query/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ScalaQuery for different Scala versions</title>
		<link>http://szeiger.de/blog/2009/07/22/scala-query-for-different-scala-versions/</link>
		<comments>http://szeiger.de/blog/2009/07/22/scala-query-for-different-scala-versions/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 20:12:11 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=31</guid>
		<description><![CDATA[I have just created a new scala-2.7 branch for ScalaQuery. My original plan was to target only Scala 2.8 but since I&#8217;ve made lots of progress during the last few weeks and I&#8217;ve seen increased interest in ScalaQuery, I tried to build it with 2.7.5.
I had to change the semantics of SimpleFunction and SimpleBinaryOperator for [...]]]></description>
			<content:encoded><![CDATA[<p>I have just created a new <a href="http://github.com/szeiger/scala-query/tree/scala-2.7">scala-2.7</a> branch for <a href="http://github.com/szeiger/scala-query/tree/master">ScalaQuery</a>. My original plan was to target only Scala 2.8 but since I&#8217;ve made lots of progress during the last few weeks and I&#8217;ve seen increased interest in ScalaQuery, I tried to build it with 2.7.5.</p>
<p>I had to change the semantics of <code>SimpleFunction</code> and <code>SimpleBinaryOperator</code> for 2.7 but I prefer the new version anyway, so it went into the main line. The code on the scala-2.7 branch is currently identical to the master branch, except for the test classes which are different in two regards:</p>
<ul>
<li>Although the Scala Language Specification mandates that the part left to the &#8220;<code>&lt;-</code>&#8221; in a for comprehension is a pattern, the wildcard pattern &#8220;<code>_</code>&#8221; does not work in 2.7. I have changed it to a dummy variable named &#8220;<code>__</code>&#8220;.</li>
<li>The type inferencer in 2.7 cannot infer the correct type for the implicit <code>OptionMapper</code> objects. <code>OptionMapper[_,_,_,_]</code> has four type parameters, the last one being used for the return type of functions which use the mapper, so it is not yet known when looking for an implicit mapper and gets inferred as <code>Nothing</code>. Scala 2.8 apparently knows that this type parameter is undetermined, finds the single matching implicit object for the other three parameters and then fills in the fourth. The type-correct interoperability of option and non-option types in ScalaQuery relies heavily on the improved type inferencer and I don&#8217;t see any way of making it work nicely with 2.7. The work-around is to add type annotations to the boolean operators, e.g. <code>a &#038;&#038; b</code> might become <code>a.&#038;&[Boolean,Option[Boolean]](b)</code>. Yuck!</li>
</ul>
<p>I&#8217;m still focused on Scala 2.8 as a target platform and will probably not spend much time integrating new features into the scala-2.7 branch but contributions are always welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/07/22/scala-query-for-different-scala-versions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implicits on Implicits</title>
		<link>http://szeiger.de/blog/2009/07/17/implicits-on-implicits/</link>
		<comments>http://szeiger.de/blog/2009/07/17/implicits-on-implicits/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 22:51:55 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=30</guid>
		<description><![CDATA[I have recently made a change to ScalaQuery which enables the use of any type for a column without needing specific Column classes and factory methods on Table for it. For this I used an approach which I had not considered earlier and which I wasn&#8217;t even sure would work.
Scala (at least in version 2.7) [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently made a change to <a href="http://github.com/szeiger/scala-query/tree/master">ScalaQuery</a> which enables the use of <em>any</em> type for a column without needing specific <code>Column</code> classes and factory methods on <code>Table</code> for it. For this I used an approach which I had not considered earlier and which I wasn&#8217;t even sure would work.</p>
<p>Scala (at least in version 2.7) only considers single function calls for implicit conversions. Take the following definitions for example:</p>
<div class="wp_syntax">
<div class="code">
<pre>class A
class B(a: A)
class C(b: B)

implicit def aToB(a: A) = new B(a)
implicit def bToC(b: B) = new C(b)

val a = new A

def useB(b: B) = ...
def useC(c: C) = ...
</pre>
</div>
</div>
<p>You can call useB(a) because the compiler finds the implicit conversion aToB(a) but you cannot call useC(a) &#8212; the compiler does not try the chained call bToC(aToB(c)).</p>
<p>But this does not mean that an implicit conversion may not rely on an implicit value! The following works just fine:</p>
<div class="wp_syntax">
<div class="code">
<pre>trait Column[T]
class ConstColumn[T](value: T, tm: TypeMapper[T]) extends Column[T]

implicit def valueToColumn[T](value: T)(implicit tm: TypeMapper[T]) =
  new ConstColumn(value, tm)

trait TypeMapper[T]
implicit object IntTypeMapper extends TypeMapper[Int]

val c1: Column[_] = 42
</pre>
</div>
</div>
<p>The Scala compiler recognizes that <code>valueToColumn[Int]</code> provides the desired conversion from <code>Int</code> to <code>Column[_]</code> and then looks for the required implicit <code>TypeMapper[Int]</code> value, which is available through the <code>implicit IntTypeMapper</code> object.</p>
<p>In ScalaQuery, the real <code>TypeMapper</code> contains only a few methods and there are predefined TypeMappers for most of the basic types used by JDBC. That&#8217;s nice because it removes some redundancy from my code base but the better news is that it allows you to write your own TypeMappers. For example, if you wanted to get the <code>java.lang.Integer</code> columns back which I <a href="http://szeiger.de/blog/2009/06/20/dealing-with-nulls-in-scalaquery/">removed</a> in favor of <code>Int</code> and <code>Option[Int]</code>, you could add this implicit object to your code:</p>
<div class="wp_syntax">
<div class="code">
<pre>implicit object IntegerTypeMapper extends TypeMapper[java.lang.Integer] {
  def zero = null
  def sqlType = java.sql.Types.INTEGER
  def setValue(v: java.lang.Integer, p: PositionedParameters) =
    if(v eq null) p.setIntOption(None) else p.setIntOption(Some(v.intValue))
  def setOption(v: Option[java.lang.Integer], p: PositionedParameters) = v match {
    case Some(null) => p.setIntOption(None)
    case Some(i) => p.setIntOption(Some(i.intValue))
    case None => p.setIntOption(None)
  }
  def nextValue(r: PositionedResult) = r.nextIntOption match {
    case None => null
    case Some(i) => java.lang.Integer.valueOf(i)
  }
}
</pre>
</div>
</div>
<p>The same should work for any database engine- or domain-specific types.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/07/17/implicits-on-implicits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dealing with NULLs in ScalaQuery</title>
		<link>http://szeiger.de/blog/2009/06/20/dealing-with-nulls-in-scalaquery/</link>
		<comments>http://szeiger.de/blog/2009/06/20/dealing-with-nulls-in-scalaquery/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 14:56:42 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[NULL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=27</guid>
		<description><![CDATA[Previously, ScalaQuery used nullable Java types for all columns. This is straight-forward for reference types like java.lang.String which are mapped 1:1 to Scala types but not for Scala&#8217;s value types like scala.Int or scala.Boolean. Although they are often implemented in terms of Java types like java.lang.Integer and java.lang.Boolean, there is no 1:1 mapping and there [...]]]></description>
			<content:encoded><![CDATA[<p>Previously, <a href="http://github.com/szeiger/scala-query/tree">ScalaQuery</a> used nullable Java types for all columns. This is straight-forward for reference types like <code>java.lang.String</code> which are mapped 1:1 to Scala types but not for Scala&#8217;s value types like <code>scala.Int</code> or <code>scala.Boolean</code>. Although they are often implemented in terms of Java types like <code>java.lang.Integer</code> and <code>java.lang.Boolean</code>, there is no 1:1 mapping and there are no aliases for those wrapper types in Scala. Most of the time this is not a problem because you can use Scala&#8217;s value types everywhere and have the compiler generate optimized code with primitive types where applicable.</p>
<p>Except there is one thing you cannot do with Scala&#8217;s value types: They may never be <code>null</code>. The reference types are nullable but that&#8217;s probably <a href="http://lambda-the-ultimate.org/node/3186">not a good idea</a>, either. Scala needs nullable reference types for interfacing with Java code but for native Scala APIs, the Option type is the preferred solution. It makes <code>None</code> values explicit and thus prevents <code>NullPointerException</code>s at runtime when a <code>null</code> value is used in a place where it shouldn&#8217;t be allowed.</p>
<p>SQL databases also use <code>NULL</code> values for various things (e.g. missing values, undefined values, <a href="http://stackoverflow.com/questions/203493/why-does-oracle-9i-treat-an-empty-string-as-null">horrid abominations</a>) so this should work nicely with Scala&#8217;s <code>Option</code> type. I rejected <code>Option</code>s for database results in ScalaQuery at first because most columns are not nullable (so you wouldn&#8217;t want to have <em>all</em> columns return an </code>Option</code> instead of just the nullable ones) yet some operations like <em>outer joins</em> need to convert non-nullable columns to nullable ones (which can probably not be typed in Scala's type system, so you'd have to make all columns return an <code>Option</code>).</p>
<p>On the other hand, having nullable <code>java.lang.Integer</code> and other Java wrapper types in a Scala API is rather ugly, so I finally removed them in favor of a more practical yet null-free solution. All columns now use proper Scala types (<code>scala.Int</code>, <code>scala.Predef.String</code>, etc.). <code>NULL</code>s from the database are returned as a default value (0 for <code>Int</code>, an empty string for <code>String</code>) which can be changed with the <code>orElse</code> method, e.g.:</p>
<div class="wp_syntax">
<div class="code">
<pre>  for(u &lt;- Users)
    yield u.first.orElse("no first name")
        ~ u.last.orElse("no last name")
</pre>
</div>
</div>
<p>Note that this value is only used when extracting rows from the result set on the client side. It does not change the handling of <code>NULL</code>s inside the database server!</p>
<p>For nullable types like <code>scala.Predef.String</code> you can use <code>orElse(null)</code> to get the old behaviour back. The argument of <code>orElse()</code> is passed by name, so you can also run an arbitrary block of code or throw an exception when a <code>NULL</code> value is encountered in the result set. There is a convencience method called <code>orFail</code> which does just that. Maybe this should be the default instead of returning a zero value?</p>
<p>The preferred solution for distinguishing between regular values and <code>NULL</code> for any type is to use the <code>?</code> method to turn a <code>SimpleColumn</code> of type <code>T</code> into one of type <code>Option[T]</code>:</p>
<div class="wp_syntax">
<div class="code">
<pre>  for(u &lt;- Users) yield u.first.? ~ u.last.?
</pre>
</div>
</div>
<p>Currently there are no operations defined on option columns so it does not make sense to declare an option column directly as part of a table. Ideally, columns of types <code>T</code> and <code>Option[T]</code> should be fully interoperable because the database server uses three-valued logic anyway.</p>
<p>I have just pushed the new code to the <a href="http://github.com/szeiger/scala-query/tree/master">master</a> branch and updated the <a href="http://github.com/szeiger/scala-query/tree/stable">stable</a> branch to include the previously redesigned AST.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/06/20/dealing-with-nulls-in-scalaquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Public GIT repo for ScalaQuery</title>
		<link>http://szeiger.de/blog/2009/02/21/public-git-repo-for-scalaquery/</link>
		<comments>http://szeiger.de/blog/2009/02/21/public-git-repo-for-scalaquery/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 13:27:55 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[relational]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=25</guid>
		<description><![CDATA[The type-safe database query library/DSL for Scala which I introduced in this post is now available in a public GIT repository at GitHub: http://github.com/szeiger/scala-query/tree
I have renamed it to ScalaQuery because SQuery and all other short names I could think of were already used by numerous other projects.
There are several changes compared to the version I [...]]]></description>
			<content:encoded><![CDATA[<p>The type-safe database query library/DSL for Scala which I introduced in <a href="http://szeiger.de/blog/2008/12/21/a-type-safe-database-query-dsl-for-scala/">this post</a> is now available in a public GIT repository at GitHub: <a href="http://github.com/szeiger/scala-query/tree">http://github.com/szeiger/scala-query/tree</a></p>
<p>I have renamed it to <em>ScalaQuery</em> because SQuery and all other short names I could think of were already used by numerous other projects.</p>
<p>There are several changes compared to the version I used in the introduction:</p>
<ul>
<li>The combinator/monad-based query classes are now in their own package <code>com.novocode.squery.combinator</code>.</li>
<li>The <em>invokers</em> (which execute a typed query through JDBC) of the combinator queries and the simple SQL queries (in <code>com.novocode.squery.simple</code>) have been unified.</li>
<li>Some minor renaming and refactoring.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2009/02/21/public-git-repo-for-scalaquery/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Type-Safe Database Query DSL for Scala</title>
		<link>http://szeiger.de/blog/2008/12/21/a-type-safe-database-query-dsl-for-scala/</link>
		<comments>http://szeiger.de/blog/2008/12/21/a-type-safe-database-query-dsl-for-scala/#comments</comments>
		<pubDate>Sun, 21 Dec 2008 15:13:39 +0000</pubDate>
		<dc:creator>Stefan Zeiger</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[ScalaQuery]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[relational]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://szeiger.de/?p=24</guid>
		<description><![CDATA[When the topic of JDBC wrappers came up on the Scala mailing list a few weeks ago, I mentioned that&#8230;
I&#8217;d prefer a type-safe DSL for database queries but that&#8217;s more
complicated. I&#8217;m still experimenting with that, too  
I think those experiments worked rather well and the code is now in a state where the major [...]]]></description>
			<content:encoded><![CDATA[<p>When the topic of JDBC wrappers came up on the Scala mailing list a few weeks ago, I <a href="http://article.gmane.org/gmane.comp.lang.scala/13655">mentioned</a> that&#8230;</p>
<blockquote><p>I&#8217;d prefer a type-safe DSL for database queries but that&#8217;s more<br />
complicated. I&#8217;m still experimenting with that, too <img src='http://szeiger.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p></blockquote>
<p>I think those experiments worked rather well and the code is now in a state where the major features are usable and I can show some example code which compiles and runs successfully as a proof of concept. Many features (like more SQL operators, more data types and column aliasing) are missing but at least I am confident that it is possible to implement them on this basis.</p>
<p>Just like <a href="http://haskelldb.sourceforge.net/">HaskellDB</a> and <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx">LINQ to SQL</a>, I am using a query monad which collects the projections and restrictions on database tables in a composable way to build an SQL statement for a query while producing the correct type for that statement&#8217;s result in Scala&#8217;s type system. Don&#8217;t worry if that sounds too abstract, there will be plenty of example code.<span id="more-24"></span></p>
<p>The basic scaffolding for the examples looks like this:</p>
<div class="wp_syntax">
<div class="code">
<pre>import java.lang.Integer
import com.novocode.squery._
import com.novocode.squery.Implicit._
import com.novocode.squery.session._
import com.novocode.squery.session.SessionFactory._

object SQuery2Test2 {
  def main(args: Array[String]) {
    val sf = new DriverManagerSessionFactory(
      "org.h2.Driver", "jdbc:h2:mem:test1")
    sf withSession {
      // Database access code goes here
    }
  }
}
</pre>
</div>
</div>
<p>The <code>session._</code> and <code>SessionFactory._</code> imports provide a thin wrapper around JDBC connections with session management and query string caching. I am using the <a href="http://www.h2database.com">H2 Database Engine</a> here because it is very easy to set up for a local in-memory database (just include a single JAR in the classpath and use the driver name and URL from above). <code>SessionFactory</code> contains an implicit session object that can be used in a <code>withSession</code> block. The <code>squery</code> package contains the actual classes and traits needed for the type-safe queries. I will explain the implicit conversions from <code>Implicit._</code> as we go along.</p>
<p>For every table we want to use in a query, we need a corresponding <code>Table</code> object. Let&#8217;s define two tables for <em>Users</em> of some shopping application and the <em>Orders</em> they placed:</p>
<div class="wp_syntax">
<div class="code">
<pre>object Users extends Table[(Integer, String, String)]("users") {
  def id = intColumn("id", O.AutoInc, O.NotNull)
  def first = stringColumn("first")
  def last = stringColumn("last")
  def * = id ~ first ~ last
}

object Orders extends Table[(Integer, Integer, String)]("orders") {
  def userID = intColumn("userID", O.NotNull)
  def orderID = intColumn("orderID", O.AutoInc, O.NotNull)
  def product = stringColumn("product")
  def * = userID ~ orderID ~ product
}
</pre>
</div>
</div>
<p>Like every object which can be used in or returned from a query, a table is parameterized with the type of the values it represents. This is always a tuple of individual column types, in our case Integers and Strings  (note the use of <code>java.lang.Integer</code> instead of <code>Int</code>; more about that later). In this respect SQuery (as I&#8217;ve named it for now) is closer to HaskellDB than to LINQ because Scala (like most languages) does not give you access to an expression&#8217;s AST at runtime. In LINQ you can write queries using the real types of the values and columns in your database and have the query expression&#8217;s AST translated to SQL at runtime. Without this option we have to use meta-objects like <code>Table</code> and <code>Column</code> to build our own AST from these.</p>
<p>The rest of the table definitions should be quite obvious if you&#8217;ve ever worked with an SQL database. Each table gets a name (&#8221;users&#8221; and &#8220;orders&#8221;) and the individual columns consist of a name, a type (depending on the method by which they are created, like <code>intColumn</code> and <code>stringColumn</code>) and options like <code>AUTO_INCREMENT</code> and <code>NOT NULL</code>.</p>
<p>Each table must define the special &#8220;*&#8221; column which is a <em>projection</em> of all of the table&#8217;s columns in their preferred order. The type of this projection is statically enforced to be the same as the table&#8217;s (i.e. a <code>Table[T]</code> contains a &#8220;*&#8221; method of type <code>ConvertableColumn[T]</code>. There are separate projection classes for different numbers of columns just like Scala has different <em>tuple</em> types. You can use the projection operator &#8220;~&#8221; to build projections incrementally:</p>
<div class="wp_syntax">
<div class="code">
<pre>trait SimpleColumn[T] extends ConvertableColumn[T] {
  def ~[U](b: SimpleColumn[U]) = new Projection2[T, U](this, b)
}

sealed trait Projection[T &lt;: Product]
  extends ConvertableColumn[T] with Product { ... }

final class Projection2[T1,T2](
  override val _1: SimpleColumn[T1],
  override val _2: SimpleColumn[T2])
extends Tuple2(_1,_2) with Projection[(T1,T2)] {
  def ~[U](c: SimpleColumn[U]) = new Projection3(_1,_2,c)
}

//... and so on with Projection3, Projection4, etc.
</pre>
</div>
</div>
<p>Before we get to the queries, we should define our tables in the database. In practice you will probably build the tables first in the database and then write the required meta-objects but it can also be done directly from the <em>Table</em> objects:</p>
<div class="wp_syntax">
<div class="code">
<pre>Users.createTable
Orders.createTable
</pre>
</div>
</div>
<p>The <code>createTable</code> method is not defined on the tables but on the <code>DDLInvoker</code> class which can be instantiated automatically with an implicit conversion:</p>
<div class="wp_syntax">
<div class="code">
<pre>object Implicit {
  implicit def tableToDDLInvoker[T](t: Table[T]): DDLInvoker[T] =
    new DDLInvoker(t)
  ...
}

class DDLInvoker[T](table: Table[T]) {
  lazy val createTableStatement =
    new DDLBuilder(table).buildCreateTable
  def createTable(implicit session: Session) = ...
}
</pre>
</div>
</div>
<p><code>createTable</code> uses the implicit session I mentioned earlier. If you prefer to make it explicit you can leave out the <code>SessionFactory._</code> import and use the alternate <code>withSession</code> method:</p>
<div class="wp_syntax">
<div class="code">
<pre>sf withSession { session =>
  Users.createTable(session)
  Orders.createTable(session)
}
</pre>
</div>
</div>
<p>All other database access methods work the same way. I will always use the implicit version in the examples from now on.</p>
<p>You can also print out the generated SQL statements:</p>
<div class="wp_syntax">
<div class="code">
<pre>> println(Users.createTableStatement)
CREATE TABLE users (id INT NOT NULL AUTO_INCREMENT,first VARCHAR,last VARCHAR)

> println(Orders.createTableStatement)
CREATE TABLE orders (userID INT NOT NULL,orderID INT NOT NULL AUTO_INCREMENT,product VARCHAR)
</pre>
</div>
</div>
<p>Let&#8217;s insert some users into the database:</p>
<div class="wp_syntax">
<div class="code">
<pre>val ins1 = (Users.first ~ Users.last).insert("Homer", "Simpson")
val ins2 = (Users.first ~ Users.last).insertAll(
  ("Marge", "Simpson"),
  ("Apu", "Nahasapeemapetilon"),
  ("Carl", "Carlson"),
  ("Lenny", "Leonard") )
val ins3 = Users.first.insertAll(
  "Santa's Little Helper",
  "Snowball" )
println("Inserted "+(ins1+ins2+ins3)+" users")
</pre>
</div>
</div>
<p>You can use any single column or projection of columns to insert values of the corresponding type (which is a tuple for projections). All columns of a projection must be from the same table but this is not statically enforced.</p>
<p>Now that we have some content in the database, we can perform queries on it. This is about the simplest SQL query you can write:</p>
<div class="wp_syntax">
<div class="code">
<pre>SELECT * from users
</pre>
</div>
</div>
<p>You can do the same in Scala with a for-comprehension:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q1 = for(u &lt;- Users) yield u
</pre>
</div>
</div>
<p>This is equivalent to</p>
<div class="wp_syntax">
<div class="code">
<pre>val q1 = Users map { u => u }
</pre>
</div>
</div>
<p>There is no <code>map</code> method defined on tables but the table gets lifted automatically to a query with another implicit conversion:</p>
<div class="wp_syntax">
<div class="code">
<pre>object Implicit {
  implicit def tableToQuery[T &lt;: TableBase.T_](t: T) =
    Query(t.withOp(new ColumnOp.BaseTableQueryOp(t)))
  ...
}
</pre>
</div>
</div>
<p>The mapping itself is just an identity mapping, so we might as well have written the query as <code>tableToQuery(Users)</code> to get a <code>Query[Users]</code> without any restrictions.</p>
<p>Note the use of <code>t.withOp(...)</code> in <code>tableToQuery</code>. What we want to get from <code>tableToQuery</code> is a node for our query AST which indicates a uniquely named table. This is needed for queries which use multiple instances of the same table, for example to get the latest version of every document in a table <em>documents(id, version, content)</em> you could use:</p>
<div class="wp_syntax">
<div class="code">
<pre>SELECT content FROM documents t1
WHERE t1.version = (
  SELECT max(t2.version) FROM documents t2
  WHERE t2.id = t1.id
)
</pre>
</div>
</div>
<p><code>new BaseTableQueryOp(t)</code> provides such a unique table instance but on the outside it doesn&#8217;t &#8220;look like&#8221; the table it wraps. We need an instance of the same type as the original table which is marked as being a <em>BaseTableQueryOp</em> but otherwise behaves like that table. This is what the trait <em>WithOp</em> provides in a rather un-functional and hackish way by cloning the receiver object and setting the clone&#8217;s <code>op</code> field to the given object (the actual AST node):</p>
<div class="wp_syntax">
<div class="code">
<pre>trait WithOp[O >: Null] extends Cloneable {
  def withOp(op: O): this.type = {
    val t = clone
    t._op = op
    t
  }
  private[WithOp] var _op: O = _
  final def op: O = _op
  override def clone(): this.type =
    super.clone.asInstanceOf[this.type]
}

object WithOp {
  def unapply[O >: Null](w: WithOp[O]) =
    if(w.op == null) None else Some(w.op)
}
</pre>
</div>
</div>
<p>(Unlike this version the current implementation in SQuery is not generic because of <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1434">bug #1434</a>.)</p>
<p>We can print out the SQL statement for the query like this:</p>
<div class="wp_syntax">
<div class="code">
<pre>> println(q1.selectStatement)
SELECT t1.id,t1.first,t1.last FROM users t1
</pre>
</div>
</div>
<p>This is just what you&#8217;d expect (taking into account that SQuery does not use &#8220;*&#8221; and aliases all tables). The query does not contain a <em>selectStatement</em> field but again there&#8217;s an implicit conversion to a <em>QueryInvoker</em> with that field:</p>
<div class="wp_syntax">
<div class="code">
<pre>object Implicit {
  implicit def queryToQueryInvoker[T](q: Query[ConvertableColumn[T]]): QueryInvoker[T,T] = QueryInvoker(q)
  ...
}

class QueryInvoker[T,R] private (q: Query[ConvertableColumn[T]], mapper: T => R) {
  lazy val selectStatement = new QueryBuilder(q).buildSelect
  def first(implicit session: Session): Option[R] = ...
  def list(implicit session: Session): List[R] = ...
  def foreach(f: R => Unit)(implicit session: Session): Unit = ...
  def elements(implicit session: Session): CloseableIterator[R] = ...
  def mapResult[U](f: (R => U)) = new QueryInvoker[T,U](q, { v:T => f(mapper(v)) })
}

object QueryInvoker {
  def apply[T](q: Query[ConvertableColumn[T]]) = new QueryInvoker[T,T](q, { v:T => v })
}
</pre>
</div>
</div>
<p>Note that you cannot convert just any <code>Query[_]</code>, it has to be a <code>Query[ConvertableColumn[_]]</code>. This is the main reason for separating queries and invokers. The same implicit conversion allows you to use a foreach loop to iterate through all elements selected by a query:</p>
<div class="wp_syntax">
<div class="code">
<pre>> for(t &lt;- q1) println("User tuple: "+t)
User tuple: (1,Homer,Simpson)
User tuple: (2,Marge,Simpson)
User tuple: (3,Apu,Nahasapeemapetilon)
User tuple: (4,Carl,Carlson)
User tuple: (5,Lenny,Leonard)
User tuple: (6,Santa's Little Helper,null)
User tuple: (7,Snowball,null)
</pre>
</div>
</div>
<p>The <em>mapResult</em> method can be used to apply a mapping function to every row which is read from the database. Unlike a projection in the query which gets translated to SQL and executed on the database server this mapping is applied on the <em>client</em> side. The <code>Query</code> class has two type parameters for the type returned by the database query and the mapped type. Let&#8217;s define a case class for <code>User</code> objects and use a mapped <code>QueryInvoker</code> to read a list of them from the database:</p>
<div class="wp_syntax">
<div class="code">
<pre>case class User(id: Integer, first: String, last: String)

val allUsers = q1.mapResult {
  case (id,f,l) => User(id,f,l)
}.list
for(u &lt;- allUsers) println("User object: "+u)
</pre>
</div>
</div>
<p>If function argument lists and tuples <a href="http://article.gmane.org/gmane.comp.lang.scala.debate/2106/">get unified</a> in a future version of Scala, it should be possible to write that mapping simply as &#8220;<code>q1.mapResult(User)</code>&#8220;.</p>
<p>It is time we looked at a more complex query with a non-trivial projection and a restriction (a <em>WHERE</em> clause in SQL). The following code can be used to find Apu&#8217;s last name and ID:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q2 = for(u &lt;- Users where {_.first is "Apu" }) yield u.last ~ u.id
println("Apu's last name and ID are: " + q2.first)
</pre>
</div>
</div>
<p>Compare this with a similar snippet which selects the same values from a <code>List[User]</code> containing all data from the database:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q2 = for(u &lt;- users if u.first == "Apu") yield (u.last, u.id)
println("Apu's last name and ID are: " + q2.firstOption)
</pre>
</div>
</div>
<p><code>where</code> is a method on <code>Query</code>, so the <code>Users</code> object gets lifted to a query of a new unique instance of the <em>Users</em> table and then <code>where</code> maps this table to a <code>Column[Boolean]</code> which is added to the query as a restriction. Note that you have to use &#8220;is&#8221; instead of &#8220;==&#8221; (and &#8220;isNot&#8221; instead of &#8220;!=&#8221;) for column expressions because the latter is defined on all objects and cannot be overwritten oder overloaded in a suitable way. The string <em>&#8220;Apu&#8221;</em> is lifted to a <code>ConstColumn[String]</code> by another implicit conversion:</p>
<div class="wp_syntax">
<div class="code">
<pre>implicit def stringToConstColumn(v: String) =
  new ConstColumn(v) with StringColumn
</pre>
</div>
</div>
<p>Instead of returning the complete <em>Users</em> tuple from the query we use the projection &#8220;<code>yield u.last ~ u.id</code>&#8221; to extract only the last name and the ID. The call to <code>first</code> consequently returns an <code>Option[(String,Integer)]</code>. The SQL statement for <em>q2</em> is:</p>
<div class="wp_syntax">
<div class="code">
<pre>SELECT t1.last,t1.id FROM users t1 WHERE (t1.first='Apu')
</pre>
</div>
</div>
<p>At the moment all constants are inserted directly into the SQL statement. A production-grade library should of course use bind variables by default, with inlined values available as an option.</p>
<p>We need data in the <em>Orders</em> table for the next query, so let&#8217;s create some rows. We insert two random orders for every user except Apu and Snowball:</p>
<div class="wp_syntax">
<div class="code">
<pre>for(u &lt;- allUsers
         if u.first != "Apu" &#038;&#038; u.first != "Snowball"; i &lt;- 1 to 2)
  Orders.insert(u.id, null, "Gizmo "+((Math.random*10)+1).toInt)
</pre>
</div>
</div>
<p>So far the queries have only used a single table instance. They can be written in terms of <code>map</code> and <code>filter</code> without making use of the monadic structure of the <code>Query</code> class. Adding a second table to the query gives us a natural way of expressing a <em>join</em>:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q3 = for {
  u &lt;- Users
  o &lt;- Orders where { o => (u.id is o.userID) &#038;&#038; (u.last isNot null) }
} yield (u.first ~ u.last ~ o.orderID ~ o.product).sortBy(u.first)
println("All Orders by Users with a last name by first name:")
q3.foreach(o => println("  "+o))
</pre>
</div>
</div>
<p>Note the use of the &#8220;&#038;&#038;&#8221; operator in the restriction. This is not the usual boolean &#8220;<em>and</em>&#8221; but an operator on two <code>Column[Boolean]</code> objects yielding another boolean column. Another new feature seen in this query is the <em>sortBy</em> method in the projection. The SQL statement for this query is:</p>
<div class="wp_syntax">
<div class="code">
<pre>SELECT t1.first,t1.last,t2.orderID,t2.product
FROM users t1, orders t2
WHERE ((t1.id=t2.userID) and (t1.last is not null))
ORDER BY t1.first
</pre>
</div>
</div>
<p>Apart from <em>joins</em>, there are two more ways of combining queries: Unions and subqueries. Unions should map nicely to monadic <em>plus</em> operations with the empty query being the <em>zero</em> value but I haven&#8217;t tried that yet. Subqueries are used by constructing a special column from a query. This is already implemented as can be seen in the following example:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q4 = for (
  u &lt;- Users;
  o &lt;- Orders
    where { o => o.orderID is
      queryToSubQuery(for {
        o2 &lt;- Orders where(o.userID is _.userID)
      } yield o2.orderID.max) }
    where { _.userID is u.id }
) yield u.first ~ o.orderID
println("Latest Order per User:")
q4.foreach(o => println("  "+o))
</pre>
</div>
</div>
<p>The <code>queryToSubQuery</code> function should ideally be implicit. It&#8217;s currently not because of <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1579">bug #1579</a> which prevents all implicit conversions to various invoker classes from working if <code>queryToSubquery</code> is also implicit.</p>
<p>The subquery is used to find the maximum of a column for each separate value in another column. This common pattern can be extracted into a combinator:</p>
<div class="wp_syntax">
<div class="code">
<pre>def maxOfPer[T &lt;: TableBase.T_]
  (c: T, m: (T => Column[Integer]), p: (T => Column[_])) =
  c where { o => m(o) is queryToSubQuery(
    for { o2 &lt;- c where( n => p(o) is p(n)) } yield m(o2).max
  ) }
</pre>
</div>
</div>
<p>We can now write the query with <code>maxOfPer</code> like this:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q4b = for (
  u &lt;- Users;
  o &lt;- maxOfPer[Orders.type](Orders, _.orderID, _.userID)
    where { _.userID is u.id }
) yield u.first ~ o.orderID
</pre>
</div>
</div>
<p>In either case, the generated SQL statement is:</p>
<div class="wp_syntax">
<div class="code">
<pre>SELECT t1.first,t2.orderID FROM orders t2, users t1
WHERE (t2.userID=t1.id) AND (t2.orderID=(
  SELECT max(t3.orderID) FROM orders t3
  WHERE (t2.userID=t3.userID))
)
</pre>
</div>
</div>
<p>Another way to create a subquery implicitly is the <em>in</em> operator (and its negation <em>notIn</em>). To find all users which haven&#8217;t placed an order we can use:</p>
<div class="wp_syntax">
<div class="code">
<pre>val q5 = Users where { _.id notIn Orders.map(_.userID) }
println("Users without Orders:")
q5.foreach(o => println("  "+o))
</pre>
</div>
</div>
<p>Any query which returns a single table can be used to delete rows with a <code>DeleteInvoker</code>:</p>
<div class="wp_syntax">
<div class="code">
<pre>println("q5: " + q5.deleteStatement)
println("Deleting them...")
val deleted = q5.delete
println("Deleted "+deleted+" rows")
</pre>
</div>
</div>
<p>And finally, we can count the rows selected by that statement (which should of course be 0 after deleting them):</p>
<div class="wp_syntax">
<div class="code">
<pre>val q6 = q5.map(_.count)
println("q6: " + q6.selectStatement)
println("Users without Orders left: " + q6.first.get)
</pre>
</div>
</div>
<p>As I already mentioned at the beginning of this post (which is getting much longer than I anticipated), I am using <code>java.lang.Integer</code> instead of <code>Int</code> for the integer columns. The underlying problem is nullability. While you can specify which columns are created nullable in the database (by placing or omitting the <em>NotNull</em> option), they are all treated as nullable in SQuery and thus they cannot use value types like <code>Int</code>. Alternatively, you could take the same approach as HaskellDB and use value types (or references types which may never be null for types like <em>String</em>) for the non-nullable columns and an <code>Option</code> of the same type for their nullable counterparts. That works fine for all the features I&#8217;ve shown so far but it makes typechecking of <em>outer joins</em> difficult (or even impossible) because an outer join has to selectively promote non-nullable columns to nullable ones. I didn&#8217;t want to give up outer joins so easily, so I chose to make everything nullable for now.</p>
<p>There&#8217;s no public repository for SQuery yet but you can <a href="http://szeiger.de/static/squery-0.1.zip">download</a> the Eclipse project as a ZIP file. Just add the <a href="http://www.h2database.com/html/download.html">H2</a> JAR (not included) to the classpath to run the supplied example class <code>test.SQuery2Test2</code> which contains all the queries from this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://szeiger.de/blog/2008/12/21/a-type-safe-database-query-dsl-for-scala/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
