You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.7 KiB
60 lines
1.7 KiB
package net.aiterp.git.ykonsole2.infrastructure.repositories
|
|
|
|
import net.aiterp.git.ykonsole2.domain.models.Device
|
|
import net.aiterp.git.ykonsole2.domain.models.DeviceRepository
|
|
import net.aiterp.git.ykonsole2.infrastructure.prepare
|
|
import net.aiterp.git.ykonsole2.infrastructure.runQuery
|
|
import net.aiterp.git.ykonsole2.infrastructure.withConnection
|
|
import java.sql.ResultSet
|
|
import javax.sql.DataSource
|
|
|
|
val DataSource.deviceRepo get() = object : DeviceRepository {
|
|
override fun findById(id: String): Device? = withConnection {
|
|
prepare("SELECT * FROM device WHERE id = ?") {
|
|
setString(1, id)
|
|
|
|
runQuery { if (next()) makeDevice() else null }
|
|
}
|
|
}
|
|
|
|
override fun fetchAll(): List<Device> = withConnection {
|
|
prepare("SELECT * FROM device") {
|
|
runQuery {
|
|
buildList { while (next()) add(makeDevice()) }
|
|
}
|
|
}
|
|
}
|
|
|
|
override fun save(device: Device) {
|
|
withConnection {
|
|
prepare(
|
|
"""
|
|
INSERT INTO device (id, name, connection_string)
|
|
VALUES (?, ?, ?)
|
|
ON DUPLICATE KEY UPDATE name = VALUES(name),
|
|
connection_string = VALUES(connection_string)
|
|
""".trimIndent()
|
|
) {
|
|
setString(1, device.id)
|
|
setString(2, device.name)
|
|
setString(3, device.connectionString)
|
|
execute()
|
|
}
|
|
}
|
|
}
|
|
|
|
override fun delete(device: Device) {
|
|
withConnection {
|
|
prepare("DELETE FROM device WHERE id = ?") {
|
|
setString(1, device.id)
|
|
execute()
|
|
}
|
|
}
|
|
}
|
|
|
|
private fun ResultSet.makeDevice() = Device(
|
|
id = getString("id"),
|
|
name = getString("name"),
|
|
connectionString = getString("connection_string"),
|
|
)
|
|
}
|