customize_column_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package gorm_test
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. type CustomizeColumn struct {
  7. ID int64 `gorm:"column:mapped_id; primary_key:yes"`
  8. Name string `gorm:"column:mapped_name"`
  9. Date time.Time `gorm:"column:mapped_time"`
  10. }
  11. // Make sure an ignored field does not interfere with another field's custom
  12. // column name that matches the ignored field.
  13. type CustomColumnAndIgnoredFieldClash struct {
  14. Body string `sql:"-"`
  15. RawBody string `gorm:"column:body"`
  16. }
  17. func TestCustomizeColumn(t *testing.T) {
  18. col := "mapped_name"
  19. DB.DropTable(&CustomizeColumn{})
  20. DB.AutoMigrate(&CustomizeColumn{})
  21. scope := DB.Model("").NewScope(&CustomizeColumn{})
  22. if !scope.Dialect().HasColumn(scope, scope.TableName(), col) {
  23. t.Errorf("CustomizeColumn should have column %s", col)
  24. }
  25. col = "mapped_id"
  26. if scope.PrimaryKey() != col {
  27. t.Errorf("CustomizeColumn should have primary key %s, but got %q", col, scope.PrimaryKey())
  28. }
  29. expected := "foo"
  30. cc := CustomizeColumn{ID: 666, Name: expected, Date: time.Now()}
  31. if count := DB.Create(&cc).RowsAffected; count != 1 {
  32. t.Error("There should be one record be affected when create record")
  33. }
  34. var cc1 CustomizeColumn
  35. DB.First(&cc1, 666)
  36. if cc1.Name != expected {
  37. t.Errorf("Failed to query CustomizeColumn")
  38. }
  39. cc.Name = "bar"
  40. DB.Save(&cc)
  41. var cc2 CustomizeColumn
  42. DB.First(&cc2, 666)
  43. if cc2.Name != "bar" {
  44. t.Errorf("Failed to query CustomizeColumn")
  45. }
  46. }
  47. func TestCustomColumnAndIgnoredFieldClash(t *testing.T) {
  48. DB.DropTable(&CustomColumnAndIgnoredFieldClash{})
  49. DB.AutoMigrate(&CustomColumnAndIgnoredFieldClash{})
  50. }