https://kotlinlang.org logo
#exposed
Title
# exposed
d

Dan Storm

10/23/2023, 12:58 PM
I'm tampering a bit as a novice with setting up my first Ktor project. I'm at a point where I'd like to create my first Postgres table. In relation to that, I'm looking into the Ktor project created by IntelliJ for my purpose. I have the following method that returns an instance of a connection:
Copy code
fun Application.connectToPostgres(embedded: Boolean): Connection {
    Class.forName("org.postgresql.Driver")
    if (embedded) {
        return DriverManager.getConnection("jdbc:<postgresql://localhost:5432/db?user=user&password=password>")
    } else {
        val url = environment.config.property("postgres.url").getString()
        val user = environment.config.property("postgres.user").getString()
        val password = environment.config.property("postgres.password").getString()

        return DriverManager.getConnection(url, user, password)
    }
}
I then tried to do the following:
Copy code
val dbConnection: Connection = connectToPostgres(embedded = true)
    Database.connect({ dbConnection })
    transaction {
        SchemaUtils.create(com.example.app.models.Systems)
    }
This results in the following error.
Copy code
Exception in thread "main" org.postgresql.util.PSQLException: This connection has been closed.
But if I instead just run the following:
Copy code
Database.connect("jdbc:<postgresql://localhost:5432/db?user=user&password=password>", driver = "org.postgresql.Driver")
    transaction {
        SchemaUtils.create(com.example.app.models.Systems)
    }
Things work as expected. Might you be able to tell me what the difference is?