kushalp
09/19/2019, 10:44 AMUPSERT
implementation in one of the GitHub issues so that it returns the existing row if it's present:
fun <T : Table> T.insertOrReturn(key: Column<*>, body: T.(InsertStatement<Number>) -> Unit) =
InsertOrReturn<Number>(this, key = key).apply {
body(this)
execute(TransactionManager.current())
}
class InsertOrReturn<Key : Any>(
table: Table,
isIgnore: Boolean = false,
private val key: Column<*>
) : InsertStatement<Key>(table, isIgnore) {
override fun prepareSQL(transaction: Transaction): String {
val tm = TransactionManager.current()
val keyIdentity = tm.identity(key)
val onConflict = "ON CONFLICT ($keyIdentity) DO UPDATE SET $keyIdentity = EXCLUDED.$keyIdentity"
return "${super.prepareSQL(transaction)} $onConflict RETURNING *"
}
}
I'm using this as follows:
val insertedCustomerRecord = Customers.insertOrReturn(Customers.uniqueId) {
it[uniqueId] = record.uniqueId
it[name] = record.name
it[dateOfBirth] = record.dateOfBirth
}