go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

Problem of `in` clause of query statements.

Open bogle-zhao opened this issue 1 year ago • 2 comments

in 查询 无法支持切片参数 无支持in查询,

  1. 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
	}
}
  1. 错误现象 切片展位符错误
   切片被展位符解析成了 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]

bogle-zhao avatar Jul 11 '22 00:07 bogle-zhao

刚好也碰到了这个问题,分享一下解决方法供参考

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...)

accaolei avatar Jul 11 '22 03:07 accaolei

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar Aug 19 '22 02:08 github-actions[bot]

This issue was closed because it has been inactive for 14 days since being marked as stale.

github-actions[bot] avatar Nov 18 '22 02:11 github-actions[bot]

I created a PR:https://github.com/zeromicro/go-zero/pull/2789

jan-bar avatar Jan 13 '23 08:01 jan-bar