2

For instance I have a set of queries:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].option
  result <- sql"<insert some data using entity>".update.run
} yield result

How NOT to insert some data, when entity is not found and raise error "entity does not exists"?

something like:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].option
  result <- entity  // Option[Entity]
    .fold(ConnectionIO.raiseError("entity does not exists"))  // ConnectionIO.raiseError does not compile
    (e => sql"<insert some data using entity>".update.run)
} yield result
Oleg
  • 899
  • 1
  • 8
  • 22

1 Answers1

6

Accordring to doc's in https://tpolecat.github.io/doobie/docs/04-Selecting.html you can use

.unique which returns a single value, raising an exception if there is not exactly one row returned.

So in your case solution would look like:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].unique
  result <- sql"<insert some data using entity>".update.run
} yield result

Hope this helps!

Ivan Kurchenko
  • 4,043
  • 1
  • 11
  • 28
  • How I can be sure, the query fails due nique condition, not other reasons? – Oleg Mar 18 '20 at 13:37
  • @Oleg As far as I understood from your question, you would like to execute `insert` operation ONLY if prev. select returns exactly one result in all other cases do not execute it all. Could you provide example of desired behavior in case of another errors, please? Thanks for your comment. – Ivan Kurchenko Mar 18 '20 at 13:44