Skip to content

Commit

Permalink
Extend the Profile List database calls to include selectors
Browse files Browse the repository at this point in the history
Since the profile selectors need to be included when listing profiles,
we need to extend the two profile list calls to list selectors as well.

Because the selectors are stored in a different table, but we still need to
retrieve them in the same Go struct defined in models, we define a new SQL
type in a migration that represents the selectors and tell sqlc to use it in
sqlc.yaml.

This new Go struct needs a Scan method as well to convert raw SQL rows
into structs as well.

Fixes: #3721

Co-authored-by: Michelangelo Mori <[email protected]>
  • Loading branch information
jhrozek and blkt committed Jul 7, 2024
1 parent 6274fe5 commit d1f9ae6
Show file tree
Hide file tree
Showing 7 changed files with 308 additions and 5 deletions.
19 changes: 19 additions & 0 deletions database/migrations/000072_profile_selector_type.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-- Copyright 2024 Stacklok, Inc
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

BEGIN;

DROP TYPE IF EXISTS profile_selector;

COMMIT;
25 changes: 25 additions & 0 deletions database/migrations/000072_profile_selectors_type.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- Copyright 2024 Stacklok, Inc
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

BEGIN;

CREATE TYPE profile_selector AS (
id UUID,
profile_id UUID,
entity entities,
selector TEXT,
comment TEXT
);

COMMIT;
33 changes: 31 additions & 2 deletions database/query/profiles.sql
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,40 @@ SELECT * FROM profiles WHERE id = $1 AND project_id = $2 FOR UPDATE;
SELECT * FROM profiles WHERE lower(name) = lower(sqlc.arg(name)) AND project_id = $1 FOR UPDATE;

-- name: ListProfilesByProjectID :many
SELECT sqlc.embed(profiles), sqlc.embed(profiles_with_entity_profiles) FROM profiles JOIN profiles_with_entity_profiles ON profiles.id = profiles_with_entity_profiles.profid
WITH helper AS(
SELECT pr.id as profid,
ARRAY_AGG(ROW(ps.id, ps.profile_id, ps.entity, ps.selector, ps.comment)::profile_selector) FILTER (WHERE ps.id IS NOT NULL) AS selectors
FROM profiles pr
LEFT JOIN profile_selectors ps
ON pr.id = ps.profile_id
WHERE pr.project_id = $1
GROUP BY pr.id
)
SELECT
sqlc.embed(profiles),
sqlc.embed(profiles_with_entity_profiles),
helper.selectors::profile_selector[] AS profiles_with_selectors
FROM profiles
JOIN profiles_with_entity_profiles ON profiles.id = profiles_with_entity_profiles.profid
JOIN helper ON profiles.id = helper.profid
WHERE profiles.project_id = $1;

