/
Acolyte.scala
322 lines (275 loc) · 8.97 KB
/
Acolyte.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// -*- mode: scala -*-
package acolyte
import java.util.{ ArrayList, List ⇒ JList }
import java.util.regex.Pattern
import java.sql.{ Statement, SQLWarning }
import scala.language.implicitConversions
import scala.collection.JavaConversions
import acolyte.ParameterMetaData.ParameterDef
import acolyte.StatementHandler.Parameter
import acolyte.AbstractCompositeHandler.{ QueryHandler, UpdateHandler }
import acolyte.RowList.Column
/**
* Acolyte DSL.
*
* {{{
* import acolyte.Acolyte.{ connection, handleStatement }
* import acolyte.Implicits._
*
* connection {
* handleStatement.withQueryDetection("...").
* withQueryHandler({ e: Execution => ... }).
* withUpdateHandler({ e: Execution => ... })
* }
* }}}
*/
object Acolyte {
/**
* Creates a connection, whose statement will be passed to given handler.
*
* @param h statement handler
* @param p connection properties
* @return a new Acolyte connection
*
* {{{
* connection(handler) // without connection properties
*
* // With connection property to fallback untyped null
* connection(handler, "acolyte.parameter.untypedNull" -> "true")
* }}}
*/
def connection(h: AbstractCompositeHandler[_], p: (String, String)*) =
Driver.connection(h, p.foldLeft(new java.util.Properties()) { (ps, t) ⇒
ps.put(t._1, t._2); ps
})
/**
* Creates a connection, managed with given handler.
*
* @param h connection handler
* @param p connection properties
* @return a new Acolyte connection
*
* {{{
* connection(handler) // without connection properties
*
* // With connection property to fallback untyped null
* connection(handler, "acolyte.parameter.untypedNull" -> "true")
* }}}
*/
def connection(h: ConnectionHandler, p: (String, String)*) =
Driver.connection(h, p.foldLeft(new java.util.Properties()) { (ps, t) ⇒
ps.put(t._1, t._2); ps
})
/**
* Creates an empty handler.
*
* {{{
* import acolyte.Acolyte.{ connection, handleStatement }
*
* connection { handleStatement }
* }}}
*/
def handleStatement = ScalaCompositeHandler.empty
/**
* Creates a new handler detecting all statements as queries
* (like `handleStatement.withQueryDetection(".*").withQueryHandler(h)`).
*
* {{{
* import acolyte.Acolyte.{ connection, handleQuery }
*
* connection { handleQuery { _ => res }
* }}}
*/
def handleQuery(h: QueryExecution ⇒ QueryResult): ScalaCompositeHandler =
handleStatement withQueryDetection ".*" withQueryHandler h
// TODO? (h: QueryExec => A)(implicit c: A => QueryResult)
}
/**
* Acolyte implicit conversions for Scala use.
*
* {{{
* import acolyte.Implicits._
* }}}
*/
object Implicits extends ScalaRowLists with CompositeHandlerImplicits {
/**
* Converts tuple to column definition.
*
* {{{
* import acolyte.Implicits.PairAsColumn
*
* rowList1(classOf[Int] -> "name") // rowList(new Column(...))
* }}}
*/
implicit def PairAsColumn[T](c: (Class[T], String)): Column[T] =
Column(c._1, c._2)
}
sealed trait Execution
case class QueryExecution(
sql: String,
parameters: List[ExecutedParameter]) extends Execution
case class UpdateExecution(
sql: String,
parameters: List[ExecutedParameter]) extends Execution
trait ExecutedParameter {
def value: Any
}
case class DefinedParameter(
value: Any,
definition: ParameterDef) extends ExecutedParameter {
override lazy val toString = s"Param($value, ${definition.sqlTypeName})"
}
object ParameterVal {
def apply(v: Any): ExecutedParameter = new ExecutedParameter {
val value = v
override lazy val toString = s"Param($value)"
}
def unapply(p: ExecutedParameter): Option[Any] = Some(p.value)
}
final class ScalaCompositeHandler(qd: Array[Pattern], qh: QueryHandler, uh: UpdateHandler) extends AbstractCompositeHandler[ScalaCompositeHandler](qd, qh, uh) {
/**
* Returns handler that detects statement matching given pattern(s)
* as query.
*
* {{{
* import acolyte.Acolyte.handleStatement
*
* // Created handle will detect as query statements
* // either starting with 'SELECT ' or containing 'EXEC proc'.
* handleStatement.withQueryDetection("^SELECT ", "EXEC proc")
* }}}
*/
def withQueryDetection(pattern: Pattern*) = new ScalaCompositeHandler(
queryDetectionPattern(pattern: _*), queryHandler, updateHandler)
/**
* Returns handler that delegates query execution to |h| function.
* Given function will be used only if executed statement is detected
* as a query by withQueryDetection.
*
* {{{
* import acolyte.QueryExecution
* import acolyte.Acolyte.handleStatement
*
* handleStatement withQueryHandler { e: QueryExecution => aQueryResult }
*
* // With pattern matching ...
* import acolyte.ParameterVal
*
* handleStatement withQueryHandler {
* _ match {
* case QueryExecution("SELECT * FROM Test WHERE id = ?", ParameterVal(1) :: Nil) => aQueryResult
* case _ => otherResult
* }
* }
* }}}
*/
def withQueryHandler(h: QueryExecution ⇒ QueryResult): ScalaCompositeHandler = new ScalaCompositeHandler(queryDetection, new QueryHandler {
def apply(sql: String, p: JList[Parameter]): QueryResult =
h(QueryExecution(sql, scalaParameters(p)))
}, updateHandler)
/**
* Returns handler that delegates update execution to |h| function.
* Given function will be used only if executed statement is not detected
* as a query by withQueryDetection.
*
* {{{
* import acolyte.UpdateExecution
* import acolyte.Acolyte.handleStatement
*
* handleStatement withUpdateHandler { e: UpdateExecution => aQueryResult }
*
* // With pattern matching ...
* import acolyte.ParameterVal
*
* handleStatement withUpdateHandler {
* _ match {
* case UpdateExecution("INSERT INTO Country (code, name) VALUES (?, ?)", ParameterVal(code) :: ParameterVal(name) :: Nil) => 1 /* update count */
* case _ => otherResult
* }
* }
* }}}
*/
def withUpdateHandler(h: UpdateExecution ⇒ UpdateResult): ScalaCompositeHandler = new ScalaCompositeHandler(queryDetection, queryHandler, new UpdateHandler {
def apply(sql: String, p: JList[Parameter]): UpdateResult =
h(UpdateExecution(sql, scalaParameters(p)))
})
private def scalaParameters(p: JList[Parameter]): List[ExecutedParameter] =
JavaConversions.collectionAsScalaIterable(p).
foldLeft(Nil: List[ExecutedParameter]) { (l, t) ⇒
l :+ DefinedParameter(t.right, t.left)
}
}
trait CompositeHandlerImplicits { srl: ScalaRowLists ⇒
/**
* Allows to directly use update count as update result.
*
* {{{
* ScalaCompositeHandler.empty withUpdateHandler { exec ⇒ 1/*count*/ }
* }}}
*/
implicit def IntUpdateResult(updateCount: Int): UpdateResult =
new UpdateResult(updateCount)
/**
* Allows to directly use row list as query result.
*
* {{{
* val qr: QueryResult = stringList
* }}}
*/
implicit def RowListAsResult[R <: RowList[_]](r: R): QueryResult = r.asResult
/**
* Allows to directly use string as query result.
*
* {{{
* val qr: QueryResult = "str"
* }}}
*/
implicit def StringAsResult(v: String): QueryResult =
(RowLists.stringList :+ v).asResult
implicit def BooleanAsResult(v: Boolean): QueryResult =
(RowLists.booleanList :+ v).asResult
implicit def ByteAsResult(v: Byte): QueryResult =
(RowLists.byteList :+ v).asResult
implicit def ShortAsResult(v: Short): QueryResult =
(RowLists.shortList :+ v).asResult
implicit def IntAsResult(v: Int): QueryResult =
(RowLists.intList :+ v).asResult
implicit def LongAsResult(v: Long): QueryResult =
(RowLists.longList :+ v).asResult
implicit def FloatAsResult(v: Float): QueryResult =
(RowLists.floatList :+ v).asResult
implicit def DoubleAsResult(v: Double): QueryResult =
(RowLists.doubleList :+ v).asResult
implicit def ScalaBigDecimalAsResult(v: BigDecimal): QueryResult =
(RowLists.bigDecimalList :+ v.bigDecimal).asResult
implicit def JavaBigDecimalAsResult(v: java.math.BigDecimal): QueryResult =
(RowLists.bigDecimalList :+ v).asResult
implicit def DateAsTimestampResult(v: java.util.Date): QueryResult =
(RowLists.timestampList :+ new java.sql.Timestamp(v.getTime)).asResult
implicit def SqlDateAsTimestampResult(v: java.sql.Timestamp): QueryResult =
(RowLists.timestampList :+ v).asResult
}
private object ScalaCompositeHandler {
def empty = new ScalaCompositeHandler(null, null, null)
}
/**
* Convertions from Java datatypes to Scala.
*/
@deprecated("Direct manipulation of row is no longer required", "1.0.12")
object JavaConverters {
/**
* Pimps result row.
*
* {{{
* row.list // Scala list equivalent to .cells
* }}}
*/
implicit def rowAsScala[R <: Row](r: R): ScalaRow = new ScalaRow(r)
final class ScalaRow(r: Row) extends Row {
lazy val cells = r.cells
lazy val list: List[Any] =
JavaConversions.iterableAsScalaIterable(cells).foldLeft(List[Any]()) {
(l, v) ⇒ l :+ v
}
}
}