Skip to content

Commit 328f301

Browse files
authored
add some test case which related the logic (go-gorm#5477)
1 parent 1223745 commit 328f301

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

schema/schema.go

+8
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,14 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam
239239
field.HasDefaultValue = true
240240
field.AutoIncrement = true
241241
}
242+
case String:
243+
if _, ok := field.TagSettings["PRIMARYKEY"]; !ok {
244+
if !field.HasDefaultValue || field.DefaultValueInterface != nil {
245+
schema.FieldsWithDefaultDBValue = append(schema.FieldsWithDefaultDBValue, field)
246+
}
247+
248+
field.HasDefaultValue = true
249+
}
242250
}
243251
}
244252

tests/postgres_test.go

+50
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,56 @@ import (
99
"gorm.io/gorm"
1010
)
1111

12+
func TestPostgresReturningIDWhichHasStringType(t *testing.T) {
13+
if DB.Dialector.Name() != "postgres" {
14+
t.Skip()
15+
}
16+
17+
type Yasuo struct {
18+
ID string `gorm:"default:gen_random_uuid()"`
19+
Name string
20+
CreatedAt time.Time `gorm:"type:TIMESTAMP WITHOUT TIME ZONE"`
21+
UpdatedAt time.Time `gorm:"type:TIMESTAMP WITHOUT TIME ZONE;default:current_timestamp"`
22+
}
23+
24+
if err := DB.Exec("CREATE EXTENSION IF NOT EXISTS pgcrypto;").Error; err != nil {
25+
t.Errorf("Failed to create extension pgcrypto, got error %v", err)
26+
}
27+
28+
DB.Migrator().DropTable(&Yasuo{})
29+
30+
if err := DB.AutoMigrate(&Yasuo{}); err != nil {
31+
t.Fatalf("Failed to migrate for uuid default value, got error: %v", err)
32+
}
33+
34+
yasuo := Yasuo{Name: "jinzhu"}
35+
if err := DB.Create(&yasuo).Error; err != nil {
36+
t.Fatalf("should be able to create data, but got %v", err)
37+
}
38+
39+
if yasuo.ID == "" {
40+
t.Fatal("should be able to has ID, but got zero value")
41+
}
42+
43+
var result Yasuo
44+
if err := DB.First(&result, "id = ?", yasuo.ID).Error; err != nil || yasuo.Name != "jinzhu" {
45+
t.Errorf("No error should happen, but got %v", err)
46+
}
47+
48+
if err := DB.Where("id = $1", yasuo.ID).First(&Yasuo{}).Error; err != nil || yasuo.Name != "jinzhu" {
49+
t.Errorf("No error should happen, but got %v", err)
50+
}
51+
52+
yasuo.Name = "jinzhu1"
53+
if err := DB.Save(&yasuo).Error; err != nil {
54+
t.Errorf("Failed to update date, got error %v", err)
55+
}
56+
57+
if err := DB.First(&result, "id = ?", yasuo.ID).Error; err != nil || yasuo.Name != "jinzhu1" {
58+
t.Errorf("No error should happen, but got %v", err)
59+
}
60+
}
61+
1262
func TestPostgres(t *testing.T) {
1363
if DB.Dialector.Name() != "postgres" {
1464
t.Skip()

0 commit comments

Comments
 (0)