go-zero
go-zero copied to clipboard
Problem of `in` clause of query statements.
in 查询 无法支持切片参数 无支持in查询,
- in query code
func (m *defaultOrderModel) Find(ctx context.Context, status []int64) (*[]Order, error) {
query := fmt.Sprintf("select %s from %s where `status` in ?", OrderRows, m.table)
var resp []Order
err := m.conn.QueryRowsCtx(ctx, &resp, query, status)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, db.ErrNotFound
default:
return nil, err
}
}
- 错误现象 切片展位符错误
切片被展位符解析成了 select xxxx from tab where status in [2,3,4.....]
Environments (please complete the following information):
- OS: [e.g. Mac]
- go-zero version [e.g. 1.3.4]
- goctl version [e.g. 1.3.8]
刚好也碰到了这个问题,分享一下解决方法供参考
func Placeholders(n int) string {
var b strings.Builder
for i := 0; i < n-1; i++ {
b.WriteString(fmt.Sprintf("$%d,", i+1))
}
if n > 0 {
b.WriteString(fmt.Sprintf("$%d", n))
}
return b.String()
}
func Int64SliceToInterface(ids []int64) []interface{} {
newIds := make([]interface{}, 0)
for _, item := range ids {
newIds = append(newIds, item)
}
return newIds
}
newIStatus := Int64SliceToInterface(status)
query := fmt.Sprintf("select %s from %s where `status` in (%s)", OrderRows, m.table,Placeholders(len(status)))
err := m.conn.QueryRowsCtx(ctx, &resp, query, status...)
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 14 days since being marked as stale.
I created a PR:https://github.com/zeromicro/go-zero/pull/2789