Skip to content

Commit

Permalink
#432 Can't seem to supply my own id for idtables
Browse files Browse the repository at this point in the history
  • Loading branch information
Tapac committed Feb 9, 2019
1 parent d3987ac commit 2c2f47d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ open class InsertStatement<Key:Any>(val table: Table, val isIgnore: Boolean = fa
@Deprecated("Will be made internal on the next releases")
open val generatedKey: Key? get() = autoIncColumns.firstOrNull()?.let { get(it) } as Key?

infix operator fun <T> get(column: Column<T>): T? = resultedValues?.get(0)?.tryGet(column)
?: if (!isIgnore) error("No key generated") else null
infix operator fun <T> get(column: Column<T>): T? {
val row = resultedValues?.get(0)
if (row == null && !isIgnore) error("No key generated")
return row?.tryGet(column)
}

private fun processResults(rs: ResultSet?, inserted: Int): List<ResultRow> {
val autoGeneratedKeys = arrayListOf<MutableMap<Column<*>, Any>>()
val autoGeneratedKeys = arrayListOf<MutableMap<Column<*>, Any?>>()

if (inserted > 0) {
val firstAutoIncColumn = autoIncColumns.firstOrNull()
Expand Down Expand Up @@ -58,16 +61,12 @@ open class InsertStatement<Key:Any>(val table: Table, val isIgnore: Boolean = fa
}

arguments!!.forEachIndexed { itemIndx, pairs ->
val map = autoGeneratedKeys.getOrNull(itemIndx) ?: hashMapOf<Column<*>, Any?>().apply {
autoGeneratedKeys.add(itemIndx, this)
}
pairs.forEach { (col, value) ->
if (!col.columnType.isAutoInc) {
val map = autoGeneratedKeys.getOrElse(itemIndx) {
hashMapOf<Column<*>, Any>().apply {
autoGeneratedKeys.add(itemIndx, this)
}
}
if (col.defaultValueFun != null && value != null/* && data[itemIndx][col] == null*/) {
map[col] = value
}
if (!col.columnType.isAutoInc && value != DefaultValueMarker) {
map[col] = value
}
}
}
Expand Down
19 changes: 19 additions & 0 deletions src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/DMLTests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1763,6 +1763,25 @@ class DMLTests : DatabaseTestsBase() {
println(result)
}
}

@Test fun testInsertWithPredefinedId() {
val stringTable = object : IdTable<String>("stringTable") {
override val id = varchar("id", 15).entityId()
val name = varchar("name", 10)
}
withTables(stringTable) {
val entityID = EntityID("id1", stringTable)
val id = stringTable.insertAndGetId {
it[id] = entityID
it[name] = "foo"
}

assertEquals(id, entityID)
val row1 = stringTable.select { stringTable.id eq entityID }.singleOrNull()
assertNotNull(row1)
assertEquals(row1[stringTable.id], entityID)
}
}
}

private val today: DateTime = DateTime.now().withTimeAtStartOfDay()
Expand Down

0 comments on commit 2c2f47d

Please sign in to comment.