Skip to content

Commit

Permalink
Fix UUID.Scan
Browse files Browse the repository at this point in the history
  • Loading branch information
apocelipes committed Dec 9, 2024
1 parent 51311da commit 76d4450
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
34 changes: 32 additions & 2 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import "C"

import (
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
"strings"

"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
)

Expand All @@ -23,12 +25,40 @@ const uuid_length = 16
type UUID [uuid_length]byte

func (u *UUID) Scan(v any) error {
if n := copy(u[:], v.([]byte)); n != uuid_length {
return fmt.Errorf("invalid UUID length: %d", n)
switch val := v.(type) {
case []byte:
if len(val) != uuid_length {
return u.Scan(string(val))
}
copy(u[:], val[:])
case string:
id, err := uuid.Parse(val)
if err != nil {
return err
}
copy(u[:], id[:])
default:
return fmt.Errorf("invalid UUID type: %#v", val)
}
return nil
}

func (u *UUID) String() string {
buf := make([]byte, 36)

hex.Encode(buf, u[:4])
buf[8] = '-'
hex.Encode(buf[9:13], u[4:6])
buf[13] = '-'
hex.Encode(buf[14:18], u[6:8])
buf[18] = '-'
hex.Encode(buf[19:23], u[8:10])
buf[23] = '-'
hex.Encode(buf[24:], u[10:])

return string(buf)
}

// duckdb_hugeint is composed of (lower, upper) components.
// The value is computed as: upper * 2^64 + lower

Expand Down
10 changes: 10 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,16 @@ func TestUUID(t *testing.T) {

require.NoError(t, db.QueryRow(`SELECT ?::uuid`, test).Scan(&val))
require.Equal(t, test, val)

var u UUID
require.NoError(t, db.QueryRow(`SELECT uuid FROM uuid_test WHERE uuid = ?`, test).Scan(&u))
require.Equal(t, test.String(), u.String())

require.NoError(t, db.QueryRow(`SELECT ?`, test).Scan(&u))
require.Equal(t, test.String(), u.String())

require.NoError(t, db.QueryRow(`SELECT ?::uuid`, test).Scan(&u))
require.Equal(t, test.String(), u.String())
}

require.NoError(t, db.Close())
Expand Down

0 comments on commit 76d4450

Please sign in to comment.