This commit is contained in:
Mike Schwörer 2022-12-11 03:12:02 +01:00
parent becd8f1ebc
commit 3a9c3f4e9e
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF

52
sq/scanner.go Normal file
View File

@ -0,0 +1,52 @@
package sq
import (
"database/sql"
"errors"
"github.com/jmoiron/sqlx"
)
func ScanSingle[TData any](rows *sqlx.Rows, close bool) (TData, error) {
if rows.Next() {
var data TData
err := rows.StructScan(&data)
if err != nil {
return *new(TData), err
}
if rows.Next() {
_ = rows.Close()
return *new(TData), errors.New("sql returned more than onw row")
}
if close {
err = rows.Close()
if err != nil {
return *new(TData), err
}
}
return data, nil
} else {
if close {
_ = rows.Close()
}
return *new(TData), sql.ErrNoRows
}
}
func ScanAll[TData any](rows *sqlx.Rows, close bool) ([]TData, error) {
res := make([]TData, 0)
for rows.Next() {
var data TData
err := rows.StructScan(&data)
if err != nil {
return nil, err
}
res = append(res, data)
}
if close {
err := rows.Close()
if err != nil {
return nil, err
}
}
return res, nil
}