2020. január 16., csütörtök 8:20:17 UTC+1 időpontban Shulhan a következőt írta: > > ## Problem > > At some point we have a function that receive an instance of database > connection to query rows in specific table. > > Let's say that function F() accept DB that query table T. > > If function F() called with DB instance, it will query only rows that has > been committed into database. > > IF function F() called with Tx instance, it will query all rows including > the one that has not been committed yet into database. > > Since DB and Tx are different types, we will have two functions that > almost have identical code, > > func F(db *sql.DB) (output int) { > q := `SELECT … FROM T WHERE …` > err := db.QueryRow(q).Scan(&output) > … > return output > } > > func FWithTx(tx *sql.Tx)(output int) { > q := `SELECT … FROM T WHERE …` > err := tx.QueryRow(q).Scan(&output) > … > return output > } > > > ## Proposed solution > > Add an interface Session (the name is not fixed yet) to package sql with > the following signature, > > type Session interface { > func Exec(query string, args ...interface{}) (Result, error) > func ExecContext(ctx context.Context, query string, args > ...interface{}) (Result, error) > func Prepare(query string) (*Stmt, error) > func PrepareContext(ctx context.Context, query string) (*Stmt, error) > func Query(query string, args ...interface{}) (*Rows, error) > func QueryContext(ctx context.Context, query string, args > ...interface{}) (*Rows, error) > func QueryRow(query string, args ...interface{}) *Row > func QueryRowContext(ctx context.Context, query string, args > ...interface{}) *Row > } > > Session interface is combination of DB and Tx that contains all identical > methods. > > > ## Rationale > > Without Session, user will have two functions that have the same code, > > By using Session, we can minimise duplicate code in the user level. for > example using the previous problems definition the function F() become one, > > func F(session sql.Session)(output int) { > q := `SELECT … FROM T WHERE …` > err := session.QueryRow().Scan(&output) > … > return output > } > > > ## Discussion > > Any thought about this proposal?
Just define the interface and use it - Go is not Java, iff a type statisfies an interface, then it also implements it! You can use anonymous interfaces also! ``` func F(db interface { QueryRow() *sql.Row })(output int) { q := `SELECT … FROM T WHERE …` err := db.QueryRow().Scan(& > > output) > … > return output > } ``` -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a81bb8a1-bc68-487d-b678-dc3fd344e9ed%40googlegroups.com.