Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NamedQuery support map #117

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,16 +474,36 @@ func NamedQuery(sql string, data map[string]interface{}) (string, []interface{},
err = fmt.Errorf("%s not found", paramName)
return ""
}

v := reflect.ValueOf(val)
if v.Type().Kind() != reflect.Slice {
vals = append(vals, val)
return paramPlaceHolder
if v.Type().Kind() == reflect.Slice {
length := v.Len()
for i := 0; i < length; i++ {
vals = append(vals, v.Index(i).Interface())
}
return createMultiPlaceholders(length)
}
length := v.Len()
for i := 0; i < length; i++ {
vals = append(vals, v.Index(i).Interface())

if v.Type().Kind() == reflect.Map {
where, ok := val.(map[string]interface{})
if !ok {
err = fmt.Errorf("%s not expected map", paramName)
return ""
}

conditions, errLocal := getWhereConditions(where, defaultIgnoreKeys)
if errLocal != nil {
err = errLocal
return ""
}

whereString, whereVals := whereConnector("AND", conditions...)
vals = append(vals, whereVals...)
return whereString
}
return createMultiPlaceholders(length)

vals = append(vals, val)
return paramPlaceHolder
})
if nil != err {
return "", nil, err
Expand Down
15 changes: 15 additions & 0 deletions builder/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,21 @@ func TestNamedQuery(t *testing.T) {
vals: []interface{}{"f1", "f2", 10, "beijing", "shanghai", "chengdu"},
err: nil,
},
{
sql: `select {{foo}},{{bar}} from tb where address in {{addr}} and {{where}}`,
data: map[string]interface{}{
"foo": "f1",
"bar": "f2",
"addr": []string{"beijing", "shanghai", "chengdu"},
"where": map[string]interface{}{
"name in": []string{"1", "2"},
"age": 10,
},
},
cond: `select ?,? from tb where address in (?,?,?) and (age=? AND name IN (?,?))`,
vals: []interface{}{"f1", "f2", "beijing", "shanghai", "chengdu", 10, "1", "2"},
err: nil,
},
}
ass := assert.New(t)
for _, tc := range testData {
Expand Down