Search code examples
gosqlx

How to execute raw queries using sqlx?


Using sqlx as my database adapter, I'd like to run queries on user profiles based on user-submitted POST data. There are several parameters like age, sex and location and many more.

So for example if only age value is submitted by the user, the query should looks like:

var profiles []model.Profile
q:= "SELECT *  FROM profile WHERE age = ?"
err = database.SQL.Select(&profiles, q, age)
if err != nil {
    log.Println(err)
} 

As you can see, since the query can not be built dynamically, this method is not flexible enough and becomes so verbose to account for all possible variations.

What I want is to construct query based on the input data then just feed the raw query to sqlx.

Something like this pseudo code:

q:= `SELECT *  FROM profile WHERE 
      age > 25   AND sex="f" AND location="London"`
    err = database.SQL.ExecRaw(&profiles, q)

How can I achieve this in sqlx?
I have looked at the docs but could not figure out how to do so.


Solution

  • If you don't want to use parameters, don't use parameters. Select doesn't prevent you from putting literals in your query.