Skip to content

chore: add templates search query to a filter #13772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
chore: add templates search query to a filter
  • Loading branch information
Emyrk committed Jul 2, 2024
commit cdeb293f6d44ad57d41ba922fb01f21c6c8c2a19
50 changes: 48 additions & 2 deletions coderd/httpapi/queryparams.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package httpapi

import (
"database/sql"
"errors"
"fmt"
"net/url"
Expand Down Expand Up @@ -104,6 +105,27 @@ func (p *QueryParamParser) PositiveInt32(vals url.Values, def int32, queryParam
return v
}

// NullableBoolean will return a null sql value if no input is provided.
// SQLc still uses sql.NullBool rather than the generic type. So converting from
// the generic type is required.
func (p *QueryParamParser) NullableBoolean(vals url.Values, def sql.NullBool, queryParam string) sql.NullBool {
v, err := parseNullableQueryParam[bool](p, vals, strconv.ParseBool, sql.Null[bool]{
V: def.Bool,
Valid: def.Valid,
}, queryParam)
if err != nil {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: queryParam,
Detail: fmt.Sprintf("Query param %q must be a valid boolean: %s", queryParam, err.Error()),
})
}

return sql.NullBool{
Bool: v.V,
Valid: v.Valid,
}
}

func (p *QueryParamParser) Boolean(vals url.Values, def bool, queryParam string) bool {
v, err := parseQueryParam(p, vals, strconv.ParseBool, def, queryParam)
if err != nil {
Expand Down Expand Up @@ -294,9 +316,34 @@ func ParseCustomList[T any](parser *QueryParamParser, vals url.Values, def []T,
return v
}

func parseNullableQueryParam[T any](parser *QueryParamParser, vals url.Values, parse func(v string) (T, error), def sql.Null[T], queryParam string) (sql.Null[T], error) {
setParse := parseSingle(parser, parse, def.V, queryParam)
return parseQueryParamSet[sql.Null[T]](parser, vals, func(set []string) (sql.Null[T], error) {
if len(set) == 0 {
return sql.Null[T]{
Valid: false,
}, nil
}

value, err := setParse(set)
if err != nil {
return sql.Null[T]{}, err
}
return sql.Null[T]{
V: value,
Valid: true,
}, nil
}, def, queryParam)
}

// parseQueryParam expects just 1 value set for the given query param.
func parseQueryParam[T any](parser *QueryParamParser, vals url.Values, parse func(v string) (T, error), def T, queryParam string) (T, error) {
setParse := func(set []string) (T, error) {
setParse := parseSingle(parser, parse, def, queryParam)
return parseQueryParamSet(parser, vals, setParse, def, queryParam)
}

func parseSingle[T any](parser *QueryParamParser, parse func(v string) (T, error), def T, queryParam string) func(set []string) (T, error) {
return func(set []string) (T, error) {
if len(set) > 1 {
// Set as a parser.Error rather than return an error.
// Returned errors are errors from the passed in `parse` function, and
Expand All @@ -311,7 +358,6 @@ func parseQueryParam[T any](parser *QueryParamParser, vals url.Values, parse fun
}
return parse(set[0])
}
return parseQueryParamSet(parser, vals, setParse, def, queryParam)
}

func parseQueryParamSet[T any](parser *QueryParamParser, vals url.Values, parse func(set []string) (T, error), def T, queryParam string) (T, error) {
Expand Down
60 changes: 60 additions & 0 deletions coderd/httpapi/queryparams_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package httpapi_test

import (
"database/sql"
"fmt"
"net/http"
"net/url"
Expand Down Expand Up @@ -220,6 +221,65 @@ func TestParseQueryParams(t *testing.T) {
testQueryParams(t, expParams, parser, parser.Boolean)
})

t.Run("NullableBoolean", func(t *testing.T) {
t.Parallel()
expParams := []queryParamTestCase[sql.NullBool]{
{
QueryParam: "valid_true",
Value: "true",
Expected: sql.NullBool{
Bool: true,
Valid: true,
},
},
{
QueryParam: "no_value_true_def",
NoSet: true,
Default: sql.NullBool{
Bool: true,
Valid: true,
},
Expected: sql.NullBool{
Bool: true,
Valid: true,
},
},
{
QueryParam: "no_value",
NoSet: true,
Expected: sql.NullBool{
Bool: false,
Valid: false,
},
},

{
QueryParam: "invalid_boolean",
Value: "yes",
Expected: sql.NullBool{
Bool: false,
Valid: false,
},
ExpectedErrorContains: "must be a valid boolean",
},
{
QueryParam: "unexpected_list",
Values: []string{"true", "false"},
ExpectedErrorContains: multipleValuesError,
// Expected value is a bit strange, but the error is raised
// in the parser, not as a parse failure. Maybe this should be
// fixed, but is how it is done atm.
Expected: sql.NullBool{
Bool: false,
Valid: true,
},
},
}

parser := httpapi.NewQueryParamParser()
testQueryParams(t, expParams, parser, parser.NullableBoolean)
})

t.Run("Int", func(t *testing.T) {
t.Parallel()
expParams := []queryParamTestCase[int]{
Expand Down
47 changes: 47 additions & 0 deletions coderd/searchquery/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,53 @@
return filter, parser.Errors
}

func Templates(ctx context.Context, db database.Store, query string) (database.GetTemplatesWithFilterParams, []codersdk.ValidationError) {
// Always lowercase for all searches.
query = strings.ToLower(query)
values, errors := searchTerms(query, func(term string, values url.Values) error {
// Default to the template name
values.Add("name", term)
return nil
})
if len(errors) > 0 {
return database.GetTemplatesWithFilterParams{}, errors
}

const dateLayout = "2006-01-02"

Check failure on line 199 in coderd/searchquery/search.go

View workflow job for this annotation

GitHub Actions / lint

const `dateLayout` is unused (unused)
parser := httpapi.NewQueryParamParser()
filter := database.GetTemplatesWithFilterParams{
Deleted: parser.Boolean(values, false, "deleted"),
// TODO: Should name be a fuzzy search?
ExactName: parser.String(values, "", "name"),
IDs: parser.UUIDs(values, []uuid.UUID{}, "ids"),
Deprecated: parser.NullableBoolean(values, sql.NullBool{}, "deprecated"),
}

// Convert the "organization" parameter to an organization uuid. This can require
// a database lookup.
organizationArg := parser.String(values, "", "organization")
if organizationArg != "" {
organizationID, err := uuid.Parse(organizationArg)
if err == nil {
filter.OrganizationID = organizationID
} else {
// Organization could be a name
organization, err := db.GetOrganizationByName(ctx, organizationArg)
if err != nil {
parser.Errors = append(parser.Errors, codersdk.ValidationError{
Field: "organization",
Detail: fmt.Sprintf("Organization %q either does not exist, or you are unauthorized to view it", organizationArg),
})
} else {
filter.OrganizationID = organization.ID
}
}
}

parser.ErrorExcessParams(values)
return filter, parser.Errors
}

func searchTerms(query string, defaultKey func(term string, values url.Values) error) (url.Values, []codersdk.ValidationError) {
searchValues := make(url.Values)

Expand Down
43 changes: 43 additions & 0 deletions coderd/searchquery/search_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -454,3 +455,45 @@ func TestSearchUsers(t *testing.T) {
})
}
}

func TestSearchTemplates(t *testing.T) {
t.Parallel()
testCases := []struct {
Name string
Query string
Expected database.GetTemplatesWithFilterParams
ExpectedErrorContains string
}{
{
Name: "Empty",
Query: "",
Expected: database.GetTemplatesWithFilterParams{},
},
}

for _, c := range testCases {
c := c
t.Run(c.Name, func(t *testing.T) {
t.Parallel()
// Do not use a real database, this is only used for an
// organization lookup.
db := dbmem.New()
values, errs := searchquery.Templates(context.Background(), db, c.Query)
if c.ExpectedErrorContains != "" {
require.True(t, len(errs) > 0, "expect some errors")
var s strings.Builder
for _, err := range errs {
_, _ = s.WriteString(fmt.Sprintf("%s: %s\n", err.Field, err.Detail))
}
require.Contains(t, s.String(), c.ExpectedErrorContains)
} else {
require.Len(t, errs, 0, "expected no error")
if c.Expected.IDs == nil {
// Nil and length 0 are the same
c.Expected.IDs = []uuid.UUID{}
}
require.Equal(t, c.Expected, values, "expected values")
}
})
}
}
Loading