This repository was archived by the owner on Jan 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgorm_test.go
More file actions
521 lines (454 loc) · 12.5 KB
/
gorm_test.go
File metadata and controls
521 lines (454 loc) · 12.5 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package turso_go_test
import (
"database/sql"
"fmt"
"testing"
"time"
_ "github.com/tursodatabase/turso-go"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Database struct {
gorm.Model
Hostname string `gorm:"unique;not null"`
Namespace string
Address string
PrimaryAddress string
CloudClusterName string
Local bool
AllowedIPs string
}
func openGormDB(t *testing.T) *gorm.DB {
t.Helper()
sqlDB, err := sql.Open("turso", ":memory:")
if err != nil {
t.Fatalf("failed to open sql connection: %v", err)
}
db, err := gorm.Open(sqlite.Dialector{
Conn: sqlDB,
}, &gorm.Config{})
if err != nil {
t.Fatalf("failed to open gorm connection: %v", err)
}
t.Cleanup(func() {
sqlDB, _ := db.DB()
sqlDB.Close()
})
return db
}
func TestReturningColumnName(t *testing.T) {
db := openGormDB(t)
sqlDB, _ := db.DB()
sqlDB.Exec("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)")
rows, _ := sqlDB.Query("INSERT INTO test (name) VALUES ('test') RETURNING id")
defer rows.Close()
cols, _ := rows.Columns()
t.Logf("Column names: %v", cols) // Should print ["id"] not ["rowid"]
if cols[0] != "id" {
t.Fatalf("expected column name 'id', got '%s'", cols[0])
}
}
func TestGormBasicOperations(t *testing.T) {
db := openGormDB(t)
// Create table
err := db.Debug().AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
record := Database{
Hostname: "test.local",
Namespace: "ns-test",
Address: "http://test:8080",
CloudClusterName: "cluster-1",
}
result := db.Debug().Create(&record)
if result.Error != nil {
t.Fatalf("create failed: %v", result.Error)
}
if result.RowsAffected != 1 {
t.Fatalf("expected 1 row affected, got %d", result.RowsAffected)
}
if record.ID == 0 {
t.Fatal("expected ID to be set after create")
}
var found Database
err = db.Debug().Where("hostname = ?", "test.local").First(&found).Error
if err != nil {
t.Fatalf("find failed: %v", err)
}
if found.Hostname != "test.local" {
t.Fatalf("unexpected hostname: %s", found.Hostname)
}
}
func TestGormUpsert(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
record := Database{
Hostname: "upsert-test.local",
Namespace: "ns-1",
Address: "http://addr1",
}
err = db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "hostname"}},
UpdateAll: true,
}).Create(&record).Error
if err != nil {
t.Fatalf("first upsert failed: %v", err)
}
originalID := record.ID
if originalID == 0 {
t.Fatal("expected ID to be set after upsert")
}
record2 := Database{
Hostname: "upsert-test.local",
Namespace: "ns-2",
Address: "http://addr2",
}
err = db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "hostname"}},
UpdateAll: true,
}).Create(&record2).Error
if err != nil {
t.Fatalf("second upsert (update) failed: %v", err)
}
var count int64
db.Model(&Database{}).Where("hostname = ?", "upsert-test.local").Count(&count)
if count != 1 {
t.Fatalf("expected 1 record, got %d", count)
}
var updated Database
db.Where("hostname = ?", "upsert-test.local").First(&updated)
if updated.Namespace != "ns-2" {
t.Fatalf("expected namespace to be updated to ns-2, got %s", updated.Namespace)
}
}
func TestReturningLimitParameters(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
record := Database{
Hostname: "returning-test.local",
Namespace: "ns-returning",
Address: "http://returning",
}
sql := "SELECT id FROM databases WHERE hostname = ? LIMIT ? OFFSET ?"
id := uint(0)
err = db.Raw(sql, id, 1, 0).Scan(&record.ID).Error
if err != nil {
t.Fatalf("raw query failed: %v", err)
}
if record.ID != 0 {
t.Fatalf("expected ID to be 0, got %d", record.ID)
}
}
func TestGormUpsertWithReturning(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
t.Run("RawSQLReturning", func(t *testing.T) {
sqlDB, _ := db.DB()
const query = `
INSERT INTO databases (created_at, updated_at, hostname, namespace, address, primary_address, cloud_cluster_name, local, allowed_ips)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (hostname) DO UPDATE SET
updated_at = excluded.updated_at,
namespace = excluded.namespace
RETURNING id`
stmt, err := sqlDB.Prepare(query)
if err != nil {
t.Fatalf("prepare failed: %v", err)
}
defer stmt.Close()
now := time.Now()
var returnedID int64
err = stmt.QueryRow(
now, now, "raw-test.local", "ns-raw",
"http://raw", "", "cluster-raw", false, "",
).Scan(&returnedID)
if err != nil {
t.Fatalf("raw upsert with returning failed: %v", err)
}
if returnedID == 0 {
t.Fatal("expected non-zero ID from RETURNING")
}
t.Logf("Raw SQL RETURNING worked, ID: %d", returnedID)
})
t.Run("BatchUpsert", func(t *testing.T) {
records := []Database{
{Hostname: "batch1.local", Namespace: "ns1"},
{Hostname: "batch2.local", Namespace: "ns2"},
{Hostname: "batch3.local", Namespace: "ns3"},
}
err := db.Debug().Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "hostname"}},
UpdateAll: true,
}).Create(&records).Error
if err != nil {
t.Fatalf("batch upsert failed: %v", err)
}
for i, r := range records {
if r.ID == 0 {
t.Errorf("record %d has zero ID after batch upsert", i)
}
}
})
}
func TestGormSoftDelete(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
testData := []Database{
{Hostname: "soft1.local", Namespace: "ns1"},
{Hostname: "soft2.local", Namespace: "ns2"},
{Hostname: "soft3.local", Namespace: "ns3"},
}
err = db.Create(&testData).Error
if err != nil {
t.Fatalf("create test data failed: %v", err)
}
// delete a row
err = db.Where("hostname = ?", "soft2.local").Delete(&Database{}).Error
if err != nil {
t.Fatalf("soft delete failed: %v", err)
}
// select non-deleted rows
var rows []Database
err = db.Find(&rows).Error
if err != nil {
t.Fatalf("find non-deleted failed: %v", err)
}
if len(rows) != 2 {
t.Fatalf("expected 2 non-deleted rows, got %d", len(rows))
}
for _, r := range rows {
if r.Hostname == "soft2.local" {
t.Fatalf("soft-deleted record still found in normal query")
}
}
}
func TestGormComplexQueries(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
testData := []Database{
{Hostname: "host1.local", Namespace: "ns1"},
{Hostname: "host2.local", Namespace: "ns2"},
{Hostname: "host3.local", Namespace: "ns3"},
}
hour := -2 * time.Hour
for _, d := range testData {
d.UpdatedAt = time.Now().Add(hour)
hour += time.Hour
db.Create(&d)
}
db.Where("hostname = ?", "host2.local").Delete(&Database{})
t.Run("GetNonDeleted", func(t *testing.T) {
rows, err := db.Debug().Model(&Database{}).Where("deleted_at IS NULL").Rows()
if err != nil {
t.Fatalf("get non-deleted failed: %v", err)
}
defer rows.Close()
count := 0
for rows.Next() {
var database Database
err := db.ScanRows(rows, &database)
if err != nil {
t.Fatalf("scan rows failed: %v", err)
}
count++
}
// Should find host1 and host3
if count != 2 {
t.Fatalf("expected 2 non-deleted records, got %d", count)
}
})
t.Run("UnscopedQuery", func(t *testing.T) {
var count int64
db.Unscoped().Model(&Database{}).Count(&count)
if count != 3 {
t.Fatalf("expected 3 total records (including soft-deleted), got %d", count)
}
})
}
func TestGormColumnCountIssue(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
t.Run("UpsertReturningColumnCount", func(t *testing.T) {
record := Database{
Hostname: "column-test.local",
}
err := db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "hostname"}},
UpdateAll: true,
}).Create(&record).Error
if err != nil {
t.Fatalf("first upsert failed: %v", err)
}
record2 := Database{
Hostname: "column-test.local",
Namespace: "ns-test",
Address: "http://test",
PrimaryAddress: "http://primary",
CloudClusterName: "cluster",
Local: true,
AllowedIPs: "192.168.1.0/24",
}
err = db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "hostname"}},
UpdateAll: true,
}).Create(&record2).Error
if err != nil {
// This is where we expect to catch the column mismatch error
t.Logf("Caught potential column mismatch error: %v", err)
t.Fatalf("second upsert failed: %v", err)
}
})
t.Run("ExplicitReturningClause", func(t *testing.T) {
sqlDB, _ := db.DB()
testCases := []struct {
name string
returning string
}{
{"returning_id", "RETURNING id"},
{"returning_star", "RETURNING *"},
{"returning_multiple", "RETURNING id, updated_at, hostname"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
query := `
INSERT INTO databases (hostname, namespace)
VALUES (?, ?)
ON CONFLICT (hostname) DO UPDATE SET
namespace = excluded.namespace
` + tc.returning
rows, err := sqlDB.Query(query, tc.name+".local", "ns-test")
if err != nil {
t.Fatalf("%s query failed: %v", tc.name, err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
t.Fatalf("get columns failed: %v", err)
}
t.Logf("%s returned %d columns: %v", tc.name, len(cols), cols)
})
}
})
}
func TestGormLastMethod(t *testing.T) {
db := openGormDB(t)
err := db.AutoMigrate(&Database{})
if err != nil {
t.Fatalf("automigrate failed: %v", err)
}
for i := 1; i <= 3; i++ {
db.Create(&Database{
Hostname: fmt.Sprintf("last-test-%d.local", i),
Namespace: fmt.Sprintf("ns-%d", i),
})
time.Sleep(10 * time.Millisecond)
}
var database Database
err = db.Where(Database{Hostname: "last-test-2.local"}).Last(&database).Error
if err != nil {
t.Fatalf("Last() failed: %v", err)
}
if database.Hostname != "last-test-2.local" {
t.Fatalf("unexpected hostname from Last(): %s", database.Hostname)
}
}
func TestGormPartialIndexes(t *testing.T) {
db := openGormDB(t)
sqlDB, _ := db.DB()
_, err := sqlDB.Exec(`
CREATE TABLE partial_index_test (
id INTEGER PRIMARY KEY,
status TEXT,
priority INTEGER,
deleted_at TIMESTAMP,
email TEXT,
active BOOLEAN
)
`)
if err != nil {
t.Fatalf("failed to create table: %v", err)
}
// Test creating partial indexes
t.Run("CreatePartialIndexes", func(t *testing.T) {
_, err := sqlDB.Exec(`
CREATE UNIQUE INDEX idx_active_email
ON partial_index_test(email)
WHERE active = 1
`)
if err != nil {
t.Fatalf("failed to create partial unique index: %v", err)
}
_, err = sqlDB.Exec(`
CREATE INDEX idx_high_priority
ON partial_index_test(priority, status)
WHERE priority > 5 AND status != 'archived'
`)
if err != nil {
t.Fatalf("failed to create partial index with complex WHERE: %v", err)
}
_, err = sqlDB.Exec(`
CREATE INDEX idx_not_deleted
ON partial_index_test(status)
WHERE deleted_at IS NULL
`)
if err != nil {
t.Fatalf("failed to create partial index with IS NULL: %v", err)
}
})
t.Run("PartialUniqueConstraint", func(t *testing.T) {
// Insert active user with email
_, err := sqlDB.Exec(`
INSERT INTO partial_index_test (email, active, status, priority)
VALUES (?, ?, ?, ?)
`, "user@example.com", true, "active", 3)
if err != nil {
t.Fatalf("failed to insert first active user: %v", err)
}
// Should succeed - same email but inactive user
_, err = sqlDB.Exec(`
INSERT INTO partial_index_test (email, active, status, priority)
VALUES (?, ?, ?, ?)
`, "user@example.com", false, "inactive", 2)
if err != nil {
t.Fatalf("failed to insert inactive user with same email: %v", err)
}
// Should fail - duplicate email for active user
_, err = sqlDB.Exec(`
INSERT INTO partial_index_test (email, active, status, priority)
VALUES (?, ?, ?, ?)
`, "user@example.com", true, "active", 5)
if err == nil {
t.Fatal("expected unique constraint violation for duplicate active email")
}
})
t.Run("ComplexWhereClause", func(t *testing.T) {
_, err := sqlDB.Exec(`
CREATE INDEX IF NOT EXISTS idx_complex
ON partial_index_test(id)
WHERE (priority BETWEEN 3 AND 7) AND status IN ('active', 'pending')
`)
if err != nil {
t.Fatalf("failed to create complex partial index: %v", err)
}
})
}