Skip to content

Commit

Permalink
Merge pull request #327 from apocelipes/fix-uuid
Browse files Browse the repository at this point in the history
Fix UUID.Scan
  • Loading branch information
taniabogatsch authored Dec 9, 2024
2 parents 51311da + c2be05c commit a3c790e
Show file tree
Hide file tree
Showing 2 changed files with 55 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 value type: %T", 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
23 changes: 23 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -643,11 +643,34 @@ 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())
}

func TestUUIDScanError(t *testing.T) {
t.Parallel()
db := openDB(t)

var u UUID
// invalid value type
require.Error(t, db.QueryRow(`SELECT 12345`).Scan(&u))
// string value not valid
require.Error(t, db.QueryRow(`SELECT 'I am not a UUID.'`).Scan(&u))
// blob value not valid
require.Error(t, db.QueryRow(`SELECT '123456789012345678901234567890123456'::BLOB`).Scan(&u))
}

func TestDate(t *testing.T) {
t.Parallel()
db := openDB(t)
Expand Down

0 comments on commit a3c790e

Please sign in to comment.