Closing a connection doesn't fully clean it up
See original GitHub issueIssue type: [x] question
Database system/driver:
[x] postgres
TypeORM version:
[x] @next
I am writing different API test suites that initialise the app once per suite. When starting my application I initialise the connection to a postgres db this way:
const connection = await createConnection();
This works fine for the first suite but from that moment on, I get the following error:
Unhandled promise rejection (rejection id: 12): TypeError: Cannot read property 'connect' of undefined
Which is coming from https://github.com/typeorm/typeorm/blob/master/src/driver/postgres/PostgresDriver.ts#L636.
After a thorough investigation I found that the following snippet would fail when requesting users for the second time:
const connection1 = await createConnection();
const result1 = await getUsers();
await connection1.close();
const connection2 = await createConnection();
const result2 = await getUsers();
await connection2.close();
This is due to:
- When we close the connection, this doesn’t become null. It is still set to the
Connection
object, however,isConnected
is false. - Hence, when you are trying to connect to the database again,
createConnection
doesn’t return what it did the first time and following queries fail with the aforementioned error.
They way I got it working is by replacing:
const connection = await createConnection();
with:
let connection;
try {
connection = await getConnection();
if (!connection.isConnected) {
await connection.connect();
}
} catch (e) {
// no connection created yet, nothing to get
connection = await createConnection();
}
My question is: should not this be handled inside the createConnection
function?
As far as I can see, the issue is down to the connection.close()
not leaving things as they were before the createConnection
and that is causing the issue. If we are happy to leave this with still a connection
object with isConnected
to false
then, when requesting a new connection, that function should be clever enough to do the logic above (createConnection VS getConnection & connect). It doesn’t feel like from an app code point of view I should be worried to do the above if I explicitly closed the connection.
What is your point of view on this? If so, I am happy to do the changes myself and submit a PR.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:5
- Comments:11 (4 by maintainers)
Top GitHub Comments
Hi, any progress on this?
Just trying to make it more obvious:
Not sure why by the root cause for the error is that
this.master
is undefined inobtainMasterConnection
whengetUsers
tries to get hold of the connection.