SELECT and then return the result or insert the new row and then return the result

31 перегляд
Перейти до першого непрочитаного повідомлення

Eugene Dzhurinsky

не прочитано,
1 трав. 2017 р., 20:05:1901.05.17
Кому: Slick / ScalaQuery
Hello!

I'm pretty new to Slick, and I am trying to figure out what would be the best way to combine SELECT and INSERT actions w/o an external execution context, to resemble this:
- SELECT something FROM table1 JOIN table 2 .....
- if there is a record - then return the wrapped case class
- if there is no record - then create a new case class instance and insert it into the database, then return the newly created object

I guess that I can implement that with the map/flatMap and collect, but those require the execution context passed from external, and I don't really want to pollute my DAO metods with the context, I need to return just an instance of Future[X]

Thanks!

Eugene Dzhurinsky

не прочитано,
1 трав. 2017 р., 20:53:0001.05.17
Кому: Slick / ScalaQuery
So far I've got something like:

      override def findCredentialsOrRegister(oauthCredentials: OAuth): Future[User] = {


        val userFound
= (for (
          creds
oauthTable.filter(x x.service === oauthCredentials.service && x.serviceId === oauthCredentials.serviceId);
          user
userTable.filter(x x.username === creds.username)
       
) yield user).result




        val authenticate
= userFound.flatMap {
         
case Seq(user)
            DBIO
.from(Future.successful(user))
         
case Seq()
            val newUUID
= UUID.randomUUID
            val user
= User(newUUID.toString, UUID.randomUUID().toString, Instant.now())
            DBIO
.seq(
              userTable
+= user,
              oauthTable
+= oauthCredentials.copy(username = newUUID.toString)
           
) andThen DBIO.from(Future.successful(user))
       
}


        db
.run(authenticate)
     
}


Doesn't really seem to be a clean & idiomatic solution.

Відповісти всім
Відповісти автору
Переслати
0 нових повідомлень