fix delete function
This commit is contained in:
30
dbHandler.go
30
dbHandler.go
@@ -218,42 +218,22 @@ func (dH *DBHandler) UpdateValuesByKey(model any, key string, value any) error {
|
||||
return dH.db.Model(lookUpModel).Updates(model).Error
|
||||
}
|
||||
|
||||
// deleteById
|
||||
//
|
||||
// Description:
|
||||
//
|
||||
// Deletes records by their ID(s).
|
||||
//
|
||||
// Behavior:
|
||||
// - If the first ID == 0, all records in the table are deleted.
|
||||
// - Otherwise, deletes the provided IDs.
|
||||
//
|
||||
// Parameters:
|
||||
// - model: Model struct type representing the table.
|
||||
// - id: Variadic list of IDs to delete.
|
||||
//
|
||||
// Returns:
|
||||
// - error: Any deletion error.
|
||||
func (dH *DBHandler) DeleteById(model any, ids ...uint) error {
|
||||
if len(ids) == 0 {
|
||||
return fmt.Errorf("no IDs provided")
|
||||
}
|
||||
|
||||
if ids[0] == 0 {
|
||||
dH.logger.Debug("deleteById", "delete all")
|
||||
return dH.db.Where("1 = 1").Delete(model).Error
|
||||
if len(ids) == 1 && ids[0] == 0 {
|
||||
dH.logger.Debug("deleteById", "delete ALL records!")
|
||||
return dH.db.Session(&gorm.Session{AllowGlobalUpdate: true}).
|
||||
Delete(model).Error
|
||||
}
|
||||
|
||||
dH.logger.Debug("deleteById", "delete ids "+fmt.Sprint(ids))
|
||||
if !dH.Exists(model, "id", ids, false) {
|
||||
return errors.New("no matching id(s) found")
|
||||
}
|
||||
|
||||
// Always use Model() to avoid GORM’s “limit 1” safeguard
|
||||
if err := dH.db.Model(model).Where("id IN ?", ids).Delete(nil).Error; err != nil {
|
||||
if err := dH.db.Delete(model, ids).Error; err != nil {
|
||||
return fmt.Errorf("delete failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user