Skip to content

Commit

Permalink
[#4600] Add support for plain SQL APIs via Scala string interpolation
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaseder committed Oct 6, 2015
1 parent cfe3013 commit abbbdba
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions jOOQ-scala/src/main/scala/org/jooq/scala/Conversions.scala
Expand Up @@ -92,6 +92,41 @@ object Conversions {
// Enhanced jOOQ types
// -------------------------------------------------------------------------

implicit class SQLInterpolation(val sc : StringContext) extends AnyVal {

@PlainSQL
def sql(args: Any*) : SQL = DSL.sql(string(args), args.asInstanceOf[Seq[AnyRef]] : _*)

@PlainSQL
def condition(args : Any*) : Condition = DSL.condition(string(args), args.asInstanceOf[Seq[AnyRef]] : _*)

@PlainSQL
def table(args : Any*) : Table[Record] = DSL.table(string(args), args.asInstanceOf[Seq[AnyRef]] : _*)

@PlainSQL
def query(args : Any*) : Query = DSL.query(string(args), args.asInstanceOf[Seq[AnyRef]] : _*)

@PlainSQL
def resultQuery(args : Any*) : ResultQuery[Record] = DSL.resultQuery(string(args), args.asInstanceOf[Seq[AnyRef]] : _*)

private def string(args : Any*) = {

This comment has been minimized.

Copy link
@er1c

er1c Jul 20, 2016

Contributor

What's the point of passing in args: Any* into this helper since it's not used anywhere in the implementation? I think I'm missing something here...

This comment has been minimized.

Copy link
@lukaseder

lukaseder Jul 20, 2016

Author Member

Aaaha! I frankly don't know. I just copy pasted this funky string interpolation code from somewhere:
http://docs.scala-lang.org/overviews/core/string-interpolation

Yes, the magic of obscure Scala :P

This comment has been minimized.

Copy link
@er1c

er1c Jul 20, 2016

Contributor

OK, I'll assume then, that this is currently broken and not the intended behavior, since it doesn't actually do any interpolation with the args :)

This comment has been minimized.

Copy link
@lukaseder

lukaseder Jul 28, 2016

Author Member

Really? Seems to work for me:

  test("String interpolation") {
    val book = T_BOOK;
    val condition = book.ID > 2;
    assert(2 == dsl.fetchOne(resultQuery"select count(*) from $book where $condition").get(0, classOf[Int]));
  }

The above executes:

select count(*) from "public"."t_book" where "public"."t_book"."id" > 2
val pi = sc.parts.iterator
val sb = new StringBuilder(pi.next())
var i = 0;

while (pi.hasNext) {
sb += '{'
sb ++= (i toString)
sb += '}'
sb ++= pi.next()

i = i + 1;
}

sb.result
}
}

implicit class ScalaDSLContext (val ctx : DSLContext) {
def fetchAnyOption[R <: Record] (table : Table[R]) : Option[R] = Option(ctx.fetchAny(table))
def fetchAnyOption[R <: Record] (table : Table[R], condition : Condition) : Option[R] = Option(ctx.fetchAny(table, condition))
Expand Down

0 comments on commit abbbdba

Please sign in to comment.