xorm icon indicating copy to clipboard operation
xorm copied to clipboard

使用Pongo2作为SQL模板时无法查出count

Open wizizm opened this issue 6 years ago • 7 comments

sql := "company.join_comp_apply.done_list.stpl"
paramMap := map[string]interface{}{"comp_id": "123"}
var applyDtos []dto.ApplyDto
to, _ := d.db.SqlTemplateClient(sql, &paramMap).Count() 
//无法查出total,报错:sql: converting argument $1 type: unsupported type map[string]interface {}, a map

i, err := d.db.SqlTemplateClient(sql, &paramMap).Limit(pager.Size(), pager.Start()).FindAndCount(&applyDtos) 
//同样无法查出total,报错:Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
//用Find方法替代FindAndCount是可以正常查出结果的

sql模板如下: SELECT a.id, FROM t_apply a LEFT JOIN t_employee e ON a.emp_id = e.id WHERE comp_id = ?comp_id

wizizm avatar Sep 26 '19 13:09 wizizm

FindAndCount的错误补充完整: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ?comp _id) t' at line 5

wizizm avatar Sep 27 '19 02:09 wizizm

Count和FindAndCount两个函数不支持模板引擎,是ORM函数

xormplus avatar Oct 07 '19 18:10 xormplus

请问我想查出total应该使用什么方法?

上面是我简化后的SQL,实际情况比这个sql复杂很多,参数也复杂很多,如果模板方式不能同时支持参数传入和查询total,感觉模板基本不能用来查列表了。

wizizm avatar Oct 08 '19 01:10 wizizm

func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) { if session.isAutoClose { defer session.Close() } if session.isSqlFunc { session.autoResetStatement = false err := session.find(rowsSlicePtr, condiBean...) if err != nil { return 0, err }

	var sql = session.statement.RawSQL
	session.autoResetStatement = true
	sql = "select count(1) from (" + sql + ") t"
	params := session.statement.RawParams
	i := len(params)

	var sqlStr string
	var args []interface{}
	if i == 1 {
		vv := reflect.ValueOf(params[0])
		if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map {
			sqlStr = sql
			args = params
		} else {
			sqlStr, args, _ = core.MapToSlice(sql, params[0])
		}
	} else {
		sqlStr = sql
		args = params
	}
	var count int64
	_, err = session.SQL(sqlStr,args...).Get(&count)

	if err != nil {
		return 0, err
	}
	return count, nil

} else {

FindAndCount 改成上面那样就正常了,麻烦看看这样改有没问题

wizizm avatar Oct 08 '19 03:10 wizizm

你提交一个PR吧,我测试看看,然后看能不能合入,因为这个函数的前置函数场景很多

xormplus avatar Oct 11 '19 09:10 xormplus

已经提交了,另外加了一个pongo2模板,单文件多SQL的支持

wizizm avatar Oct 14 '19 01:10 wizizm

好的,我周末测一下

xormplus avatar Oct 15 '19 11:10 xormplus