kodeshare/src/main/kotlin/moe/kageru/kodeshare/persistence/PasteDao.kt
2019-09-29 17:18:38 +02:00

68 lines
2.0 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 = registerColumn<String>("content", MediumTextColumnType())
val created = datetime("created").index()
val uri = varchar("uri", 10).uniqueIndex()
}
class MediumTextColumnType : IColumnType by TextColumnType() {
override fun sqlType(): String = "MEDIUMTEXT"
}
/*
* 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)