queryx: add binding transformer

This commit is contained in:
Nikita Karmatskikh
2021-11-23 21:58:26 +03:00
committed by Michal Jan Matczuk
parent 5e98fb6f71
commit 504f6523d9
4 changed files with 94 additions and 1 deletions

View File

@@ -93,7 +93,9 @@ type Queryx struct {
*gocql.Query
Names []string
Mapper *reflectx.Mapper
err error
tr Transformer
err error
}
// Query creates a new Queryx from gocql.Query using a default mapper.
@@ -104,9 +106,17 @@ func Query(q *gocql.Query, names []string) *Queryx {
Query: q,
Names: names,
Mapper: DefaultMapper,
tr: DefaultBindTransformer,
}
}
// WithBindTransformer sets the query bind transformer.
// The transformer is called right before binding a value to a named parameter.
func (q *Queryx) WithBindTransformer(tr Transformer) *Queryx {
q.tr = tr
return q
}
// BindStruct binds query named parameters to values from arg using mapper. If
// value cannot be found error is reported.
func (q *Queryx) BindStruct(arg interface{}) *Queryx {
@@ -157,6 +167,10 @@ func (q *Queryx) bindStructArgs(arg0 interface{}, arg1 map[string]interface{}) (
arglist = append(arglist, val)
}
if q.tr != nil {
arglist[i] = q.tr(q.Names[i], arglist[i])
}
return nil
})
@@ -184,6 +198,10 @@ func (q *Queryx) bindMapArgs(arg map[string]interface{}) ([]interface{}, error)
if !ok {
return arglist, fmt.Errorf("could not find name %q in %#v", name, arg)
}
if q.tr != nil {
val = q.tr(name, val)
}
arglist = append(arglist, val)
}
return arglist, nil