Home > Software design >  Implementing filters in ORM golang
Implementing filters in ORM golang

Time:10-01

I am working on an api which takes in parameters for filters (as given below)

/api/endpoint?filter_key_1=filter_value_1&...

I've previously worked on spring where the criteria API allows for dynamically building SQL queries without much hassle. In golang I'm using gorm for handling the ORM operations. Is there anyway to build the queries with optional parameters without writing redundant code?.

For example: If the request sent is:

/api/endpoint?fk_1=fv_1&fk_2=fv_2&fk_3=fv_3

Query generated should be :

select * from table where fk_1 = fv_1 AND fk_2 = fv_2 AND fk_3 = fv_3

but in case of :

/api/endpoint?fk_1=fv_1

Query generated should be:

select * from table where fk_1 = fv_1

Currently my approach is to check if each variable is present and build the query as a string :

query:="select * from table where "
if fk_1 != ""{
query  = "fk_1 = fv_1"
}
... and so on 

but this seems very awkward and error prone

Any help will be appreciated! Thanks

EDIT Building on @bjornaer's answer what helped me was to get the map[string][]string in a form that I can send the same to gorm, map[string]interface{}.

This thread will help in the same.

Now there's no longer a need for redundant checks or string operations in the filters

CodePudding user response:

so it seems to me your question has 2 parts:

  1. you need to retrieve your query values from your url and
  2. insert them to your db query

I don't see how you are handling your requests so let's assume you use the http package: from req.URL you get the URL object and from that calling the Query() method yields a map[string][]string of your query parameters, with those in a variable URLQuery let's pause and look at how you query with gorm:

db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
  QueryFields: true,
})

here I open a sqlite, then you can pass a variable reference to fill with your query, for example:

result := db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)

now from the example above, replace your variable in:

result := db.Where(map[string]interface{}URLQuery).Find(&users)

you can find it in the docs

  • Related