Created
May 15, 2015 15:56
-
-
Save d6y/56d982cadb609f91d1fc to your computer and use it in GitHub Desktop.
Flags (for Slick 3.0)
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
import slick.driver.H2Driver.api._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Await | |
import scala.concurrent.duration._ | |
object EnrichExample extends App { | |
sealed case class Flag(val value: Boolean) | |
object Flag { | |
val True: Flag = Flag(true) | |
val False: Flag = Flag(false) | |
} | |
implicit val flagMapper = MappedColumnType.base[Flag, Boolean](_.value, Flag.apply) | |
case class Message(content: String, important: Option[Flag] = None) | |
class MessageTable(tag: Tag) extends Table[Message](tag, "message") { | |
def content = column[String]("content") | |
def important = column[Option[Flag]]("important") | |
def * = (content, important) <> (Message.tupled, Message.unapply) | |
} | |
lazy val messages = TableQuery[MessageTable] | |
def testData = Seq( | |
Message("First!"), | |
Message("Party details", Some(Flag.True)), | |
Message("Timesheet reminder", Some(Flag.False)) | |
) | |
import scala.language.higherKinds | |
implicit class QueryEnrichment[M,U,C[_]](q: Query[M,U,C]) { | |
def notFlagged(selector: M => Rep[Option[Flag]]): Query[M,U,C] = | |
q.filter(t => selector(t).isEmpty || selector(t) === Flag.False) | |
} | |
val prog = for { | |
_ <- messages.schema.create | |
_ <- messages ++= testData | |
msgs <- messages.notFlagged(_.important).result | |
} yield msgs | |
val db = Database.forConfig("h2chapter01") | |
val msgs = db.run(prog).map { _ foreach println } | |
Await.result(msgs, 2 seconds) | |
db.close | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment