Kotlin/PostgreSQL query returning only last row when expected all rows with selected id

Viewed 132

I am working for the first time with Kotlin and functional programming. I have a piece of code where I expected that the query would return all the rows from the DB where the id matches the selected id. In my case I have a consigment table where one of the columns is order_id. I am trying to get all rows with specific order_id like this:

val consignmentIdsV = orderIdsV.validFlatMap { validateMoveOrder(ctx, it.second) }.named("consignmentId")

Where validateMoveOrder looks like this:

private fun validateMoveOrder(ctx: Ctx, orderIds: List<Long>): Validated<Err, List<Long>> =
    fetchRows(ctx, "select c.id, c.state, c.slot_id from consignment c where order_id = any(:orderIds)", mapOf("orderIds" to orderIds))
        .map {
          return if (consignmentCanBeMoved.contains(ConsignmentState.byName(it["state"] as String)) && it["slotId"] == null)
            listOf(it["id"].toString().toLong()).valid()
          else
            SErr(GlowErrs.ORDER_CANNOT_BE_MOVED, "Order ${it["id"]} cannot be moved").invalid()
        }.joinInvalid()

But, this is currently not working. In my case when I have few consigments (3 to be more specific) with the same order_id, I get only the last row as a result. Why am I not getting all 3 rows as expected?

1 Answers

It looks like you're returning a list with only one item if your condition is met. You need to collect all items before returning the list. My pseudo code would look a little different as I would use filter() instead of map():

return fetchRows(...)
.filter(...)
.toList()
Related