Transaction Named Get
It'd be neat if sqlx had a convenience function for the Tx type that allowed named Gets.
I'm currently trying to use named parameters and transactions everywhere in my code.
Consider the following query:
SELECT *
FROM my_table
WHERE id=:id
And the following type:
type myStruct struct {
ID string `db:"id"`
Name string `db:"name"`
}
If I have a *Tx (or a *sqlx.DB), it'd be nice if I could use this struct as an argument for the above query with something like:
const query = "SELECT * FROM my_table WHERE id=:id"
arg := myStruct{
ID: "123",
}
var result myStruct
err = tx.NamedGetContext(ctx, &result, query, arg)
...
Currently this throws an error along the lines of:
sql: converting argument $1 type: unsupported type myStruct, a struct
I figured this could be achieved by preparing a named statement, then executing that. But a nice 1-liner using the existing transaction, like I can for inserts would be nice.
Why does this not exist?
This is already implemented, you just have to use the SQLX types instead of the regular SQL ones.
DB, _ := sqlx.Open(/* your DB connection */) // returns *sqlx.DB instead of *sql.DB
tx, _ := DB.Beginx() // returns *sqlx.Tx instead of *sql.Tx
rows, err := tx.NamedExec(/* your DB query */)
if err == nil {
tx.Commit()
} else {
tx.Rollback()
}