-
Notifications
You must be signed in to change notification settings - Fork 0
/
gormuuid.go
49 lines (41 loc) · 1.24 KB
/
gormuuid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package gormuuid
import (
"database/sql/driver"
"strings"
"github.com/google/uuid"
"github.com/ubgo/gouuid"
)
type UUIDArray []uuid.UUID
func (uidarray UUIDArray) GormDataType() string {
return "uuid[]"
}
func (a UUIDArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
params := "{" + strings.Join(gouuid.ToStringSlice(a), ",") + "}"
return params, nil
}
// Do not delete - Why we did not use this
// GormValue does not accepts the pointer type value so in order to support i had to create two different types
// So i decied to used the Value() method above
// func (uidarray UUIDArray) GormValue(ctx context.Context, db *gorm.DB) (expr clause.Expr) {
// params := "{" + strings.Join(ArrayToString(uidarray), ",") + "}"
// return clause.Expr{
// SQL: "?::uuid[]",
// Vars: []interface{}{params},
// }
// }
// Scan implements the sql.Scanner interface
func (uidarray *UUIDArray) Scan(v interface{}) error {
val := ""
switch s := v.(type) {
case []byte: // if used sql.DB as driver and pass to gorm as conn then it returns []uint8
val = string(s)
case string: // if used using gorm driver then it returns as string
val = string(s)
}
parsed := gouuid.PgStringArrayToUUIDSlide(val)
*uidarray = parsed
return nil
}