添加 gets 查询

This commit is contained in:
xing 2023-02-21 22:15:35 +08:00
parent 409ffd8081
commit 0bc93850ed
2 changed files with 54 additions and 0 deletions

View File

@ -279,3 +279,19 @@ func FindScannerFromDB[T Model](db dbQuery, ctx context.Context, fn func(T), q *
func FindScanner[T Model](ctx context.Context, fn func(T), q *QueryCondition) error { func FindScanner[T Model](ctx context.Context, fn func(T), q *QueryCondition) error {
return findScanner[T](globalBb, ctx, fn, q) return findScanner[T](globalBb, ctx, fn, q)
} }
func Gets[T Model](ctx context.Context, q *QueryCondition) (T, error) {
return gets[T](globalBb, ctx, q)
}
func GetsFromDB[T Model](db dbQuery, ctx context.Context, q *QueryCondition) (T, error) {
return gets[T](db, ctx, q)
}
func gets[T Model](db dbQuery, ctx context.Context, q *QueryCondition) (r T, err error) {
s, args, err := BuildQuerySql[T](q)
if err != nil {
return
}
err = db.Get(ctx, &r, s, args...)
return
}

View File

@ -531,3 +531,41 @@ func BenchmarkFindsXX(b *testing.B) {
} }
} }
} }
func Test_gets(t *testing.T) {
type args struct {
db dbQuery
ctx context.Context
q *QueryCondition
}
type testCase[T Model] struct {
name string
args args
wantR T
wantErr bool
}
tests := []testCase[options]{
{
name: "t1",
args: args{
db: glob,
ctx: ctx,
q: Conditions(Where(SqlBuilder{{"option_name", "blogname"}})),
},
wantR: options{3, "blogname", "记录并见证自己的成长", "yes"},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, err := gets[options](tt.args.db, tt.args.ctx, tt.args.q)
if (err != nil) != tt.wantErr {
t.Errorf("gets() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("gets() gotR = %v, want %v", gotR, tt.wantR)
}
})
}
}