Exposed icon indicating copy to clipboard operation
Exposed copied to clipboard

BatchInsertStatement.removeLastBatch() throws NoSuchElementException when only one batch has been added

Open tsushanth opened this issue 4 months ago • 1 comments

Description

BatchInsertStatement.removeLastBatch() throws java.util.NoSuchElementException: List is empty. when it is called after exactly one batch has been added (i.e. when data will be empty after the removal).

Location

exposed-core/src/main/kotlin/org/jetbrains/exposed/v1/core/statements/BatchInsertStatement.kt, removeLastBatch():

fun removeLastBatch() {
    data.removeAt(data.size - 1)   // data is now empty when only 1 batch existed
    allColumnsInDataSet.clear()
    data.flatMapTo(allColumnsInDataSet) { it.keys }
    values.clear()
    values.putAll(data.last())     // ← throws NoSuchElementException on empty list
    arguments = null
    hasBatchedValues = data.isNotEmpty()
}

kotlin.collections.last() throws NoSuchElementException on an empty list instead of giving the caller a descriptive error or a no-op.

Reproduction

transaction {
    val stmt = BatchInsertStatement(MyTable)
    stmt[MyTable.name] = "first"
    stmt.addBatch()          // data.size == 1
    stmt.removeLastBatch()   // crashes: java.util.NoSuchElementException: List is empty.
}

The production call-site in Queries.kt guards with notTheFirstBatch (data.size > 1), so the internal batch-insert helper is never affected. But removeLastBatch() is a public API and any caller that removes the sole remaining batch hits this.

Expected behaviour

Either a no-op / clean empty state (values cleared, hasBatchedValues = false), or a descriptive BatchDataInconsistentException.

Suggested fix

fun removeLastBatch() {
    data.removeAt(data.size - 1)
    allColumnsInDataSet.clear()
    data.flatMapTo(allColumnsInDataSet) { it.keys }
    values.clear()
    data.lastOrNull()?.let { values.putAll(it) }   // guard against empty list
    arguments = null
    hasBatchedValues = data.isNotEmpty()
}

tsushanth avatar Jul 20 '26 20:07 tsushanth

Hi! I’d like to work on this issue if it’s still available.

I’ve reproduced the problem locally and I’m preparing a minimal fix with a regression test. I’ll open a PR once it’s ready.

cfcromn avatar Jul 21 '26 08:07 cfcromn