Commit b30ff7a8 authored by Amos Wenger's avatar Amos Wenger

Add *Context.Delete()

parent 82b32c0f
Pipeline #11001 passed with stage
in 30 seconds
package hades
import (
"reflect"
"crawshaw.io/sqlite"
"github.com/go-xorm/builder"
"github.com/pkg/errors"
)
func (c *Context) Delete(conn *sqlite.Conn, model interface{}, cond builder.Cond) error {
modelType := reflect.TypeOf(model)
scope := c.ScopeMap.ByType(modelType)
if scope == nil {
return errors.Errorf("%v is not a model known to this hades context", modelType)
}
if cond == builder.NewCond() {
return errors.Errorf("refusing to blindly delete all %v without an explicit builder.Expr(\"1\") clause", modelType)
}
b := builder.Delete(cond).From(scope.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_Delete(t *testing.T) {
type Story struct {
ID int64
Body string
}
models := []interface{}{&Story{}}
withContext(t, models, func(conn *sqlite.Conn, c *hades.Context) {
stories := []*Story{
&Story{
ID: 1,
Body: "jesus wept",
},
&Story{
ID: 2,
Body: "exit status 1",
},
&Story{
ID: 8,
Body: "ice cold",
},
}
var count int64
var err error
wtest.Must(t, c.SaveOne(conn, stories))
count, err = c.Count(conn, &Story{}, builder.NewCond())
wtest.Must(t, err)
assert.EqualValues(t, 3, count)
err = c.Delete(conn, &Story{}, builder.NewCond())
assert.Error(t, err, "must refuse to delete with empty cond")
assert.Contains(t, err.Error(), "refusing to blindly")
err = c.Delete(conn, &Story{}, builder.Eq{"id": 1})
wtest.Must(t, err)
count, err = c.Count(conn, &Story{}, builder.NewCond())
wtest.Must(t, err)
assert.EqualValues(t, 2, count)
err = c.Delete(conn, &Story{}, builder.Expr("1"))
assert.NoError(t, err, "must delete all with expr")
count, err = c.Count(conn, &Story{}, builder.NewCond())
wtest.Must(t, err)
assert.EqualValues(t, 0, count)
})
}
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