Skip to content

Commit

Permalink
modify behavior for auto_increment column
Browse files Browse the repository at this point in the history
  • Loading branch information
t-tiger committed Nov 24, 2019
1 parent 55fd473 commit eab1a9e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ Basically, inserting struct values are automatically chosen. However if you want

In the above pattern `Name` and `Email` fields are excluded.

### AUTO INCREMENT

If auto_increment attribute is assigned to the primary key etc, make sure to set `AUTO_INCREMENT` in model struct.

```go
type fakeTable struct {
ID int `gorm:"AUTO_INCREMENT"`
Name string
}
```

This is necessary to exclude the auto_increment column from insertion and be numbered by database system. The reason for this requirement is that if all primary keys are excluded, only the surrogate key like auto_increment can be inserted and natural key cannot at all.

### Feature

- Just pass a slice of struct as using gorm normally, records will be created.
Expand Down
4 changes: 2 additions & 2 deletions 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 && !(field.DBName == "id" || fieldIsAutoIncrement(field)) {
!field.IsIgnored && !fieldIsAutoIncrement(field) {
if field.Struct.Name == "CreatedAt" || field.Struct.Name == "UpdatedAt" {
attrs[field.DBName] = time.Now()
} else if field.StructField.HasDefaultValue && field.IsBlank {
Expand All @@ -125,5 +125,5 @@ func fieldIsAutoIncrement(field *gorm.Field) bool {
if value, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok {
return strings.ToLower(value) != "false"
}
return field.IsPrimaryKey
return false
}

0 comments on commit eab1a9e

Please sign in to comment.