64 lines
1.9 KiB
Kotlin
64 lines
1.9 KiB
Kotlin
package moe.kageru.kodeshare.persistence
|
|
|
|
import moe.kageru.kodeshare.Paste
|
|
import moe.kageru.kodeshare.config.DatabaseSpec
|
|
import moe.kageru.kodeshare.config.config
|
|
import org.jetbrains.exposed.sql.*
|
|
import org.jetbrains.exposed.sql.transactions.transaction
|
|
import org.mariadb.jdbc.MariaDbDataSource
|
|
|
|
object PasteDao {
|
|
fun select(id: Long): Transient<Paste>? = transaction {
|
|
PasteTable.select { PasteTable.id.eq(id) }.firstOrNull()
|
|
}?.toPaste()
|
|
|
|
fun insert(paste: Paste): Transient<Paste> = transaction {
|
|
val id = PasteTable.insert {
|
|
it[content] = paste.content
|
|
it[created] = paste.created
|
|
it[uri] = paste.uri
|
|
}[PasteTable.id]
|
|
Transient(id, paste)
|
|
}
|
|
|
|
fun selectByUri(uri: String): Transient<Paste>? = transaction {
|
|
PasteTable.select { PasteTable.uri.eq(uri) }.firstOrNull()
|
|
}?.toPaste()
|
|
|
|
init {
|
|
val source = MariaDbDataSource().apply {
|
|
userName = config[DatabaseSpec.user]
|
|
setPassword(config[DatabaseSpec.password])
|
|
databaseName = config[DatabaseSpec.database]
|
|
port = config[DatabaseSpec.port]
|
|
}
|
|
Database.connect(source)
|
|
transaction {
|
|
SchemaUtils.createMissingTablesAndColumns(PasteTable)
|
|
}
|
|
}
|
|
}
|
|
|
|
private fun ResultRow.toPaste() = Transient(
|
|
get(PasteTable.id),
|
|
Paste(
|
|
content = get(PasteTable.content),
|
|
created = get(PasteTable.created),
|
|
uri = get(PasteTable.uri)
|
|
)
|
|
)
|
|
|
|
private object PasteTable : Table() {
|
|
val id = long("id").primaryKey().autoIncrement().uniqueIndex()
|
|
val content = text("content")
|
|
val created = datetime("created").index()
|
|
val uri = varchar("uri", 10).uniqueIndex()
|
|
}
|
|
|
|
/*
|
|
* Better have that one generic class
|
|
* after deciding to make everything else
|
|
* not generic because it would be overkill
|
|
*/
|
|
data class Transient<DATA>(val id: Long, val data: DATA)
|