|
| 1 | +package tests |
| 2 | + |
| 3 | +import ( |
| 4 | + "regexp" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "gorm.io/gorm" |
| 8 | +) |
| 9 | + |
| 10 | +type Student struct { |
| 11 | + ID uint |
| 12 | + Name string |
| 13 | +} |
| 14 | + |
| 15 | +func (s Student) TableName() string { |
| 16 | + return "STUDENTS" |
| 17 | +} |
| 18 | + |
| 19 | +func TestSkipQuoteIdentifiers(t *testing.T) { |
| 20 | + db, err := openTestDBWithOptions(true, &gorm.Config{ |
| 21 | + Logger: newLogger, |
| 22 | + }) |
| 23 | + if err != nil { |
| 24 | + t.Fatalf("failed to connect database, got error %v", err) |
| 25 | + } |
| 26 | + |
| 27 | + db.Migrator().DropTable(&Student{}) |
| 28 | + db.Migrator().CreateTable(&Student{}) |
| 29 | + |
| 30 | + if !db.Migrator().HasTable(&Student{}) { |
| 31 | + t.Errorf("Failed to get table: student") |
| 32 | + } |
| 33 | + |
| 34 | + if !db.Migrator().HasColumn(&Student{}, "ID") { |
| 35 | + t.Errorf("Failed to get column: id") |
| 36 | + } |
| 37 | + |
| 38 | + if !db.Migrator().HasColumn(&Student{}, "NAME") { |
| 39 | + t.Errorf("Failed to get column: name") |
| 40 | + } |
| 41 | + |
| 42 | + dryrunDB := db.Session(&gorm.Session{DryRun: true}) |
| 43 | + |
| 44 | + result := dryrunDB.Model(&Student{}).Create(&Student{ID: 1, Name: "John"}) |
| 45 | + if !regexp.MustCompile(`^INSERT INTO STUDENTS \(name,id\) VALUES \(:1,:2\)$`).MatchString(result.Statement.SQL.String()) { |
| 46 | + t.Errorf("invalid insert SQL, got %v", result.Statement.SQL.String()) |
| 47 | + } |
| 48 | + |
| 49 | + result = dryrunDB.First(&Student{}) |
| 50 | + if !regexp.MustCompile(`^SELECT \* FROM STUDENTS ORDER BY STUDENTS\.id FETCH NEXT 1 ROW ONLY$`).MatchString(result.Statement.SQL.String()) { |
| 51 | + t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String()) |
| 52 | + } |
| 53 | + |
| 54 | + result = dryrunDB.Find(&Student{ID: 1, Name: "John"}) |
| 55 | + if !regexp.MustCompile(`^SELECT \* FROM STUDENTS WHERE STUDENTS\.id = :1$`).MatchString(result.Statement.SQL.String()) { |
| 56 | + t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String()) |
| 57 | + } |
| 58 | + |
| 59 | + result = dryrunDB.Save(&Student{ID: 2, Name: "Mary"}) |
| 60 | + if !regexp.MustCompile(`^UPDATE STUDENTS SET name=:1 WHERE id = :2$`).MatchString(result.Statement.SQL.String()) { |
| 61 | + t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String()) |
| 62 | + } |
| 63 | + |
| 64 | + // Update with conditions |
| 65 | + result = dryrunDB.Model(&Student{}).Where("id = ?", 1).Update("name", "hello") |
| 66 | + if !regexp.MustCompile(`^UPDATE STUDENTS SET name=:1 WHERE id = :2$`).MatchString(result.Statement.SQL.String()) { |
| 67 | + t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String()) |
| 68 | + } |
| 69 | +} |
0 commit comments