Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,26 @@ func (p *processor) Execute(db *DB) *DB {

stmt.ReflectValue = stmt.ReflectValue.Elem()
}
if (stmt.ReflectValue.Kind() == reflect.Slice || stmt.ReflectValue.Kind() == reflect.Array) &&
(stmt.ReflectValue.Len() > 0 && stmt.ReflectValue.Index(0).Kind() == reflect.Interface) {
len := stmt.ReflectValue.Len()
firstElem := stmt.ReflectValue.Index(0)
for firstElem.Kind() == reflect.Interface || firstElem.Kind() == reflect.Ptr {
firstElem = firstElem.Elem()
}
elemType := firstElem.Type()
sliceType := reflect.SliceOf(elemType)
structArrayReflectValue := reflect.MakeSlice(sliceType, 0, len)

for i := 0; i < len; i++ {
elem := stmt.ReflectValue.Index(i)
for elem.Kind() == reflect.Interface || elem.Kind() == reflect.Ptr {
elem = elem.Elem()
}
structArrayReflectValue = reflect.Append(structArrayReflectValue, elem)
}
stmt.ReflectValue = structArrayReflectValue
}
if !stmt.ReflectValue.IsValid() {
db.AddError(ErrInvalidValue)
}
Expand Down
8 changes: 8 additions & 0 deletions schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam
modelType = modelType.Elem()
}

if modelType.Kind() == reflect.Interface {
if value.Len() > 0 {
modelType = reflect.Indirect(value.Index(0)).Elem().Type()
}
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
}
}
if modelType.Kind() != reflect.Struct {
if modelType.PkgPath() == "" {
return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest)
Expand Down
12 changes: 12 additions & 0 deletions tests/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -791,3 +791,15 @@ func TestCreateFromMapWithTable(t *testing.T) {
t.Errorf("failed to create data from map with table, @id != id")
}
}

func TestCreateWithInterfaceArrayType(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it work for queries with an interface array as result?

user := *GetUser("create", Config{})
type UserInterface interface{}
var userInterface UserInterface = &user

if results := DB.Create([]UserInterface{userInterface}); results.Error != nil {
t.Fatalf("errors happened when create: %v", results.Error)
} else if results.RowsAffected != 1 {
t.Fatalf("rows affected expects: %v, got %v", 1, results.RowsAffected)
}
}
Loading