diff --git a/internal/db/read_writer.go b/internal/db/read_writer.go index 78249a9b3..838c784de 100644 --- a/internal/db/read_writer.go +++ b/internal/db/read_writer.go @@ -1014,15 +1014,21 @@ func (rw *Db) LookupWhere(_ context.Context, resource interface{}, where string, } // SearchWhere will search for all the resources it can find using a where -// clause with parameters. Supports the WithLimit option. If -// WithLimit < 0, then unlimited results are returned. If WithLimit == 0, then -// default limits are used for results. Supports the WithOrder option. +// clause with parameters. An error will be returned if args are provided without a +// where clause. +// +// Supports the WithLimit option. If WithLimit < 0, then unlimited results are returned. +// If WithLimit == 0, then default limits are used for results. +// Supports the WithOrder option. func (rw *Db) SearchWhere(_ context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error { const op = "db.SearchWhere" opts := GetOpts(opt...) if rw.underlying == nil { return errors.New(errors.InvalidParameter, op, "missing underlying db") } + if where == "" && len(args) > 0 { + return errors.New(errors.InvalidParameter, op, "args provided with empty where") + } if reflect.ValueOf(resources).Kind() != reflect.Ptr { return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer") } @@ -1038,10 +1044,7 @@ func (rw *Db) SearchWhere(_ context.Context, resources interface{}, where string db = db.Limit(opts.WithLimit) } - // Perform argument subst - switch len(args) { - case 0: - default: + if where != "" { db = db.Where(where, args...) } @@ -1059,7 +1062,7 @@ func filterPaths(paths []string) []string { if len(paths) == 0 { return nil } - filtered := []string{} + var filtered []string for _, p := range paths { switch { case strings.EqualFold(p, "CreateTime"): diff --git a/internal/db/read_writer_test.go b/internal/db/read_writer_test.go index a9d16adfe..eccbe2735 100644 --- a/internal/db/read_writer_test.go +++ b/internal/db/read_writer_test.go @@ -925,6 +925,16 @@ func TestDb_SearchWhere(t *testing.T) { wantErr: false, wantNameOrder: true, }, + { + name: "no-where", + db: Db{underlying: db}, + createCnt: 10, + args: args{ + opt: []Option{WithLimit(10)}, + }, + wantCnt: 10, + wantErr: false, + }, { name: "custom-limit", db: Db{underlying: db}, @@ -948,6 +958,27 @@ func TestDb_SearchWhere(t *testing.T) { wantCnt: 1, wantErr: false, }, + { + name: "no args", + db: Db{underlying: db}, + createCnt: 1, + args: args{ + where: fmt.Sprintf("public_id = '%v'", knownUser.PublicId), + opt: []Option{WithLimit(3)}, + }, + wantCnt: 1, + wantErr: false, + }, + { + name: "no where, but with args", + db: Db{underlying: db}, + createCnt: 1, + args: args{ + arg: []interface{}{knownUser.PublicId}, + opt: []Option{WithLimit(3)}, + }, + wantErr: true, + }, { name: "not-found", db: Db{underlying: db},