Repository navigation
Expand file tree
/
Copy pathcreate_test.go
More file actions
284 lines (233 loc) · 7.31 KB
/
Copy pathcreate_test.go
File metadata and controls
284 lines (233 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package sqlserver_test
import (
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type testSchemaUser struct {
ID int64 `gorm:"primaryKey"`
Name string
}
func (testSchemaUser) TableName() string {
return "users"
}
func setupSchemaTable(t *testing.T, db *gorm.DB) {
t.Helper()
if err := db.Exec("CREATE SCHEMA testschema").Error; err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := db.Exec("DROP TABLE IF EXISTS testschema.users").Error; err != nil {
t.Error(err)
}
if err := db.Exec("DROP SCHEMA IF EXISTS testschema").Error; err != nil {
t.Error(err)
}
})
if err := db.Exec(`
CREATE TABLE testschema.users (
id BIGINT IDENTITY(1,1) PRIMARY KEY,
name NVARCHAR(100)
)
`).Error; err != nil {
t.Fatal(err)
}
}
func assertUser(t *testing.T, db *gorm.DB, id int64, name string) {
t.Helper()
var got testSchemaUser
if err := db.Table("testschema.users").First(&got, id).Error; err != nil {
t.Fatal(err)
}
if got.Name != name {
t.Fatalf("expected %q, got %q", name, got.Name)
}
}
func TestCreateWithSchemaTable(t *testing.T) {
db, err := gorm.Open(sqlserver.Open(sqlserverDSN))
if err != nil {
t.Fatal(err)
}
setupSchemaTable(t, db)
if err := db.Table("testschema.users").Create(&testSchemaUser{
ID: 1,
Name: "gorm",
}).Error; err != nil {
t.Fatal(err)
}
assertUser(t, db, 1, "gorm")
}
func TestSaveWithSchemaTable(t *testing.T) {
db, err := gorm.Open(sqlserver.Open(sqlserverDSN))
if err != nil {
t.Fatal(err)
}
setupSchemaTable(t, db)
if err := db.Table("testschema.users").Save(&testSchemaUser{
ID: 1,
Name: "gorm",
}).Error; err != nil {
t.Fatal(err)
}
assertUser(t, db, 1, "gorm")
}
type mergeSchemaTableModel struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"column:name"`
}
func (mergeSchemaTableModel) TableName() string {
return "testschema.users"
}
type identityInsertSchemaTableModel struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Name string `gorm:"column:name"`
}
func (identityInsertSchemaTableModel) TableName() string {
return "testschema.identity_models"
}
type compositeKeySchemaModel struct {
TenantID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey"`
Name string `gorm:"column:name"`
}
func (compositeKeySchemaModel) TableName() string {
return "testschema.composite_models"
}
type noPrimaryKeyModel struct {
Name string `gorm:"column:name"`
}
func openDryRunDB(t *testing.T) *gorm.DB {
t.Helper()
sqlDB, _, err := sqlmock.New()
if err != nil {
t.Fatalf("failed to create sqlmock: %v", err)
}
t.Cleanup(func() {
_ = sqlDB.Close()
})
db, err := gorm.Open(sqlserver.New(sqlserver.Config{Conn: sqlDB}), &gorm.Config{
DryRun: true,
SkipDefaultTransaction: true,
})
if err != nil {
t.Fatalf("failed to open dry run db: %v", err)
}
return db
}
func TestCreateSQL_MergeUsesSchemaQualifiedTable(t *testing.T) {
db := openDryRunDB(t)
tx := db.Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&mergeSchemaTableModel{ID: 1, Name: "alice"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, `MERGE INTO "testschema"."users" AS "target"`) {
t.Fatalf("expected schema-qualified MERGE target with alias, got SQL: %s", sql)
}
if !strings.Contains(sql, `"target"."id" = "excluded"."id"`) {
t.Fatalf("expected target alias column in ON clause, got SQL: %s", sql)
}
}
func TestCreateSQL_MergeWithCompositePrimaryKey(t *testing.T) {
db := openDryRunDB(t)
tx := db.Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&compositeKeySchemaModel{TenantID: 1, ID: 2, Name: "charlie"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, `MERGE INTO "testschema"."composite_models" AS "target"`) {
t.Fatalf("expected schema-qualified MERGE target with alias, got SQL: %s", sql)
}
expectedOn := `"target"."tenant_id" = "excluded"."tenant_id" AND "target"."id" = "excluded"."id"`
if !strings.Contains(sql, expectedOn) {
t.Fatalf("expected composite key ON clause %q, got SQL: %s", expectedOn, sql)
}
}
func TestCreateSQL_MergeWithTableOverride(t *testing.T) {
db := openDryRunDB(t)
tx := db.Table("archive.custom_users").Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&testSchemaUser{ID: 1, Name: "alice"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, `MERGE INTO "archive"."custom_users" AS "target"`) {
t.Fatalf("expected MERGE INTO \"archive\".\"custom_users\" AS \"target\", got: %s", sql)
}
if !strings.Contains(sql, `"target"."id" = "excluded"."id"`) {
t.Fatalf("expected ON \"target\".\"id\" = \"excluded\".\"id\", got: %s", sql)
}
}
func TestCreateSQL_MergeWithMap(t *testing.T) {
db := openDryRunDB(t)
defer func() {
if r := recover(); r != nil {
t.Fatalf("panicked on map with OnConflict: %v", r)
}
}()
tx := db.Table("users").Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(map[string]interface{}{"name": "alice"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if strings.Contains(sql, "MERGE INTO") {
t.Fatalf("expected map create without schema to fall back to INSERT, got: %s", sql)
}
if !strings.Contains(sql, `INSERT INTO "users"`) {
t.Fatalf("expected INSERT fallback, got: %s", sql)
}
}
func TestCreateSQL_NoPrimaryKeyFallsBackToInsert(t *testing.T) {
db := openDryRunDB(t)
tx := db.Model(&noPrimaryKeyModel{}).Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&noPrimaryKeyModel{Name: "alice"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if strings.Contains(sql, "MERGE INTO") {
t.Fatalf("expected model without primary key to fall back to INSERT, got: %s", sql)
}
}
func TestMergeCreate_DirectCallGuard(t *testing.T) {
db := openDryRunDB(t)
// Direct call with nil schema
stmt := &gorm.Statement{DB: db}
dbNilSchema := db.Session(&gorm.Session{})
dbNilSchema.Statement = stmt
if sqlserver.MergeCreate(dbNilSchema, clause.OnConflict{}, clause.Values{}) {
t.Fatalf("expected MergeCreate to return false for nil schema")
}
// Direct call with empty primary fields
if err := db.Statement.Parse(&noPrimaryKeyModel{}); err != nil {
t.Fatalf("failed to parse model: %v", err)
}
if sqlserver.MergeCreate(db, clause.OnConflict{}, clause.Values{}) {
t.Fatalf("expected MergeCreate to return false for schema without primary keys")
}
}
func TestCreateSQL_IdentityInsertUsesSchemaQualifiedTable(t *testing.T) {
db := openDryRunDB(t)
tx := db.Create(&identityInsertSchemaTableModel{ID: 42, Name: "bob"})
if tx.Error != nil {
t.Fatalf("create failed: %v", tx.Error)
}
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, `SET IDENTITY_INSERT "testschema"."identity_models" ON;`) {
t.Fatalf("expected schema-qualified IDENTITY_INSERT ON, got SQL: %s", sql)
}
if !strings.Contains(sql, `SET IDENTITY_INSERT "testschema"."identity_models" OFF;`) {
t.Fatalf("expected schema-qualified IDENTITY_INSERT OFF, got SQL: %s", sql)
}
}