WIP on execution / SQLite integration tests
This commit is contained in:
54
src/main/kotlin/Document.kt
Normal file
54
src/main/kotlin/Document.kt
Normal file
@@ -0,0 +1,54 @@
|
||||
package solutions.bitbadger.documents
|
||||
|
||||
import java.sql.Connection
|
||||
import solutions.bitbadger.documents.query.Document
|
||||
|
||||
/**
|
||||
* Functions for manipulating documents
|
||||
*/
|
||||
object Document {
|
||||
|
||||
/**
|
||||
* Insert a new document
|
||||
*
|
||||
* @param tableName The table into which the document should be inserted (may include schema)
|
||||
* @param document The document to be inserted
|
||||
* @param conn The connection on which the query should be executed
|
||||
*/
|
||||
inline fun <reified TDoc> insert(tableName: String, document: TDoc, conn: Connection) {
|
||||
val strategy = Configuration.autoIdStrategy
|
||||
val query = if (strategy == AutoId.DISABLED) {
|
||||
Document.insert(tableName)
|
||||
} else {
|
||||
val idField = Configuration.idField
|
||||
val dialect = Configuration.dialect("Create auto-ID insert query")
|
||||
val dataParam = if (AutoId.needsAutoId(strategy, document, idField)) {
|
||||
when (strategy) {
|
||||
AutoId.NUMBER -> "(SELECT coalesce(max(data->>'$idField'), 0) + 1 FROM $tableName)"
|
||||
AutoId.UUID -> "'${AutoId.generateUUID()}'"
|
||||
AutoId.RANDOM_STRING -> "'${AutoId.generateRandomString()}'"
|
||||
else -> "(:data)->>'$idField'"
|
||||
}.let {
|
||||
when (dialect) {
|
||||
Dialect.POSTGRESQL -> ":data::jsonb || ('{\"$idField\":$it}')::jsonb"
|
||||
Dialect.SQLITE -> "json_set(:data, '$.$idField', $it)"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
":data"
|
||||
}
|
||||
|
||||
Document.insert(tableName).replace(":data", dataParam)
|
||||
}
|
||||
conn.customNonQuery(query, listOf(Parameters.json(":data", document)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a new document
|
||||
*
|
||||
* @param tableName The table into which the document should be inserted (may include schema)
|
||||
* @param document The document to be inserted
|
||||
*/
|
||||
inline fun <reified TDoc> insert(tableName: String, document: TDoc) =
|
||||
Configuration.dbConn().use { insert(tableName, document, it) }
|
||||
}
|
||||
Reference in New Issue
Block a user