Skip to content

Commit

Permalink
feat: support search in postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
mlabouardy committed Jun 15, 2023
1 parent 394f380 commit 97d7e05
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
10 changes: 8 additions & 2 deletions handlers/resources_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,14 @@ func (handler *ApiHandler) FilterResourcesHandler(c *gin.Context) {
if len(filters) == 0 {
if len(query) > 0 {
whereClause := fmt.Sprintf("(name LIKE '%%%s%%' OR region LIKE '%%%s%%' OR service LIKE '%%%s%%' OR provider LIKE '%%%s%%' OR account LIKE '%%%s%%' OR (tags LIKE '%%%s%%'))", query, query, query, query, query, query)
err = handler.db.NewRaw(fmt.Sprintf("SELECT * FROM resources WHERE %s ORDER BY id LIMIT %d OFFSET %d", whereClause, limit, skip)).Scan(handler.ctx, &resources)
searchQuery := fmt.Sprintf("SELECT * FROM resources WHERE %s ORDER BY id LIMIT %d OFFSET %d", whereClause, limit, skip)

if handler.db.Dialect().Name() == dialect.PG {
whereClause = fmt.Sprintf("(name LIKE '%%%s%%' OR region LIKE '%%%s%%' OR service LIKE '%%%s%%' OR provider LIKE '%%%s%%' OR account LIKE '%%%s%%' OR (value->>'key' LIKE '%%%s%%') OR (value->>'value' LIKE '%%%s%%'))", query, query, query, query, query, query, query)
searchQuery = fmt.Sprintf("SELECT * FROM resources CROSS JOIN jsonb_array_elements(tags) WHERE %s ORDER BY id LIMIT %d OFFSET %d", whereClause, limit, skip)
}

err = handler.db.NewRaw(searchQuery).Scan(handler.ctx, &resources)
if err != nil {
logrus.WithError(err).Error("scan failed")
}
Expand All @@ -268,7 +275,6 @@ func (handler *ApiHandler) FilterResourcesHandler(c *gin.Context) {
query = fmt.Sprintf("SELECT DISTINCT resources.id, resources.resource_id, resources.provider, resources.account, resources.service, resources.region, resources.name, resources.created_at, resources.fetched_at, resources.cost, resources.metadata, resources.tags, resources.link FROM resources CROSS JOIN json_each(tags) WHERE resources.id NOT IN (%s) AND type='object' AND %s ORDER BY resources.id LIMIT %d OFFSET %d", strings.Trim(string(s), "[]"), whereClause, limit, skip)
}
}

err = handler.db.NewRaw(query).Scan(handler.ctx, &resources)
if err != nil {
logrus.WithError(err).Error("scan failed")
Expand Down
2 changes: 1 addition & 1 deletion models/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type Resource struct {
Metadata map[string]string `json:"metadata"`
Tags []Tag `json:"tags" bun:"tags,default:'[]'"`
Link string `json:"link" bson:"link"`
Value string `bun:"-"` //to be deprecated
Value string `bun:",scanonly"` //to be deprecated
}

type Tag struct {
Expand Down

0 comments on commit 97d7e05

Please sign in to comment.