Last active
October 12, 2024 19:30
-
-
Save hielfx/4469d35127d085fc3501d483e34d4bad to your computer and use it in GitHub Desktop.
Generic interface for using both sqlx.DB and sqlx.Tx independently. E.g. if you want to use a transaction or not but want the possibility to use both any time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package domain | |
import ( | |
"context" | |
"database/sql" | |
"github.com/jmoiron/sqlx" | |
) | |
//SQLDB An interface to use for both sqlx.DB and sqlx.Tx (to use a transaction or not) | |
type SQLDB interface { | |
BindNamed(query string, arg interface{}) (string, []interface{}, error) | |
DriverName() string | |
Get(dest interface{}, query string, args ...interface{}) error | |
GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error | |
MustExec(query string, args ...interface{}) sql.Result | |
MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result | |
NamedExec(query string, arg interface{}) (sql.Result, error) | |
NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) | |
NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) | |
PrepareNamed(query string) (*sqlx.NamedStmt, error) | |
PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error) | |
Preparex(query string) (*sqlx.Stmt, error) | |
PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error) | |
QueryRowx(query string, args ...interface{}) *sqlx.Row | |
QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row | |
Queryx(query string, args ...interface{}) (*sqlx.Rows, error) | |
QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) | |
Rebind(query string) string | |
Select(dest interface{}, query string, args ...interface{}) error | |
SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example:
Imagine the following function:
You can use it without transaction:
Or with a previously created transaction: