Search code examples
scalascalaquery

Select * or Equivalent in Scala Query


I've got this ScalaQuery model in Playframework 2

object User {
    implicit object UserFormat extends Format[User] {
    def reads(json: JsValue) : User = User(
        None,
        (json \ "firstName").as[String],
        (json \ "lastName").as[String],
        (json \ "email").as[String]
    )

    def writes(user: User) : JsValue = JsObject(Seq(
        "firstName" -> JsString(user.firstName),
        "lastName" -> JsString(user.lastName),
        "email" -> JsString(user.email))
    )
    }
}

object UsersTable extends Table[User]("users") {
    def id = column[Long]("USER_ID", O.PrimaryKey, O.AutoInc)
    def fName = column[String]("USER_FIRSTNAME", O.NotNull)
    def lName= column[String]("USER_LASTNAME", O.NotNull)
    def email = column[String]("USER_EMAIL", O.NotNull)

    def user_email_idx = index("user_email_idx", email, unique = true)

    def * =  id.? ~ fName ~ lName ~ email <> (User.apply _, User.unapply _)
    def forInsert = fName ~ lName ~ email <> ({ (f, l, e) => User(None, f, l, e) }, { u:User => Some((u.firstName, u.lastName, u.email)) })
}

I'd like to perform a Select * and return all the rows in UsersTable. Is it possible to do this using the UsersTable projection? I've seen some examples that look like this

        UsersTable.where(_.fName startsWith "H").list 

to select rows that fit a criteria. How do I do this without passing in any of that?

Thanks!


Solution

  • All you should need to do is this:

    val query = for(r <- MyTable) yield r
    val results = query.list
    

    The first line creates the actual query object that represents something like select * from MyTable, and the second line actual invokes that and loads the results into memory.

    The important implicits you might want to know about are tableToQuery, which lets the MyTable have for-comprehensions on it; and queryToQueryInvoker, which pimps the query so that it has methods like list.

    Alternatively you should be able to do something like

    val query: Query[User] = MyTable
    

    which should use the tableToQuery implicit to satisfy the type requirement.