-- name: ListProfilesByProjectIDAndLabel :many
SELECT sqlc.embed(profiles), sqlc.embed(profiles_with_entity_profiles) FROM profiles JOIN profiles_with_entity_profiles ON profiles.id = profiles_with_entity_profiles.profid
WITH helper AS(
SELECT pr.id as profid,
ARRAY_AGG(ROW(ps.id, ps.profile_id, ps.entity, ps.selector, ps.comment)::profile_selector) FILTER (WHERE ps.id IS NOT NULL) AS selectors
FROM profiles pr
LEFT JOIN profile_selectors ps
ON pr.id = ps.profile_id
WHERE pr.project_id = $1
GROUP BY pr.id
)
SELECT sqlc.embed(profiles),
sqlc.embed(profiles_with_entity_profiles),
helper.selectors::profile_selector[] AS profiles_with_selectors
FROM profiles
JOIN profiles_with_entity_profiles ON profiles.id = profiles_with_entity_profiles.profid
JOIN helper ON profiles.id = helper.profid
WHERE profiles.project_id = $1
AND (
-- the most common case first, if the include_labels is empty, we list profiles with no labels
Expand Down
69 changes: 69 additions & 0 deletions internal/db/profile_selector_scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2024 Stacklok, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package db

import (
"fmt"
"strings"
)

// Scan implements the sql.Scanner interface for the SelectorInfo struct
func (s *ProfileSelector) Scan(value interface{}) error {
if value == nil {
return nil
}

// Convert the value to a string
bytes, ok := value.([]byte)
if !ok {
return fmt.Errorf("failed to scan SelectorInfo: %v", value)
}
str := string(bytes)

// Remove the parentheses
str = strings.TrimPrefix(str, "(")
str = strings.TrimSuffix(str, ")")

// Split the string by commas to get the individual field values
parts := strings.Split(str, ",")

// Assign the values to the struct fields
if len(parts) != 5 {
return fmt.Errorf("failed to scan SelectorInfo: unexpected number of fields")
}

if err := s.ID.Scan(parts[0]); err != nil {
return fmt.Errorf("failed to scan id: %v", err)
}

if err := s.ProfileID.Scan(parts[1]); err != nil {
return fmt.Errorf("failed to scan profile_id: %v", err)
}

s.Entity = NullEntities{}
if parts[2] != "" {
if err := s.Entity.Scan(parts[2]); err != nil {
return fmt.Errorf("failed to scan entity: %v", err)
}
}

selector := strings.TrimPrefix(parts[3], "\"")
selector = strings.TrimSuffix(selector, "\"")
s.Selector = selector

s.Comment = parts[4]

return nil
}
37 changes: 35 additions & 2 deletions internal/db/profiles.sql.go

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

124 changes: 124 additions & 0 deletions internal/db/profiles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,25 @@ func createRandomProfile(t *testing.T, projectID uuid.UUID, labels []string) Pro
return prof
}

func createRepoSelector(t *testing.T, profileId uuid.UUID, sel string, comment string) ProfileSelector {
t.Helper()
return createEntitySelector(t, profileId, NullEntities{Entities: EntitiesRepository, Valid: true}, sel, comment)
}

func createEntitySelector(t *testing.T, profileId uuid.UUID, ent NullEntities, sel string, comment string) ProfileSelector {
t.Helper()
dbSel, err := testQueries.CreateSelector(context.Background(), CreateSelectorParams{
ProfileID: profileId,
Entity: ent,
Selector: sel,
Comment: comment,
})
require.NoError(t, err)
require.NotEmpty(t, dbSel)

return dbSel
}

func createRandomRuleType(t *testing.T, projectID uuid.UUID) RuleType {
t.Helper()

Expand Down Expand Up @@ -192,6 +211,111 @@ func createTestRandomEntities(t *testing.T) *testRandomEntities {
}
}

func matchIdWithListLabelRow(t *testing.T, id uuid.UUID) func(r ListProfilesByProjectIDAndLabelRow) bool {
t.Helper()

return func(r ListProfilesByProjectIDAndLabelRow) bool {
return r.Profile.ID == id
}
}

func matchIdWithListRow(t *testing.T, id uuid.UUID) func(r ListProfilesByProjectIDRow) bool {
t.Helper()

return func(r ListProfilesByProjectIDRow) bool {
return r.Profile.ID == id
}
}

func findRowWithLabels(t *testing.T, rows []ListProfilesByProjectIDAndLabelRow, id uuid.UUID) int {
t.Helper()

return slices.IndexFunc(rows, matchIdWithListLabelRow(t, id))
}

func findRow(t *testing.T, rows []ListProfilesByProjectIDRow, id uuid.UUID) int {
t.Helper()

return slices.IndexFunc(rows, matchIdWithListRow(t, id))
}

