mitrakov

Slick: Boolean values

Jan 22nd, 2018 (edited)
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.22 KB | None | 0 0
  1. // 1. Let's add some data with ambiguous Boolean values (-1, 0, 1, 2)
  2. INSERT INTO `faculty` (`name`, `isArts`) VALUES
  3.   ('mathematics', 0),
  4.   ('biologic', 1),
  5.   ('physics', 0),
  6.   ('phylology', 2),
  7.   ('historical', -1);
  8.  
  9.  
  10.  
  11. // 2. Now create a DAO
  12. import javax.inject.Inject
  13. import scala.concurrent.Future
  14.  
  15. import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
  16. import play.db.NamedDatabase
  17. import slick.jdbc.JdbcProfile
  18. import slick.lifted.ProvenShape
  19.  
  20. case class Faculty(facultyId: Option[Long], name: String, isArts: Boolean)
  21.  
  22. class FacultyDao @Inject() (
  23.     @NamedDatabase("students") val dbConfigProvider: DatabaseConfigProvider
  24.   ) extends HasDatabaseConfigProvider[JdbcProfile] {
  25.  
  26.   import profile.api._
  27.  
  28.   private class FacultyTable(tag: Tag) extends Table[Faculty](tag, "faculty") {
  29.     def facultyId: Rep[Long] = column[Long]("faculty_id", O.PrimaryKey, O.AutoInc)
  30.     def name: Rep[String] = column[String]("name")
  31.     def isArts: Rep[Boolean] = column[Boolean]("isArts")
  32.  
  33.     override def * : ProvenShape[Faculty] = (facultyId.?, name, isArts) <> (Faculty.tupled, Faculty.unapply)
  34.   }
  35.  
  36.   private lazy val table = TableQuery[FacultyTable]
  37.  
  38.   def getAll: Future[Seq[Faculty]] = {
  39.     val query = table.result
  40.     println(query.statements.mkString)
  41.     db.run(query)
  42.   }
  43. }
  44.  
  45.  
  46.  
  47. // 3. Now inject this DAO to our controller:
  48. import javax.inject.Inject
  49. import scala.concurrent.ExecutionContext
  50. import play.api.mvc._
  51. import dao.FacultyDao
  52.  
  53. class TestController @Inject()(
  54.     facultyDao: FacultyDao, cc: ControllerComponents)(implicit ec: ExecutionContext) extends AbstractController(cc) {
  55.  
  56.   // add to routes file: GET    /testBoolean    controllers.TestController.testBoolean
  57.   def testBoolean: Action[AnyContent] = Action.async {
  58.     facultyDao.getAll map { lst =>
  59.       Ok(s"Result:\n${lst.mkString("\n")}")
  60.     }
  61.   }
  62. }
  63.  
  64.  
  65.  
  66. // 4. Call endpoint and see the output:
  67. // select `faculty_id`, `name`, `isArts` from `faculty`
  68. //
  69. // Result:
  70. // Faculty(Some(1),mathematics,false)
  71. // Faculty(Some(2),biologic,true)
  72. // Faculty(Some(3),physics,false)
  73. // Faculty(Some(4),phylology,true)
  74. // Faculty(Some(5),historical,true)
  75.  
  76. // Summary: Boolean is a C-style: 0 = false, !0 = true
Add Comment
Please, Sign In to add comment