Fix count tests; use types for varying comparison values

This commit is contained in:
2025-02-28 18:10:47 -05:00
parent a84c8289b1
commit e14fd23ead
6 changed files with 204 additions and 107 deletions

View File

@@ -3,7 +3,6 @@ package solutions.bitbadger.documents
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Types
/**
* Functions to assist with the creation and implementation of parameters for SQL queries
@@ -58,7 +57,7 @@ object Parameters {
*/
fun replaceNamesInQuery(query: String, parameters: Collection<Parameter<*>>) =
parameters.sortedByDescending { it.name.length }.fold(query) { acc, param -> acc.replace(param.name, "?") }
.also(::println)
/**
* Apply the given parameters to the given query, returning a prepared statement
*
@@ -69,6 +68,7 @@ object Parameters {
* @throws DocumentException If parameter names are invalid or number value types are invalid
*/
fun apply(conn: Connection, query: String, parameters: Collection<Parameter<*>>): PreparedStatement {
if (parameters.isEmpty()) return try {
conn.prepareStatement(query)
} catch (ex: SQLException) {
@@ -88,34 +88,9 @@ object Parameters {
replaceNamesInQuery(query, parameters)
.let { conn.prepareStatement(it) }
.also { stmt ->
replacements.sortedBy { it.first }.map { it.second }.forEachIndexed { index, param ->
val idx = index + 1
when (param.type) {
ParameterType.NUMBER -> {
when (param.value) {
null -> stmt.setNull(idx, Types.NULL)
is Byte -> stmt.setByte(idx, param.value)
is Short -> stmt.setShort(idx, param.value)
is Int -> stmt.setInt(idx, param.value)
is Long -> stmt.setLong(idx, param.value)
else -> throw DocumentException(
"Number parameter must be Byte, Short, Int, or Long " +
"(${param.value::class.simpleName})"
)
}
}
ParameterType.STRING -> {
when (param.value) {
null -> stmt.setNull(idx, Types.NULL)
is String -> stmt.setString(idx, param.value)
else -> stmt.setString(idx, param.value.toString())
}
}
ParameterType.JSON -> stmt.setObject(idx, param.value as String, Types.OTHER)
}
}
replacements.sortedBy { it.first }
.map { it.second }
.forEachIndexed { index, param -> param.bind(stmt, index + 1) }
}
} catch (ex: SQLException) {
throw DocumentException("Error creating query / binding parameters: ${ex.message}", ex)