Skip to content

Instantly share code, notes, and snippets.

@CattenLinger
Created June 14, 2021 15:59
Show Gist options
  • Save CattenLinger/d49ef5c72af39daccd654f0699aab866 to your computer and use it in GitHub Desktop.
Save CattenLinger/d49ef5c72af39daccd654f0699aab866 to your computer and use it in GitHub Desktop.
Simple Kotlin Exposed transaction extension that executes string SQL queries.
/**
The SimpleQueryStatement enfoces the statement type to "SELECT". It's useful
when using some special sql querys, such as sqlite3 query 'PRAGMA database_list;'.
Usage:
Like `Transaction.exec()`
```
val someValue = transaction {
query("sql") {
//... do resultSet transformations here
}
}
```
*/
class SimpleQueryStatement<T>(private val sql : String, private val transform : (ResultSet) -> T?) : Statement<T>(StatementType.SELECT, emptyList()) {
override fun prepareSQL(transaction: Transaction) = sql
override fun arguments(): Iterable<Iterable<Pair<IColumnType, Any?>>> = emptyList()
override fun PreparedStatementApi.executeInternal(transaction: Transaction) : T? {
return executeQuery().use { transform(it) }
}
}
fun <T> Transaction.query(sql : String, transform : (ResultSet) -> T?) : T? = exec(SimpleQueryStatement(sql, transform))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment