mirror of https://github.com/VinGarcia/ksql.git
Add delete operation
parent
4e156b8f26
commit
67cedb1f81
15
postgres.go
15
postgres.go
|
@ -52,3 +52,18 @@ func (c Client) Insert(
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete deletes one or more instances from the database by id
|
||||
func (c Client) Delete(
|
||||
ctx context.Context,
|
||||
entities ...interface{},
|
||||
) error {
|
||||
for _, entity := range entities {
|
||||
r := c.db.Table(c.tableName).Delete(entity)
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -75,8 +75,7 @@ func TestInsert(t *testing.T) {
|
|||
tableName: "users",
|
||||
}
|
||||
|
||||
user := User{}
|
||||
err = c.Insert(ctx, &user)
|
||||
err = c.Insert(ctx)
|
||||
assert.Equal(t, err, nil)
|
||||
})
|
||||
|
||||
|
@ -106,6 +105,56 @@ func TestInsert(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestDelete(t *testing.T) {
|
||||
err := createTable()
|
||||
if err != nil {
|
||||
t.Fatal("could not create test table!")
|
||||
}
|
||||
|
||||
t.Run("should ignore empty lists of users", func(t *testing.T) {
|
||||
db := connectDB(t)
|
||||
defer db.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
c := Client{
|
||||
db: db,
|
||||
tableName: "users",
|
||||
}
|
||||
|
||||
err = c.Delete(ctx)
|
||||
assert.Equal(t, err, nil)
|
||||
})
|
||||
|
||||
t.Run("should delete one user correctly", func(t *testing.T) {
|
||||
db := connectDB(t)
|
||||
defer db.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
c := Client{
|
||||
db: db,
|
||||
tableName: "users",
|
||||
}
|
||||
|
||||
u := User{
|
||||
Name: "Fernanda",
|
||||
}
|
||||
|
||||
err := c.Insert(ctx, &u)
|
||||
assert.Equal(t, err, nil)
|
||||
|
||||
err = c.Delete(ctx, &u)
|
||||
assert.Equal(t, err, nil)
|
||||
|
||||
result := User{}
|
||||
it := c.db.Raw("SELECT * FROM users WHERE id=?", u.ID)
|
||||
it.Scan(&result)
|
||||
|
||||
assert.Equal(t, it.Error, nil)
|
||||
assert.Equal(t, uint(0), result.ID)
|
||||
assert.Equal(t, "", result.Name)
|
||||
})
|
||||
}
|
||||
|
||||
func createTable() error {
|
||||
db, err := gorm.Open("sqlite3", "/tmp/test.db")
|
||||
if err != nil {
|
||||
|
|
Loading…
Reference in New Issue