/db/src/main/scala/uk/co/randomcoding/partsdb/db/mongo/MongoDbAccess.scala

https://github.com/jmrowe/PartsDbWebApp · Scala · 115 lines · 20 code · 7 blank · 88 comment · 0 complexity · de9d58f521c433e35b8d500ac3230cb1 MD5 · raw file

  1. /**
  2. *
  3. */
  4. package uk.co.randomcoding.partsdb.db.mongo
  5. import scala.collection.mutable.{ Map => MMap }
  6. import com.mongodb.casbah.Imports._
  7. import uk.co.randomcoding.partsdb.db.DbAccess
  8. import uk.co.randomcoding.partsdb.db.mongo.MongoConverters._
  9. import net.liftweb.common.Logger
  10. /**
  11. * Provides access to stored items in a MongoDB Collection
  12. *
  13. * @constructor Creates a new instance of this access object. Should be called from the companion object
  14. * @author RandomCoder <randomcoder@randomcoding.co.uk>
  15. *
  16. */
  17. class MongoDbAccess(val mongoCollection: MongoCollection) extends DbAccess with Logger {
  18. override def add[T <: AnyRef](t: T): Unit = {
  19. val dbo: DBObject = t
  20. mongoCollection += dbo
  21. }
  22. /*private val incrementUniqueId = (currentId: Long) => {
  23. val newIdObject = MongoDBObject("uniqueId" -> (currentId + 1))
  24. val findIdObjectQuery = "uniqueId" $exists true
  25. mongoCollection.findOne(findIdObjectQuery) match {
  26. case None => mongoCollection += newIdObject
  27. case _ => mongoCollection.findAndModify(findIdObjectQuery, newIdObject)
  28. }
  29. }
  30. val idQuery = "uniqueId" $exists true
  31. */
  32. /**
  33. * Gets the next value for the unique id.
  34. *
  35. * This also increments the current value that is stored in the database
  36. */ /*
  37. override def nextId(): Long = {
  38. val findOneQuery = mongoCollection.findOne(idQuery)
  39. val idValue = findOneQuery match {
  40. case None => {
  41. 0
  42. }
  43. case Some(v) => {
  44. v.as[Long]("uniqueId")
  45. }
  46. }
  47. incrementUniqueId(idValue)
  48. idValue
  49. }
  50. private val addressQuery = (addressId: AddressId) => MongoDBObject("addressId" -> MongoDBObject("id" -> addressId.id))
  51. private val addressesQuery = () => "addressId" $exists true
  52. override def addresses: Set[Address] = {
  53. val results = for (result <- mongoCollection.find(addressesQuery()).toSet[DBObject]) yield {
  54. val address: Address = convertFromMongoDbObject[Address](result)
  55. address
  56. }
  57. debug("Got addresses: %s".format(results.mkString("[", ", ", "]")))
  58. results
  59. }
  60. override def address(id: AddressId): Option[Address] = {
  61. val addresses = for (result <- mongoCollection.findOne(addressQuery(id)).toList) yield {
  62. val address: Address = convertFromMongoDbObject[Address](result)
  63. address
  64. }
  65. addresses match {
  66. case Nil => None
  67. case head :: Nil => Some(head)
  68. case head :: _ => {
  69. warn("Query for address with id %s returned %d results:\n%s.\n\nReturning first value as result".format(id, addresses.size, addresses.mkString("[", ", ", "]")))
  70. Some(head)
  71. }
  72. }
  73. }*/
  74. }
  75. /**
  76. * Factory for [[uk.co.randomcoding.partsdb.db.mongo.MongoDBAccess]] instances
  77. *
  78. * == Sample ==
  79. * {{{
  80. * val access = MongoDBAccess("test-db", "test-collection")
  81. * }}}
  82. * Will create an instance of the access class using the collection '''test-collection''' from the database '''test-db'''.
  83. *
  84. * If the database and/or collection do not exist, then I believe MongoDB will create them for you.
  85. */
  86. object MongoDbAccess {
  87. import scala.collection.mutable.{ Map => MMap }
  88. private val accessObjects = MMap.empty[String, MongoDbAccess].withDefault(key => {
  89. val parts = key.split(":")
  90. new MongoDbAccess(MongoConfig.getCollection(parts(0), parts(1)))
  91. })
  92. /**
  93. * Get the instance of an [[uk.co.randomcoding.partsdb.db.mongo.MongoDBAccess]] object for the given collection within the database
  94. *
  95. * @param dbName The name of the database to connect to
  96. * @param collectionName The name of the collection to connect to
  97. * @return The instance of the MongoDbAccess object for the given collection and database
  98. */
  99. def apply(dbName: String, collectionName: String): MongoDbAccess = accessObjects("%s:%s".format(dbName, collectionName))
  100. }