feat: Ignore LastInsertID failed

LastInsertID not yet supported by some database drivers. Users could avoid errors through configuration.

Close https://github.com/go-gorm/gorm/issues/6343
This commit is contained in:
Krisdiano 2025-05-29 19:52:36 +08:00
parent 49b01a3e93
commit 273cf6491f
2 changed files with 25 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package callbacks
import (
"database/sql/driver"
"fmt"
"reflect"
"strings"
@ -68,8 +69,8 @@ func Create(config *Config) func(db *gorm.DB) {
db.Statement.Build(db.Statement.BuildClauses...)
}
isDryRun := !db.DryRun && db.Error == nil
if !isDryRun {
notDryRun := !db.DryRun && db.Error == nil
if !notDryRun {
return
}
@ -126,6 +127,22 @@ func Create(config *Config) func(db *gorm.DB) {
insertOk := err == nil && insertID > 0
if !insertOk {
if db.Config.IgnoreLastInsertIDWhenNotSupport {
_, rowsAffectedErr := driver.RowsAffected(0).LastInsertId()
if strings.Compare(err.Error(), rowsAffectedErr.Error()) == 0 {
return
}
_, resultNoRowsErr := driver.ResultNoRows.LastInsertId()
if strings.Compare(err.Error(), resultNoRowsErr.Error()) == 0 {
return
}
if db.Config.IsNotSupportLastInsertIDErr != nil && db.Config.IsNotSupportLastInsertIDErr(err) {
return
}
if db.Logger != nil {
db.Logger.Warn(db.Statement.Context, "Failed to get last insert ID, err: %v", err)
}
}
if !supportReturning {
db.AddError(err)
}

View File

@ -24,6 +24,12 @@ type Config struct {
SkipDefaultTransaction bool
DefaultTransactionTimeout time.Duration
// Not all database support LastInsertId, you can set `IgnoreLastInsertIDWhenNotSupport` to true in those cases
IgnoreLastInsertIDWhenNotSupport bool
// When 'IgnoreLastInsertIDWhenNotSupport' is true, you can set `IsNotSupportLastInsertIDErr` to check if the error is 'NotSupportLastInsertID'
// Gorm only asserts the type of returned sql/driver.Result if 'IsNotSupportLastInsertIDErr' is not set.
IsNotSupportLastInsertIDErr func(error) bool
// NamingStrategy tables, columns naming strategy
NamingStrategy schema.Namer
// FullSaveAssociations full save associations