MCPcopy
hub / github.com/go-gorm/gorm / TestUpsertSlice

Function TestUpsertSlice

tests/upsert_test.go:91–136  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

89}
90
91func TestUpsertSlice(t *testing.T) {
92 langs := []Language{
93 {Code: "upsert-slice1", Name: "Upsert-slice1"},
94 {Code: "upsert-slice2", Name: "Upsert-slice2"},
95 {Code: "upsert-slice3", Name: "Upsert-slice3"},
96 }
97 DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&langs)
98
99 var langs2 []Language
100 if err := DB.Find(&langs2, "code LIKE ?", "upsert-slice%").Error; err != nil {
101 t.Errorf("no error should happen when find languages with code, but got %v", err)
102 } else if len(langs2) != 3 {
103 t.Errorf("should only find only 3 languages, but got %+v", langs2)
104 }
105
106 DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&langs)
107 var langs3 []Language
108 if err := DB.Find(&langs3, "code LIKE ?", "upsert-slice%").Error; err != nil {
109 t.Errorf("no error should happen when find languages with code, but got %v", err)
110 } else if len(langs3) != 3 {
111 t.Errorf("should only find only 3 languages, but got %+v", langs3)
112 }
113
114 for idx, lang := range langs {
115 lang.Name = lang.Name + "_new"
116 langs[idx] = lang
117 }
118
119 if err := DB.Clauses(clause.OnConflict{
120 Columns: []clause.Column{{Name: "code"}},
121 DoUpdates: clause.AssignmentColumns([]string{"name"}),
122 }).Create(&langs).Error; err != nil {
123 t.Fatalf("failed to upsert, got %v", err)
124 }
125
126 for _, lang := range langs {
127 var results []Language
128 if err := DB.Find(&results, "code = ?", lang.Code).Error; err != nil {
129 t.Errorf("no error should happen when find languages with code, but got %v", err)
130 } else if len(results) != 1 {
131 t.Errorf("should only find only 1 languages, but got %+v", langs)
132 } else if results[0].Name != lang.Name {
133 t.Errorf("should update name on conflict, but got name %+v", results[0].Name)
134 }
135 }
136}
137
138func TestUpsertSliceWithReturning(t *testing.T) {
139 langs := []Language{

Callers

nothing calls this directly

Calls 4

AssignmentColumnsFunction · 0.92
ClausesMethod · 0.80
CreateMethod · 0.65
FindMethod · 0.65

Tested by

no test coverage detected