alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (ToSql.scala)

This example Play Framework source code file (ToSql.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

a, int, play, play framework, seq, seqparameter, string, tosql

The ToSql.scala Play Framework example source code

package anorm

/** Set value as prepared SQL statement fragment. */
trait ToSql[A] {

  /**
   * Prepares SQL fragment for value,
   * using [[java.sql.PreparedStatement]] syntax (with '?').
   *
   * @return SQL fragment and count of "?" placeholders in it
   */
  def fragment(value: A): (String, Int)
}

/** Provided ToSql implementations. */
object ToSql {
  import scala.language.implicitConversions

  /**
   * Returns fragment for each value, separated by ", ".
   *
   * {{{
   * seqToSql(Seq("A", "B", "C"))
   * // "?, ?, ?"
   * }}}
   */
  implicit def seqToSql[A](implicit conv: ToSql[A] = null) = new ToSql[Seq[A]] {
    def fragment(values: Seq[A]): (String, Int) = {
      val c: A => (String, Int) =
        if (conv == null) _ => ("?" -> 1) else conv.fragment

      values.foldLeft("" -> 0) { (s, v) =>
        val frag = c(v)
        val st = if (s._2 > 0) ", " + frag._1 else frag._1
        (s._1 + st, s._2 + frag._2)
      }
    }
  }

  /** Returns fragment for each value, with custom formatting. */
  implicit def seqParamToSql[A](implicit conv: ToSql[A] = null) =
    new ToSql[SeqParameter[A]] {
      def fragment(p: SeqParameter[A]): (String, Int) = {
        val before = p.before.getOrElse("")
        val after = p.after.getOrElse("")
        val c: A => (String, Int) =
          if (conv == null) _ => ("?" -> 1) else conv.fragment

        p.values.foldLeft("" -> 0) { (s, v) =>
          val frag = c(v)
          val st =
            if (s._2 > 0) p.separator + before + frag._1 else before + frag._1
          (s._1 + st + after, s._2 + frag._2)
        }
      }
    }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework ToSql.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.