Dan Storm
10/23/2023, 12:58 PMfun 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:
val dbConnection: Connection = connectToPostgres(embedded = true)
Database.connect({ dbConnection })
transaction {
SchemaUtils.create(com.example.app.models.Systems)
}
This results in the following error.
Exception in thread "main" org.postgresql.util.PSQLException: This connection has been closed.
But if I instead just run the following:
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?Chantal Loncle
12/20/2023, 9:11 PMDatabase.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.Dan Storm
12/21/2023, 9:42 AMChantal Loncle
01/02/2024, 9:52 PM