From 0bc93850ed7567262d258011ee710feee40ea889 Mon Sep 17 00:00:00 2001 From: xing Date: Tue, 21 Feb 2023 22:15:35 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20gets=20=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/querycondition.go | 16 +++++++++++++++ model/querycondition_test.go | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) 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) + } + }) + } +}