sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Transaction Named Get

Open Mungrel opened this issue 6 years ago • 2 comments

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.

Mungrel avatar May 15 '19 21:05 Mungrel

Why does this not exist?

Emyrk avatar Feb 15 '23 17:02 Emyrk

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()
}

TheJanzap avatar Sep 05 '24 18:09 TheJanzap