Add support for array binding
All checks were successful
Build / build (push) Successful in 1m39s

This commit is contained in:
Sebastiaan de Schaetzen 2025-03-24 12:05:10 +01:00
parent 58d63b6cf3
commit 87f10c73d6
2 changed files with 24 additions and 7 deletions

View File

@ -34,21 +34,37 @@ func (d *Db) query(query string) *Query {
} }
func (q *Query) Bind(args ...any) *Query { func (q *Query) Bind(args ...any) *Query {
into := 0
return q.bindInto(&into, args...)
}
func (q *Query) bindInto(into *int, args ...any) *Query {
if q.err != nil || q.stmt == nil { if q.err != nil || q.stmt == nil {
return q return q
} }
for i, arg := range args { for i, arg := range args {
*into++
if asString, ok := arg.(string); ok { if asString, ok := arg.(string); ok {
q.stmt.BindText(i+1, asString) q.stmt.BindText(*into, asString)
} else if asInt, ok := arg.(int); ok { } else if asInt, ok := arg.(int); ok {
q.stmt.BindInt64(i+1, int64(asInt)) q.stmt.BindInt64(*into, int64(asInt))
} else if asInt, ok := arg.(int64); ok { } else if asInt, ok := arg.(int64); ok {
q.stmt.BindInt64(i+1, asInt) q.stmt.BindInt64(*into, asInt)
} else if asBool, ok := arg.(bool); ok { } else if asBool, ok := arg.(bool); ok {
q.stmt.BindBool(i+1, asBool) q.stmt.BindBool(*into, asBool)
} else { } else {
q.err = fmt.Errorf("unsupported column type %s at index %d", reflect.TypeOf(arg).Name(), i) // Check if the argument is a slice or array of any type
return q v := reflect.ValueOf(arg)
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
*into--
for i := 0; i < v.Len(); i++ {
q.bindInto(into, v.Index(i).Interface())
}
} else {
*into--
q.err = fmt.Errorf("unsupported column type %s at index %d", reflect.TypeOf(arg).Name(), i)
return q
}
} }
} }
return q return q

View File

@ -141,7 +141,8 @@ func TestQueryWithInClause(t *testing.T) {
db.Query("insert into mytable(key, value) values ('key2', 'value2')").MustExec() db.Query("insert into mytable(key, value) values ('key2', 'value2')").MustExec()
// Execute query with IN clause // Execute query with IN clause
rows, err := db.Query("select key, value from mytable where key in (?, ?)").Bind("foo", "key2").ScanMulti() args := []string{"foo", "key2"}
rows, err := db.Query("select key, value from mytable where key in (?, ?)").Bind(args).ScanMulti()
require.NoError(t, err) require.NoError(t, err)
defer rows.MustFinish() defer rows.MustFinish()