2019-09-19 22:04:23 +02:00
package moe.kageru.kodeshare.persistence
import moe.kageru.kodeshare.Paste
2019-09-29 08:17:31 +02:00
import moe.kageru.kodeshare.config.DatabaseSpec
import moe.kageru.kodeshare.config.config
2019-09-19 22:04:23 +02:00
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
2019-09-29 08:17:31 +02:00
it [ created ] = paste . created
2019-09-19 22:04:23 +02:00
} [ PasteTable . id ]
Transient ( id , paste )
}
init {
val source = MariaDbDataSource ( ) . apply {
2019-09-29 08:17:31 +02:00
userName = config [ DatabaseSpec . user ]
setPassword ( config [ DatabaseSpec . password ] )
databaseName = config [ DatabaseSpec . database ]
port = config [ DatabaseSpec . port ]
2019-09-19 22:04:23 +02:00
}
Database . connect ( source )
transaction {
SchemaUtils . create ( PasteTable )
}
}
}
private fun ResultRow . toPaste ( ) = Transient (
get ( PasteTable . id ) ,
Paste (
content = get ( PasteTable . content ) ,
2019-09-29 08:17:31 +02:00
created = get ( PasteTable . created )
2019-09-19 22:04:23 +02:00
)
)
private object PasteTable : Table ( ) {
2019-09-29 08:17:31 +02:00
val id = long ( " id " ) . primaryKey ( ) . autoIncrement ( ) . index ( )
2019-09-19 22:04:23 +02:00
val content = text ( " content " )
2019-09-29 08:17:31 +02:00
val created = datetime ( " created " ) . index ( )
2019-09-19 22:04:23 +02:00
}
/ *
* 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 )