Home > Blockchain >  Can't use WithContext(ctx) method on *gorm.db instead of gorm.db
Can't use WithContext(ctx) method on *gorm.db instead of gorm.db

Time:10-31

I initialize my db as a struct

type DBStorage struct {
   db *gorm.DB
}

with

db, err := gorm.Open("postgres", DatabaseURL)
...
return &DBStorage{
   db: db,
}

Everything works fine: queries, updates, and all other operations. But then I tried to add Contexts to my project it didn't work like that:

func (dbStorage DBStorage) PutOrder(order service.Order, ctx context.Context) error {
...
   dbStorage.db.WithContext(ctx).Create(&order)
...
}

It says that WithContext is an unresolved reference. While dbStorage.db.Create(&order) works fine. How should I fix this?

I tried some silly things like removing * from the struct, but it kinda breaks the whole incapsulation idea. Also tried reading https://gorm.io/docs/method_chaining.html but didn't get how to implement it and if it is a solution for my case. If it is, I ask for some clarification.

CodePudding user response:

Check your import statement. It should be import gorm.io/gorm instead of import github.com/jinzhu/gorm.

The first version of the library is github.com/jinzhu/gorm where the gorm.DB type has no WithContext() method.

GORM V2 moved to https://github.com/go-gorm/gorm and has import path gorm.io/gorm. Version 2 added the DB.WithContext() method.

  • Related