diff --git a/types.go b/types.go index 8f601714..6faf705b 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 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 diff --git a/types_test.go b/types_test.go index da5d8942..bca361d0 100644 --- a/types_test.go +++ b/types_test.go @@ -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())