Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I've noticed that the GetContext method isn't part of any interface.I propose adding an interface, possibly named GetterContext, to address this issue. What are your thoughts? #933

Open
Imran-imtiaz48 opened this issue Jun 27, 2024 · 1 comment

Comments

@Imran-imtiaz48
Copy link

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?

@Kangaroux
Copy link

Kangaroux commented Jun 30, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants