Your Question

I have a custom callback like this:

func customAfterModifyCallback(db *gorm.DB) {
    if db.Error == nil { //This should only happen if GORM successfully make a `commit`
        tbName := db.Statement.Schema.Table
        var rowId any                                      //Row ID should only be a string or a number
        for _, field := range db.Statement.Schema.Fields { //Get model fields
            if field.PrimaryKey {
                rowId, _ = field.ValueOf(db.Statement.Context, db.Statement.ReflectValue)
            }
        }
        fmt.Println(db.RowsAffected, tbName, rowId)
    }
}

//...
if svDB, err := gorm.Open(sqlite.Open(serverDsn), &gorm.Config{SkipDefaultTransaction: true, PrepareStmt: true}); err == nil {
    //
    svDB.Callback().Create().After("gorm:commit").Register("cbf:customAfterModifyCallback", customAfterModifyCallback)
    svDB.Callback().Update().After("gorm:commit").Register("cbf:customAfterModifyCallback", customAfterModifyCallback)
    svDB.Callback().Delete().After("gorm:commit").Register("cbf:customAfterModifyCallback", customAfterModifyCallback)
    //
}

How do I know which operation was use in the callback? For instance, I want to know if it was INSERT, UPDATE or DELETE operation?

Thanks,

The document you expected this should be explained

N/A

Expected answer

...

Comment From: clov3r

I expect you could figure it out eventually by examining the db.Statement. Maybe you could range over db.Statement.Clauses? Maybe you can infer it from db.Statement.Selects? Maybe you could regexp match db.Statement.SQL?

I don't know, that all sounds pretty sketchy.

I were you, I would create separate functions for each callback, and "hard code" it:

``` func customAfterModifyCallback(db gorm.DB, operationType string / or some type */) { // your implementation }

func customAfterCreateCallback(db * gorm.DB) { customAfterModifyCallback(db, "create") }

func customAfterUpdateCallback(db * gorm.DB) { customAfterModifyCallback(db, "update") }

func customAfterDeleteCallback(db * gorm.DB) { customAfterModifyCallback(db, "delete") }

// ... svDB.Callback().Create().After("gorm:commit").Register("cbf:customAfterCreateCallback", customAfterCreateCallback) svDB.Callback().Update().After("gorm:commit").Register("cbf:customAfterUpdateCallback", customAfterUpdateCallback) svDB.Callback().Delete().After("gorm:commit").Register("cbf:customAfterDeleteCallback", customAfterDeleteCallback)