Your Question

I created a pagination plugin that basically do a select count(*) once a select query is triggered. The code can be found here: https://github.com/manuelarte/pagorminator

But, I want to reuse the "context" from the original query, in the select count query that the plugin does.

So basically I am registering a callback like this:

func (p PaGormMinator) Initialize(db *gorm.DB) error {
    err := db.Callback().Query().Before("gorm:query").Register("pagorminator:count", p.count)
    if err != nil {
        return err
    }

    return nil
}

And inside my count method I want to reuse the context

newDB := db.Session(&gorm.Session{NewDB: true})
newDB.Statement = db.Statement.Statement

var totalElements int64

tx := newDB.Set(countKey, true).WithContext(db.Statement.Context)
...

But if I add that context, then my tests fails, and I can't even see the query being run, so my feeling is that it's not run.

So, my quesiton is, very likely I am doing something wrong, is it expected that I can reuse the context? any idea what can be wrong?

I created a branch with the above code already ready: https://github.com/manuelarte/pagorminator/tree/chore/example-reusing-ctx

Thanks for the library and for your support! 🫡

The document you expected this should be explained

https://gorm.io/docs/context.html#Context-in-Hooks-Callbacks

Expected answer

I would expect that inside my plugins, I can reuse the context, so then if it gets cancelled, the possible queriesn (or any other activities) the plugin does, can be cancelled.