From 7427820abac0fa694e0d522882a56e67b78fa5ae Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Tue, 26 Apr 2022 08:37:10 -0500 Subject: [PATCH] Scan binary UUID to string https://github.com/jackc/pgx/issues/1191 --- pgtype/uuid.go | 21 +++++++++++++++++++++ pgtype/uuid_test.go | 5 +++++ 2 files changed, 26 insertions(+) diff --git a/pgtype/uuid.go b/pgtype/uuid.go index 8c3bbba5..96a4c32f 100644 --- a/pgtype/uuid.go +++ b/pgtype/uuid.go @@ -173,6 +173,8 @@ func (UUIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan switch target.(type) { case UUIDScanner: return scanPlanBinaryUUIDToUUIDScanner{} + case TextScanner: + return scanPlanBinaryUUIDToTextScanner{} } case TextFormatCode: switch target.(type) { @@ -203,6 +205,25 @@ func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { return scanner.ScanUUID(uuid) } +type scanPlanBinaryUUIDToTextScanner struct{} + +func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + if len(src) != 16 { + return fmt.Errorf("invalid length for UUID: %v", len(src)) + } + + var buf [16]byte + copy(buf[:], src) + + return scanner.ScanText(Text{String: encodeUUID(buf), Valid: true}) +} + type scanPlanTextAnyToUUIDScanner struct{} func (scanPlanTextAnyToUUIDScanner) Scan(src []byte, dst any) error { diff --git a/pgtype/uuid_test.go b/pgtype/uuid_test.go index 06ff38c2..2dc258b1 100644 --- a/pgtype/uuid_test.go +++ b/pgtype/uuid_test.go @@ -27,6 +27,11 @@ func TestUUIDCodec(t *testing.T) { new(pgtype.UUID), isExpectedEq(pgtype.UUID{Bytes: [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Valid: true}), }, + { + pgtype.UUID{Bytes: [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Valid: true}, + new(string), + isExpectedEq("00010203-0405-0607-0809-0a0b0c0d0e0f"), + }, {pgtype.UUID{}, new([]byte), isExpectedEqBytes([]byte(nil))}, {pgtype.UUID{}, new(pgtype.UUID), isExpectedEq(pgtype.UUID{})}, {nil, new(pgtype.UUID), isExpectedEq(pgtype.UUID{})},