Search code examples
scaladoobie

How to raise error while composing ConnectionIO?


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

Solution

  • 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!