Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore: add organization search query to workspaces#14474

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Emyrk merged 2 commits intomainfromstevenmasley/workspace_org_search
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
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
6 changes: 6 additions & 0 deletionscoderd/database/dbmem/dbmem.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9964,6 +9964,12 @@ func (q *FakeQuerier) GetAuthorizedWorkspaces(ctx context.Context, arg database.
}
}

if arg.OrganizationID != uuid.Nil {
if workspace.OrganizationID != arg.OrganizationID {
continue
}
}

if arg.OwnerUsername != "" {
owner, err := q.getUserByIDNoLock(workspace.OwnerID)
if err == nil && !strings.EqualFold(arg.OwnerUsername, owner.Username) {
Expand Down
1 change: 1 addition & 0 deletionscoderd/database/modelqueries.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -247,6 +247,7 @@ func (q *sqlQuerier) GetAuthorizedWorkspaces(ctx context.Context, arg GetWorkspa
arg.Deleted,
arg.Status,
arg.OwnerID,
arg.OrganizationID,
pq.Array(arg.HasParam),
arg.OwnerUsername,
arg.TemplateName,
Expand Down
62 changes: 35 additions & 27 deletionscoderd/database/queries.sql.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

6 changes: 6 additions & 0 deletionscoderd/database/queries/workspaces.sql
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,12 @@ WHERE
workspaces.owner_id = @owner_id
ELSE true
END
-- Filter by organization_id
AND CASE
WHEN @organization_id :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
workspaces.organization_id = @organization_id
ELSE true
END
-- Filter by build parameter
-- @has_param will match any build that includes the parameter.
AND CASE WHEN array_length(@has_param :: text[], 1) > 0 THEN
Expand Down
74 changes: 26 additions & 48 deletionscoderd/searchquery/search.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ func AuditLogs(ctx context.Context, db database.Store, query string) (database.G
Email: parser.String(values, "", "email"),
DateFrom: parser.Time(values, time.Time{}, "date_from", dateLayout),
DateTo: parser.Time(values, time.Time{}, "date_to", dateLayout),
OrganizationID: parseOrganization(ctx, db, parser, values, "organization"),
ResourceType: string(httpapi.ParseCustom(parser, values, "", "resource_type", httpapi.ParseEnum[database.ResourceType])),
Action: string(httpapi.ParseCustom(parser, values, "", "action", httpapi.ParseEnum[database.AuditAction])),
BuildReason: string(httpapi.ParseCustom(parser, values, "", "build_reason", httpapi.ParseEnum[database.BuildReason])),
Expand All@@ -47,27 +48,6 @@ func AuditLogs(ctx context.Context, db database.Store, query string) (database.G
filter.DateTo = filter.DateTo.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
}

// 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
}
Expand DownExpand Up@@ -95,7 +75,7 @@ func Users(query string) (database.GetUsersParams, []codersdk.ValidationError) {
return filter, parser.Errors
}

func Workspaces(query string, page codersdk.Pagination, agentInactiveDisconnectTimeout time.Duration) (database.GetWorkspacesParams, []codersdk.ValidationError) {
func Workspaces(ctx context.Context, db database.Store,query string, page codersdk.Pagination, agentInactiveDisconnectTimeout time.Duration) (database.GetWorkspacesParams, []codersdk.ValidationError) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

aside: I see why we do it in this package, but this is kind of a weird naming scheme for something that returns database query params.

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Fair. Maybe it should be namedWorkspacesFilter or something. I won't address here though

filter := database.GetWorkspacesParams{
AgentInactiveDisconnectTimeoutSeconds: int64(agentInactiveDisconnectTimeout.Seconds()),

Expand DownExpand Up@@ -145,6 +125,7 @@ func Workspaces(query string, page codersdk.Pagination, agentInactiveDisconnectT
// which will return all workspaces.
Valid: values.Has("outdated"),
}
filter.OrganizationID = parseOrganization(ctx, db, parser, values, "organization")

type paramMatch struct {
name string
Expand DownExpand Up@@ -198,32 +179,12 @@ func Templates(ctx context.Context, db database.Store, query string) (database.G

parser := httpapi.NewQueryParamParser()
filter := database.GetTemplatesWithFilterParams{
Deleted: parser.Boolean(values, false, "deleted"),
ExactName: parser.String(values, "", "exact_name"),
FuzzyName: 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
}
}
Deleted: parser.Boolean(values, false, "deleted"),
ExactName: parser.String(values, "", "exact_name"),
FuzzyName: parser.String(values, "", "name"),
IDs: parser.UUIDs(values, []uuid.UUID{}, "ids"),
Deprecated: parser.NullableBoolean(values, sql.NullBool{}, "deprecated"),
OrganizationID: parseOrganization(ctx, db, parser, values, "organization"),
}

parser.ErrorExcessParams(values)
Expand DownExpand Up@@ -271,6 +232,23 @@ func searchTerms(query string, defaultKey func(term string, values url.Values) e
return searchValues, nil
}

func parseOrganization(ctx context.Context, db database.Store, parser *httpapi.QueryParamParser, vals url.Values, queryParam string) uuid.UUID {
return httpapi.ParseCustom(parser, vals, uuid.Nil, queryParam, func(v string) (uuid.UUID, error) {
if v == "" {
return uuid.Nil, nil
}
organizationID, err := uuid.Parse(v)
if err == nil {
return organizationID, nil
}
organization, err := db.GetOrganizationByName(ctx, v)
if err != nil {
return uuid.Nil, xerrors.Errorf("organization %q either does not exist, or you are unauthorized to view it", v)
}
return organization.ID, nil
})
}

// splitQueryParameterByDelimiter takes a query string and splits it into the individual elements
// of the query. Each element is separated by a delimiter. All quoted strings are
// kept as a single element.
Expand Down
36 changes: 34 additions & 2 deletionscoderd/searchquery/search_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import (
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/database/dbmem"
"github.com/coder/coder/v2/coderd/searchquery"
"github.com/coder/coder/v2/codersdk"
Expand All@@ -25,6 +26,7 @@ func TestSearchWorkspace(t *testing.T) {
Query string
Expected database.GetWorkspacesParams
ExpectedErrorContains string
Setup func(t *testing.T, db database.Store)
}{
{
Name: "Empty",
Expand DownExpand Up@@ -195,6 +197,31 @@ func TestSearchWorkspace(t *testing.T) {
ParamValues: []string{"bar"},
},
},
{
Name: "Organization",
Query: `organization:4fe722f0-49bc-4a90-a3eb-4ac439bfce20`,
Setup: func(t *testing.T, db database.Store) {
dbgen.Organization(t, db, database.Organization{
ID: uuid.MustParse("4fe722f0-49bc-4a90-a3eb-4ac439bfce20"),
})
},
Expected: database.GetWorkspacesParams{
OrganizationID: uuid.MustParse("4fe722f0-49bc-4a90-a3eb-4ac439bfce20"),
},
},
{
Name: "OrganizationByName",
Query: `organization:foobar`,
Setup: func(t *testing.T, db database.Store) {
dbgen.Organization(t, db, database.Organization{
ID: uuid.MustParse("08eb6715-02f8-45c5-b86d-03786fcfbb4e"),
Name: "foobar",
})
},
Expected: database.GetWorkspacesParams{
OrganizationID: uuid.MustParse("08eb6715-02f8-45c5-b86d-03786fcfbb4e"),
},
},

// Failures
{
Expand DownExpand Up@@ -243,7 +270,12 @@ func TestSearchWorkspace(t *testing.T) {
c := c
t.Run(c.Name, func(t *testing.T) {
t.Parallel()
values, errs := searchquery.Workspaces(c.Query, codersdk.Pagination{}, 0)
// TODO: Replace this with the mock database.
db := dbmem.New()
if c.Setup != nil {
c.Setup(t, db)
}
values, errs := searchquery.Workspaces(context.Background(), db, c.Query, codersdk.Pagination{}, 0)
Comment on lines +274 to +278
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Can we not use the traditional way of getting a DB in tests so this can run against postgres too?

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I'd prefer not to for this. What would be even better is if I used the mock database, but I haven't messed with that at all yet.

if c.ExpectedErrorContains != "" {
assert.True(t, len(errs) > 0, "expect some errors")
var s strings.Builder
Expand All@@ -270,7 +302,7 @@ func TestSearchWorkspace(t *testing.T) {

query := ``
timeout := 1337 * time.Second
values, errs := searchquery.Workspaces(query, codersdk.Pagination{}, timeout)
values, errs := searchquery.Workspaces(context.Background(), dbmem.New(),query, codersdk.Pagination{}, timeout)
require.Empty(t, errs)
require.Equal(t, int64(timeout.Seconds()), values.AgentInactiveDisconnectTimeoutSeconds)
})
Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp