Commit 47671728 authored by Amos Wenger's avatar Amos Wenger

Add Context.Update

parent b30ff7a8
Pipeline #11002 passed with stage
in 30 seconds
package hades
import (
"reflect"
"crawshaw.io/sqlite"
"github.com/go-xorm/builder"
"github.com/pkg/errors"
)
type WhereCond interface {
Cond() builder.Cond
}
type whereImpl struct {
cond builder.Cond
}
func (wt whereImpl) Cond() builder.Cond {
return wt.cond
}
func Where(cond builder.Cond) WhereCond {
return whereImpl{cond: cond}
}
func (c *Context) Update(conn *sqlite.Conn, model interface{}, where WhereCond, updates ...builder.Eq) error {
modelType := reflect.TypeOf(model)
scope := c.ScopeMap.ByType(modelType)
if scope == nil {
return errors.Errorf("%v is not a know model type", modelType)
}
tableName := scope.TableName()
b := builder.Update(updates...).Where(where.Cond()).Into(tableName)
return c.Exec(conn, b, nil)
}
package hades_test
import (
"testing"
"crawshaw.io/sqlite"
"github.com/go-xorm/builder"
"github.com/itchio/hades"
"github.com/itchio/wharf/wtest"
"github.com/stretchr/testify/assert"
)
func Test_Update(t *testing.T) {
type Mistake struct {
ID int64
Body string
}
models := []interface{}{&Mistake{}}
withContext(t, models, func(conn *sqlite.Conn, c *hades.Context) {
mistakes := []*Mistake{
&Mistake{
ID: 1,
Body: "rewrote everything",
},
&Mistake{
ID: 2,
Body: "mostly alone",
},
}
var count int64
var err error
wtest.Must(t, c.SaveOne(conn, mistakes))
count, err = c.Count(conn, &Mistake{}, builder.NewCond())
wtest.Must(t, err)
assert.EqualValues(t, 2, count)
wtest.Must(t, c.Update(conn, &Mistake{},
hades.Where(builder.Eq{"id": 1}),
builder.Eq{"body": "rewrote almost everything"},
))
var m Mistake
var found bool
found, err = c.SelectOne(conn, &m, builder.Eq{"id": 1})
wtest.Must(t, err)
assert.True(t, found)
assert.EqualValues(t, "rewrote almost everything", m.Body)
wtest.Must(t, c.Update(conn, &Mistake{},
hades.Where(builder.Expr("1")),
builder.Eq{"body": "nothing"},
))
found, err = c.SelectOne(conn, &m, builder.Eq{"id": 1})
wtest.Must(t, err)
assert.True(t, found)
assert.EqualValues(t, "nothing", m.Body)
found, err = c.SelectOne(conn, &m, builder.Eq{"id": 2})
wtest.Must(t, err)
assert.True(t, found)
assert.EqualValues(t, "nothing", m.Body)
})
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment