Here's my code. It permits to create typesafe MongoDB queries using Casbah
trait TypesafeQuery[ObjectType, BuildType] {
def build: BuildType
}
trait TypesafeMongoQuery[ObjectType] extends TypesafeQuery[ObjectType, DBObject]
case class TypesafeMongoQueryConjunction[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) extends TypesafeMongoQuery[ObjectType] {
override def build(): DBObject = $and(queries.map(_.build))
}
case class TypesafeMongoQueryDisjunction[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) extends TypesafeMongoQuery[ObjectType] {
override def build(): DBObject = $or(queries.map(_.build))
}
object TypesafeMongoQuery {
// TODO could probably be reworked? see https://mcmap.net/q/1501968/-best-way-to-create-a-mongo-expression-that-never-matches
val AlwaysMatchingQuery: DBObject = $()
val NeverMatchingQuery: DBObject = $and($("_id" -> 1), $("_id" -> -1))
def AlwaysMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = AlwaysMatchingQuery }
def NeverMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = NeverMatchingQuery }
def and[ObjectType](queries: TypesafeMongoQuery[ObjectType]*) = TypesafeMongoQueryConjunction(queries)
def or[ObjectType](queries: TypesafeMongoQuery[ObjectType]*) = TypesafeMongoQueryDisjunction(queries)
// TODO maybe define Scalaz Monoids
def foldAnd[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) = {
queries.foldLeft(AlwaysMatchingTypesafeQuery[ObjectType]) { (currentQuery, queryInList) =>
TypesafeMongoQuery.and(currentQuery, queryInList)
}
}
def foldOr[ObjectType](base: TypesafeMongoQuery[ObjectType], queries: Seq[TypesafeMongoQuery[ObjectType]]) = {
queries.foldLeft(NeverMatchingTypesafeQuery[ObjectType]) { (currentQuery, queryInList) =>
TypesafeMongoQuery.or(currentQuery, queryInList)
}
}
}
It works fine, except I'm not satisfied with these lines:
def AlwaysMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = AlwaysMatchingQuery }
def NeverMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = NeverMatchingQuery }
I think It would be possible to not create a new instance of these 2 objects for each folding operation, but rather using a val / singleton of type TypesafeMongoQuery[Nothing]
since the underlying DBObject being built would always be the same.
I've tried some things, like replacing my signatures everywhere by [ObjectType,T <% ObjectType]
but with no great success.
Any idea on how to solve my problem?