diff --git a/model/querycondition.go b/model/querycondition.go index d391f7e..31c4514 100644 --- a/model/querycondition.go +++ b/model/querycondition.go @@ -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 { 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 +} diff --git a/model/querycondition_test.go b/model/querycondition_test.go index 0f37088..d2ccbde 100644 --- a/model/querycondition_test.go +++ b/model/querycondition_test.go @@ -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) + } + }) + } +}