1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

add a query helper on x/sqlx sub-package and fix the example for basicauth

This commit is contained in:
Gerasimos (Makis) Maropoulos
2022-03-08 19:45:25 +02:00
parent ad80a14b8f
commit 5a7485124c
5 changed files with 75 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
package sqlx
import (
"context"
"database/sql"
"fmt"
"reflect"
@@ -54,6 +55,11 @@ func Register(tableName string, value interface{}) *Schema {
return DefaultSchema.Register(tableName, value)
}
// Query is a shortcut of executing a query and bind the result to "dst".
func Query(ctx context.Context, db *sql.DB, dst interface{}, query string, args ...interface{}) error {
return DefaultSchema.Query(ctx, db, dst, query, args...)
}
// Bind sets "dst" to the result of "src" and reports any errors.
func Bind(dst interface{}, src *sql.Rows) error {
return DefaultSchema.Bind(dst, src)
@@ -90,6 +96,21 @@ func (s *Schema) Register(tableName string, value interface{}) *Schema {
return s
}
// Query is a shortcut of executing a query and bind the result to "dst".
func (s *Schema) Query(ctx context.Context, db *sql.DB, dst interface{}, query string, args ...interface{}) error {
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
return err
}
if !s.AutoCloseRows { // if not close on bind, we must close it here.
defer rows.Close()
}
err = s.Bind(dst, rows)
return err
}
// Bind sets "dst" to the result of "src" and reports any errors.
func (s *Schema) Bind(dst interface{}, src *sql.Rows) error {
typ := reflect.TypeOf(dst)