fetch sql files and save Queries into List

This commit is contained in:
2019-06-05 17:02:25 +02:00
parent 81e46735df
commit 9b7d2ffa8c
6 changed files with 69 additions and 9 deletions

View File

@@ -5,6 +5,7 @@ import com.github.jasync.sql.db.postgresql.PostgreSQLConnection
import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder
import fr.postgresjson.entity.EntityI
import fr.postgresjson.serializer.Serializer
import java.io.File
class Connection(
@@ -12,11 +13,24 @@ class Connection(
private val port: Int = 5432,
private val database: String = "dc-project",
private val username: String = "dc-project",
private val password: String = "dc-project"
private val password: String = "dc-project",
queriesDirectory: File? = null
) {
private val queries = mutableMapOf<String, MutableMap<String, String>>()
private lateinit var connection: ConnectionPool<PostgreSQLConnection>
val serializer = Serializer()
init {
if (queriesDirectory === null) {
val resource = this::class.java.getResource("/sql/query")
if (resource !== null) {
fetchQueries(File(resource.toURI()))
}
} else {
fetchQueries(queriesDirectory)
}
}
fun connect(): ConnectionPool<PostgreSQLConnection> {
if (!::connection.isInitialized || !connection.isConnected()) {
connection = PostgreSQLConnectionBuilder.createConnectionPool(
@@ -26,7 +40,13 @@ class Connection(
return connection
}
inline fun <T, reified R : EntityI<T?>> selectOne(sql: String, values: List<Any?> = emptyList()): R? {
inline fun <T, reified R : EntityI<T?>?> selectOne(group: String, name: String, values: List<Any?> = emptyList()): R? {
val sql: String = getQuery(group, name)
return selectOne<T, R>(sql, values)
}
inline fun <T, reified R : EntityI<T?>?> selectOne(sql: String, values: List<Any?> = emptyList()): R? {
val future = connect().sendPreparedStatement(sql, values)
val json = future.get().rows[0].getString(0)
if (json === null) {
@@ -49,4 +69,24 @@ class Connection(
return obj
}
}
private fun fetchQueries(queriesDirectory: File) {
queriesDirectory.walk().filter{it.isDirectory}.forEach { directory ->
val group = directory.name
directory.walk().filter{it.isFile}.forEach { file ->
val sql = file.readText()
if (queries[group] === null) {
queries[group] = mutableMapOf()
}
queries[group]!![file.nameWithoutExtension] = sql
}
}
}
fun getQuery(group: String, name: String): String {
if (queries[group] === null || queries[group]!![name] === null) {
throw Exception("No query defined for $group/$name")
}
return queries[group]!![name]!!
}
}