Skip to content

Fix: Correctly decode jsonb to String by stripping version byte #568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Sources/PostgresNIO/New/Data/String+PostgresCodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ extension String: PostgresDecodable {
context: PostgresDecodingContext<JSONDecoder>
) throws {
switch (format, type) {
case (.binary, .jsonb):
// Discard the version byte
guard let version = buffer.readInteger(as: UInt8.self), version == 1 else {
throw PostgresDecodingError.Code.failure
}
self = buffer.readString(length: buffer.readableBytes)!
case (_, .varchar),
(_, .bpchar),
(_, .text),
Expand Down
16 changes: 16 additions & 0 deletions Tests/IntegrationTests/PostgresNIOTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,22 @@ final class PostgresNIOTests: XCTestCase {
}
}

func testJSONBDecodeString() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow(try conn?.close().wait()) }

do {
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select '{\"hello\": \"world\"}'::jsonb as data").wait())

var resultString: String?
XCTAssertNoThrow(resultString = try rows?.first?.decode(String.self, context: .default))

XCTAssertEqual(resultString, "{\"hello\": \"world\"}")
}
}

func testInt4RangeSerialize() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
Expand Down
11 changes: 11 additions & 0 deletions Tests/PostgresNIOTests/New/Data/String+PSQLCodableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,15 @@ class String_PSQLCodableTests: XCTestCase {
XCTAssertEqual($0 as? PostgresDecodingError.Code, .failure)
}
}

func testDecodeFromJSONB() {
let json = #"{"hello": "world"}"#
var buffer = ByteBuffer()
buffer.writeInteger(UInt8(1))
buffer.writeString(json)

var decoded: String?
XCTAssertNoThrow(decoded = try String(from: &buffer, type: .jsonb, format: .binary, context: .default))
XCTAssertEqual(decoded, json)
}
}
Loading