1 Star 1 Fork 0

loveUer / gourm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
which.go 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
loveuer 提交于 2020-01-08 14:22 . add which can define column custom
package gourm
import (
"fmt"
"log"
"reflect"
"strings"
)
func (d *DB) Which(out interface{}, outPrimaryVal ...interface{}) error {
if reflect.TypeOf(out).Kind() != reflect.Ptr {
return fmt.Errorf("out not a struct pointer")
}
rflctVal := reflect.ValueOf(out).Elem()
columns := getColumns(rflctVal)
primaryKey := getPrimaryKey(rflctVal)
var condition string
if len(outPrimaryVal) == 0 {
primaryVal := getColumnVal(rflctVal, primaryKey)
condition = fmt.Sprintf("%s = '%v'", primaryKey, primaryVal)
} else if len(outPrimaryVal) == 1 {
condition = fmt.Sprintf("%s = '%v'", primaryKey, outPrimaryVal[0])
} else if len(outPrimaryVal) == 2 {
if reflect.TypeOf(outPrimaryVal[0]).Kind() != reflect.String {
return fmt.Errorf("gourm which: col val must be string but => %v", reflect.TypeOf(outPrimaryVal[0]))
}
condition = fmt.Sprintf("%s = '%v'", outPrimaryVal[0].(string), outPrimaryVal[1])
} else {
return fmt.Errorf("primary key length not 0 or 1 but %d", len(outPrimaryVal))
}
var sliceout []interface{}
sentence := fmt.Sprintf("select %s from %s where %s limit 1", strings.Join(columns, ", "), getTableName(rflctVal), condition)
for i := 1; i < rflctVal.NumField(); i++ {
sliceout = append(sliceout, rflctVal.Field(i).Addr().Interface())
}
row := dbConn.QueryRow(sentence)
err := row.Scan(sliceout...)
if err != nil {
log.Printf("<model><model><Which>scan with sentence: %s err: %v\n", sentence, err)
return err
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/loveuer/gourm.git
git@gitee.com:loveuer/gourm.git
loveuer
gourm
gourm
master

搜索帮助

Bbcd6f05 5694891 0cc6727d 5694891