| 1 |
package callbacks |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"sync" |
| 6 |
"testing" |
| 7 |
"time" |
| 8 |
|
| 9 |
"gorm.io/gorm" |
| 10 |
"gorm.io/gorm/clause" |
| 11 |
"gorm.io/gorm/schema" |
| 12 |
) |
| 13 |
|
| 14 |
var schemaCache = &sync.Map{} |
| 15 |
|
| 16 |
func TestConvertToCreateValues_DestType_Slice(t *testing.T) { |
| 17 |
type user struct { |
| 18 |
ID int `gorm:"primaryKey"` |
| 19 |
Name string |
| 20 |
Email string `gorm:"default:(-)"` |
| 21 |
Age int `gorm:"default:(-)"` |
| 22 |
} |
| 23 |
|
| 24 |
s, err := schema.Parse(&user{}, schemaCache, schema.NamingStrategy{}) |
| 25 |
if err != nil { |
| 26 |
t.Errorf("parse schema error: %v, is not expected", err) |
| 27 |
return |
| 28 |
} |
| 29 |
dest := []*user{ |
| 30 |
{ |
| 31 |
ID: 1, |
| 32 |
Name: "alice", |
| 33 |
Email: "email", |
| 34 |
Age: 18, |
| 35 |
}, |
| 36 |
{ |
| 37 |
ID: 2, |
| 38 |
Name: "bob", |
| 39 |
Email: "email", |
| 40 |
Age: 19, |
| 41 |
}, |
| 42 |
} |
| 43 |
stmt := &gorm.Statement{ |
| 44 |
DB: &gorm.DB{ |
| 45 |
Config: &gorm.Config{ |
| 46 |
NowFunc: func() time.Time { return time.Time{} }, |
| 47 |
}, |
| 48 |
Statement: &gorm.Statement{ |
| 49 |
Settings: sync.Map{}, |
| 50 |
Schema: s, |
| 51 |
}, |
| 52 |
}, |
| 53 |
ReflectValue: reflect.ValueOf(dest), |
| 54 |
Dest: dest, |
| 55 |
} |
| 56 |
|
| 57 |
stmt.Schema = s |
| 58 |
|
| 59 |
values := ConvertToCreateValues(stmt) |
| 60 |
expected := clause.Values{ |
| 61 |
// column has value + defaultValue column has value (which should have a stable order) |
| 62 |
Columns: []clause.Column{{Name: "name"}, {Name: "email"}, {Name: "age"}, {Name: "id"}}, |
| 63 |
Values: [][]interface{}{ |
| 64 |
{"alice", "email", 18, 1}, |
| 65 |
{"bob", "email", 19, 2}, |
| 66 |
}, |
| 67 |
} |
| 68 |
if !reflect.DeepEqual(expected, values) { |
| 69 |
t.Errorf("expected: %v got %v", expected, values) |
| 70 |
} |
| 71 |
} |