func TestProfileListWithSelectors(t *testing.T) {
t.Parallel()

randomEntities := createTestRandomEntities(t)

noSelectors := createRandomProfile(t, randomEntities.proj.ID, []string{})
oneSelectorProfile := createRandomProfile(t, randomEntities.proj.ID, []string{})
oneSel := createRepoSelector(t, oneSelectorProfile.ID, "one_selector1", "one_comment1")

multiSelectorProfile := createRandomProfile(t, randomEntities.proj.ID, []string{})
mulitSel1 := createRepoSelector(t, multiSelectorProfile.ID, "multi_selector1", "multi_comment1")
mulitSel2 := createRepoSelector(t, multiSelectorProfile.ID, "multi_selector2", "multi_comment2")
mulitSel3 := createRepoSelector(t, multiSelectorProfile.ID, "multi_selector3", "multi_comment3")

genericSelectorProfile := createRandomProfile(t, randomEntities.proj.ID, []string{})
genericSel := createEntitySelector(t, genericSelectorProfile.ID, NullEntities{}, "gen_selector1", "gen_comment1")

t.Run("list profiles with selectors using the label list", func(t *testing.T) {
t.Parallel()

rows, err := testQueries.ListProfilesByProjectIDAndLabel(
context.Background(), ListProfilesByProjectIDAndLabelParams{
ProjectID: randomEntities.proj.ID,
})
require.NoError(t, err)

require.Len(t, rows, 4)

noSelIdx := findRowWithLabels(t, rows, noSelectors.ID)
require.True(t, noSelIdx >= 0, "noSelectors not found in rows")
require.Empty(t, rows[noSelIdx].ProfilesWithSelectors)

oneSelIdx := findRowWithLabels(t, rows, oneSelectorProfile.ID)
require.True(t, oneSelIdx >= 0, "oneSelector not found in rows")
require.Len(t, rows[oneSelIdx].ProfilesWithSelectors, 1)
require.Contains(t, rows[oneSelIdx].ProfilesWithSelectors, oneSel)

multiSelIdx := findRowWithLabels(t, rows, multiSelectorProfile.ID)
require.True(t, multiSelIdx >= 0, "multiSelectorProfile not found in rows")
require.Len(t, rows[multiSelIdx].ProfilesWithSelectors, 3)
require.Subset(t, rows[multiSelIdx].ProfilesWithSelectors, []ProfileSelector{mulitSel1, mulitSel2, mulitSel3})

genSelIdx := findRowWithLabels(t, rows, genericSelectorProfile.ID)
require.Len(t, rows[genSelIdx].ProfilesWithSelectors, 1)
require.Contains(t, rows[genSelIdx].ProfilesWithSelectors, genericSel)
})

t.Run("list profiles with selectors using the non-label list", func(t *testing.T) {
t.Parallel()

rows, err := testQueries.ListProfilesByProjectID(
context.Background(), randomEntities.proj.ID)
require.NoError(t, err)

require.Len(t, rows, 4)

noSelIdx := findRow(t, rows, noSelectors.ID)
require.True(t, noSelIdx >= 0, "noSelectors not found in rows")
require.Empty(t, rows[noSelIdx].ProfilesWithSelectors)

oneSelIdx := findRow(t, rows, oneSelectorProfile.ID)
require.True(t, oneSelIdx >= 0, "oneSelector not found in rows")
require.Len(t, rows[oneSelIdx].ProfilesWithSelectors, 1)
require.Contains(t, rows[oneSelIdx].ProfilesWithSelectors, oneSel)

multiSelIdx := findRow(t, rows, multiSelectorProfile.ID)
require.True(t, multiSelIdx >= 0, "multiSelectorProfile not found in rows")
require.Len(t, rows[multiSelIdx].ProfilesWithSelectors, 3)
require.Subset(t, rows[multiSelIdx].ProfilesWithSelectors, []ProfileSelector{mulitSel1, mulitSel2, mulitSel3})

genSelIdx := findRow(t, rows, genericSelectorProfile.ID)
require.Len(t, rows[genSelIdx].ProfilesWithSelectors, 1)
require.Contains(t, rows[genSelIdx].ProfilesWithSelectors, genericSel)
})

}

func TestProfileLabels(t *testing.T) {
t.Parallel()

Expand Down
6 changes: 5 additions & 1 deletion sqlc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ packages:
emit_prepared_queries: false
emit_interface: true
emit_exact_table_names: false
emit_empty_slices: true
emit_empty_slices: true
overrides:
- db_type: profile_selector
go_type:
type: "ProfileSelector"

0 comments on commit d1f9ae6

Please sign in to comment.