Skip to content

Commit

Permalink
Don't update expires in set if it is nil (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler authored Sep 25, 2024
1 parent 02bb8e6 commit 08fcd81
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
30 changes: 21 additions & 9 deletions Sources/HummingbirdPostgres/PostgresPersistDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,27 @@ public final class PostgresPersistDriver: PersistDriver {

/// Set value for key.
public func set(key: String, value: some Codable, expires: Duration?) async throws {
let expires = expires.map { Date.now + Double($0.components.seconds) } ?? Date.distantFuture
try await self.client.query(
"""
INSERT INTO _hb_pg_persist (id, data, expires) VALUES (\(key), \(WrapperObject(value)), \(expires))
ON CONFLICT (id)
DO UPDATE SET data = \(WrapperObject(value)), expires = \(expires)
""",
logger: self.logger
)
if let expires {
let expires = Date.now + Double(expires.components.seconds)
try await self.client.query(
"""
INSERT INTO _hb_pg_persist (id, data, expires) VALUES (\(key), \(WrapperObject(value)), \(expires))
ON CONFLICT (id)
DO UPDATE SET data = \(WrapperObject(value)), expires = \(expires)
""",
logger: self.logger
)

} else {
try await self.client.query(
"""
INSERT INTO _hb_pg_persist (id, data, expires) VALUES (\(key), \(WrapperObject(value)), \(Date.distantFuture))
ON CONFLICT (id)
DO UPDATE SET data = \(WrapperObject(value))
""",
logger: self.logger
)
}
}

/// Get value for key
Expand Down
4 changes: 2 additions & 2 deletions Tests/HummingbirdPostgresTests/PersistTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ final class PersistTests: XCTestCase {
try await app.test(.router) { client in

let tag = UUID().uuidString
try await client.execute(uri: "/persist/\(tag)/0", method: .put, body: ByteBufferAllocator().buffer(string: "ThisIsTest1")) { _ in }
try await client.execute(uri: "/persist/\(tag)/0", method: .put, body: ByteBuffer(string: "ThisIsTest1")) { _ in }
try await Task.sleep(nanoseconds: 1_000_000_000)
try await client.execute(uri: "/persist/\(tag)", method: .get) { response in
XCTAssertEqual(response.status, .noContent)
}
try await client.execute(uri: "/persist/\(tag)/10", method: .put, body: ByteBufferAllocator().buffer(string: "ThisIsTest1")) { response in
try await client.execute(uri: "/persist/\(tag)/10", method: .put, body: ByteBuffer(string: "ThisIsTest1")) { response in
XCTAssertEqual(response.status, .ok)
}
try await client.execute(uri: "/persist/\(tag)", method: .get) { response in
Expand Down

0 comments on commit 08fcd81

Please sign in to comment.