Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

October 20, 2021

PostgreSQL database connection in Ktor part-1

October 20, 2021 Posted by Piash , No comments
PostgreSQL database connection in Ktor. 

 build.gradle dependency

// Exposed ORM library
implementation "org.jetbrains.exposed:exposed-core:0.35.1"
implementation "org.jetbrains.exposed:exposed-dao:0.35.1"
implementation "org.jetbrains.exposed:exposed-jdbc:0.35.1"
implementation "org.postgresql:postgresql:42.2.2"
implementation 'com.zaxxer:HikariCP:3.4.2'

resource/hikari.properties

dataSourceClassName=org.postgresql.ds.PGSimpleDataSource
dataSource.user=postgres
dataSource.password=p123
dataSource.databaseName=db_ktor
dataSource.portNumber=5432
dataSource.serverName=localh

Database helper class

object DatabaseFactory {
fun init() {
// Database.connect(hikari())
initDB()
transaction {
//create(Fruits, UserTable, ProductTable)
}
}

private fun initDB() {
// database connection is handled from hikari properties
val config = HikariConfig("/hikari.properties")
val ds = HikariDataSource(config)
Database.connect(ds)
}

// database connection for h2 d
private fun hikari(): HikariDataSource {
val config = HikariConfig()
config.driverClassName = "org.h2.Driver"
config.jdbcUrl = "jdbc:h2:file:~/documents/db/h2db"
config.maximumPoolSize = 3
config.isAutoCommit = false
config.transactionIsolation = "TRANSACTION_REPEATABLE_READ"
config.validate()
return HikariDataSource(config)
}
}

Application class

fun main() {
//val environment = System.getenv("KTOR_ENVIRONMENT") ?: "development"
val configName = "application.conf"
val appEngineEnv = applicationEngineEnvironment {
config = HoconApplicationConfig(ConfigFactory.load(configName))
log = LoggerFactory.getLogger("ktor.application")
module {
DatabaseFactory.init()
}
connector {
host = config.property("ktor.deployment.host").getString()
port = config.property("ktor.deployment.port").getString().toInt()
}
}

embeddedServer(Netty, appEngineEnv).start(wait = true)
}

0 comments:

Post a Comment