mirror of https://github.com/go-gorm/gorm.git
add binary UUID support to postgres
Check if the value is a byte array of 16 bytes and its type is named "uuid" or "guid", and if so, use postgres `uuid` type.
This commit is contained in:
parent
2a46856d52
commit
3cb95264df
21
postgres.go
21
postgres.go
|
@ -5,6 +5,7 @@ import (
|
||||||
"database/sql/driver"
|
"database/sql/driver"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/lib/pq/hstore"
|
"github.com/lib/pq/hstore"
|
||||||
|
@ -52,13 +53,31 @@ func (postgres) SqlTag(value reflect.Value, size int, autoIncrease bool) string
|
||||||
return "hstore"
|
return "hstore"
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
if _, ok := value.Interface().([]byte); ok {
|
if isByteArray(value) {
|
||||||
|
if isUUID(value) {
|
||||||
|
return "uuid"
|
||||||
|
}
|
||||||
return "bytea"
|
return "bytea"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
panic(fmt.Sprintf("invalid sql type %s (%s) for postgres", value.Type().Name(), value.Kind().String()))
|
panic(fmt.Sprintf("invalid sql type %s (%s) for postgres", value.Type().Name(), value.Kind().String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var byteType = reflect.TypeOf(uint8(0))
|
||||||
|
|
||||||
|
func isByteArray(value reflect.Value) bool {
|
||||||
|
return value.Kind() == reflect.Array && value.Type().Elem() == byteType
|
||||||
|
}
|
||||||
|
|
||||||
|
func isUUID(value reflect.Value) bool {
|
||||||
|
if value.Type().Len() != 16 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
typename := value.Type().Name()
|
||||||
|
lower := strings.ToLower(typename)
|
||||||
|
return "uuid" == lower || "guid" == lower
|
||||||
|
}
|
||||||
|
|
||||||
func (s postgres) ReturningStr(tableName, key string) string {
|
func (s postgres) ReturningStr(tableName, key string) string {
|
||||||
return fmt.Sprintf("RETURNING %v.%v", tableName, key)
|
return fmt.Sprintf("RETURNING %v.%v", tableName, key)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue