-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdelete.go
84 lines (73 loc) · 2.38 KB
/
delete.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gormet
import (
"errors"
"fmt"
)
// DeleteById removes an entity from the database using its ID.
//
// This method takes an ID as an argument, ensures it is not nil, and then uses GORM's Delete method
// to delete the corresponding record from the database. The repository's primary key name is used
// in the query condition. If the operation is successful, it returns nil. If the operation fails,
// an error is returned, which could be due to database connectivity issues or other constraints.
//
// Usage:
// err := repo.DeleteById(id)
//
// if err != nil {
// // Handle error
// }
//
// Parameters:
// - id: An interface{} representing the ID of the entity to be deleted from the database.
// It should not be nil.
//
// Returns:
// - nil if the entity is successfully deleted from the database.
// - An error if the ID is nil or if GORM encounters any issues while deleting the record.
func (r *Repository[T]) DeleteById(id interface{}) error {
if id == nil {
return errors.New("the ID should not be nil")
}
condition := fmt.Sprintf("%s = ?", r.pkName)
deleteResult := r.db.Delete(new(T), condition, id)
if deleteResult.Error != nil {
return deleteResult.Error
}
if deleteResult.RowsAffected == 0 {
return fmt.Errorf("no register found")
}
return nil
}
// Delete removes an entity from the database.
//
// This method takes an entity as an argument, ensures it is not nil, and then uses GORM's Delete method
// to delete the corresponding record from the database. If the operation is successful, it returns nil.
// If the operation fails, an error is returned, which could be due to database connectivity issues or other constraints.
//
// Usage:
// err := repo.Delete(&entity)
//
// if err != nil {
// // Handle error
// }
//
// Parameters:
// - entity: A pointer to an instance of type T that represents the entity to be deleted from the database.
// It should not be nil.
//
// Returns:
// - nil if the entity is successfully deleted from the database.
// - An error if the entity is nil or if GORM encounters any issues while deleting the record.
func (r *Repository[T]) Delete(entity *T) error {
if entity == nil {
return errors.New("the entity should not be nil")
}
deleteResult := r.db.Delete(entity)
if deleteResult.Error != nil {
return deleteResult.Error
}
if deleteResult.RowsAffected == 0 {
return fmt.Errorf("no register found")
}
return nil
}