/
MetaMapper.scala
2129 lines (1752 loc) · 76.6 KB
/
MetaMapper.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2006-2011 WorldWide Conferencing, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.liftweb
package mapper
import java.lang.reflect.Method
import java.sql.{ResultSet, Types, PreparedStatement}
import java.util.{Date, Locale}
import collection.mutable.{ListBuffer, HashMap}
import collection.immutable.{SortedMap, TreeMap}
import xml._
import common._
import json._
import util.Helpers._
import util.{NamedPF, FieldError, Helpers}
import http.{LiftRules, S, SHtml, RequestMemoize, Factory}
import http.js._
trait BaseMetaMapper {
type RealType <: Mapper[RealType]
def beforeSchemifier: Unit
def afterSchemifier: Unit
def dbTableName: String
def _dbTableNameLC: String
def mappedFields: scala.collection.Seq[BaseMappedField];
def dbAddTable: Box[() => Unit]
def dbIndexes: List[BaseIndex[RealType]]
}
/**
* Rules and functions shared by all Mappers
*/
object MapperRules extends Factory {
/**
* This function converts a header name into the appropriate
* XHTML format for displaying across the headers of a
* formatted block. The default is <th> for use
* in XHTML tables. If you change this function, the change
* will be used for all MetaMappers, unless they've been
* explicitly changed.
*/
var displayNameToHeaderElement: String => NodeSeq = in => <th>{in}</th>
/**
* This function converts an element into the appropriate
* XHTML format for displaying across a line
* formatted block. The default is <td> for use
* in XHTML tables. If you change this function, the change
* will be used for all MetaMappers, unless they've been
* explicitly changed.
*/
var displayFieldAsLineElement: NodeSeq => NodeSeq = in => <td>{in}</td>
/**
* This function is the global (for all MetaMappers that have
* not changed their formatFormElement function) that
* converts a name and form for a given field in the
* model to XHTML for presentation in the browser. By
* default, a table row ( <tr> ) is presented, but
* you can change the function to display something else.
*/
var formatFormElement: (NodeSeq, NodeSeq) => NodeSeq =
(name, form) =>
<xml:group><tr>
<td>{name}</td>
<td>{form}</td>
</tr></xml:group>
/**
* What are the rules and mechanisms for putting quotes around table names?
*/
val quoteTableName: FactoryMaker[String => String] =
new FactoryMaker[String => String]((s: String) => if (s.indexOf(' ') >= 0) '"'+s+'"' else s) {}
/**
* What are the rules and mechanisms for putting quotes around column names?
*/
val quoteColumnName: FactoryMaker[String => String] =
new FactoryMaker[String => String]((s: String) => if (s.indexOf(' ') >= 0) '"'+s+'"' else s) {}
/**
* Function that determines if foreign key constraints are
* created by Schemifier for the specified connection.
*
* Note: The driver choosen must also support foreign keys for
* creation to happen
*/
var createForeignKeys_? : ConnectionIdentifier => Boolean = c => false
/**
* This function is used to calculate the displayName of a field. Can be
* used to easily localize fields based on the locale in the
* current request
*/
val displayNameCalculator: FactoryMaker[(BaseMapper, Locale, String) => String] =
new FactoryMaker[(BaseMapper, Locale, String) => String]((m: BaseMapper,l: Locale,name: String) => name) {}
/**
* Calculate the name of a column based on the name
* of the MappedField. Must be set in Boot before any code
* that touches the MetaMapper.
*
* To get snake_case, use this:
*
* MapperRules.columnName = (_,name) => StringHelpers.snakify(name)
*/
var columnName: (ConnectionIdentifier,String) => String = (_,name) => name.toLowerCase
/**
* Calculate the name of a table based on the name
* of the Mapper. Must be set in Boot before any code
* that tocuhes the MetaMapper.
*
* To get snake_case, use this
*
* MapperRules.tableName = (_,name) => StringHelpers.snakify(name)
*/
var tableName: (ConnectionIdentifier,String) => String = (_,name) => name.toLowerCase
}
trait MetaMapper[A<:Mapper[A]] extends BaseMetaMapper with Mapper[A] {
self: A =>
private val logger = Logger(classOf[MetaMapper[A]])
case class FieldHolder(name: String, method: Method, field: MappedField[_, A])
type RealType = A
def beforeValidation: List[A => Unit] = Nil
def beforeValidationOnCreate: List[A => Unit] = Nil
def beforeValidationOnUpdate: List[A => Unit] = Nil
def afterValidation: List[A => Unit] = Nil
def afterValidationOnCreate: List[A => Unit] = Nil
def afterValidationOnUpdate: List[A => Unit] = Nil
def beforeSave: List[A => Unit] = Nil
def beforeCreate: List[(A) => Unit] = Nil
def beforeUpdate: List[(A) => Unit] = Nil
def afterSave: List[(A) => Unit] = Nil
def afterCreate: List[(A) => Unit] = Nil
def afterUpdate: List[(A) => Unit] = Nil
def beforeDelete: List[(A) => Unit] = Nil
def afterDelete: List[(A) => Unit] = Nil
/**
* If there are model-specific validations to perform, override this
* method and return an additional list of validations to perform
*/
def validation: List[A => List[FieldError]] = Nil
private def clearPostCommit(in: A) {
in.addedPostCommit = false
}
private def clearPCFunc: A => Unit = clearPostCommit _
def afterCommit: List[A => Unit] = Nil
def dbDefaultConnectionIdentifier: ConnectionIdentifier = DefaultConnectionIdentifier
def findAll(): List[A] =
findMapDb(dbDefaultConnectionIdentifier, Nil :_*)(v => Full(v))
def findAllDb(dbId:ConnectionIdentifier): List[A] =
findMapDb(dbId, Nil :_*)(v => Full(v))
def countByInsecureSql(query: String, checkedBy: IHaveValidatedThisSQL): scala.Long =
countByInsecureSqlDb(dbDefaultConnectionIdentifier, query, checkedBy)
def countByInsecureSqlDb(dbId: ConnectionIdentifier, query: String, checkedBy: IHaveValidatedThisSQL): scala.Long =
DB.use(dbId)(DB.prepareStatement(query, _)(DB.exec(_)(rs => if (rs.next) rs.getLong(1) else 0L)))
def findAllByInsecureSql(query: String, checkedBy: IHaveValidatedThisSQL): List[A] = findAllByInsecureSqlDb(dbDefaultConnectionIdentifier, query, checkedBy)
/**
* Execute a PreparedStatement and return a List of Mapper instances. {@code f} is
* where the user will do the work of creating the PreparedStatement and
* preparing it for execution.
*
* @param f A function that takes a SuperConnection and returns a PreparedStatement.
* @return A List of Mapper instances.
*/
def findAllByPreparedStatement(f: SuperConnection => PreparedStatement): List[A] = {
DB.use(dbDefaultConnectionIdentifier) {
conn =>
findAllByPreparedStatement(dbDefaultConnectionIdentifier, f(conn))
}
}
def findAllByPreparedStatement(dbId: ConnectionIdentifier, stmt: PreparedStatement): List[A] = findAllByPreparedStatementDb(dbId, stmt)(a => Full(a))
def findAllByPreparedStatementDb[T](dbId: ConnectionIdentifier, stmt: PreparedStatement)(f: A => Box[T]): List[T] = {
DB.exec(stmt) {
rs => createInstances(dbId, rs, Empty, Empty, f)
}
}
def findAllByInsecureSqlDb(dbId: ConnectionIdentifier, query: String, checkedBy: IHaveValidatedThisSQL): List[A] =
findMapByInsecureSqlDb(dbId, query, checkedBy)(a => Full(a))
def findMapByInsecureSql[T](query: String, checkedBy: IHaveValidatedThisSQL)
(f: A => Box[T]): List[T] =
findMapByInsecureSqlDb(dbDefaultConnectionIdentifier, query, checkedBy)(f)
def findMapByInsecureSqlDb[T](dbId: ConnectionIdentifier, query: String, checkedBy: IHaveValidatedThisSQL)(f: A => Box[T]): List[T] = {
DB.use(dbId) {
conn =>
DB.prepareStatement(query, conn) {
st =>
DB.exec(st) {
rs =>
createInstances(dbId, rs, Empty, Empty, f)
}
}
}
}
def dbAddTable: Box[() => Unit] = Empty
def count: Long = countDb(dbDefaultConnectionIdentifier, Nil :_*)
def count(by: QueryParam[A]*): Long = countDb(dbDefaultConnectionIdentifier, by:_*)
def countDb(dbId: ConnectionIdentifier, by: QueryParam[A]*): Long = {
DB.use(dbId) {
conn =>
val bl = by.toList ::: addlQueryParams.get
val (query, start, max) = addEndStuffs(addFields("SELECT COUNT(*) FROM "+MapperRules.quoteTableName.vend(_dbTableNameLC)+" ", false, bl, conn), bl, conn)
DB.prepareStatement(query, conn) {
st =>
setStatementFields(st, bl, 1, conn)
DB.exec(st) {
rs =>
if (rs.next) rs.getLong(1)
else 0
}
}
}
}
//type KeyDude = T forSome {type T}
type OtherMapper = KeyedMapper[_, _] // T forSome {type T <: KeyedMapper[KeyDude, T]}
type OtherMetaMapper = KeyedMetaMapper[_, _] // T forSome {type T <: KeyedMetaMapper[KeyDude, OtherMapper]}
//type OtherMapper = KeyedMapper[_, (T forSome {type T})]
//type OtherMetaMapper = KeyedMetaMapper[_, OtherMapper]
def findAllFields(fields: scala.collection.Seq[SelectableField],
by: QueryParam[A]*): List[A] =
findMapFieldDb(dbDefaultConnectionIdentifier,
fields, by :_*)(v => Full(v))
def findAllFieldsDb(dbId: ConnectionIdentifier,
fields: Seq[SelectableField],
by: QueryParam[A]*):
List[A] = findMapFieldDb(dbId, fields, by :_*)(v => Full(v))
private def dealWithPrecache(ret: List[A], by: Seq[QueryParam[A]]): List[A] = {
val precache: List[PreCache[A, _, _]] = by.toList.flatMap{case j: PreCache[A, _, _] => List[PreCache[A, _, _]](j) case _ => Nil}
for (j <- precache) {
type FT = j.field.FieldType
type MT = T forSome {type T <: KeyedMapper[FT, T]}
val ol: List[MT] = if (!j.deterministic) {
def filter(in: Seq[FT]): Seq[FT] =
in.flatMap{
case null => Nil
case x: Number if x.longValue == 0L => Nil
case x => List(x)
}
val lst: Set[FT] = Set(filter(ret.map(v => v.getSingleton.getActualField(v, j.field).get.asInstanceOf[FT])) :_*)
j.field.dbKeyToTable.
asInstanceOf[MetaMapper[A]].
findAll(ByList(j.field.dbKeyToTable.primaryKeyField.
asInstanceOf[MappedField[FT, A]], lst.toList)).asInstanceOf[List[MT]]
} else {
j.field.dbKeyToTable.
asInstanceOf[MetaMapper[A]].
findAll(new InThing[A]{
type JoinType = FT
type InnerType = A
val outerField: MappedField[JoinType, A] =
j.field.dbKeyToTable.primaryKeyField.asInstanceOf[MappedField[JoinType, A]]
val innerField: MappedField[JoinType, A] = j.field.asInstanceOf[MappedField[JoinType, A]]
val innerMeta: MetaMapper[A] = j.field.fieldOwner.getSingleton
def notIn = false
val queryParams: List[QueryParam[A]] = by.toList
}.asInstanceOf[QueryParam[A]] ).asInstanceOf[List[MT]]
}
val map: Map[FT, MT] =
Map(ol.map(v => (v.primaryKeyField.get, v)) :_*)
for (i <- ret) {
val field: MappedForeignKey[FT, A, _] =
getActualField(i, j.field).asInstanceOf[MappedForeignKey[FT, A, _]]
map.get(field.get) match {
case v => field._primeObj(Box(v))
}
//field.primeObj(Box(map.get(field.get).map(_.asInstanceOf[QQ])))
}
}
ret
}
def findAll(by: QueryParam[A]*): List[A] =
dealWithPrecache(findMapDb(dbDefaultConnectionIdentifier, by :_*)
(v => Full(v)), by)
def findAllDb(dbId: ConnectionIdentifier,by: QueryParam[A]*): List[A] =
dealWithPrecache(findMapDb(dbId, by :_*)(v => Full(v)), by)
def bulkDelete_!!(by: QueryParam[A]*): Boolean = bulkDelete_!!(dbDefaultConnectionIdentifier, by :_*)
def bulkDelete_!!(dbId: ConnectionIdentifier, by: QueryParam[A]*): Boolean = {
DB.use(dbId) {
conn =>
val bl = by.toList ::: addlQueryParams.get
val (query, start, max) = addEndStuffs(addFields("DELETE FROM "+MapperRules.quoteTableName.vend(_dbTableNameLC)+" ", false, bl, conn), bl, conn)
DB.prepareStatement(query, conn) {
st =>
setStatementFields(st, bl, 1, conn)
st.executeUpdate
true
}
}
}
private def distinct(in: Seq[QueryParam[A]]): String =
in.find {case Distinct() => true case _ => false}.isDefined match {
case false => ""
case true => " DISTINCT "
}
def findMap[T](by: QueryParam[A]*)(f: A => Box[T]) =
findMapDb(dbDefaultConnectionIdentifier, by :_*)(f)
def findMapDb[T](dbId: ConnectionIdentifier,
by: QueryParam[A]*)(f: A => Box[T]): List[T] =
findMapFieldDb(dbId, mappedFields, by :_*)(f)
/**
* Given fields, a connection and the query parameters, build a query and return the query String,
* and Start or MaxRows values (depending on whether the driver supports LIMIT and OFFSET)
* and the complete List of QueryParams based on any synthetic query parameters calculated during the
* query creation.
*
* @param fields -- a Seq of the fields to be selected
* @param conn -- the SuperConnection to be used for calculating the query
* @param by -- the varg of QueryParams
*
* @return a Tuple of the Query String, Start (offset), MaxRows (limit), and the list of all query parameters
* including and synthetic query parameters
*/
def buildSelectString(fields: Seq[SelectableField], conn: SuperConnection, by: QueryParam[A]*):
(String, Box[Long], Box[Long], List[QueryParam[A]]) = {
val bl = by.toList ::: addlQueryParams.get
val selectStatement = "SELECT "+
distinct(by)+
fields.map(_.dbSelectString).
mkString(", ")+
" FROM "+MapperRules.quoteTableName.vend(_dbTableNameLC)+" "
val (str, start, max) = addEndStuffs(addFields(selectStatement, false, bl, conn), bl, conn)
(str, start, max, bl)
}
def findMapFieldDb[T](dbId: ConnectionIdentifier, fields: Seq[SelectableField],
by: QueryParam[A]*)(f: A => Box[T]): List[T] = {
DB.use(dbId) {
conn =>
val (query, start, max, bl) = buildSelectString(fields, conn, by :_*)
DB.prepareStatement(query, conn) {
st =>
setStatementFields(st, bl, 1, conn)
DB.exec(st)(createInstances(dbId, _, start, max, f))
}
}
}
def create: A = createInstance
object addlQueryParams extends net.liftweb.http.RequestVar[List[QueryParam[A]]](Nil) {
override val __nameSalt = randomString(10)
}
private[mapper] def addFields(what: String, whereAdded: Boolean,
by: List[QueryParam[A]], conn: SuperConnection): String = {
var wav = whereAdded
def whereOrAnd = if (wav) " AND " else {wav = true; " WHERE "}
class DBFuncWrapper(dbFunc: Box[String]) {
def apply(field: String) = dbFunc match {
case Full(f) => f+"("+field+")"
case _ => field
}
}
implicit def dbfToFunc(in: Box[String]): DBFuncWrapper = new DBFuncWrapper(in)
by match {
case Nil => what
case x :: xs => {
var updatedWhat = what
x match {
case Cmp(field, opr, Full(_), _, dbFunc) =>
(1 to field.dbColumnCount).foreach {
cn =>
updatedWhat = updatedWhat + whereOrAnd + dbFunc(MapperRules.quoteColumnName.vend(field.dbColumnNames(field.name)(cn - 1)))+" "+opr+" ? "
}
case Cmp(field, opr, _, Full(otherField), dbFunc) =>
(1 to field.dbColumnCount).foreach {
cn =>
updatedWhat = updatedWhat + whereOrAnd + dbFunc(MapperRules.quoteColumnName.vend(field.dbColumnNames(field.name)(cn - 1)))+" "+opr+" "+
MapperRules.quoteColumnName.vend(otherField.dbColumnNames(otherField.name)(cn - 1))
}
case Cmp(field, opr, Empty, Empty, dbFunc) =>
(1 to field.dbColumnCount).foreach (cn => updatedWhat = updatedWhat + whereOrAnd + dbFunc(MapperRules.quoteColumnName.vend(field.dbColumnNames(field.name)(cn - 1)))+" "+opr+" ")
// For vals, add "AND $fieldname = ? [OR $fieldname = ?]*" to the query. The number
// of fields you add onto the query is equal to vals.length
case ByList(field, orgVals) =>
val vals = Set(orgVals :_*).toList // faster than list.removeDuplicates
if (vals.isEmpty) updatedWhat = updatedWhat + whereOrAnd + " 0 = 1 "
else updatedWhat = updatedWhat +
vals.map(v => MapperRules.quoteColumnName.vend(field._dbColumnNameLC)+ " = ?").mkString(whereOrAnd+" (", " OR ", ")")
case in: InRaw[A, _] =>
updatedWhat = updatedWhat + whereOrAnd + (in.rawSql match {
case null | "" => " 0 = 1 "
case sql => " "+MapperRules.quoteColumnName.vend(in.field._dbColumnNameLC)+" IN ( "+sql+" ) "
})
case (in: InThing[A]) =>
updatedWhat = updatedWhat + whereOrAnd +
MapperRules.quoteColumnName.vend(in.outerField._dbColumnNameLC)+in.inKeyword+
"("+in.innerMeta.addEndStuffs(in.innerMeta.addFields("SELECT "+
in.distinct+
MapperRules.quoteColumnName.vend(in.innerField._dbColumnNameLC)+
" FROM "+
MapperRules.quoteTableName.vend(in.innerMeta._dbTableNameLC)+" ",false,
in.queryParams, conn), in.queryParams, conn)._1+" ) "
// Executes a subquery with {@code query}
case BySql(query, _, _*) =>
updatedWhat = updatedWhat + whereOrAnd + " ( "+ query +" ) "
case _ =>
}
addFields(updatedWhat, wav, xs, conn)
}
}
}
private[mapper] def setStatementFields(st: PreparedStatement, by: List[QueryParam[A]], curPos: Int, conn: SuperConnection): Int = {
by match {
case Nil => curPos
case Cmp(field, _, Full(value), _, _) :: xs =>
setPreparedStatementValue(conn, st, curPos, field, field.targetSQLType, field.convertToJDBCFriendly(value), objectSetterFor(field))
setStatementFields(st, xs, curPos + 1, conn)
case ByList(field, orgVals) :: xs => {
val vals = Set(orgVals :_*).toList
var newPos = curPos
vals.foreach(v => {
setPreparedStatementValue(conn, st, newPos, field, field.targetSQLType, field.convertToJDBCFriendly(v), objectSetterFor(field))
newPos = newPos + 1
})
setStatementFields(st, xs, newPos, conn)
}
case (in: InThing[A]) :: xs =>
val newPos = in.innerMeta.setStatementFields(st, in.queryParams,
curPos, conn)
setStatementFields(st, xs, newPos, conn)
case BySql(query, who, params @ _*) :: xs => {
params.toList match {
case Nil => setStatementFields(st, xs, curPos, conn)
case List(i: Int) =>
st.setInt(curPos, i)
setStatementFields(st, xs, curPos + 1, conn)
case List(lo: Long) =>
st.setLong(curPos, lo)
setStatementFields(st, xs, curPos + 1, conn)
case List(s: String) =>
st.setString(curPos, s)
setStatementFields(st, xs, curPos + 1, conn)
// Allow specialization of time-related values based on the input parameter
case List(t: java.sql.Timestamp) =>
st.setTimestamp(curPos, t)
setStatementFields(st, xs, curPos + 1, conn)
case List(d: java.sql.Date) =>
st.setDate(curPos, d)
setStatementFields(st, xs, curPos + 1, conn)
case List(t: java.sql.Time) =>
st.setTime(curPos, t)
setStatementFields(st, xs, curPos + 1, conn)
// java.util.Date goes last, since it's a superclass of java.sql.{Date,Time,Timestamp}
case List(d: Date) =>
st.setTimestamp(curPos, new java.sql.Timestamp(d.getTime))
setStatementFields(st, xs, curPos + 1, conn)
case List(field: BaseMappedField) =>
setPreparedStatementValue(conn, st, curPos, field, field.targetSQLType, field.jdbcFriendly, objectSetterFor(field))
setStatementFields(st, xs, curPos + 1, conn)
case p :: ps =>
setStatementFields(st, BySql[A](query, who, p) :: BySql[A](query, who, ps: _*) :: xs, curPos, conn)
}
}
case _ :: xs => {
setStatementFields(st, xs, curPos, conn)
}
}
}
// def find(by: QueryParam): Box[A] = find(List(by))
private def _addOrdering(in: String, params: List[QueryParam[A]]): String = {
params.flatMap{
case OrderBy(field, order, nullOrder) => List(MapperRules.quoteColumnName.vend(field._dbColumnNameLC)+" "+order.sql+" "+(nullOrder.map(_.getSql).openOr("")))
case OrderBySql(sql, _) => List(sql)
case _ => Nil
} match {
case Nil => in
case xs => in + " ORDER BY "+xs.mkString(" , ")
}
}
protected def addEndStuffs(in: String, params: List[QueryParam[A]], conn: SuperConnection): (String, Box[Long], Box[Long]) = {
val tmp = _addOrdering(in, params)
val max = params.foldRight(Empty.asInstanceOf[Box[Long]]){(a,b) => a match {case MaxRows(n) => Full(n); case _ => b}}
val start = params.foldRight(Empty.asInstanceOf[Box[Long]]){(a,b) => a match {case StartAt(n) => Full(n); case _ => b}}
if (conn.brokenLimit_?) (tmp, start, max) else {
val ret = (max, start) match {
case (Full(max), Full(start)) => tmp + " LIMIT "+max+" OFFSET "+start
case (Full(max), _) => tmp + " LIMIT "+max
case (_, Full(start)) => tmp + " LIMIT "+conn.driverType.maxSelectLimit+" OFFSET "+start
case _ => tmp
}
(ret, Empty, Empty)
}
}
def delete_!(toDelete : A): Boolean =
toDelete match {
case x: MetaMapper[_] => throw new MapperException("Cannot delete the MetaMapper singleton")
case _ =>
thePrimaryKeyField.map(im =>
DB.use(toDelete.connectionIdentifier) {
conn =>
_beforeDelete(toDelete)
val ret = DB.prepareStatement("DELETE FROM "+MapperRules.quoteTableName.vend(_dbTableNameLC) +" WHERE "+im+" = ?", conn) {
st =>
val indVal = indexedField(toDelete)
indVal.map{indVal =>
setPreparedStatementValue(conn, st, 1, indVal, im, objectSetterFor(indVal))
st.executeUpdate == 1
} openOr false
}
_afterDelete(toDelete)
ret
}
).openOr(false)
}
type AnyBound = T forSome {type T}
private[mapper] def ??(meth: Method, inst: A) = meth.invoke(inst).asInstanceOf[MappedField[AnyBound, A]]
def dirty_?(toTest: A): Boolean = mappedFieldList.exists(
mft =>
??(mft.method, toTest).dirty_?
)
def indexedField(toSave: A): Box[MappedField[Any, A]] =
thePrimaryKeyField.map(im => ??(mappedColumns(im.toLowerCase), toSave))
def saved_?(toSave: A): Boolean =
toSave match {
case x: MetaMapper[_] => throw new MapperException("Cannot test the MetaMapper singleton for saved status")
case _ => toSave.persisted_?
}
/**
* This method will update the instance from JSON. It allows for
* attacks from untrusted JSON as it bypasses normal security. By
* default, the method is protected. You can write a proxy method
* to expose the functionality.
*/
protected def updateFromJSON_!(toUpdate: A, json: JsonAST.JObject): A = {
import JsonAST._
toUpdate.runSafe {
for {
field <- json.obj
meth <- _mappedFields.get(field.name)
} {
val f = ??(meth, toUpdate)
f.setFromAny(field.value)
}
}
toUpdate
}
/**
* This method will encode the instance as JSON. It may reveal
* data in fields that might otherwise be proprietary. It should
* be used with caution and only exposed as a public method
* after a security review.
*/
protected def encodeAsJSON_! (toEncode: A): JsonAST.JObject = {
toEncode.runSafe {
JsonAST.JObject(JsonAST.JField("$persisted",
JsonAST.JBool(toEncode.persisted_?)) ::
this.mappedFieldList.
flatMap(fh => ??(fh.method, toEncode).asJsonField))
}
}
/**
* Decode the fields from a JSON Object. Should the fields be marked as dirty?
*/
protected def decodeFromJSON_!(json: JsonAST.JObject, markFieldsAsDirty: Boolean): A = {
val ret: A = createInstance
import JsonAST._
ret.runSafe {
for {
field <- json.obj
JField("$persisted", JBool(per)) <- field
} ret.persisted_? = per
for {
field <- json.obj
meth <- _mappedFields.get(field.name)
} {
val f = ??(meth, ret)
f.setFromAny(field.value)
if (!markFieldsAsDirty) f.resetDirty
}
}
ret
}
def whatToSet(toSave : A) : String = {
mappedColumns.filter{c => ??(c._2, toSave).dirty_?}.map{c => c._1 + " = ?"}.toList.mkString("", ",", "")
}
/**
* Run the list of field validations, etc. This is the raw validation,
* without the notifications. This method can be over-ridden.
*/
protected def runValidationList(toValidate: A): List[FieldError] =
mappedFieldList.flatMap(f => ??(f.method, toValidate).validate) :::
validation.flatMap{
case pf: PartialFunction[A, List[FieldError]] =>
if (pf.isDefinedAt(toValidate)) pf(toValidate)
else Nil
case f => f(toValidate)
}
final def validate(toValidate: A): List[FieldError] = {
logger.debug("Validating dbName=%s, entity=%s".format(dbName, toValidate))
val saved_? = this.saved_?(toValidate)
_beforeValidation(toValidate)
if (saved_?) _beforeValidationOnUpdate(toValidate) else _beforeValidationOnCreate(toValidate)
val ret: List[FieldError] = runValidationList(toValidate)
_afterValidation(toValidate)
if (saved_?) _afterValidationOnUpdate(toValidate) else _afterValidationOnCreate(toValidate)
logger.debug("Validated dbName=%s, entity=%s, result=%s".format(dbName, toValidate, ret))
ret
}
val elemName = getClass.getSuperclass.getName.split("\\.").toList.last
def toXml(what: A): Elem =
Elem(null,elemName,
mappedFieldList.foldRight[MetaData](Null) {(p, md) => val fld = ??(p.method, what)
new UnprefixedAttribute(p.name, Text(fld.toString), md)}
,TopScope)
/**
* Returns true if none of the fields are dirty
*/
def clean_?(toCheck: A): Boolean = mappedColumns.foldLeft(true)((bool, ptr) => bool && !(??(ptr._2, toCheck).dirty_?))
/**
* Sets a prepared statement value based on the given MappedField's value
* and column name. This delegates to the BaseMappedField overload of
* setPreparedStatementValue by retrieving the necessary values.
*
* @param conn The connection for this prepared statement
* @param st The prepared statement
* @param index The index for this prepared statement value
* @param field The field corresponding to this prepared statement value
* @param columnName The column name to use to retrieve the type and value
* @param setObj A function that we can delegate to for setObject calls
*/
private def setPreparedStatementValue(conn: SuperConnection,
st: PreparedStatement,
index: Int,
field: MappedField[_, A],
columnName : String,
setObj : (PreparedStatement, Int, AnyRef, Int) => Unit) {
setPreparedStatementValue(conn, st, index, field,
field.targetSQLType(columnName),
field.jdbcFriendly(columnName),
setObj)
}
/**
* Sets a prepared statement value based on the given BaseMappedField's type and value. This
* allows us to do special handling based on the type in a central location.
*
* @param conn The connection for this prepared statement
* @param st The prepared statement
* @param index The index for this prepared statement value
* @param field The field corresponding to this prepared statement value
* @param columnType The JDBC SQL Type for this value
* @param value The value itself
* @param setObj A function that we can delegate to for setObject calls
*/
private def setPreparedStatementValue(conn: SuperConnection,
st: PreparedStatement,
index: Int,
field: BaseMappedField,
columnType : Int,
value : Object,
setObj : (PreparedStatement, Int, AnyRef, Int) => Unit) {
// Remap the type if the driver wants
val mappedColumnType = conn.driverType.columnTypeMap(columnType)
// We generally use setObject for everything, but we've found some broken JDBC drivers
// which has prompted us to use type-specific handling for certain types
mappedColumnType match {
case Types.VARCHAR =>
// Set a string with a simple guard for null values
st.setString(index, if (value ne null) value.toString else value.asInstanceOf[String])
// Sybase SQL Anywhere and DB2 choke on using setObject for boolean data
case Types.BOOLEAN => value match {
case intData : java.lang.Integer => st.setBoolean(index, intData.intValue != 0)
case b : java.lang.Boolean => st.setBoolean(index, b.booleanValue)
// If we can't figure it out, maybe the driver can
case other => setObj(st, index, other, mappedColumnType)
}
// In all other cases, delegate to the driver
case _ => setObj(st, index, value, mappedColumnType)
}
}
/**
* This is a utility method to simplify using setObject. It's intended use is to
* generate a setObject proxy so that the intermediate code doesn't need to be aware
* of drivers that ignore column types.
*/
private def objectSetterFor(field : BaseMappedField) = {
(st : PreparedStatement, index : Int, value : AnyRef, columnType : Int) => {
if (field.dbIgnoreSQLType_?) {
st.setObject(index, value)
} else {
st.setObject(index, value, columnType)
}
}
}
def save(toSave: A): Boolean = {
toSave match {
case x: MetaMapper[_] => throw new MapperException("Cannot save the MetaMapper singleton")
case _ =>
logger.debug("Saving dbName=%s, entity=%s".format(dbName, toSave))
/**
* @return true if there was exactly one row in the result set, false if not.
*/
def runAppliers(rs: ResultSet) : Boolean = {
try {
if (rs.next) {
val meta = rs.getMetaData
toSave.runSafe {
for {
indexMap <- thePrimaryKeyField
auto <- primaryKeyAutogenerated if auto
} {
findApplier(indexMap, rs.getObject(1)) match {
case Full(ap) => ap.apply(toSave, rs.getObject(1))
case _ =>
}
}
}
!rs.next
} else false
} finally {
rs.close
}
}
/**
* Checks whether the result set has exactly one row.
*/
def hasOneRow(rs: ResultSet) : Boolean = {
try {
val firstRow = rs.next
(firstRow && !rs.next)
} finally {
rs.close
}
}
if (saved_?(toSave) && clean_?(toSave)) true else {
val ret = DB.use(toSave.connectionIdentifier) {
conn =>
_beforeSave(toSave)
val ret = if (saved_?(toSave)) {
_beforeUpdate(toSave)
val ret: Boolean = if (!dirty_?(toSave)) true else {
val ret: Boolean = DB.prepareStatement("UPDATE "+MapperRules.quoteTableName.vend(_dbTableNameLC)+" SET "+whatToSet(toSave)+" WHERE "+thePrimaryKeyField.openOrThrowException("Cross your fingers") +" = ?", conn) {
st =>
var colNum = 1
// Here we apply each column's value to the prepared statement
for (col <- mappedColumns) {
val colVal = ??(col._2, toSave)
if (!columnPrimaryKey_?(col._1) && colVal.dirty_?) {
setPreparedStatementValue(conn, st, colNum, colVal, col._1, objectSetterFor(colVal))
colNum = colNum + 1
}
}
for {
indVal <- indexedField(toSave)
indexColumnName <- thePrimaryKeyField
} {
setPreparedStatementValue(conn, st, colNum, indVal, indexColumnName, objectSetterFor(indVal))
}
st.executeUpdate
true
}
ret
}
_afterUpdate(toSave)
ret
} else {
_beforeCreate(toSave)
val query = "INSERT INTO "+MapperRules.quoteTableName.vend(_dbTableNameLC)+" ("+columnNamesForInsert+") VALUES ("+columnQueriesForInsert+")"
def prepStat(st : PreparedStatement) {
var colNum = 1
for (col <- mappedColumns) {
if (!columnPrimaryKey_?(col._1)) {
val colVal = col._2.invoke(toSave).asInstanceOf[MappedField[AnyRef, A]]
setPreparedStatementValue(conn, st, colNum, colVal, col._1, objectSetterFor(colVal))
colNum = colNum + 1
}
}
}
// Figure out which columns are auto-generated
val generatedColumns = (mappedColumnInfo.filter(_._2.dbAutogenerated_?).map(_._1)).toList
val ret = conn.driverType.performInsert(conn, query, prepStat, MapperRules.quoteTableName.vend(_dbTableNameLC), generatedColumns) {
case Right(count) => count == 1
case Left(rs) => runAppliers(rs)
}
_afterCreate(toSave)
toSave.persisted_? = true
ret
}
_afterSave(toSave)
ret
}
// clear dirty and get rid of history
for (col <- mappedColumns) {
val colVal = ??(col._2, toSave)
if (!columnPrimaryKey_?(col._1) && colVal.dirty_?) {
colVal.resetDirty
colVal.doneWithSave
}
}
ret
}
}
}
/**
* This method returns true if the named column is the primary key and
* it is autogenerated
*/
def columnPrimaryKey_?(name: String) = mappedColumnInfo.get(name).map(c => (c.dbPrimaryKey_? && c.dbAutogenerated_?)) getOrElse false
def createInstances(dbId: ConnectionIdentifier, rs: ResultSet, start: Box[Long], omax: Box[Long]) : List[A] = createInstances(dbId, rs, start, omax, v => Full(v))
def createInstances[T](dbId: ConnectionIdentifier, rs: ResultSet, start: Box[Long], omax: Box[Long], f: A => Box[T]) : List[T] = {
var ret = new ListBuffer[T]
val bm = buildMapper(rs)
var pos = (start openOr 0L) * -1L
val max = omax openOr java.lang.Long.MAX_VALUE
while (pos < max && rs.next()) {
if (pos >= 0L) {
f(createInstance(dbId, rs, bm)).foreach(v => ret += v)
}
pos = pos + 1L
}
ret.toList
}
def appendFieldToStrings(in: A): String = mappedFieldList.map(p => ??(p.method, in).asString).mkString(",")
private val columnNameToMappee = new HashMap[String, Box[(ResultSet, Int, A) => Unit]]
def buildMapper(rs: ResultSet): List[Box[(ResultSet,Int,A) => Unit]] = columnNameToMappee.synchronized {
val meta = rs.getMetaData
val colCnt = meta.getColumnCount
for {
pos <- (1 to colCnt).toList
colName = meta.getColumnName(pos).toLowerCase
} yield
columnNameToMappee.get(colName) match {
case None =>
val colType = meta.getColumnType(pos)
Box(mappedColumns.get(colName)).flatMap{
fieldInfo =>
val setTo = {
val tField = fieldInfo.invoke(this).asInstanceOf[MappedField[AnyRef, A]]
Some(colType match {
case Types.INTEGER | Types.BIGINT => {
val bsl = tField.buildSetLongValue(fieldInfo, colName)
(rs: ResultSet, pos: Int, objInst: A) => bsl(objInst, rs.getLong(pos), rs.wasNull)}
case Types.VARCHAR => {
val bsl = tField.buildSetStringValue(fieldInfo, colName)
(rs: ResultSet, pos: Int, objInst: A) => bsl(objInst, rs.getString(pos))}
case Types.DATE | Types.TIME | Types.TIMESTAMP =>
val bsl = tField.buildSetDateValue(fieldInfo, colName)
(rs: ResultSet, pos: Int, objInst: A) => bsl(objInst, rs.getTimestamp(pos))