Created
February 10, 2011 05:21
-
-
Save k4200/819993 to your computer and use it in GitHub Desktop.
Aggregate functions for Lift MetaMapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright Kazuo KASHIMA 2011 | |
* k4200 [at] kazu [dot] tv | |
* Licensed under the same license as Lift framework (Apache 2.0) | |
*/ | |
// Some methods used here are private[mapper], so I need to put these traits | |
// under net.liftweb.mapper. | |
package net.liftweb { | |
package mapper { | |
/** | |
* How to use this trait: | |
* | |
* object SomeModel extends SomeModel with LongKeyedMetaMapper[SomeModel] | |
* with AggregateFunctions[SomeModel] { | |
* //: | |
* } | |
*/ | |
trait AggregateFunctions[A<:Mapper[A]] { | |
self: A with MetaMapper[A] => | |
def max(field: SelectableField): Long = | |
aggregateDb(dbDefaultConnectionIdentifier, "max", field, Nil :_*) | |
def max(field: SelectableField, by: QueryParam[A]*): Long = | |
aggregateDb(dbDefaultConnectionIdentifier, "max", field, by :_*) | |
//TODO implement average, sum and others if need be. | |
protected def aggregateDb(dbId: ConnectionIdentifier, func: String, | |
field: SelectableField, by: QueryParam[A]*): Long = { | |
DB.use(dbId) { | |
conn => | |
val bl = by.toList ::: addlQueryParams.is | |
val (query, start, max) = | |
addEndStuffs(addFields("SELECT %s(%s) FROM %s " | |
.format(func, field.dbSelectString, | |
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 | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment