Skip to content

Commit

Permalink
add fieldIsPrimaryAndBlank function to handle with both auto_increm…
Browse files Browse the repository at this point in the history
…ent column and naturary key column
  • Loading branch information
t-tiger committed Dec 2, 2019
1 parent 2b57f99 commit 8a8235c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion bulk_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func extractMapValue(value interface{}, excludeColumns []string) (map[string]int
_, hasForeignKey := field.TagSettingsGet("FOREIGNKEY")

if !containString(excludeColumns, field.Struct.Name) && field.StructField.Relationship == nil && !hasForeignKey &&
!field.IsIgnored && !fieldIsAutoIncrement(field) {
!field.IsIgnored && !fieldIsAutoIncrement(field) && !fieldIsPrimaryAndBlank(field) {
if (field.Struct.Name == "CreatedAt" || field.Struct.Name == "UpdatedAt") && field.IsBlank {
attrs[field.DBName] = time.Now()
} else if field.StructField.HasDefaultValue && field.IsBlank {
Expand All @@ -127,3 +127,7 @@ func fieldIsAutoIncrement(field *gorm.Field) bool {
}
return false
}

func fieldIsPrimaryAndBlank(field *gorm.Field) bool {
return field.IsPrimaryKey && field.IsBlank
}
24 changes: 24 additions & 0 deletions bulk_insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,27 @@ func Test_fieldIsAutoIncrement(t *testing.T) {
}
}
}

func Test_fieldIsPrimaryAndBlank(t *testing.T) {
type notPrimaryTable struct {
Dummy int
}
type primaryKeyTable struct {
ID int `gorm:"column:id;primary_key"`
}

cases := []struct {
Value interface{}
Expected bool
}{
{notPrimaryTable{Dummy: 0}, false},
{notPrimaryTable{Dummy: 1}, false},
{primaryKeyTable{ID: 0}, true},
{primaryKeyTable{ID: 1}, false},
}
for _, c := range cases {
for _, field := range (&gorm.Scope{Value: c.Value}).Fields() {
assert.Equal(t, fieldIsPrimaryAndBlank(field), c.Expected)
}
}
}

0 comments on commit 8a8235c

Please sign in to comment.