sss.openstar.message.storeservice.MessagePersist.scala Maven / Gradle / Ivy
package sss.openstar.message.storeservice
import sss.ancillary.Guid
import sss.db._
import sss.openstar.schemamigration.SqlSchemaNames.ColumnNames._
import sss.openstar.message._
import sss.db.ops.DbOps.DbRunOps
import sss.openstar.schemamigration.SqlSchemaNames.TableNames.messagesTableName
/**
* Created by alan on 6/6/16.
*/
object MessagePersist {
private object MsgStatus extends Enumeration {
type MsgStatus = Value
val Pending = Value(0)
val Accepted = Value(1)
val Rejected = Value(2)
}
}
class MessagePersist(implicit val db: Db) {
import MessagePersist.MsgStatus._
lazy private val table = db.table(messagesTableName)
private def toMsg(r: Row): Message = Message(
r.arrayByte(messagePayloadCol).toMessagePayload,
Guid(r.arrayByte(uniqueCol)),
r.arrayByteOpt(parentUniqueCol) map Guid.apply
)
def pending(to: String,
guid: Guid,
parentGuid: Option[Guid],
msgPayload: MessagePayload): Message = {
val row = table.insert(Map(
toCol -> to,
messagePayloadCol -> msgPayload.toBytes,
statusCol -> Pending.id,
uniqueCol -> guid.value,
parentUniqueCol -> parentGuid.map(_.value.toArray)
)
).dbRunSyncGet
toMsg(row)
}
def accept(to: String, guid: Guid): Unit = {
table.update(
Map(
statusCol -> Accepted.id
),
where(
uniqueCol -> guid.value,
toCol -> to
)
).dbRunSyncGet
}
def reject(to: String, guid: Guid): Boolean =
table
.delete(
where(
uniqueCol -> guid.value,
toCol -> to
)
).dbRunSyncGet == 1
def page(mostRecent: Long, to: String, pageSize: Int): Seq[(Message, Long)] = {
table
.map(r => (
toMsg(r), r.id),
where(s"$idCol > ?", mostRecent)
and where(
statusCol -> Accepted.id,
toCol -> to
)
orderAsc idCol
limit pageSize
)
}.dbRunSyncGet
def delete(to: String, guid: Guid): Boolean =
table.delete(
where(
uniqueCol -> guid.value,
toCol -> to
)
).dbRunSyncGet == 1
}