I'm tampering a bit as a novice with setting up my...
# exposed
d
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?
c
Hi @Dan Storm The function that you're using
Database.connect(getNewConnection: () -> Connection, ...)
accepts a function that returns a new connection as its first argument. Exposed will attempt to retrieve a new connection for every transaction at the first moment that a database connection is actually needed. So it needs to know how you want it to do that. By providing
{ dbConnection }
you're passing in an already instantiated connection that may end up being closed by the database at some point before Exposed needs it. Passing in the function directly
Database.connect({ connectToPostgres() })
or as a function reference
Database.connect(::connectToPostgres)
should work as instantiation won't happen until it's required.
d
Hi @Chantal Loncle, thank you for getting back to me on the topic. I eventually left Exposed and finally Ktor. Community support was sparse and learning resources were equally so.
c
Hi @Dan Storm. I'm sorry to hear about your experience with both Exposed and Ktor. As we endeavour towards a stable 1.0 release and a proper documentation website, it is my hope that you'll consider both of them again in the future.