-
Notifications
You must be signed in to change notification settings - Fork 2
/
DataAccess.kt
84 lines (73 loc) · 2.81 KB
/
DataAccess.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package net.minevn.libs.db
import net.minevn.libs.db.pool.DatabasePool
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Statement
import kotlin.reflect.KClass
import kotlin.reflect.cast
abstract class DataAccess {
lateinit var dbPool: DatabasePool
/**
* Initialize the PreparedStatement with the given SQL statement
*/
protected fun <R> String.statement(action: PreparedStatement.() -> R) =
statement(action, false)
/**
* Initialize the PreparedStatement with the given SQL statement, with the option to return generated keys
*/
protected fun <R> String.statementWithKey(action: PreparedStatement.() -> R) : R =
statement(action, true)
private fun <R> String.statement(action: PreparedStatement.() -> R, getGeneratedKey: Boolean) : R {
val transaction = getTransaction()
val isTransactional = transaction != null
val connection = transaction?.connection ?: dbPool.getConnection()
return try {
if (!getGeneratedKey) {
connection.prepareStatement(this).use { it.action() }
} else {
connection.prepareStatement(this, Statement.RETURN_GENERATED_KEYS).use { it.action() }
}
} finally {
if (!isTransactional) {
connection.close()
}
}
}
/**
* Process the ResultSet
*/
protected fun <R> PreparedStatement.fetch(action: ResultSet.() -> R) =
executeQuery().use { it.action() }
/**
* Iterate through all records in the ResultSet
*/
protected fun <R> PreparedStatement.fetchIterate(action: ResultSet.() -> R) =
fetch {
while (next()) {
action()
}
}
@Synchronized
protected fun PreparedStatement.update() = executeUpdate()
/**
* Map all records in the ResultSet to a list
*/
protected fun <R> PreparedStatement.fetchRecords(action: ResultSet.() -> R): List<R> =
fetch { generateSequence { if (next()) action() else null }.toList() }
}
class DataAccessPool(private val databaseConnection: DatabasePool, val loader: ClassLoader) {
private var instanceList = mutableMapOf<KClass<out DataAccess>, DataAccess>()
@Synchronized
fun <T : DataAccess> getInstance(type: KClass<T>): T {
val dbType = databaseConnection.getTypeName()
var instance = instanceList[type]
if (instance == null) {
val basePackage = type.java.`package`.name
val daoClass = Class.forName("$basePackage.$dbType.${type.simpleName}Impl", true, loader)
instance = type.cast(daoClass.getDeclaredConstructor().newInstance())
instance.dbPool = databaseConnection
instanceList[type] = instance
}
return type.cast(instance)
}
}