Last active
December 6, 2017 08:24
-
-
Save oshai/9b58cf3365257c9324fa4dcccb2481b2 to your computer and use it in GitHub Desktop.
The update or insert definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun execute(cities: List<City>) { | |
transaction { | |
Cities.batchInsertOnDuplicateKeyUpdate( cities, listOf(id, name) ) { batch, city -> | |
batch[Cities.id] = city.id | |
batch[Cities.name] = city.name | |
} | |
} | |
} | |
// The below code is just a copy-paste that should actually be in the lib | |
class BatchInsertUpdateOnDuplicate(table: Table, val onDupUpdate: List<Column<*>>) : BatchInsertStatement(table, false) { | |
override fun prepareSQL(transaction: Transaction): String { | |
val onUpdateSQL = if (onDupUpdate.isNotEmpty()) { | |
" ON DUPLICATE KEY UPDATE " + onDupUpdate.joinToString { "${transaction.identity(it)}=VALUES(${transaction.identity(it)})" } | |
} else "" | |
return super.prepareSQL(transaction) + onUpdateSQL | |
} | |
} | |
fun <T : Table, E> T.batchInsertOnDuplicateKeyUpdate(data: List<E>, onDupUpdateColumns: List<Column<*>>, body: T.(BatchInsertUpdateOnDuplicate, E) -> Unit) { | |
data. | |
takeIf { it.isNotEmpty() }?. | |
let { | |
val insert = BatchInsertUpdateOnDuplicate(this, onDupUpdateColumns) | |
data.forEach { | |
insert.addBatch() | |
body(insert, it) | |
} | |
TransactionManager.current().exec(insert) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment