map insert support return increment id

This commit is contained in:
方圣卿 2023-10-26 21:32:51 +08:00
parent c1e911f6ed
commit 5b4695a334
2 changed files with 36 additions and 1 deletions

View File

@ -148,6 +148,39 @@ func Create(config *Config) func(db *gorm.DB) {
}
}
}
// append @id column with value for auto-increment primary key
// the @id value is correct, when: 1. without setting auto-increment primary key, 2. database AutoIncrementIncrement = 1
if db.RowsAffected != 0 && db.Statement.Schema == nil && db.Statement.Dest != nil {
insertID, err := result.LastInsertId()
insertOk := err == nil && insertID > 0
if !insertOk {
db.AddError(err)
return
}
switch values := db.Statement.Dest.(type) {
case map[string]interface{}:
values["@id"] = insertID
case *map[string]interface{}:
(*values)["@id"] = insertID
case []map[string]interface{}, *[]map[string]interface{}:
mapValues, ok := values.([]map[string]interface{})
if !ok {
if v, ok := values.(*[]map[string]interface{}); ok {
if *v != nil {
mapValues = *v
}
}
}
for _, mapValue := range mapValues {
if mapValue != nil {
mapValue["@id"] = insertID
}
insertID += schema.DefaultAutoIncrementIncrement
}
}
}
}
}

View File

@ -49,6 +49,8 @@ const (
Bytes DataType = "bytes"
)
const DefaultAutoIncrementIncrement int64 = 1
// Field is the representation of model schema's field
type Field struct {
Name string
@ -119,7 +121,7 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
NotNull: utils.CheckTruth(tagSetting["NOT NULL"], tagSetting["NOTNULL"]),
Unique: utils.CheckTruth(tagSetting["UNIQUE"]),
Comment: tagSetting["COMMENT"],
AutoIncrementIncrement: 1,
AutoIncrementIncrement: DefaultAutoIncrementIncrement,
}
for field.IndirectFieldType.Kind() == reflect.Ptr {