/
SQLBuilder.scala
59 lines (45 loc) · 1.37 KB
/
SQLBuilder.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package slick.util
import java.sql.PreparedStatement
import scala.collection.mutable.ArrayBuffer
final class SQLBuilder extends SQLBuilderCompat { self =>
import SQLBuilder._
private val sb = new StringBuilder(128)
private val setters = new ArrayBuffer[Setter]
private var currentIndentLevel: Int = 0
def +=(s: String) = { sb append s; this }
def +=(c: Char) = { sb append c; this }
def +?=(f: Setter) = { setters append f; sb append '?'; this }
def sep[T](sequence: ConstArray[T], separator: String)(f: T => Unit): Unit = {
var i = 0
while(i < sequence.length) {
if(i != 0) self += separator
f(sequence(i))
i += 1
}
}
def build = Result(sb.toString, { (p: PreparedStatement, idx: Int, param: Any) =>
var i = idx
for(s <- setters) {
s(p, i, param)
i += 1
}
})
def newLineIndent(): Unit = {
currentIndentLevel += 1
newLine()
}
def newLineDedent(): Unit = {
currentIndentLevel -= 1
newLine()
}
def newLineOrSpace(): Unit =
if(GlobalConfig.sqlIndent) newLine() else this += " "
private def newLine(): Unit = if(GlobalConfig.sqlIndent) {
this += "\n"
if (1 <= currentIndentLevel) 1.to(currentIndentLevel).foreach(_ => this += " ")
}
}
object SQLBuilder {
final type Setter = ((PreparedStatement, Int, Any) => Unit)
final case class Result(sql: String, setter: Setter)
}