如何在 Go 中对动态查询进行参数化

用户可以根据许多不同的标准请求产品价格,这将导致它可能访问表中的不同列。我正在遍历请求的产品并构建一堆查询,但遇到了一些麻烦。


一个一个地运行它们并组合结果比将它们联合起来需要更长的时间。因此,我尝试构建如下查询,它有效且速度快,但现在容易受到注入的影响。


没有联盟有没有更好的方法来做到这一点?或者有没有一种简单的方法可以参数化这样的动态查询?


    var fullQuery string

    var counter int

    for i, d:= range dataMap{

    if counter != 0 {

        fullQuery = fullQuery + " UNION "

    }

    var records string

    for _, p := range d{

        records = records + `'` + string(p) + `',`

    }

    recordLength:= len(records)

    if recordLength> 0 && records [recordLength-1] == ',' {

        records = records[:recordLength-1]

    }

    counter++

    fullQuery = fullQuery + fmt.Sprintf(`

SELECT 

    price_`+fmt.Sprint(p.type)+` as price,                

  FROM products

  WHERE products.id in (%s) and products.store= %s

  

`, records, p.store)


}


err := sqlx.Select(db, &dataStruct, fullQuery)

所以,在某些情况下,我可能会有以下查询:


SELECT 

    price_`+fmt.Sprint(p.type)+` as price,                

  FROM products

  WHERE products.id in (%s) and products.store= %s

在其他情况下(取决于请求),我可能会有这样的事情:


SELECT 

    price_`+fmt.Sprint(p.type)+` as price,                

  FROM products

  WHERE products.id in ('testid1', 'testid2') and products.store= 2

UNION

SELECT 

    price_`+fmt.Sprint(p.type)+` as price,                

  FROM products

  WHERE products.id in ('testid3', 'testid4') and products.store= 1

如果我确定查询是什么,我只会使用 $1、$2 等,但我不认为我可以在这里,因为我不知道会有多少参数并且它们都需要不同.


慕标5832272
浏览 111回答 1
1回答

拉风的咖菲猫

弄清楚了,未经测试的粗略示例,说明我如何最终做到这一点,以防其他人遇到这种情况。 var counter int = 1 var parameters []interface{} for _, d:= range data{    if counter != 1 {        fullQuery = fullQuery + " UNION "    }    fullQuery = fullQuery + fmt.Sprintf(`SELECT     price_`+fmt.Sprint(d.type)+` as price,                  FROM products  WHERE products.id = ANY($%v) and products.store= $%d  `, counter, counter+1)   counter+=2   parameters = append(parameters, pq.Array(d.ids), d.store)}err := sqlx.Select(db, &dataStruct, fullQuery, parameters...)Will still need to validate column names prior to querying to prevent injection.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go