Skip to content

Commit 9f706b5

Browse files
baardetanner0101
authored andcommitted
Fix a retain cycle in PostgreSQLConnection (vapor#116)
By adding a handler that retains self on the channel's close future, the connection gets retained until the channel is closed. We break the retain cycle by using a weak reference to self. The completion handler in `send(:onResponse:)` is enough to ensure that the connection stays alive while a message is sent to the server.
1 parent cbe5505 commit 9f706b5

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Sources/PostgreSQL/Connection/PostgreSQLConnection.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ public final class PostgreSQLConnection: DatabaseConnection, BasicWorker, Databa
3939
self.isClosed = false
4040
self.extend = [:]
4141
self.pipeline = channel.eventLoop.newSucceededFuture(result: ())
42-
channel.closeFuture.always {
43-
self.isClosed = true
44-
if let current = self.currentSend {
42+
channel.closeFuture.always { [weak self] in
43+
self?.isClosed = true
44+
if let current = self?.currentSend {
4545
current.fail(error: closeError)
4646
}
4747
}

Tests/PostgreSQLTests/PostgreSQLConnectionTests.swift

+15
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,20 @@ class PostgreSQLConnectionTests: XCTestCase {
606606
}
607607
}
608608
}
609+
610+
func testClosureRetainCycle() throws {
611+
weak var connection: PostgreSQLConnection?
612+
let request: EventLoopFuture<Void>
613+
do {
614+
let conn = try PostgreSQLConnection.makeTest()
615+
request = conn.simpleQuery("SELECT true")
616+
connection = conn
617+
}
618+
XCTAssertNotNil(connection)
619+
try request.wait()
620+
try request.eventLoop.future().wait()
621+
XCTAssertNil(connection)
622+
}
609623

610624
static var allTests = [
611625
("testBenchmark", testBenchmark),
@@ -628,6 +642,7 @@ class PostgreSQLConnectionTests: XCTestCase {
628642
("testEmptyArray", testEmptyArray),
629643
("testZeroNumeric", testZeroNumeric),
630644
("testNumericDecode", testNumericDecode),
645+
("testClosureRetainCycle", testClosureRetainCycle),
631646
]
632647
}
633648

0 commit comments

Comments
 (0)