Adding better binary type support for common SQL dialects

This commit is contained in:
Rob Rodriguez 2017-04-19 00:21:56 -07:00
parent 403487d5dd
commit bae0799bd8
5 changed files with 14 additions and 13 deletions

View File

@ -149,3 +149,8 @@ func (DefaultForeignKeyNamer) BuildForeignKeyName(tableName, field, dest string)
keyName = regexp.MustCompile("(_*[^a-zA-Z]+_*|_+)").ReplaceAllString(keyName, "_")
return keyName
}
// IsByteArrayOrSlice returns true of the reflected value is an array or slice
func IsByteArrayOrSlice(value reflect.Value) bool {
return (value.Kind() == reflect.Array || value.Kind() == reflect.Slice) && value.Type().Elem() == reflect.TypeOf(uint8(0))
}

View File

@ -87,7 +87,7 @@ func (s *mysql) DataTypeOf(field *StructField) string {
}
}
default:
if _, ok := dataValue.Interface().([]byte); ok {
if IsByteArrayOrSlice(dataValue) {
if size > 0 && size < 65532 {
sqlType = fmt.Sprintf("varbinary(%d)", size)
} else {

View File

@ -65,7 +65,7 @@ func (s *postgres) DataTypeOf(field *StructField) string {
sqlType = "hstore"
}
default:
if isByteArrayOrSlice(dataValue) {
if IsByteArrayOrSlice(dataValue) {
sqlType = "bytea"
} else if isUUID(dataValue) {
sqlType = "uuid"
@ -120,10 +120,6 @@ func (postgres) SupportLastInsertID() bool {
return false
}
func isByteArrayOrSlice(value reflect.Value) bool {
return (value.Kind() == reflect.Array || value.Kind() == reflect.Slice) && value.Type().Elem() == reflect.TypeOf(uint8(0))
}
func isUUID(value reflect.Value) bool {
if value.Kind() != reflect.Array || value.Type().Len() != 16 {
return false

View File

@ -54,7 +54,7 @@ func (s *sqlite3) DataTypeOf(field *StructField) string {
sqlType = "datetime"
}
default:
if _, ok := dataValue.Interface().([]byte); ok {
if IsByteArrayOrSlice(dataValue) {
sqlType = "blob"
}
}

View File

@ -58,21 +58,21 @@ func (s *mssql) DataTypeOf(field *gorm.StructField) string {
case reflect.Float32, reflect.Float64:
sqlType = "float"
case reflect.String:
if size > 0 && size < 65532 {
if size > 0 && size < 8000 {
sqlType = fmt.Sprintf("nvarchar(%d)", size)
} else {
sqlType = "text"
sqlType = "nvarchar(max)"
}
case reflect.Struct:
if _, ok := dataValue.Interface().(time.Time); ok {
sqlType = "datetime2"
}
default:
if _, ok := dataValue.Interface().([]byte); ok {
if size > 0 && size < 65532 {
sqlType = fmt.Sprintf("varchar(%d)", size)
if gorm.IsByteArrayOrSlice(dataValue) {
if size > 0 && size < 8000 {
sqlType = fmt.Sprintf("varbinary(%d)", size)
} else {
sqlType = "text"
sqlType = "varbinary(max)"
}
}
}