Open Imran-imtiaz48 opened 4 months ago
I ran into this issue when I had a function that needed to accept either *sqlx.DB
or *sqlx.Tx
. The best solution I found was just making an interface that satisfied what the function needed. I only needed 2 or 3 interfaces to handle all the CRUD operations my services did. If some function needed access to extra methods, I just created an interface above that function. It made adding transaction support easy and test mocks are simpler because I only need to satisfy one or two methods.
// I suppose you could call this NamedQueryer, but that is not going to scale well
// if you have an interface with multiple methods.
type Creator interface {
NamedQuery(string, interface{}) (*sqlx.Rows, error)
}
func CreateFoo(db Creator, obj *Foo) error {
result, err := db.NamedQuery(`INSERT INTO foo ... RETURNING id`, obj)
if err != nil {
return err
}
result.Next()
result.Scan(&obj.ID)
return nil
}
Interfaces are much nicer to use/mock when they are small. Having a high level connection interface is a bit cumbersome.
Hello, I have noticed that the connx method GetContext does not exist within an interface, nor is there any general interface for which connx implements
This has made it troublesome to mock connx for testing and using in code
Possibly we could also add an interface that defines a connection under something like the name Connector
What are your thoughts?