git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/dbx/dbx.go (about) 1 package dbx 2 3 import ( 4 "context" 5 "database/sql" 6 7 "github.com/jmoiron/sqlx" 8 ) 9 10 type Queryer interface { 11 sqlx.QueryerContext 12 sqlx.ExecerContext 13 } 14 15 // Get single result or return an error. 16 func Get[T any](ctx context.Context, db Queryer, query string, args ...any) (result T, err error) { 17 err = sqlx.GetContext(ctx, db, &result, query, args...) 18 return 19 } 20 21 // Select creates slice of results based on SQL query. In case of zero results it will return non-nil empty slice. 22 func Select[T any](ctx context.Context, db Queryer, query string, args ...any) (results []T, err error) { 23 results = make([]T, 0) 24 25 err = sqlx.SelectContext(ctx, db, &results, query, args...) 26 return 27 } 28 29 // Exec executes a query without returning any rows. The args are for any placeholder parameters in the query. 30 func Exec(ctx context.Context, db Queryer, query string, args ...any) (sql.Result, error) { 31 return db.ExecContext(ctx, query, args...) 32 } 33 34 // Query executes a query that returns rows, typically a SELECT. The args are for any placeholder 35 // parameters in the query. 36 func Query(ctx context.Context, db Queryer, query string, args ...any) (*sql.Rows, error) { 37 return db.QueryContext(ctx, query, args...) 38 }