diff --git a/types.go b/types.go index 8f601714..ff6f190e 100644 --- a/types.go +++ b/types.go @@ -7,10 +7,12 @@ import "C" import ( "encoding/binary" + "encoding/hex" "fmt" "math/big" "strings" + "github.com/google/uuid" "github.com/mitchellh/mapstructure" ) @@ -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 diff --git a/types_test.go b/types_test.go index da5d8942..22998de6 100644 --- a/types_test.go +++ b/types_test.go @@ -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)