Last active
October 17, 2023 18:34
-
-
Save lundha/d592bd11f1c490999e3bcdb272e114bc to your computer and use it in GitHub Desktop.
Gorm v2.0 cleanup hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func DeleteCreatedEntities(db *gorm.DB) func() { | |
hookName := "cleanupHook" | |
type entity struct { | |
table string | |
key string | |
value interface{} | |
} | |
var entries []entity | |
db.Callback().Create().After("gorm:create").Register(hookName, func(db *gorm.DB) { | |
field := db.Statement.Schema.PrioritizedPrimaryField | |
fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue) | |
if isZero { | |
fmt.Printf("field %s is zero\n", field.Name) | |
return | |
} | |
fmt.Printf("Inserted entities of %s with %v=%v\n", db.Statement.Table, field.Name, fieldValue) | |
entries = append(entries, entity{table: db.Statement.Table, key: field.Name, value: fieldValue}) | |
}) | |
return func() { | |
// clean up | |
defer db.Callback().Create().Remove(hookName) | |
for i := len(entries) - 1; i >= 0; i-- { | |
entry := entries[i] | |
fmt.Printf("Deleting entities from '%s' table with key %v\n and value %v\n", entry.table, entry.key, entry.value) | |
db.Table(entry.table).Where(entry.key+" = ?", entry.value).Delete("") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment