Compare commits
2 Commits
v1.0.6
...
98094abf3e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98094abf3e | ||
|
|
97a3ebf3a0 |
37
dbHandler.go
37
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
|
||||
}
|
||||
|
||||
@@ -314,15 +294,10 @@ func (dH *DBHandler) Exists(model any, key string, value any, likeSearch bool) (
|
||||
|
||||
dH.logger.Debug("exists", "checking existence for key "+query+" value "+fmt.Sprint(args))
|
||||
|
||||
t := reflect.TypeOf(model)
|
||||
if t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
tx := dH.db.Where(query, args).Find(model)
|
||||
|
||||
if tx.Error != nil {
|
||||
dH.logger.Error("Exists", fmt.Sprintf("query failed: %w", tx.Error))
|
||||
dH.logger.Error("Exists", fmt.Sprintf("query failed: %v", tx.Error))
|
||||
return false
|
||||
}
|
||||
return tx.RowsAffected > 0
|
||||
|
||||
Reference in New Issue
Block a user