'Kotlin - updating DB rows happening asynchronously instead of synchronously

I am using Kotlin in my legacy project. I have a function where I am running an update to DB and then fetching updated rows and sending them as a response:

internal fun addEvent(
    ctx: Ctx,
    eventType: EventType,
    packageIds: List<Long>,
    terminalId: Long? = null
): Either<Failure, FlatResp> = either.eager {
  runInTransactionWithEither(ctx) { tx ->
    val txCtx = ctx.copy(dbSession = tx)
    either.eager {
      updatePackageState(txCtx, packageIds, eventType).bind()
      insertEvent(txCtx, packageIds, eventType, terminalId).bind()
    }
  }
  createResponse(ctx, packageIds).bind()
}

private fun createResponse(ctx: Ctx, packageIds: List<Long>): Either<Failure, FlatResp> = either.eager {
      val packagesResult = toFlatRespUsingFlatRespName(
          commandQueryFor(ctx) { queryBackend(ctx,"packages", jsonObject("packageIds" to packageIds.toJsonArray())) }.bind()
      )
      val events = commandQueryFor(ctx) { getEvents(it, packageIds) }.bind()
      packagesResult.mergeFlatResps(events)

The problem I have is that I can see that updatePackageState is called first here in order, but SQL or an actual change in DB is executed only after createResponse has been called and returned a response. I am therefor not getting an updated result. I don't understand why is an update in DB executed after createResponse function when updatePackageState was called first. This is how updatePackageState looks like:

private fun updatePackageState(ctx: Ctx, packageIds: List<Long>, packageState: EventType): Either<Failure, Int> =
    update(
        ctx, updateSql, mapOf(
        "updated_by" to ctx.userId,
        "packageIds" to packageIds,
        "state" to packageState.name
    ))

@Language("PostgreSQL")
private const val updateSql = """
  UPDATE public.package
  SET
    state = :state,
    updated_at = now(),
    updated_by = :updated_by
  WHERE
    id = any(: packageIds)"""

And this is an update function:

fun update(ctx: WithSessionOrDataSource, updateSql: String, values: Map<String, Any?>): Either<Failure, Int> = try {
  runInSession(ctx) { session ->
    session.run(queryOf(updateSql, jdbcConvert(session, values)).asUpdate)
  }.right()
} catch (e: PSQLException) {
  mapSqlErrors(e)
}

I thought the update was synchronous and that everything will be executed in order, so that is why don't understand why rows in DB are update after createResponse. What should I do here, how can I fix this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source