Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.00 KB | None | 0 0
  1. package models
  2.  
  3. import java.sql.Date
  4. import scala.slick.driver.PostgresDriver.simple._
  5. import play.api.Play.current
  6.  
  7. case class Question(id: Option[Int] = None, title: String, body: String,
  8.                     creationDate: Date, link: String, tags: String)
  9.  
  10. class QuestionTable(tag: Tag) extends Table[Question](tag, "question") {
  11.   // Auto Increment the id primary key column
  12.   def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  13.   def title = column[String]("title")
  14.   def body = column[String]("body")
  15.   def creationDate = column[Date]("creationDate")
  16.   def link = column[String]("link")
  17.   def tags = column[String]("tags")
  18.   // the * projection (e.g. select * ...) auto-transforms the tupled
  19.   // column values to / from a Configuration
  20.   def * = (id.?, title, body, creationDate, link, tags) <> (Question.tupled, Question.unapply)
  21. }
  22.  
  23. /**
  24.  * Helper for pagination.
  25.  */
  26. case class Page[A](items: Seq[A], page: Int, offset: Int, total: Int) {
  27.   lazy val prev = Option(page - 1).filter(_ >= 0)
  28.   lazy val next = Option(page + 1).filter(_ => (offset + items.size) < total)
  29. }
  30.  
  31. object QuestionTable {
  32.   val db = play.api.db.slick.DB
  33.   val questions = TableQuery[QuestionTable]
  34.   def findById(id: Int): Question = db.withSession{ implicit session =>
  35.     questions.filter(_.id === id).first
  36.   }
  37.   def update(updateQuestion: Question) = db.withTransaction{ implicit session =>
  38.     questions.filter(_.id === updateQuestion.id).update(updateQuestion)
  39.   }
  40.   def listQuestions: List[Question] = db.withSession { implicit session =>
  41.     questions.sortBy(_.id.asc.nullsFirst).list
  42.   }
  43.   def getQuestionsWithTags(filter : String): List[Question] = db.withSession { implicit session =>
  44.     questions.filter(_.tags.like(filter,'%')).list
  45.   }
  46.   def list(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Page[(Question)] = {
  47.     val offset = pageSize * page
  48.     val questionsReturned = this.getQuestionsWithTags(filter)
  49.  
  50.     Page(questionsReturned,page,offset,questionsReturned.size)
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement