From c824c729d2a787495277190ce561a523aeef7237 Mon Sep 17 00:00:00 2001 From: Yash Mehrotra Date: Thu, 23 Jan 2025 12:08:17 +0530 Subject: [PATCH] fix: add != functionality for tags/labels in resource selector --- query/models.go | 9 ++++++--- tests/query_resource_selector_test.go | 6 ++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/query/models.go b/query/models.go index bb6542ad..6d50683b 100644 --- a/query/models.go +++ b/query/models.go @@ -36,8 +36,11 @@ var AgentMapper = func(ctx context.Context, id string) (any, error) { return nil, fmt.Errorf("invalid agent: %s", id) } -var JSONPathMapper = func(ctx context.Context, tx *gorm.DB, column string, path string, val string) *gorm.DB { - return tx.Where(fmt.Sprintf(`TRIM(BOTH '"' from jsonb_path_query_first(%s, '$.%s')::TEXT) = ?`, column, path), val) +var JSONPathMapper = func(ctx context.Context, tx *gorm.DB, column string, op types.QueryOperator, path string, val string) *gorm.DB { + if !slices.Contains([]types.QueryOperator{types.Eq, types.Neq}, op) { + op = types.Eq + } + return tx.Where(fmt.Sprintf(`TRIM(BOTH '"' from jsonb_path_query_first(%s, '$.%s')::TEXT) %s ?`, column, path, op), val) } var CommonFields = map[string]func(ctx context.Context, tx *gorm.DB, val string) (*gorm.DB, error){ @@ -230,7 +233,7 @@ func (qm QueryModel) Apply(ctx context.Context, q types.QueryField, tx *gorm.DB) for _, column := range qm.JSONColumns { if strings.HasPrefix(originalField, column) { - tx = JSONPathMapper(ctx, tx, column, strings.TrimPrefix(originalField, column+"."), val) + tx = JSONPathMapper(ctx, tx, column, q.Op, strings.TrimPrefix(originalField, column+"."), val) q.Field = column } } diff --git a/tests/query_resource_selector_test.go b/tests/query_resource_selector_test.go index 59ee1f80..07542a87 100644 --- a/tests/query_resource_selector_test.go +++ b/tests/query_resource_selector_test.go @@ -431,6 +431,12 @@ var _ = ginkgo.Describe("Resoure Selector with PEG", ginkgo.Ordered, func() { expectedIDs: []uuid.UUID{dummy.EKSCluster.ID, dummy.EC2InstanceB.ID}, resource: "config", }, + { + description: "config labels not equal query", + query: `labels.account=flanksource labels.environment!=production`, + expectedIDs: []uuid.UUID{dummy.KubernetesCluster.ID, dummy.EC2InstanceA.ID}, + resource: "config", + }, { description: "config array query", query: `config.spec.template.spec.containers[0].name=logistics-api`,