Fire event after datasource delete (#38090)

This commit is contained in:
Travis Patterson 2021-08-20 14:51:31 -06:00 committed by GitHub
parent b88f8bacf3
commit 32e11434da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 0 deletions

View File

@ -46,3 +46,11 @@ type UserUpdated struct {
Login string `json:"login"`
Email string `json:"email"`
}
type DataSourceDeleted struct {
Timestamp time.Time `json:"timestamp"`
Name string `json:"name"`
ID int64 `json:"id"`
UID string `json:"uid"`
OrgID int64 `json:"org_id"`
}

View File

@ -5,6 +5,7 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/util/errutil"
"github.com/grafana/grafana/pkg/components/simplejson"
@ -145,6 +146,15 @@ func DeleteDataSource(cmd *models.DeleteDataSourceCommand) error {
return inTransaction(func(sess *DBSession) error {
result, err := sess.Exec(params...)
cmd.DeletedDatasourcesCount, _ = result.RowsAffected()
sess.publishAfterCommit(&events.DataSourceDeleted{
Timestamp: time.Now(),
Name: cmd.Name,
ID: cmd.ID,
UID: cmd.UID,
OrgID: cmd.OrgID,
})
return err
})
}

View File

@ -6,7 +6,10 @@ import (
"errors"
"strconv"
"testing"
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -204,6 +207,29 @@ func TestDataAccess(t *testing.T) {
})
})
t.Run("fires an event when the datasource is deleted", func(t *testing.T) {
InitTestDB(t)
ds := initDatasource()
var deleted *events.DataSourceDeleted
bus.AddEventListener(func(e *events.DataSourceDeleted) error {
deleted = e
return nil
})
err := DeleteDataSource(&models.DeleteDataSourceCommand{ID: ds.Id, UID: "nisse-uid", Name: "nisse", OrgID: 123123})
require.NoError(t, err)
require.Eventually(t, func() bool {
return assert.NotNil(t, deleted)
}, time.Second, time.Millisecond)
require.Equal(t, ds.Id, deleted.ID)
require.Equal(t, int64(123123), deleted.OrgID)
require.Equal(t, "nisse", deleted.Name)
require.Equal(t, "nisse-uid", deleted.UID)
})
t.Run("DeleteDataSourceByName", func(t *testing.T) {
InitTestDB(t)
ds := initDatasource()