Chore: Remove dashboards from models pkg (#61578)

* Copy dashboard models to dashboard pkg

* Use some models from current pkg instead of models

* Adjust api pkg

* Adjust pkg services

* Fix lint

* Chore: Remove dashboards models

* Remove dashboards from models pkg

* Fix lint in tests

* Fix lint in tests 2

* Fix for import in auth

* Remove newline

* Revert unused fix
This commit is contained in:
idafurjes
2023-01-18 13:52:41 +01:00
committed by GitHub
parent db0be6bc95
commit b573b19ca3
56 changed files with 497 additions and 822 deletions

View File

@@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/channels_config"
@@ -147,7 +148,7 @@ func (hs *HTTPServer) GetAlerts(c *models.ReqContext) response.Response {
}
for _, alert := range query.Result {
alert.Url = models.GetDashboardUrl(alert.DashboardUid, alert.DashboardSlug)
alert.Url = dashboards.GetDashboardURL(alert.DashboardUid, alert.DashboardSlug)
}
return response.JSON(http.StatusOK, query.Result)

View File

@@ -64,7 +64,7 @@ func dashboardGuardianResponse(err error) response.Response {
// 401: unauthorisedError
// 500: internalServerError
func (hs *HTTPServer) TrimDashboard(c *models.ReqContext) response.Response {
cmd := models.TrimDashboardCommand{}
cmd := dashboards.TrimDashboardCommand{}
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
@@ -169,7 +169,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
meta := dtos.DashboardMeta{
IsStarred: isStarred,
Slug: dash.Slug,
Type: models.DashTypeDB,
Type: dashboards.DashTypeDB,
CanStar: c.IsSignedIn,
CanSave: canSave,
CanEdit: canEdit,
@@ -217,7 +217,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
meta.ProvisionedExternalId, err = filepath.Rel(
hs.ProvisioningService.GetDashboardProvisionerResolvedPath(provisioningData.Name),
provisioningData.ExternalId,
provisioningData.ExternalID,
)
if err != nil {
// Not sure when this could happen so not sure how to better handle this. Right now ProvisionedExternalId
@@ -429,7 +429,7 @@ func (hs *HTTPServer) postDashboard(c *models.ReqContext, cmd dashboards.SaveDas
}
}
var provisioningData *models.DashboardProvisioning
var provisioningData *dashboards.DashboardProvisioning
if dash.ID != 0 {
data, err := hs.dashboardProvisioningService.GetProvisionedDashboardDataByDashboardID(c.Req.Context(), dash.ID)
if err != nil {
@@ -536,7 +536,7 @@ func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) response.Response {
slugQuery := dashboards.GetDashboardRefByIDQuery{ID: preference.HomeDashboardID}
err := hs.DashboardService.GetDashboardUIDByID(c.Req.Context(), &slugQuery)
if err == nil {
url := models.GetDashboardUrl(slugQuery.Result.UID, slugQuery.Result.Slug)
url := dashboards.GetDashboardURL(slugQuery.Result.UID, slugQuery.Result.Slug)
dashRedirect := dtos.DashboardRedirect{RedirectUri: url}
return response.JSON(http.StatusOK, &dashRedirect)
}
@@ -786,7 +786,7 @@ func (hs *HTTPServer) GetDashboardVersion(c *models.ReqContext) response.Respons
// 403: forbiddenError
// 500: internalServerError
func (hs *HTTPServer) ValidateDashboard(c *models.ReqContext) response.Response {
cmd := models.ValidateDashboardCommand{}
cmd := dashboards.ValidateDashboardCommand{}
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -1018,7 +1018,7 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext) response.Res
// 401: unauthorisedError
// 500: internalServerError
func (hs *HTTPServer) GetDashboardTags(c *models.ReqContext) {
query := models.GetDashboardTagsQuery{OrgId: c.OrgID}
query := dashboards.GetDashboardTagsQuery{OrgID: c.OrgID}
err := hs.DashboardService.GetDashboardTags(c.Req.Context(), &query)
if err != nil {
c.JsonApiErr(500, "Failed to get tags from database", err)
@@ -1137,7 +1137,7 @@ type DeleteDashboardByUIDParams struct {
type PostDashboardParams struct {
// in:body
// required:true
Body models.SaveDashboardCommand
Body dashboards.SaveDashboardCommand
}
// swagger:parameters calculateDashboardDiff
@@ -1160,7 +1160,7 @@ type CalcDashboardDiffParams struct {
type TrimDashboardParams struct {
// in:body
// required:true
Body models.TrimDashboardCommand
Body dashboards.TrimDashboardCommand
}
// swagger:response dashboardResponse
@@ -1249,7 +1249,7 @@ type GetHomeDashboardResponse struct {
// swagger:response getDashboardsTagsResponse
type DashboardsTagsResponse struct {
// in: body
Body []*models.DashboardTagCloudItem `json:"body"`
Body []*dashboards.DashboardTagCloudItem `json:"body"`
}
// Get home dashboard response.

View File

@@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/web"
)
@@ -82,7 +83,7 @@ func (hs *HTTPServer) GetDashboardPermissionList(c *models.ReqContext) response.
perm.TeamAvatarUrl = dtos.GetGravatarUrlWithDefault(perm.TeamEmail, perm.Team)
}
if perm.Slug != "" {
perm.Url = models.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug)
perm.Url = dashboards.GetDashboardFolderURL(perm.IsFolder, perm.Uid, perm.Slug)
}
filteredACLs = append(filteredACLs, perm)

View File

@@ -216,7 +216,7 @@ func (hs *HTTPServer) GetDashboardSnapshot(c *models.ReqContext) response.Respon
dto := dtos.DashboardFullWithMeta{
Dashboard: snapshot.Dashboard,
Meta: dtos.DashboardMeta{
Type: models.DashTypeSnapshot,
Type: dashboards.DashTypeSnapshot,
IsSnapshot: true,
Created: snapshot.Created,
Expires: snapshot.Expires,

View File

@@ -578,14 +578,14 @@ func TestDashboardAPIEndpoint(t *testing.T) {
})
t.Run("Given two dashboards with the same title in different folders", func(t *testing.T) {
dashOne := models.NewDashboard("dash")
dashOne.Id = 2
dashOne.FolderId = 1
dashOne := dashboards.NewDashboard("dash")
dashOne.ID = 2
dashOne.FolderID = 1
dashOne.HasACL = false
dashTwo := models.NewDashboard("dash")
dashTwo.Id = 4
dashTwo.FolderId = 3
dashTwo := dashboards.NewDashboard("dash")
dashTwo.ID = 4
dashTwo.FolderID = 3
dashTwo.HasACL = false
})
@@ -597,14 +597,14 @@ func TestDashboardAPIEndpoint(t *testing.T) {
const folderID int64 = 3
const dashID int64 = 2
cmd := models.SaveDashboardCommand{
OrgId: 1,
UserId: 5,
cmd := dashboards.SaveDashboardCommand{
OrgID: 1,
UserID: 5,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"title": "Dash",
}),
Overwrite: true,
FolderId: folderID,
FolderID: folderID,
IsFolder: false,
Message: "msg",
}
@@ -629,14 +629,14 @@ func TestDashboardAPIEndpoint(t *testing.T) {
const folderUid string = "folderUID"
const dashID int64 = 2
cmd := models.SaveDashboardCommand{
OrgId: 1,
UserId: 5,
cmd := dashboards.SaveDashboardCommand{
OrgID: 1,
UserID: 5,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"title": "Dash",
}),
Overwrite: true,
FolderUid: folderUid,
FolderUID: folderUid,
IsFolder: false,
Message: "msg",
}
@@ -662,14 +662,14 @@ func TestDashboardAPIEndpoint(t *testing.T) {
})
t.Run("Given a request with incorrect folder uid for creating a dashboard with", func(t *testing.T) {
cmd := models.SaveDashboardCommand{
OrgId: 1,
UserId: 5,
cmd := dashboards.SaveDashboardCommand{
OrgID: 1,
UserID: 5,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"title": "Dash",
}),
Overwrite: true,
FolderUid: "folderUID",
FolderUID: "folderUID",
IsFolder: false,
Message: "msg",
}
@@ -712,8 +712,8 @@ func TestDashboardAPIEndpoint(t *testing.T) {
{SaveError: dashboards.UpdatePluginDashboardError{PluginId: "plug"}, ExpectedStatusCode: 412},
}
cmd := models.SaveDashboardCommand{
OrgId: 1,
cmd := dashboards.SaveDashboardCommand{
OrgID: 1,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"title": "",
}),
@@ -736,7 +736,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
sqlmock := mockstore.SQLStoreMock{}
t.Run("When an invalid dashboard json is posted", func(t *testing.T) {
cmd := models.ValidateDashboardCommand{
cmd := dashboards.ValidateDashboardCommand{
Dashboard: "{\"hello\": \"world\"}",
}
@@ -752,7 +752,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
})
t.Run("When a dashboard with a too-low schema version is posted", func(t *testing.T) {
cmd := models.ValidateDashboardCommand{
cmd := dashboards.ValidateDashboardCommand{
Dashboard: "{\"schemaVersion\": 1}",
}
@@ -771,7 +771,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
devenvDashboard, readErr := os.ReadFile("../../devenv/dev-dashboards/home.json")
assert.Empty(t, readErr)
cmd := models.ValidateDashboardCommand{
cmd := dashboards.ValidateDashboardCommand{
Dashboard: string(devenvDashboard),
}
@@ -930,7 +930,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
t.Run("Given provisioned dashboard", func(t *testing.T) {
mockSQLStore := mockstore.NewSQLStoreMock()
dashboardStore := dashboards.NewFakeDashboardStore(t)
dashboardStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&models.DashboardProvisioning{ExternalId: "/dashboard1.json"}, nil).Once()
dashboardStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&dashboards.DashboardProvisioning{ExternalID: "/dashboard1.json"}, nil).Once()
teamService := &teamtest.FakeService{}
dashboardService := dashboards.NewFakeDashboardService(t)
@@ -1086,7 +1086,7 @@ func callPostDashboardShouldReturnSuccess(sc *scenarioContext) {
assert.Equal(sc.t, 200, sc.resp.Code)
}
func postDashboardScenario(t *testing.T, desc string, url string, routePattern string, cmd models.SaveDashboardCommand, dashboardService dashboards.DashboardService, folderService folder.Service, fn scenarioFunc) {
func postDashboardScenario(t *testing.T, desc string, url string, routePattern string, cmd dashboards.SaveDashboardCommand, dashboardService dashboards.DashboardService, folderService folder.Service, fn scenarioFunc) {
t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) {
cfg := setting.NewCfg()
hs := HTTPServer{
@@ -1109,7 +1109,7 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s
c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json")
sc.context = c
sc.context.SignedInUser = &user.SignedInUser{OrgID: cmd.OrgId, UserID: cmd.UserId}
sc.context.SignedInUser = &user.SignedInUser{OrgID: cmd.OrgID, UserID: cmd.UserID}
return hs.PostDashboard(c)
})
@@ -1120,7 +1120,7 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s
})
}
func postValidateScenario(t *testing.T, desc string, url string, routePattern string, cmd models.ValidateDashboardCommand,
func postValidateScenario(t *testing.T, desc string, url string, routePattern string, cmd dashboards.ValidateDashboardCommand,
role org.RoleType, fn scenarioFunc, sqlmock db.DB) {
t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) {
cfg := setting.NewCfg()
@@ -1250,7 +1250,7 @@ type mockDashboardProvisioningService struct {
}
func (s mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (
*models.DashboardProvisioning, error) {
*dashboards.DashboardProvisioning, error) {
return nil, nil
}

View File

@@ -64,7 +64,7 @@ func (hs *HTTPServer) GetFolderPermissionList(c *models.ReqContext) response.Res
}
if perm.Slug != "" {
perm.Url = models.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug)
perm.Url = dashboards.GetDashboardFolderURL(perm.IsFolder, perm.Uid, perm.Slug)
}
filteredACLs = append(filteredACLs, perm)

View File

@@ -8,7 +8,6 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
_ "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/playlist"
"github.com/grafana/grafana/pkg/services/search"
@@ -30,7 +29,7 @@ func (hs *HTTPServer) populateDashboardsByID(ctx context.Context, dashboardByIDs
Slug: item.Slug,
Title: item.Title,
Uri: "db/" + item.Slug,
Url: models.GetDashboardUrl(item.UID, item.Slug),
Url: dashboards.GetDashboardURL(item.UID, item.Slug),
Order: dashboardIDOrder[item.ID],
})
}

View File

@@ -184,14 +184,14 @@ func test(t *testing.T, dashboardProps DashboardProps, dashboardPermission *Dash
var aclUserID int64
if dashboardPermission != nil {
aclUserID = createDummyACL(t, sqlStore, dashboardPermission, search, dashboard.Id)
aclUserID = createDummyACL(t, sqlStore, dashboardPermission, search, dashboard.ID)
t.Logf("Created ACL with user ID %d\n", aclUserID)
}
dashboards := getDashboards(t, sqlStore, search, aclUserID)
if shouldFind {
require.Len(t, dashboards, 1, "Should return one dashboard")
assert.Equal(t, dashboard.Id, dashboards[0].Id, "Should return created dashboard")
assert.Equal(t, dashboard.ID, dashboards[0].Id, "Should return created dashboard")
} else {
assert.Empty(t, dashboards, "Should not return any dashboard")
}
@@ -226,33 +226,33 @@ func createDummyUser(t *testing.T, sqlStore DB) *user.User {
return usr
}
func createDummyDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, dashboardProps DashboardProps) *models.Dashboard {
func createDummyDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, dashboardProps DashboardProps) *dashboards.Dashboard {
t.Helper()
json, err := simplejson.NewJson([]byte(`{"schemaVersion":17,"title":"gdev dashboards","uid":"","version":1}`))
require.NoError(t, err)
saveDashboardCmd := models.SaveDashboardCommand{
saveDashboardCmd := dashboards.SaveDashboardCommand{
Dashboard: json,
UserId: 0,
UserID: 0,
Overwrite: false,
Message: "",
RestoredFrom: 0,
PluginId: "",
FolderId: 0,
PluginID: "",
FolderID: 0,
IsFolder: false,
UpdatedAt: time.Time{},
}
if dashboardProps.OrgId != 0 {
saveDashboardCmd.OrgId = dashboardProps.OrgId
saveDashboardCmd.OrgID = dashboardProps.OrgId
} else {
saveDashboardCmd.OrgId = 1
saveDashboardCmd.OrgID = 1
}
dash := insertTestDashboard(t, sqlStore, "", saveDashboardCmd.OrgId, 0, false, nil)
dash := insertTestDashboard(t, sqlStore, "", saveDashboardCmd.OrgID, 0, false, nil)
require.NoError(t, err)
t.Logf("Created dashboard with ID %d and org ID %d\n", dash.Id, dash.OrgId)
t.Logf("Created dashboard with ID %d and org ID %d\n", dash.ID, dash.OrgID)
return dash
}
@@ -332,11 +332,11 @@ func getDashboards(t *testing.T, sqlStore *sqlstore.SQLStore, search Search, acl
// TODO: Use FakeDashboardStore when org has its own service
func insertTestDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
folderId int64, isFolder bool, tags ...interface{}) *dashboards.Dashboard {
t.Helper()
cmd := models.SaveDashboardCommand{
OrgId: orgId,
FolderId: folderId,
cmd := dashboards.SaveDashboardCommand{
OrgID: orgId,
FolderID: folderId,
IsFolder: isFolder,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": nil,
@@ -345,25 +345,25 @@ func insertTestDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, title string
}),
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := sqlStore.WithDbSession(context.Background(), func(sess *Session) error {
dash = cmd.GetDashboardModel()
dash.SetVersion(1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Uid = util.GenerateShortUID()
dash.UID = util.GenerateShortUID()
_, err := sess.Insert(dash)
return err
})
require.NoError(t, err)
require.NotNil(t, dash)
dash.Data.Set("id", dash.Id)
dash.Data.Set("uid", dash.Uid)
dash.Data.Set("id", dash.ID)
dash.Data.Set("uid", dash.UID)
err = sqlStore.WithDbSession(context.Background(), func(sess *Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: dash.Version,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,
@@ -415,7 +415,7 @@ func updateDashboardACL(t *testing.T, sqlStore *sqlstore.SQLStore, dashboardID i
}
// Update dashboard HasACL flag
dashboard := models.Dashboard{HasACL: true}
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})

View File

@@ -1,268 +0,0 @@
package models
import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/setting"
)
const RootFolderName = "General"
const (
DashTypeDB = "db"
DashTypeSnapshot = "snapshot"
)
// Dashboard model
type Dashboard struct {
Id int64
Uid string
Slug string
OrgId int64
GnetId int64
Version int
PluginId string
Created time.Time
Updated time.Time
UpdatedBy int64
CreatedBy int64
FolderId int64
IsFolder bool
HasACL bool `xorm:"has_acl"`
Title string
Data *simplejson.Json
}
func (d *Dashboard) SetId(id int64) {
d.Id = id
d.Data.Set("id", id)
}
func (d *Dashboard) SetUid(uid string) {
d.Uid = uid
d.Data.Set("uid", uid)
}
func (d *Dashboard) SetVersion(version int) {
d.Version = version
d.Data.Set("version", version)
}
// NewDashboard creates a new dashboard
func NewDashboard(title string) *Dashboard {
dash := &Dashboard{}
dash.Data = simplejson.New()
dash.Data.Set("title", title)
dash.Title = title
dash.Created = time.Now()
dash.Updated = time.Now()
dash.UpdateSlug()
return dash
}
// NewDashboardFolder creates a new dashboard folder
func NewDashboardFolder(title string) *Dashboard {
folder := NewDashboard(title)
folder.IsFolder = true
folder.Data.Set("schemaVersion", 17)
folder.Data.Set("version", 0)
folder.IsFolder = true
return folder
}
// GetTags turns the tags in data json into go string array
func (d *Dashboard) GetTags() []string {
return d.Data.Get("tags").MustStringArray()
}
func NewDashboardFromJson(data *simplejson.Json) *Dashboard {
dash := &Dashboard{}
dash.Data = data
dash.Title = dash.Data.Get("title").MustString()
dash.UpdateSlug()
update := false
if id, err := dash.Data.Get("id").Float64(); err == nil {
dash.Id = int64(id)
update = true
}
if uid, err := dash.Data.Get("uid").String(); err == nil {
dash.Uid = uid
update = true
}
if version, err := dash.Data.Get("version").Float64(); err == nil && update {
dash.Version = int(version)
dash.Updated = time.Now()
} else {
dash.Data.Set("version", 0)
dash.Created = time.Now()
dash.Updated = time.Now()
}
if gnetId, err := dash.Data.Get("gnetId").Float64(); err == nil {
dash.GnetId = int64(gnetId)
}
return dash
}
// GetDashboardModel turns the command into the saveable model
func (cmd *SaveDashboardCommand) GetDashboardModel() *Dashboard {
dash := NewDashboardFromJson(cmd.Dashboard)
userId := cmd.UserId
if userId == 0 {
userId = -1
}
dash.UpdatedBy = userId
dash.OrgId = cmd.OrgId
dash.PluginId = cmd.PluginId
dash.IsFolder = cmd.IsFolder
dash.FolderId = cmd.FolderId
dash.UpdateSlug()
return dash
}
// UpdateSlug updates the slug
func (d *Dashboard) UpdateSlug() {
title := d.Data.Get("title").MustString()
d.Slug = slugify.Slugify(title)
}
// GetUrl return the html url for a folder if it's folder, otherwise for a dashboard
func (d *Dashboard) GetUrl() string {
return GetDashboardFolderUrl(d.IsFolder, d.Uid, d.Slug)
}
// GetDashboardFolderUrl return the html url for a folder if it's folder, otherwise for a dashboard
func GetDashboardFolderUrl(isFolder bool, uid string, slug string) string {
if isFolder {
return GetFolderUrl(uid, slug)
}
return GetDashboardUrl(uid, slug)
}
// GetDashboardUrl returns the HTML url for a dashboard.
func GetDashboardUrl(uid string, slug string) string {
return fmt.Sprintf("%s/d/%s/%s", setting.AppSubUrl, uid, slug)
}
// GetKioskModeDashboardUrl returns the HTML url for a dashboard in kiosk mode.
func GetKioskModeDashboardUrl(uid string, slug string, theme Theme) string {
return fmt.Sprintf("%s?kiosk&theme=%s", GetDashboardUrl(uid, slug), string(theme))
}
// GetFullDashboardUrl returns the full URL for a dashboard.
func GetFullDashboardUrl(uid string, slug string) string {
return fmt.Sprintf("%sd/%s/%s", setting.AppUrl, uid, slug)
}
// GetFolderUrl returns the HTML url for a folder.
func GetFolderUrl(folderUid string, slug string) string {
return fmt.Sprintf("%s/dashboards/f/%s/%s", setting.AppSubUrl, folderUid, slug)
}
//
// COMMANDS
//
type SaveDashboardCommand struct {
Dashboard *simplejson.Json `json:"dashboard" binding:"Required"`
UserId int64 `json:"userId"`
Overwrite bool `json:"overwrite"`
Message string `json:"message"`
OrgId int64 `json:"-"`
RestoredFrom int `json:"-"`
PluginId string `json:"-"`
FolderId int64 `json:"folderId"`
FolderUid string `json:"folderUid"`
IsFolder bool `json:"isFolder"`
UpdatedAt time.Time
Result *Dashboard `json:"-"`
}
type ValidateDashboardCommand struct {
Dashboard string `json:"dashboard" binding:"Required"`
}
type TrimDashboardCommand struct {
Dashboard *simplejson.Json `json:"dashboard" binding:"Required"`
Meta *simplejson.Json `json:"meta"`
Result *Dashboard `json:"-"`
}
type DashboardProvisioning struct {
Id int64
DashboardId int64
Name string
ExternalId string
CheckSum string
Updated int64
}
type DeleteDashboardCommand struct {
Id int64
OrgId int64
ForceDeleteFolderRules bool
}
type DeleteOrphanedProvisionedDashboardsCommand struct {
ReaderNames []string
}
//
// QUERIES
//
type GetDashboardQuery struct {
Slug string // required if no Id or Uid is specified
Id int64 // optional if slug is set
Uid string // optional if slug is set
OrgId int64
Result *Dashboard
}
type DashboardTagCloudItem struct {
Term string `json:"term"`
Count int `json:"count"`
}
type GetDashboardTagsQuery struct {
OrgId int64
Result []*DashboardTagCloudItem
}
type GetDashboardsQuery struct {
DashboardIds []int64
DashboardUIds []string
Result []*Dashboard
}
type GetDashboardsByPluginIdQuery struct {
OrgId int64
PluginId string
Result []*Dashboard
}
type DashboardRef struct {
Uid string
Slug string
}
type GetDashboardRefByIdQuery struct {
Id int64
Result *DashboardRef
}

View File

@@ -30,22 +30,6 @@ func NewFolder(title string) *Folder {
return folder
}
// DashboardToFolder converts Dashboard to Folder
func DashboardToFolder(dash *Dashboard) *Folder {
return &Folder{
Id: dash.Id,
Uid: dash.Uid,
Title: dash.Title,
HasACL: dash.HasACL,
Url: dash.GetUrl(),
Version: dash.Version,
Created: dash.Created,
CreatedBy: dash.CreatedBy,
Updated: dash.Updated,
UpdatedBy: dash.UpdatedBy,
}
}
//
// COMMANDS
//

View File

@@ -67,22 +67,6 @@ type ChannelHandlerFactory interface {
GetHandlerForPath(path string) (ChannelHandler, error)
}
// DashboardActivityChannel is a service to advertise dashboard activity
type DashboardActivityChannel interface {
// Called when a dashboard is saved -- this includes the error so we can support a
// gitops workflow that knows if the value was saved to the local database or not
// in many cases all direct save requests will fail, but the request should be forwarded
// to any gitops observers
DashboardSaved(orgID int64, user *user.UserDisplayDTO, message string, dashboard *Dashboard, err error) error
// Called when a dashboard is deleted
DashboardDeleted(orgID int64, user *user.UserDisplayDTO, uid string) error
// Experimental! Indicate is GitOps is active. This really means
// someone is subscribed to the `grafana/dashboards/gitops` channel
HasGitOpsObserver(orgID int64) bool
}
type LiveMessage struct {
Id int64
OrgId int64

View File

@@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/annotations/annotationstest"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources"
fd "github.com/grafana/grafana/pkg/services/datasources/fakes"
encryptionprovider "github.com/grafana/grafana/pkg/services/encryption/provider"
@@ -82,7 +83,7 @@ func (a *AlertStoreMock) GetOrCreateAlertNotificationState(c context.Context, cm
return nil
}
func (a *AlertStoreMock) GetDashboardUIDById(_ context.Context, _ *models.GetDashboardRefByIdQuery) error {
func (a *AlertStoreMock) GetDashboardUIDById(_ context.Context, _ *dashboards.GetDashboardRefByIDQuery) error {
return nil
}

View File

@@ -142,7 +142,7 @@ func (c *EvalContext) GetRuleURL() (string, error) {
if err != nil {
return "", err
}
return fmt.Sprintf(urlFormat, models.GetFullDashboardUrl(ref.UID, ref.Slug), c.Rule.PanelID, c.Rule.OrgID), nil
return fmt.Sprintf(urlFormat, dashboards.GetFullDashboardURL(ref.UID, ref.Slug), c.Rule.PanelID, c.Rule.OrgID), nil
}
// GetNewState returns the new state from the alert rule evaluation.

View File

@@ -42,7 +42,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
defer resetTimeNow()
var store *sqlStore
var testDash *models.Dashboard
var testDash *dashboards.Dashboard
var items []*models.Alert
setup := func(t *testing.T) {
@@ -63,8 +63,8 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
items = []*models.Alert{
{
PanelId: 1,
DashboardId: testDash.Id,
OrgId: testDash.OrgId,
DashboardId: testDash.ID,
OrgId: testDash.OrgID,
Name: "Alerting title",
Message: "Alerting message",
Settings: simplejson.New(),
@@ -73,7 +73,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
},
}
err = store.SaveAlerts(context.Background(), testDash.Id, items)
err = store.SaveAlerts(context.Background(), testDash.ID, items)
require.Nil(t, err)
}
@@ -81,7 +81,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
setup(t)
// Get alert so we can use its ID in tests
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
@@ -138,13 +138,13 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("Can read properties", func(t *testing.T) {
setup(t)
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
alert := alertQuery.Result[0]
require.Nil(t, err2)
require.Greater(t, alert.Id, int64(0))
require.Equal(t, testDash.Id, alert.DashboardId)
require.Equal(t, testDash.ID, alert.DashboardId)
require.Equal(t, int64(1), alert.PanelId)
require.Equal(t, "Alerting title", alert.Name)
require.Equal(t, models.AlertStateUnknown, alert.State)
@@ -160,7 +160,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("Viewer can read alerts", func(t *testing.T) {
setup(t)
viewerUser := &user.SignedInUser{OrgRole: org.RoleViewer, OrgID: 1}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: viewerUser}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: viewerUser}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
@@ -172,14 +172,14 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
modifiedItems := items
modifiedItems[0].Name = "Name"
err := store.SaveAlerts(context.Background(), testDash.Id, items)
err := store.SaveAlerts(context.Background(), testDash.ID, items)
t.Run("Can save alerts with same dashboard and panel id", func(t *testing.T) {
require.Nil(t, err)
})
t.Run("Alerts should be updated", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
@@ -192,7 +192,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
})
t.Run("Updates without changes should be ignored", func(t *testing.T) {
err3 := store.SaveAlerts(context.Background(), testDash.Id, items)
err3 := store.SaveAlerts(context.Background(), testDash.ID, items)
require.Nil(t, err3)
})
})
@@ -201,21 +201,21 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
setup(t)
multipleItems := []*models.Alert{
{
DashboardId: testDash.Id,
DashboardId: testDash.ID,
PanelId: 1,
Name: "1",
OrgId: 1,
Settings: simplejson.New(),
},
{
DashboardId: testDash.Id,
DashboardId: testDash.ID,
PanelId: 2,
Name: "2",
OrgId: 1,
Settings: simplejson.New(),
},
{
DashboardId: testDash.Id,
DashboardId: testDash.ID,
PanelId: 3,
Name: "3",
OrgId: 1,
@@ -223,12 +223,12 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
},
}
err := store.SaveAlerts(context.Background(), testDash.Id, multipleItems)
err := store.SaveAlerts(context.Background(), testDash.ID, multipleItems)
t.Run("Should save 3 dashboards", func(t *testing.T) {
require.Nil(t, err)
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &queryForDashboard)
require.Nil(t, err2)
@@ -238,10 +238,10 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("should updated two dashboards and delete one", func(t *testing.T) {
missingOneAlert := multipleItems[:2]
err = store.SaveAlerts(context.Background(), testDash.Id, missingOneAlert)
err = store.SaveAlerts(context.Background(), testDash.ID, missingOneAlert)
t.Run("should delete the missing alert", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
require.Equal(t, 2, len(query.Result))
@@ -254,24 +254,24 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
items := []*models.Alert{
{
PanelId: 1,
DashboardId: testDash.Id,
DashboardId: testDash.ID,
Name: "Alerting title",
Message: "Alerting message",
},
}
err := store.SaveAlerts(context.Background(), testDash.Id, items)
err := store.SaveAlerts(context.Background(), testDash.ID, items)
require.Nil(t, err)
err = store.db.WithDbSession(context.Background(), func(sess *db.Session) error {
dash := models.Dashboard{Id: testDash.Id, OrgId: 1}
dash := dashboards.Dashboard{ID: testDash.ID, OrgID: 1}
_, err := sess.Delete(dash)
return err
})
require.Nil(t, err)
t.Run("Alerts should be removed", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
@@ -292,21 +292,21 @@ func TestIntegrationPausingAlerts(t *testing.T) {
sqlStore := sqlStore{db: ss, log: log.New(), tagService: tagimpl.ProvideService(ss, ss.Cfg)}
testDash := insertTestDashboard(t, sqlStore.db, "dashboard with alerts", 1, 0, false, "alert")
alert, err := insertTestAlert("Alerting title", "Alerting message", testDash.OrgId, testDash.Id, simplejson.New(), sqlStore)
alert, err := insertTestAlert("Alerting title", "Alerting message", testDash.OrgID, testDash.ID, simplejson.New(), sqlStore)
require.Nil(t, err)
stateDateBeforePause := alert.NewStateDate
stateDateAfterPause := stateDateBeforePause
// Get alert so we can use its ID in tests
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := sqlStore.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
insertedAlert := alertQuery.Result[0]
t.Run("when paused", func(t *testing.T) {
_, err := sqlStore.pauseAlert(t, testDash.OrgId, insertedAlert.Id, true)
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.Id, true)
require.Nil(t, err)
t.Run("the NewStateDate should be updated", func(t *testing.T) {
@@ -319,7 +319,7 @@ func TestIntegrationPausingAlerts(t *testing.T) {
})
t.Run("when unpaused", func(t *testing.T) {
_, err := sqlStore.pauseAlert(t, testDash.OrgId, insertedAlert.Id, false)
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.Id, false)
require.Nil(t, err)
t.Run("the NewStateDate should be updated again", func(t *testing.T) {
@@ -380,11 +380,11 @@ func (ss *sqlStore) pauseAllAlerts(t *testing.T, pauseState bool) error {
}
func insertTestDashboard(t *testing.T, store db.DB, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
folderId int64, isFolder bool, tags ...interface{}) *dashboards.Dashboard {
t.Helper()
cmd := models.SaveDashboardCommand{
OrgId: orgId,
FolderId: folderId,
cmd := dashboards.SaveDashboardCommand{
OrgID: orgId,
FolderID: folderId,
IsFolder: isFolder,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": nil,
@@ -393,25 +393,25 @@ func insertTestDashboard(t *testing.T, store db.DB, title string, orgId int64,
}),
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := store.WithDbSession(context.Background(), func(sess *db.Session) error {
dash = cmd.GetDashboardModel()
dash.SetVersion(1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Uid = util.GenerateShortUID()
dash.UID = util.GenerateShortUID()
_, err := sess.Insert(dash)
return err
})
require.NoError(t, err)
require.NotNil(t, dash)
dash.Data.Set("id", dash.Id)
dash.Data.Set("uid", dash.Uid)
dash.Data.Set("id", dash.ID)
dash.Data.Set("uid", dash.UID)
err = store.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: dash.Version,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,

View File

@@ -5,7 +5,6 @@ import (
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboardimport"
@@ -45,7 +44,7 @@ type ImportDashboardService struct {
}
func (s *ImportDashboardService) ImportDashboard(ctx context.Context, req *dashboardimport.ImportDashboardRequest) (*dashboardimport.ImportDashboardResponse, error) {
var draftDashboard *models.Dashboard
var draftDashboard *dashboards.Dashboard
if req.PluginId != "" {
loadReq := &plugindashboards.LoadPluginDashboardRequest{
PluginID: req.PluginId,
@@ -57,7 +56,7 @@ func (s *ImportDashboardService) ImportDashboard(ctx context.Context, req *dashb
draftDashboard = resp.Dashboard
}
} else {
draftDashboard = models.NewDashboardFromJson(req.Dashboard)
draftDashboard = dashboards.NewDashboardFromJson(req.Dashboard)
}
evaluator := utils.NewDashTemplateEvaluator(draftDashboard.Data, req.Inputs)

View File

@@ -7,7 +7,6 @@ import (
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboardimport"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/folder"
@@ -172,7 +171,7 @@ func loadTestDashboard(ctx context.Context, req *plugindashboards.LoadPluginDash
}
return &plugindashboards.LoadPluginDashboardResponse{
Dashboard: models.NewDashboardFromJson(dashboardJSON),
Dashboard: dashboards.NewDashboardFromJson(dashboardJSON),
}, nil
}

View File

@@ -18,7 +18,7 @@ type DashboardService interface {
GetDashboard(ctx context.Context, query *GetDashboardQuery) error
GetDashboardACLInfoList(ctx context.Context, query *models.GetDashboardACLInfoListQuery) error
GetDashboards(ctx context.Context, query *GetDashboardsQuery) error
GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error
GetDashboardTags(ctx context.Context, query *GetDashboardTagsQuery) error
GetDashboardUIDByID(ctx context.Context, query *GetDashboardRefByIDQuery) error
HasAdminPermissionInDashboardsOrFolders(ctx context.Context, query *models.HasAdminPermissionInDashboardsOrFoldersQuery) error
HasEditPermissionInFolders(ctx context.Context, query *models.HasEditPermissionInFoldersQuery) error
@@ -33,18 +33,18 @@ type DashboardService interface {
// PluginService is a service for operating on plugin dashboards.
type PluginService interface {
GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error
GetDashboardsByPluginID(ctx context.Context, query *GetDashboardsByPluginIDQuery) error
}
// DashboardProvisioningService is a service for operating on provisioned dashboards.
//
//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go
type DashboardProvisioningService interface {
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *DeleteOrphanedProvisionedDashboardsCommand) error
DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error
GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error)
GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error)
GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error)
GetProvisionedDashboardData(ctx context.Context, name string) ([]*DashboardProvisioning, error)
GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*DashboardProvisioning, error)
GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*DashboardProvisioning, error)
SaveFolderForProvisionedDashboards(context.Context, *SaveDashboardDTO) (*Dashboard, error)
SaveProvisionedDashboard(ctx context.Context, dto *SaveDashboardDTO, provisioning *DashboardProvisioning) (*Dashboard, error)
UnprovisionDashboard(ctx context.Context, dashboardID int64) error
@@ -54,19 +54,19 @@ type DashboardProvisioningService interface {
//
//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go
type Store interface {
DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
DeleteDashboard(ctx context.Context, cmd *DeleteDashboardCommand) error
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *DeleteOrphanedProvisionedDashboardsCommand) error
FindDashboards(ctx context.Context, query *models.FindPersistedDashboardsQuery) ([]DashboardSearchProjection, error)
GetDashboard(ctx context.Context, query *GetDashboardQuery) (*Dashboard, error)
GetDashboardACLInfoList(ctx context.Context, query *models.GetDashboardACLInfoListQuery) error
GetDashboardUIDByID(ctx context.Context, query *GetDashboardRefByIDQuery) error
GetDashboards(ctx context.Context, query *GetDashboardsQuery) error
// GetDashboardsByPluginID retrieves dashboards identified by plugin.
GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error
GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error
GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error)
GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error)
GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error)
GetDashboardsByPluginID(ctx context.Context, query *GetDashboardsByPluginIDQuery) error
GetDashboardTags(ctx context.Context, query *GetDashboardTagsQuery) error
GetProvisionedDashboardData(ctx context.Context, name string) ([]*DashboardProvisioning, error)
GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*DashboardProvisioning, error)
GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*DashboardProvisioning, error)
HasAdminPermissionInDashboardsOrFolders(ctx context.Context, query *models.HasAdminPermissionInDashboardsOrFoldersQuery) error
HasEditPermissionInFolders(ctx context.Context, query *models.HasEditPermissionInFoldersQuery) error
// SaveAlerts saves dashboard alerts.

View File

@@ -5,7 +5,6 @@ package dashboards
import (
context "context"
models "github.com/grafana/grafana/pkg/models"
mock "github.com/stretchr/testify/mock"
)
@@ -15,11 +14,11 @@ type FakeDashboardProvisioning struct {
}
// DeleteOrphanedProvisionedDashboards provides a mock function with given fields: ctx, cmd
func (_m *FakeDashboardProvisioning) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error {
func (_m *FakeDashboardProvisioning) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *DeleteOrphanedProvisionedDashboardsCommand) error {
ret := _m.Called(ctx, cmd)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.DeleteOrphanedProvisionedDashboardsCommand) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *DeleteOrphanedProvisionedDashboardsCommand) error); ok {
r0 = rf(ctx, cmd)
} else {
r0 = ret.Error(0)
@@ -43,15 +42,15 @@ func (_m *FakeDashboardProvisioning) DeleteProvisionedDashboard(ctx context.Cont
}
// GetProvisionedDashboardData provides a mock function with given fields: ctx, name
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error) {
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardData(ctx context.Context, name string) ([]*DashboardProvisioning, error) {
ret := _m.Called(ctx, name)
var r0 []*models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, string) []*models.DashboardProvisioning); ok {
var r0 []*DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, string) []*DashboardProvisioning); ok {
r0 = rf(ctx, name)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*models.DashboardProvisioning)
r0 = ret.Get(0).([]*DashboardProvisioning)
}
}
@@ -66,15 +65,15 @@ func (_m *FakeDashboardProvisioning) GetProvisionedDashboardData(ctx context.Con
}
// GetProvisionedDashboardDataByDashboardID provides a mock function with given fields: ctx, dashboardID
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error) {
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*DashboardProvisioning, error) {
ret := _m.Called(ctx, dashboardID)
var r0 *models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64) *models.DashboardProvisioning); ok {
var r0 *DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64) *DashboardProvisioning); ok {
r0 = rf(ctx, dashboardID)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.DashboardProvisioning)
r0 = ret.Get(0).(*DashboardProvisioning)
}
}
@@ -89,15 +88,15 @@ func (_m *FakeDashboardProvisioning) GetProvisionedDashboardDataByDashboardID(ct
}
// GetProvisionedDashboardDataByDashboardUID provides a mock function with given fields: ctx, orgID, dashboardUID
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error) {
func (_m *FakeDashboardProvisioning) GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*DashboardProvisioning, error) {
ret := _m.Called(ctx, orgID, dashboardUID)
var r0 *models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *models.DashboardProvisioning); ok {
var r0 *DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *DashboardProvisioning); ok {
r0 = rf(ctx, orgID, dashboardUID)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.DashboardProvisioning)
r0 = ret.Get(0).(*DashboardProvisioning)
}
}

View File

@@ -138,11 +138,11 @@ func (_m *FakeDashboardService) GetDashboardACLInfoList(ctx context.Context, que
}
// GetDashboardTags provides a mock function with given fields: ctx, query
func (_m *FakeDashboardService) GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error {
func (_m *FakeDashboardService) GetDashboardTags(ctx context.Context, query *GetDashboardTagsQuery) error {
ret := _m.Called(ctx, query)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.GetDashboardTagsQuery) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *GetDashboardTagsQuery) error); ok {
r0 = rf(ctx, query)
} else {
r0 = ret.Error(0)

View File

@@ -100,40 +100,40 @@ func (d *DashboardStore) GetFolderByTitle(ctx context.Context, orgID int64, titl
// there is a unique constraint on org_id, folder_id, title
// there are no nested folders so the parent folder id is always 0
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Title: title}
dashboard := dashboards.Dashboard{OrgID: orgID, FolderID: 0, Title: title}
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
has, err := sess.Table(&dashboards.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
if !has {
return dashboards.ErrFolderNotFound
}
dashboard.SetId(dashboard.Id)
dashboard.SetUid(dashboard.Uid)
dashboard.SetID(dashboard.ID)
dashboard.SetUID(dashboard.UID)
return nil
})
return folder.FromDashboard(&dashboard), err
return dashboards.FromDashboard(&dashboard), err
}
func (d *DashboardStore) GetFolderByID(ctx context.Context, orgID int64, id int64) (*folder.Folder, error) {
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Id: id}
dashboard := dashboards.Dashboard{OrgID: orgID, FolderID: 0, ID: id}
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
has, err := sess.Table(&dashboards.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
if !has {
return dashboards.ErrFolderNotFound
}
dashboard.SetId(dashboard.Id)
dashboard.SetUid(dashboard.Uid)
dashboard.SetID(dashboard.ID)
dashboard.SetUID(dashboard.UID)
return nil
})
if err != nil {
return nil, err
}
return folder.FromDashboard(&dashboard), nil
return dashboards.FromDashboard(&dashboard), nil
}
func (d *DashboardStore) GetFolderByUID(ctx context.Context, orgID int64, uid string) (*folder.Folder, error) {
@@ -141,42 +141,42 @@ func (d *DashboardStore) GetFolderByUID(ctx context.Context, orgID int64, uid st
return nil, dashboards.ErrDashboardIdentifierNotSet
}
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Uid: uid}
dashboard := dashboards.Dashboard{OrgID: orgID, FolderID: 0, UID: uid}
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
has, err := sess.Table(&dashboards.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
if !has {
return dashboards.ErrFolderNotFound
}
dashboard.SetId(dashboard.Id)
dashboard.SetUid(dashboard.Uid)
dashboard.SetID(dashboard.ID)
dashboard.SetUID(dashboard.UID)
return nil
})
if err != nil {
return nil, err
}
return folder.FromDashboard(&dashboard), nil
return dashboards.FromDashboard(&dashboard), nil
}
func (d *DashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error) {
var data models.DashboardProvisioning
func (d *DashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*dashboards.DashboardProvisioning, error) {
var data dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", dashboardID).Get(&data)
return err
})
if data.DashboardId == 0 {
if data.DashboardID == 0 {
return nil, nil
}
return &data, err
}
func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error) {
var provisionedDashboard models.DashboardProvisioning
func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*dashboards.DashboardProvisioning, error) {
var provisionedDashboard dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var dashboard models.Dashboard
var dashboard dashboards.Dashboard
exists, err := sess.Where("org_id = ? AND uid = ?", orgID, dashboardUID).Get(&dashboard)
if err != nil {
return err
@@ -184,7 +184,7 @@ func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, o
if !exists {
return dashboards.ErrDashboardNotFound
}
exists, err = sess.Where("dashboard_id = ?", dashboard.Id).Get(&provisionedDashboard)
exists, err = sess.Where("dashboard_id = ?", dashboard.ID).Get(&provisionedDashboard)
if err != nil {
return err
}
@@ -196,8 +196,8 @@ func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, o
return &provisionedDashboard, err
}
func (d *DashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error) {
var result []*models.DashboardProvisioning
func (d *DashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*dashboards.DashboardProvisioning, error) {
var result []*dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return sess.Where("name = ?", name).Find(&result)
})
@@ -251,7 +251,7 @@ func (d *DashboardStore) UpdateDashboardACL(ctx context.Context, dashboardID int
}
// Update dashboard HasACL flag
dashboard := models.Dashboard{HasACL: true}
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})
@@ -280,14 +280,14 @@ func (d *DashboardStore) SaveAlerts(ctx context.Context, dashID int64, alerts []
// The dashboard will still have `created_by = -1` to see it was not created by any particular user.
func (d *DashboardStore) UnprovisionDashboard(ctx context.Context, id int64) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", id).Delete(&models.DashboardProvisioning{})
_, err := sess.Where("dashboard_id = ?", id).Delete(&dashboards.DashboardProvisioning{})
return err
})
}
func (d *DashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error {
func (d *DashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *dashboards.DeleteOrphanedProvisionedDashboardsCommand) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
var result []*models.DashboardProvisioning
var result []*dashboards.DashboardProvisioning
convertedReaderNames := make([]interface{}, len(cmd.ReaderNames))
for index, readerName := range cmd.ReaderNames {
@@ -300,7 +300,7 @@ func (d *DashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context
}
for _, deleteDashCommand := range result {
err := d.DeleteDashboard(ctx, &models.DeleteDashboardCommand{Id: deleteDashCommand.DashboardId})
err := d.DeleteDashboard(ctx, &dashboards.DeleteDashboardCommand{ID: deleteDashCommand.DashboardID})
if err != nil && !errors.Is(err, dashboards.ErrDashboardNotFound) {
return err
}
@@ -357,7 +357,7 @@ func (d *DashboardStore) Count(ctx context.Context, scopeParams *quota.ScopePara
func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.Dashboard, dialect migrator.Dialect, overwrite bool) (bool, error) {
dashWithIdExists := false
isParentFolderChanged := false
var existingById models.Dashboard
var existingById dashboards.Dashboard
if dash.ID > 0 {
var err error
@@ -371,12 +371,12 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
}
if dash.UID == "" {
dash.SetUID(existingById.Uid)
dash.SetUID(existingById.UID)
}
}
dashWithUidExists := false
var existingByUid models.Dashboard
var existingByUid dashboards.Dashboard
if dash.UID != "" {
var err error
@@ -387,7 +387,7 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
}
if dash.FolderID > 0 {
var existingFolder models.Dashboard
var existingFolder dashboards.Dashboard
folderExists, err := sess.Where("org_id=? AND id=? AND is_folder=?", dash.OrgID, dash.FolderID,
dialect.BooleanStr(true)).Get(&existingFolder)
if err != nil {
@@ -403,15 +403,15 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
return false, nil
}
if dashWithIdExists && dashWithUidExists && existingById.Id != existingByUid.Id {
if dashWithIdExists && dashWithUidExists && existingById.ID != existingByUid.ID {
return false, dashboards.ErrDashboardWithSameUIDExists
}
existing := existingById
if !dashWithIdExists && dashWithUidExists {
dash.SetID(existingByUid.Id)
dash.SetUID(existingByUid.Uid)
dash.SetID(existingByUid.ID)
dash.SetUID(existingByUid.UID)
existing = existingByUid
}
@@ -420,7 +420,7 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
return isParentFolderChanged, dashboards.ErrDashboardTypeMismatch
}
if !dash.IsFolder && dash.FolderID != existing.FolderId {
if !dash.IsFolder && dash.FolderID != existing.FolderID {
isParentFolderChanged = true
}
@@ -434,8 +434,8 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
}
// do not allow plugin dashboard updates without overwrite flag
if existing.PluginId != "" && !overwrite {
return isParentFolderChanged, dashboards.UpdatePluginDashboardError{PluginId: existing.PluginId}
if existing.PluginID != "" && !overwrite {
return isParentFolderChanged, dashboards.UpdatePluginDashboardError{PluginId: existing.PluginID}
}
return isParentFolderChanged, nil
@@ -443,14 +443,14 @@ func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.D
func getExistingDashboardByTitleAndFolder(sess *db.Session, dash *dashboards.Dashboard, dialect migrator.Dialect, overwrite,
isParentFolderChanged bool) (bool, error) {
var existing models.Dashboard
var existing dashboards.Dashboard
exists, err := sess.Where("org_id=? AND slug=? AND (is_folder=? OR folder_id=?)", dash.OrgID, dash.Slug,
dialect.BooleanStr(true), dash.FolderID).Get(&existing)
if err != nil {
return isParentFolderChanged, fmt.Errorf("SQL query for existing dashboard by org ID or folder ID failed: %w", err)
}
if exists && dash.ID != existing.Id {
if exists && dash.ID != existing.ID {
if existing.IsFolder && !dash.IsFolder {
return isParentFolderChanged, dashboards.ErrDashboardWithSameNameAsFolder
}
@@ -459,13 +459,13 @@ func getExistingDashboardByTitleAndFolder(sess *db.Session, dash *dashboards.Das
return isParentFolderChanged, dashboards.ErrDashboardFolderWithSameNameAsDashboard
}
if !dash.IsFolder && (dash.FolderID != existing.FolderId || dash.ID == 0) {
if !dash.IsFolder && (dash.FolderID != existing.FolderID || dash.ID == 0) {
isParentFolderChanged = true
}
if overwrite {
dash.SetID(existing.Id)
dash.SetUID(existing.Uid)
dash.SetID(existing.ID)
dash.SetUID(existing.UID)
dash.SetVersion(existing.Version)
} else {
return isParentFolderChanged, dashboards.ErrDashboardWithSameNameInFolderExists
@@ -485,7 +485,7 @@ func saveDashboard(sess *db.Session, cmd *dashboards.SaveDashboardCommand, emitE
}
if dash.ID > 0 {
var existing models.Dashboard
var existing dashboards.Dashboard
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.ID, dash.OrgID).Get(&existing)
if err != nil {
return err
@@ -504,8 +504,8 @@ func saveDashboard(sess *db.Session, cmd *dashboards.SaveDashboardCommand, emitE
}
// do not allow plugin dashboard updates without overwrite flag
if existing.PluginId != "" && !cmd.Overwrite {
return dashboards.UpdatePluginDashboardError{PluginId: existing.PluginId}
if existing.PluginID != "" && !cmd.Overwrite {
return dashboards.UpdatePluginDashboardError{PluginId: existing.PluginID}
}
}
@@ -599,7 +599,7 @@ func generateNewDashboardUid(sess *db.Session, orgId int64) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
exists, err := sess.Where("org_id=? AND uid=?", orgId, uid).Get(&models.Dashboard{})
exists, err := sess.Where("org_id=? AND uid=?", orgId, uid).Get(&dashboards.Dashboard{})
if err != nil {
return "", err
}
@@ -613,18 +613,18 @@ func generateNewDashboardUid(sess *db.Session, orgId int64) (string, error) {
}
func saveProvisionedData(sess *db.Session, provisioning *dashboards.DashboardProvisioning, dashboard *dashboards.Dashboard) error {
result := &models.DashboardProvisioning{}
result := &dashboards.DashboardProvisioning{}
exist, err := sess.Where("dashboard_id=? AND name = ?", dashboard.ID, provisioning.Name).Get(result)
if err != nil {
return err
}
provisioning.ID = result.Id
provisioning.ID = result.ID
provisioning.DashboardID = dashboard.ID
if exist {
_, err = sess.ID(result.Id).Update(provisioning)
_, err = sess.ID(result.ID).Update(provisioning)
} else {
_, err = sess.Insert(provisioning)
}
@@ -749,25 +749,25 @@ func (d *DashboardStore) deleteAlertByIdInternal(alertId int64, reason string, s
return nil
}
func (d *DashboardStore) GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error {
func (d *DashboardStore) GetDashboardsByPluginID(ctx context.Context, query *dashboards.GetDashboardsByPluginIDQuery) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
var dashboards = make([]*models.Dashboard, 0)
var dashboards = make([]*dashboards.Dashboard, 0)
whereExpr := "org_id=? AND plugin_id=? AND is_folder=" + d.store.GetDialect().BooleanStr(false)
err := dbSession.Where(whereExpr, query.OrgId, query.PluginId).Find(&dashboards)
err := dbSession.Where(whereExpr, query.OrgID, query.PluginID).Find(&dashboards)
query.Result = dashboards
return err
})
}
func (d *DashboardStore) DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
func (d *DashboardStore) DeleteDashboard(ctx context.Context, cmd *dashboards.DeleteDashboardCommand) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return d.deleteDashboard(cmd, sess, d.emitEntityEvent())
})
}
func (d *DashboardStore) deleteDashboard(cmd *models.DeleteDashboardCommand, sess *db.Session, emitEntityEvent bool) error {
dashboard := dashboards.Dashboard{ID: cmd.Id, OrgID: cmd.OrgId}
func (d *DashboardStore) deleteDashboard(cmd *dashboards.DeleteDashboardCommand, sess *db.Session, emitEntityEvent bool) error {
dashboard := dashboards.Dashboard{ID: cmd.ID, OrgID: cmd.OrgID}
has, err := sess.Get(&dashboard)
if err != nil {
return err
@@ -1066,7 +1066,7 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
return res, nil
}
func (d *DashboardStore) GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error {
func (d *DashboardStore) GetDashboardTags(ctx context.Context, query *dashboards.GetDashboardTagsQuery) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `SELECT
COUNT(*) as count,
@@ -1077,8 +1077,8 @@ func (d *DashboardStore) GetDashboardTags(ctx context.Context, query *models.Get
GROUP BY term
ORDER BY term`
query.Result = make([]*models.DashboardTagCloudItem, 0)
sess := dbSession.SQL(sql, query.OrgId)
query.Result = make([]*dashboards.DashboardTagCloudItem, 0)
sess := dbSession.SQL(sql, query.OrgID)
err := sess.Find(&query.Result)
return err
})
@@ -1096,7 +1096,7 @@ func (d *DashboardStore) CountDashboardsInFolder(
err = d.store.WithDbSession(ctx, func(sess *db.Session) error {
session := sess.In("folder_id", req.FolderID).In("org_id", req.OrgID).
In("is_folder", d.store.GetDialect().BooleanStr(false))
count, err = session.Count(&models.Dashboard{})
count, err = session.Count(&dashboards.Dashboard{})
return err
})
return count, err

View File

@@ -9,7 +9,6 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/quota/quotatest"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
@@ -86,7 +85,7 @@ func TestIntegrationDashboardProvisioningTest(t *testing.T) {
require.Nil(t, err)
require.NotNil(t, query.Result)
deleteCmd := &models.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: []string{"default"}}
deleteCmd := &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: []string{"default"}}
require.Nil(t, dashboardStore.DeleteOrphanedProvisionedDashboards(context.Background(), deleteCmd))
query = &dashboards.GetDashboardsQuery{DashboardIDs: []int64{dash.ID, anotherDash.ID}}
@@ -102,7 +101,7 @@ func TestIntegrationDashboardProvisioningTest(t *testing.T) {
require.Nil(t, err)
require.Equal(t, 1, len(rslt))
require.Equal(t, dashId, rslt[0].DashboardId)
require.Equal(t, dashId, rslt[0].DashboardID)
require.Equal(t, now.Unix(), rslt[0].Updated)
})
@@ -119,9 +118,9 @@ func TestIntegrationDashboardProvisioningTest(t *testing.T) {
})
t.Run("Deleting folder should delete provision meta data", func(t *testing.T) {
deleteCmd := &models.DeleteDashboardCommand{
Id: dash.ID,
OrgId: 1,
deleteCmd := &dashboards.DeleteDashboardCommand{
ID: dash.ID,
OrgID: 1,
}
require.Nil(t, dashboardStore.DeleteDashboard(context.Background(), deleteCmd))

View File

@@ -159,9 +159,9 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
setup()
dash := insertTestDashboard(t, dashboardStore, "delete me", 1, 0, false, "delete this")
err := dashboardStore.DeleteDashboard(context.Background(), &models.DeleteDashboardCommand{
Id: dash.ID,
OrgId: 1,
err := dashboardStore.DeleteDashboard(context.Background(), &dashboards.DeleteDashboardCommand{
ID: dash.ID,
OrgID: 1,
})
require.NoError(t, err)
})
@@ -233,14 +233,14 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
setup()
emptyFolder := insertTestDashboard(t, dashboardStore, "2 test dash folder", 1, 0, true, "prod", "webapp")
deleteCmd := &models.DeleteDashboardCommand{Id: emptyFolder.ID}
deleteCmd := &dashboards.DeleteDashboardCommand{ID: emptyFolder.ID}
err := dashboardStore.DeleteDashboard(context.Background(), deleteCmd)
require.NoError(t, err)
})
t.Run("Should be not able to delete a dashboard if force delete rules is disabled", func(t *testing.T) {
setup()
deleteCmd := &models.DeleteDashboardCommand{Id: savedFolder.ID, ForceDeleteFolderRules: false}
deleteCmd := &dashboards.DeleteDashboardCommand{ID: savedFolder.ID, ForceDeleteFolderRules: false}
err := dashboardStore.DeleteDashboard(context.Background(), deleteCmd)
require.True(t, errors.Is(err, dashboards.ErrFolderContainsAlertRules))
})
@@ -266,7 +266,7 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
pubdashConfig, _ := publicDashboardStore.FindByAccessToken(context.Background(), "an-access-token")
require.NotNil(t, pubdashConfig)
deleteCmd := &models.DeleteDashboardCommand{Id: savedDash.ID, OrgId: savedDash.OrgID}
deleteCmd := &dashboards.DeleteDashboardCommand{ID: savedDash.ID, OrgID: savedDash.OrgID}
err = dashboardStore.DeleteDashboard(context.Background(), deleteCmd)
require.NoError(t, err)
@@ -301,7 +301,7 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
pubdashConfig, _ := publicDashboardStore.FindByAccessToken(context.Background(), "an-access-token")
require.NotNil(t, pubdashConfig)
deleteCmd := &models.DeleteDashboardCommand{Id: savedFolder.ID, ForceDeleteFolderRules: true}
deleteCmd := &dashboards.DeleteDashboardCommand{ID: savedFolder.ID, ForceDeleteFolderRules: true}
err = dashboardStore.DeleteDashboard(context.Background(), deleteCmd)
require.NoError(t, err)
@@ -319,7 +319,7 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
t.Run("Should be able to delete a dashboard folder and its children if force delete rules is enabled", func(t *testing.T) {
setup()
deleteCmd := &models.DeleteDashboardCommand{Id: savedFolder.ID, ForceDeleteFolderRules: true}
deleteCmd := &dashboards.DeleteDashboardCommand{ID: savedFolder.ID, ForceDeleteFolderRules: true}
err := dashboardStore.DeleteDashboard(context.Background(), deleteCmd)
require.NoError(t, err)
@@ -380,7 +380,7 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
t.Run("Should be able to get dashboard tags", func(t *testing.T) {
setup()
query := models.GetDashboardTagsQuery{OrgId: 1}
query := dashboards.GetDashboardTagsQuery{OrgID: 1}
err := dashboardStore.GetDashboardTags(context.Background(), &query)
require.NoError(t, err)
@@ -598,9 +598,9 @@ func TestIntegrationDashboardDataAccessGivenPluginWithImportedDashboards(t *test
insertTestDashboardForPlugin(t, dashboardStore, "app-dash1", 1, appFolder.ID, false, pluginId)
insertTestDashboardForPlugin(t, dashboardStore, "app-dash2", 1, appFolder.ID, false, pluginId)
query := models.GetDashboardsByPluginIdQuery{
PluginId: pluginId,
OrgId: 1,
query := dashboards.GetDashboardsByPluginIDQuery{
PluginID: pluginId,
OrgID: 1,
}
err = dashboardStore.GetDashboardsByPluginID(context.Background(), &query)
@@ -866,7 +866,7 @@ func makeQueryResult(query *models.FindPersistedDashboardsQuery, res []dashboard
UID: item.UID,
Title: item.Title,
URI: "db/" + item.Slug,
URL: models.GetDashboardFolderUrl(item.IsFolder, item.UID, item.Slug),
URL: dashboards.GetDashboardFolderURL(item.IsFolder, item.UID, item.Slug),
Type: hitType,
FolderID: item.FolderID,
FolderUID: item.FolderUID,
@@ -875,7 +875,7 @@ func makeQueryResult(query *models.FindPersistedDashboardsQuery, res []dashboard
}
if item.FolderID > 0 {
hit.FolderURL = models.GetFolderUrl(item.FolderUID, item.FolderSlug)
hit.FolderURL = dashboards.GetFolderURL(item.FolderUID, item.FolderSlug)
}
if query.Sort.MetaName != "" {

View File

@@ -1,11 +1,11 @@
// Code generated by mockery v2.14.0. DO NOT EDIT.
// Code generated by mockery v2.16.0. DO NOT EDIT.
package dashboards
import (
context "context"
models "github.com/grafana/grafana/pkg/models"
folder "github.com/grafana/grafana/pkg/services/folder"
mock "github.com/stretchr/testify/mock"
)
@@ -15,15 +15,15 @@ type FakeFolderStore struct {
}
// GetFolderByID provides a mock function with given fields: ctx, orgID, id
func (_m *FakeFolderStore) GetFolderByID(ctx context.Context, orgID int64, id int64) (*models.Folder, error) {
func (_m *FakeFolderStore) GetFolderByID(ctx context.Context, orgID int64, id int64) (*folder.Folder, error) {
ret := _m.Called(ctx, orgID, id)
var r0 *models.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, int64) *models.Folder); ok {
var r0 *folder.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, int64) *folder.Folder); ok {
r0 = rf(ctx, orgID, id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.Folder)
r0 = ret.Get(0).(*folder.Folder)
}
}
@@ -38,15 +38,15 @@ func (_m *FakeFolderStore) GetFolderByID(ctx context.Context, orgID int64, id in
}
// GetFolderByTitle provides a mock function with given fields: ctx, orgID, title
func (_m *FakeFolderStore) GetFolderByTitle(ctx context.Context, orgID int64, title string) (*models.Folder, error) {
func (_m *FakeFolderStore) GetFolderByTitle(ctx context.Context, orgID int64, title string) (*folder.Folder, error) {
ret := _m.Called(ctx, orgID, title)
var r0 *models.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *models.Folder); ok {
var r0 *folder.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *folder.Folder); ok {
r0 = rf(ctx, orgID, title)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.Folder)
r0 = ret.Get(0).(*folder.Folder)
}
}
@@ -61,15 +61,15 @@ func (_m *FakeFolderStore) GetFolderByTitle(ctx context.Context, orgID int64, ti
}
// GetFolderByUID provides a mock function with given fields: ctx, orgID, uid
func (_m *FakeFolderStore) GetFolderByUID(ctx context.Context, orgID int64, uid string) (*models.Folder, error) {
func (_m *FakeFolderStore) GetFolderByUID(ctx context.Context, orgID int64, uid string) (*folder.Folder, error) {
ret := _m.Called(ctx, orgID, uid)
var r0 *models.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *models.Folder); ok {
var r0 *folder.Folder
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *folder.Folder); ok {
r0 = rf(ctx, orgID, uid)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.Folder)
r0 = ret.Get(0).(*folder.Folder)
}
}

View File

@@ -260,9 +260,9 @@ type GetDashboardsQuery struct {
Result []*Dashboard
}
type GetDashboardsByPluginIdQuery struct {
type GetDashboardsByPluginIDQuery struct {
OrgID int64
PluginId string
PluginID string
Result []*Dashboard
}
@@ -335,7 +335,7 @@ func FromDashboard(dash *Dashboard) *folder.Folder {
UID: dash.UID,
Title: dash.Title,
HasACL: dash.HasACL,
Url: models.GetFolderUrl(dash.UID, dash.Slug),
Url: GetFolderURL(dash.UID, dash.Slug),
Version: dash.Version,
Created: dash.Created,
CreatedBy: dash.CreatedBy,

View File

@@ -1,4 +1,4 @@
package models
package dashboards
import (
"testing"
@@ -15,7 +15,7 @@ func TestGetDashboardUrl(t *testing.T) {
t.Cleanup(func() { setting.AppUrl = origAppURL })
setting.AppUrl = ""
url := GetDashboardUrl("uid", "my-dashboard")
url := GetDashboardURL("uid", "my-dashboard")
assert.Equal(t, "/d/uid/my-dashboard", url)
}
@@ -24,7 +24,7 @@ func TestGetFullDashboardUrl(t *testing.T) {
t.Cleanup(func() { setting.AppUrl = origAppURL })
setting.AppUrl = "http://grafana.local/"
url := GetFullDashboardUrl("uid", "my-dashboard")
url := GetFullDashboardURL("uid", "my-dashboard")
assert.Equal(t, "http://grafana.local/d/uid/my-dashboard", url)
}
@@ -62,10 +62,10 @@ func TestSaveDashboardCommand_GetDashboardModel(t *testing.T) {
json := simplejson.New()
json.Set("title", "test dash")
cmd := &SaveDashboardCommand{Dashboard: json, FolderId: 1}
cmd := &SaveDashboardCommand{Dashboard: json, FolderID: 1}
dash := cmd.GetDashboardModel()
assert.Equal(t, int64(1), dash.FolderId)
assert.Equal(t, int64(1), dash.FolderID)
})
}

View File

@@ -64,15 +64,15 @@ func ProvideDashboardService(
}
}
func (dr *DashboardServiceImpl) GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error) {
func (dr *DashboardServiceImpl) GetProvisionedDashboardData(ctx context.Context, name string) ([]*dashboards.DashboardProvisioning, error) {
return dr.dashboardStore.GetProvisionedDashboardData(ctx, name)
}
func (dr *DashboardServiceImpl) GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error) {
func (dr *DashboardServiceImpl) GetProvisionedDashboardDataByDashboardID(ctx context.Context, dashboardID int64) (*dashboards.DashboardProvisioning, error) {
return dr.dashboardStore.GetProvisionedDataByDashboardID(ctx, dashboardID)
}
func (dr *DashboardServiceImpl) GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error) {
func (dr *DashboardServiceImpl) GetProvisionedDashboardDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*dashboards.DashboardProvisioning, error) {
return dr.dashboardStore.GetProvisionedDataByDashboardUID(ctx, orgID, dashboardUID)
}
@@ -93,7 +93,7 @@ func (dr *DashboardServiceImpl) BuildSaveDashboardCommand(ctx context.Context, d
return nil, dashboards.ErrDashboardFolderCannotHaveParent
}
if dash.IsFolder && strings.EqualFold(dash.Title, models.RootFolderName) {
if dash.IsFolder && strings.EqualFold(dash.Title, dashboards.RootFolderName) {
return nil, dashboards.ErrDashboardFolderNameExists
}
@@ -187,7 +187,7 @@ func (dr *DashboardServiceImpl) UpdateDashboardACL(ctx context.Context, uid int6
return dr.dashboardStore.UpdateDashboardACL(ctx, uid, items)
}
func (dr *DashboardServiceImpl) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error {
func (dr *DashboardServiceImpl) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *dashboards.DeleteOrphanedProvisionedDashboardsCommand) error {
return dr.dashboardStore.DeleteOrphanedProvisionedDashboards(ctx, cmd)
}
@@ -382,7 +382,7 @@ func (dr *DashboardServiceImpl) DeleteDashboard(ctx context.Context, dashboardId
return dr.deleteDashboard(ctx, dashboardId, orgId, true)
}
func (dr *DashboardServiceImpl) GetDashboardByPublicUid(ctx context.Context, dashboardPublicUid string) (*models.Dashboard, error) {
func (dr *DashboardServiceImpl) GetDashboardByPublicUid(ctx context.Context, dashboardPublicUid string) (*dashboards.Dashboard, error) {
return nil, nil
}
@@ -445,7 +445,7 @@ func (dr *DashboardServiceImpl) deleteDashboard(ctx context.Context, dashboardId
return dashboards.ErrDashboardCannotDeleteProvisionedDashboard
}
}
cmd := &models.DeleteDashboardCommand{OrgId: orgId, Id: dashboardId}
cmd := &dashboards.DeleteDashboardCommand{OrgID: orgId, ID: dashboardId}
return dr.dashboardStore.DeleteDashboard(ctx, cmd)
}
@@ -481,7 +481,7 @@ func (dr *DashboardServiceImpl) UnprovisionDashboard(ctx context.Context, dashbo
return dr.dashboardStore.UnprovisionDashboard(ctx, dashboardId)
}
func (dr *DashboardServiceImpl) GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error {
func (dr *DashboardServiceImpl) GetDashboardsByPluginID(ctx context.Context, query *dashboards.GetDashboardsByPluginIDQuery) error {
return dr.dashboardStore.GetDashboardsByPluginID(ctx, query)
}
@@ -571,7 +571,7 @@ func makeQueryResult(query *models.FindPersistedDashboardsQuery, res []dashboard
UID: item.UID,
Title: item.Title,
URI: "db/" + item.Slug,
URL: models.GetDashboardFolderUrl(item.IsFolder, item.UID, item.Slug),
URL: dashboards.GetDashboardFolderURL(item.IsFolder, item.UID, item.Slug),
Type: getHitType(item),
FolderID: item.FolderID,
FolderUID: item.FolderUID,
@@ -580,7 +580,7 @@ func makeQueryResult(query *models.FindPersistedDashboardsQuery, res []dashboard
}
if item.FolderID > 0 {
hit.FolderURL = models.GetFolderUrl(item.FolderUID, item.FolderSlug)
hit.FolderURL = dashboards.GetFolderURL(item.FolderUID, item.FolderSlug)
}
if query.Sort.MetaName != "" {
@@ -609,7 +609,7 @@ func (dr *DashboardServiceImpl) HasEditPermissionInFolders(ctx context.Context,
return dr.dashboardStore.HasEditPermissionInFolders(ctx, query)
}
func (dr *DashboardServiceImpl) GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error {
func (dr *DashboardServiceImpl) GetDashboardTags(ctx context.Context, query *dashboards.GetDashboardTagsQuery) error {
return dr.dashboardStore.GetDashboardTags(ctx, query)
}

View File

@@ -91,7 +91,7 @@ func TestDashboardService(t *testing.T) {
t.Run("Should return validation error if dashboard is provisioned", func(t *testing.T) {
fakeStore.On("ValidateDashboardBeforeSave", mock.Anything, mock.Anything, mock.AnythingOfType("bool")).Return(true, nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&models.DashboardProvisioning{}, nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&dashboards.DashboardProvisioning{}, nil).Once()
dto.Dashboard = dashboards.NewDashboard("Dash")
dto.Dashboard.SetID(3)
@@ -176,7 +176,7 @@ func TestDashboardService(t *testing.T) {
t.Run("Should return validation error if dashboard is provisioned", func(t *testing.T) {
fakeStore.On("ValidateDashboardBeforeSave", mock.Anything, mock.Anything, mock.AnythingOfType("bool")).Return(true, nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&models.DashboardProvisioning{}, nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&dashboards.DashboardProvisioning{}, nil).Once()
dto.Dashboard = dashboards.NewDashboard("Dash")
dto.Dashboard.SetID(3)
@@ -188,14 +188,14 @@ func TestDashboardService(t *testing.T) {
t.Run("Given provisioned dashboard", func(t *testing.T) {
t.Run("DeleteProvisionedDashboard should delete it", func(t *testing.T) {
args := &models.DeleteDashboardCommand{OrgId: 1, Id: 1}
args := &dashboards.DeleteDashboardCommand{OrgID: 1, ID: 1}
fakeStore.On("DeleteDashboard", mock.Anything, args).Return(nil).Once()
err := service.DeleteProvisionedDashboard(context.Background(), 1, 1)
require.NoError(t, err)
})
t.Run("DeleteDashboard should fail to delete it when provisioning information is missing", func(t *testing.T) {
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&models.DashboardProvisioning{}, nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(&dashboards.DashboardProvisioning{}, nil).Once()
err := service.DeleteDashboard(context.Background(), 1, 1)
require.Equal(t, err, dashboards.ErrDashboardCannotDeleteProvisionedDashboard)
})
@@ -203,14 +203,14 @@ func TestDashboardService(t *testing.T) {
t.Run("Given non provisioned dashboard", func(t *testing.T) {
t.Run("DeleteProvisionedDashboard should delete the dashboard", func(t *testing.T) {
args := &models.DeleteDashboardCommand{OrgId: 1, Id: 1, ForceDeleteFolderRules: false}
args := &dashboards.DeleteDashboardCommand{OrgID: 1, ID: 1, ForceDeleteFolderRules: false}
fakeStore.On("DeleteDashboard", mock.Anything, args).Return(nil).Once()
err := service.DeleteProvisionedDashboard(context.Background(), 1, 1)
require.NoError(t, err)
})
t.Run("DeleteDashboard should delete it", func(t *testing.T) {
args := &models.DeleteDashboardCommand{OrgId: 1, Id: 1}
args := &dashboards.DeleteDashboardCommand{OrgID: 1, ID: 1}
fakeStore.On("DeleteDashboard", mock.Anything, args).Return(nil).Once()
fakeStore.On("GetProvisionedDataByDashboardID", mock.Anything, mock.AnythingOfType("int64")).Return(nil, nil).Once()
err := service.DeleteDashboard(context.Background(), 1, 1)

View File

@@ -77,11 +77,11 @@ func (_m *FakeDashboardStore) DeleteACLByUser(_a0 context.Context, _a1 int64) er
}
// DeleteDashboard provides a mock function with given fields: ctx, cmd
func (_m *FakeDashboardStore) DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
func (_m *FakeDashboardStore) DeleteDashboard(ctx context.Context, cmd *DeleteDashboardCommand) error {
ret := _m.Called(ctx, cmd)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.DeleteDashboardCommand) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *DeleteDashboardCommand) error); ok {
r0 = rf(ctx, cmd)
} else {
r0 = ret.Error(0)
@@ -91,11 +91,11 @@ func (_m *FakeDashboardStore) DeleteDashboard(ctx context.Context, cmd *models.D
}
// DeleteOrphanedProvisionedDashboards provides a mock function with given fields: ctx, cmd
func (_m *FakeDashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error {
func (_m *FakeDashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *DeleteOrphanedProvisionedDashboardsCommand) error {
ret := _m.Called(ctx, cmd)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.DeleteOrphanedProvisionedDashboardsCommand) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *DeleteOrphanedProvisionedDashboardsCommand) error); ok {
r0 = rf(ctx, cmd)
} else {
r0 = ret.Error(0)
@@ -165,11 +165,11 @@ func (_m *FakeDashboardStore) GetDashboardACLInfoList(ctx context.Context, query
}
// GetDashboardTags provides a mock function with given fields: ctx, query
func (_m *FakeDashboardStore) GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error {
func (_m *FakeDashboardStore) GetDashboardTags(ctx context.Context, query *GetDashboardTagsQuery) error {
ret := _m.Called(ctx, query)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.GetDashboardTagsQuery) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *GetDashboardTagsQuery) error); ok {
r0 = rf(ctx, query)
} else {
r0 = ret.Error(0)
@@ -207,11 +207,11 @@ func (_m *FakeDashboardStore) GetDashboards(ctx context.Context, query *GetDashb
}
// GetDashboardsByPluginID provides a mock function with given fields: ctx, query
func (_m *FakeDashboardStore) GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error {
func (_m *FakeDashboardStore) GetDashboardsByPluginID(ctx context.Context, query *GetDashboardsByPluginIDQuery) error {
ret := _m.Called(ctx, query)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *models.GetDashboardsByPluginIdQuery) error); ok {
if rf, ok := ret.Get(0).(func(context.Context, *GetDashboardsByPluginIDQuery) error); ok {
r0 = rf(ctx, query)
} else {
r0 = ret.Error(0)
@@ -290,15 +290,15 @@ func (_m *FakeDashboardStore) GetFolderByUID(ctx context.Context, orgID int64, u
}
// GetProvisionedDashboardData provides a mock function with given fields: ctx, name
func (_m *FakeDashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error) {
func (_m *FakeDashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*DashboardProvisioning, error) {
ret := _m.Called(ctx, name)
var r0 []*models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, string) []*models.DashboardProvisioning); ok {
var r0 []*DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, string) []*DashboardProvisioning); ok {
r0 = rf(ctx, name)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*models.DashboardProvisioning)
r0 = ret.Get(0).([]*DashboardProvisioning)
}
}
@@ -313,15 +313,15 @@ func (_m *FakeDashboardStore) GetProvisionedDashboardData(ctx context.Context, n
}
// GetProvisionedDataByDashboardID provides a mock function with given fields: ctx, dashboardID
func (_m *FakeDashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error) {
func (_m *FakeDashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*DashboardProvisioning, error) {
ret := _m.Called(ctx, dashboardID)
var r0 *models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64) *models.DashboardProvisioning); ok {
var r0 *DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64) *DashboardProvisioning); ok {
r0 = rf(ctx, dashboardID)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.DashboardProvisioning)
r0 = ret.Get(0).(*DashboardProvisioning)
}
}
@@ -336,15 +336,15 @@ func (_m *FakeDashboardStore) GetProvisionedDataByDashboardID(ctx context.Contex
}
// GetProvisionedDataByDashboardUID provides a mock function with given fields: ctx, orgID, dashboardUID
func (_m *FakeDashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error) {
func (_m *FakeDashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*DashboardProvisioning, error) {
ret := _m.Called(ctx, orgID, dashboardUID)
var r0 *models.DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *models.DashboardProvisioning); ok {
var r0 *DashboardProvisioning
if rf, ok := ret.Get(0).(func(context.Context, int64, string) *DashboardProvisioning); ok {
r0 = rf(ctx, orgID, dashboardUID)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*models.DashboardProvisioning)
r0 = ret.Get(0).(*DashboardProvisioning)
}
}

View File

@@ -10,7 +10,6 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/util"
@@ -28,21 +27,21 @@ func testIntegrationGetDashboardVersion(t *testing.T, fn getStore) {
savedDash := insertTestDashboard(t, ss, "test dash 26", 1, 0, false, "diff")
query := dashver.GetDashboardVersionQuery{
DashboardID: savedDash.Id,
DashboardID: savedDash.ID,
Version: savedDash.Version,
OrgID: 1,
}
res, err := dashVerStore.Get(context.Background(), &query)
require.Nil(t, err)
assert.Equal(t, query.DashboardID, savedDash.Id)
assert.Equal(t, query.DashboardID, savedDash.ID)
assert.Equal(t, query.Version, savedDash.Version)
assert.Equal(t, createdById, res.CreatedBy)
dashCmd := &models.Dashboard{
Id: res.ID,
Uid: savedDash.Uid,
OrgId: savedDash.OrgId,
dashCmd := &dashboards.Dashboard{
ID: res.ID,
UID: savedDash.UID,
OrgID: savedDash.OrgID,
}
err = getDashboard(t, ss, dashCmd)
require.Nil(t, err)
@@ -82,7 +81,7 @@ func testIntegrationGetDashboardVersion(t *testing.T, fn getStore) {
savedDash := insertTestDashboard(t, ss, "test dash 43", 1, 0, false, "diff-all")
t.Run("Get all versions for a given Dashboard ID", func(t *testing.T) {
query := dashver.ListDashboardVersionsQuery{
DashboardID: savedDash.Id,
DashboardID: savedDash.ID,
OrgID: 1,
Limit: 1000,
}
@@ -105,7 +104,7 @@ func testIntegrationGetDashboardVersion(t *testing.T, fn getStore) {
updateTestDashboard(t, ss, savedDash, map[string]interface{}{
"tags": "different-tag",
})
query := dashver.ListDashboardVersionsQuery{DashboardID: savedDash.Id, OrgID: 1, Limit: 1000}
query := dashver.ListDashboardVersionsQuery{DashboardID: savedDash.ID, OrgID: 1, Limit: 1000}
res, err := dashVerStore.List(context.Background(), &query)
require.Nil(t, err)
@@ -113,7 +112,7 @@ func testIntegrationGetDashboardVersion(t *testing.T, fn getStore) {
})
}
func getDashboard(t *testing.T, sqlStore db.DB, dashboard *models.Dashboard) error {
func getDashboard(t *testing.T, sqlStore db.DB, dashboard *dashboards.Dashboard) error {
t.Helper()
return sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
has, err := sess.Get(dashboard)
@@ -124,8 +123,8 @@ func getDashboard(t *testing.T, sqlStore db.DB, dashboard *models.Dashboard) err
return dashboards.ErrDashboardNotFound
}
dashboard.SetId(dashboard.Id)
dashboard.SetUid(dashboard.Uid)
dashboard.SetID(dashboard.ID)
dashboard.SetUID(dashboard.UID)
return nil
})
}
@@ -135,39 +134,39 @@ var (
)
func insertTestDashboard(t *testing.T, sqlStore db.DB, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
folderId int64, isFolder bool, tags ...interface{}) *dashboards.Dashboard {
t.Helper()
cmd := models.SaveDashboardCommand{
OrgId: orgId,
FolderId: folderId,
cmd := dashboards.SaveDashboardCommand{
OrgID: orgId,
FolderID: folderId,
IsFolder: isFolder,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": nil,
"title": title,
"tags": tags,
}),
UserId: createdById,
UserID: createdById,
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dash = cmd.GetDashboardModel()
dash.SetVersion(1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Uid = util.GenerateShortUID()
dash.UID = util.GenerateShortUID()
_, err := sess.Insert(dash)
return err
})
require.NoError(t, err)
require.NotNil(t, dash)
dash.Data.Set("id", dash.Id)
dash.Data.Set("uid", dash.Uid)
dash.Data.Set("id", dash.ID)
dash.Data.Set("uid", dash.UID)
err = sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: dash.Version,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,
@@ -190,23 +189,23 @@ func insertTestDashboard(t *testing.T, sqlStore db.DB, title string, orgId int64
return dash
}
func updateTestDashboard(t *testing.T, sqlStore db.DB, dashboard *models.Dashboard, data map[string]interface{}) {
func updateTestDashboard(t *testing.T, sqlStore db.DB, dashboard *dashboards.Dashboard, data map[string]interface{}) {
t.Helper()
data["id"] = dashboard.Id
data["id"] = dashboard.ID
parentVersion := dashboard.Version
cmd := models.SaveDashboardCommand{
OrgId: dashboard.OrgId,
cmd := dashboards.SaveDashboardCommand{
OrgID: dashboard.OrgID,
Overwrite: true,
Dashboard: simplejson.NewFromAny(data),
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
var existing models.Dashboard
var existing dashboards.Dashboard
dash = cmd.GetDashboardModel()
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.Id, dash.OrgId).Get(&existing)
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.ID, dash.OrgID).Get(&existing)
require.NoError(t, err)
require.True(t, dashWithIdExists)
@@ -218,10 +217,10 @@ func updateTestDashboard(t *testing.T, sqlStore db.DB, dashboard *models.Dashboa
dash.SetVersion(dash.Version + 1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Id = dashboard.Id
dash.Uid = util.GenerateShortUID()
dash.ID = dashboard.ID
dash.UID = util.GenerateShortUID()
_, err = sess.MustCols("folder_id").ID(dash.Id).Update(dash)
_, err = sess.MustCols("folder_id").ID(dash.ID).Update(dash)
return err
})
@@ -229,7 +228,7 @@ func updateTestDashboard(t *testing.T, sqlStore db.DB, dashboard *models.Dashboa
err = sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: parentVersion,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,

View File

@@ -378,9 +378,9 @@ func (s *Service) Create(ctx context.Context, cmd *folder.CreateFolderCommand) (
// (legacy) folder.
logger.Error("error saving folder to nested folder store", "error", err)
// do not shallow create error if the legacy folder delete fails
if deleteErr := s.dashboardStore.DeleteDashboard(ctx, &models.DeleteDashboardCommand{
Id: createdFolder.ID,
OrgId: createdFolder.OrgID,
if deleteErr := s.dashboardStore.DeleteDashboard(ctx, &dashboards.DeleteDashboardCommand{
ID: createdFolder.ID,
OrgID: createdFolder.OrgID,
}); deleteErr != nil {
logger.Error("error deleting folder after failed save to nested folder store", "error", err)
}
@@ -557,7 +557,7 @@ func (s *Service) Delete(ctx context.Context, cmd *folder.DeleteFolderCommand) e
}
func (s *Service) legacyDelete(ctx context.Context, cmd *folder.DeleteFolderCommand, dashFolder *folder.Folder) error {
deleteCmd := models.DeleteDashboardCommand{OrgId: cmd.OrgID, Id: dashFolder.ID, ForceDeleteFolderRules: cmd.ForceDeleteRules}
deleteCmd := dashboards.DeleteDashboardCommand{OrgID: cmd.OrgID, ID: dashFolder.ID, ForceDeleteFolderRules: cmd.ForceDeleteRules}
if err := s.dashboardStore.DeleteDashboard(ctx, &deleteCmd); err != nil {
return toFolderError(err)

View File

@@ -230,9 +230,9 @@ func TestIntegrationFolderService(t *testing.T) {
f.UID = util.GenerateShortUID()
dashStore.On("GetFolderByUID", mock.Anything, orgID, f.UID).Return(f, nil)
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
expectedForceDeleteRules := rand.Int63()%2 == 0
@@ -244,8 +244,8 @@ func TestIntegrationFolderService(t *testing.T) {
})
require.NoError(t, err)
require.NotNil(t, actualCmd)
require.Equal(t, f.ID, actualCmd.Id)
require.Equal(t, orgID, actualCmd.OrgId)
require.Equal(t, f.ID, actualCmd.ID)
require.Equal(t, orgID, actualCmd.OrgID)
require.Equal(t, expectedForceDeleteRules, actualCmd.ForceDeleteFolderRules)
})
@@ -378,10 +378,10 @@ func TestNestedFolderService(t *testing.T) {
t.Run("When delete folder, no delete in folder table done", func(t *testing.T) {
dashboardsvc := dashboards.FakeDashboardService{}
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore := &dashboards.FakeDashboardStore{}
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
dashStore.On("GetFolderByUID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("string")).Return(&folder.Folder{}, nil)
@@ -473,9 +473,9 @@ func TestNestedFolderService(t *testing.T) {
dashStore.On("ValidateDashboardBeforeSave", mock.Anything, mock.AnythingOfType("*dashboards.Dashboard"), mock.AnythingOfType("bool")).Return(true, nil)
dashStore.On("SaveDashboard", mock.Anything, mock.AnythingOfType("dashboards.SaveDashboardCommand")).Return(dashboardFolder, nil)
dashStore.On("GetFolderByID", mock.Anything, orgID, dashboardFolder.ID).Return(f, nil)
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
folderStore := NewFakeStore()
@@ -519,9 +519,9 @@ func TestNestedFolderService(t *testing.T) {
dashStore.On("SaveDashboard", mock.Anything, mock.AnythingOfType("dashboards.SaveDashboardCommand")).Return(&dashboards.Dashboard{}, nil)
dashStore.On("GetFolderByID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("int64")).Return(&folder.Folder{}, nil)
dashStore.On("GetFolderByUID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("string")).Return(&folder.Folder{}, nil)
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
// return an error from the folder store
@@ -698,9 +698,9 @@ func TestNestedFolderService(t *testing.T) {
dashboardsvc := dashboards.FakeDashboardService{}
dashStore := &dashboards.FakeDashboardStore{}
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
dashStore.On("GetFolderByUID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("string")).Return(&folder.Folder{}, nil)
@@ -735,9 +735,9 @@ func TestNestedFolderService(t *testing.T) {
dashStore.On("SaveDashboard", mock.Anything, mock.AnythingOfType("dashboards.SaveDashboardCommand")).Return(&dashboards.Dashboard{}, nil)
dashStore.On("GetFolderByID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("int64")).Return(&folder.Folder{}, nil)
dashStore.On("GetFolderByUID", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("string")).Return(&folder.Folder{}, nil)
var actualCmd *models.DeleteDashboardCommand
var actualCmd *dashboards.DeleteDashboardCommand
dashStore.On("DeleteDashboard", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
actualCmd = args.Get(1).(*models.DeleteDashboardCommand)
actualCmd = args.Get(1).(*dashboards.DeleteDashboardCommand)
}).Return(nil).Once()
parents := make([]*folder.Folder, 0, folder.MaxNestedFolderDepth)

View File

@@ -11,7 +11,7 @@ import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/setting"
@@ -180,7 +180,7 @@ func (ss *sqlStore) Get(ctx context.Context, q folder.GetFolderQuery) (*folder.F
}
return nil
})
foldr.Url = models.GetFolderUrl(foldr.UID, slugify.Slugify(foldr.Title))
foldr.Url = dashboards.GetFolderURL(foldr.UID, slugify.Slugify(foldr.Title))
return foldr, err
}

View File

@@ -3,8 +3,6 @@ package folder
import (
"time"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util/errutil"
)
@@ -148,34 +146,3 @@ type GetChildrenQuery struct {
SignedInUser *user.SignedInUser `json:"-"`
}
// ToLegacyModel is temporary until the two folder services are merged
func (f *Folder) ToLegacyModel() *models.Folder {
return &models.Folder{
Id: f.ID,
Uid: f.UID,
Title: f.Title,
Url: models.GetFolderUrl(f.UID, slugify.Slugify(f.Title)),
Version: 0,
Created: f.Created,
Updated: f.Updated,
UpdatedBy: 0,
CreatedBy: 0,
HasACL: false,
}
}
func FromDashboard(dash *models.Dashboard) *Folder {
return &Folder{
ID: dash.Id,
UID: dash.Uid,
Title: dash.Title,
HasACL: dash.HasACL,
Url: models.GetFolderUrl(dash.Uid, dash.Slug),
Version: dash.Version,
Created: dash.Created,
CreatedBy: dash.CreatedBy,
Updated: dash.Updated,
UpdatedBy: dash.UpdatedBy,
}
}

View File

@@ -11,7 +11,6 @@ import (
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/accesscontrol/ossaccesscontrol"
@@ -588,8 +587,8 @@ func setupAccessControlGuardianTest(t *testing.T, uid string, permissions []acce
t.Helper()
store := db.InitTestDB(t)
toSave := models.NewDashboard(uid)
toSave.SetUid(uid)
toSave := dashboards.NewDashboard(uid)
toSave.SetUID(uid)
// seed dashboard
quotaService := quotatest.New(false, nil)

View File

@@ -16,6 +16,7 @@ import (
"github.com/grafana/grafana/pkg/infra/appcontext"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
@@ -883,8 +884,19 @@ func testScenario(t *testing.T, desc string, fn func(t *testing.T, sc scenarioCo
sqlStore: sqlStore,
}
sc.folder = createFolderWithACL(t, sc.sqlStore, "ScenarioFolder", sc.user, []folderACLItem{}).ToLegacyModel()
folder := createFolderWithACL(t, sc.sqlStore, "ScenarioFolder", sc.user, []folderACLItem{})
sc.folder = &models.Folder{
Id: folder.ID,
Uid: folder.UID,
Title: folder.Title,
Url: dashboards.GetFolderURL(folder.UID, slugify.Slugify(folder.Title)),
Version: 0,
Created: folder.Created,
Updated: folder.Updated,
UpdatedBy: 0,
CreatedBy: 0,
HasACL: false,
}
fn(t, sc)
})
}

View File

@@ -222,7 +222,7 @@ func (s *ServiceImpl) getHomeNode(c *models.ReqContext, prefs *pref.Preference)
slugQuery := dashboards.GetDashboardRefByIDQuery{ID: prefs.HomeDashboardID}
err := s.dashboardService.GetDashboardUIDByID(c.Req.Context(), &slugQuery)
if err == nil {
homeUrl = models.GetDashboardUrl(slugQuery.Result.UID, slugQuery.Result.Slug)
homeUrl = dashboards.GetDashboardURL(slugQuery.Result.UID, slugQuery.Result.Slug)
}
}

View File

@@ -3,7 +3,7 @@ package plugindashboards
import (
"context"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
)
// PluginDashboard plugin dashboard model..
@@ -43,7 +43,7 @@ type LoadPluginDashboardRequest struct {
// LoadPluginDashboardResponse response object for loading a plugin dashboard.
type LoadPluginDashboardResponse struct {
Dashboard *models.Dashboard
Dashboard *dashboards.Dashboard
}
// Service interface for listing plugin dashboards.

View File

@@ -143,14 +143,14 @@ func (du *DashboardUpdater) handlePluginStateChanged(ctx context.Context, event
du.syncPluginDashboards(ctx, p, event.OrgId)
} else {
query := models.GetDashboardsByPluginIdQuery{PluginId: event.PluginId, OrgId: event.OrgId}
query := dashboards.GetDashboardsByPluginIDQuery{PluginID: event.PluginId, OrgID: event.OrgId}
if err := du.dashboardPluginService.GetDashboardsByPluginID(ctx, &query); err != nil {
return err
}
for _, dash := range query.Result {
du.logger.Info("Deleting plugin dashboard", "pluginId", event.PluginId, "dashboard", dash.Slug)
if err := du.dashboardService.DeleteDashboard(ctx, dash.Id, dash.OrgId); err != nil {
if err := du.dashboardService.DeleteDashboard(ctx, dash.ID, dash.OrgID); err != nil {
return err
}
}

View File

@@ -210,8 +210,8 @@ func TestDashboardUpdater(t *testing.T) {
require.NoError(t, err)
require.Len(t, ctx.dashboardPluginService.args, 1)
require.Equal(t, int64(2), ctx.dashboardPluginService.args[0].OrgId)
require.Equal(t, "test", ctx.dashboardPluginService.args[0].PluginId)
require.Equal(t, int64(2), ctx.dashboardPluginService.args[0].OrgID)
require.Equal(t, "test", ctx.dashboardPluginService.args[0].PluginID)
require.Empty(t, ctx.dashboardService.deleteDashboardArgs)
})
})
@@ -258,8 +258,8 @@ func TestDashboardUpdater(t *testing.T) {
require.NoError(t, err)
require.Len(t, ctx.dashboardPluginService.args, 1)
require.Equal(t, int64(2), ctx.dashboardPluginService.args[0].OrgId)
require.Equal(t, "test", ctx.dashboardPluginService.args[0].PluginId)
require.Equal(t, int64(2), ctx.dashboardPluginService.args[0].OrgID)
require.Equal(t, "test", ctx.dashboardPluginService.args[0].PluginID)
require.Len(t, ctx.dashboardService.deleteDashboardArgs, 3)
})
@@ -458,7 +458,7 @@ func (s *dashboardServiceMock) DeleteDashboard(_ context.Context, dashboardId in
return nil
}
func (s *dashboardServiceMock) GetDashboardByPublicUid(ctx context.Context, dashboardPublicUid string) (*models.Dashboard, error) {
func (s *dashboardServiceMock) GetDashboardByPublicUid(ctx context.Context, dashboardPublicUid string) (*dashboards.Dashboard, error) {
return nil, nil
}
@@ -514,14 +514,14 @@ func scenario(t *testing.T, desc string, input scenarioInput, f func(ctx *scenar
pluginFunc: getPlugin,
}
pluginDashboards := map[string][]*models.Dashboard{}
pluginDashboards := map[string][]*dashboards.Dashboard{}
for _, pluginDashboard := range input.pluginDashboards {
if _, exists := pluginDashboards[pluginDashboard.PluginId]; !exists {
pluginDashboards[pluginDashboard.PluginId] = []*models.Dashboard{}
pluginDashboards[pluginDashboard.PluginId] = []*dashboards.Dashboard{}
}
pluginDashboards[pluginDashboard.PluginId] = append(pluginDashboards[pluginDashboard.PluginId], &models.Dashboard{
PluginId: pluginDashboard.PluginId,
pluginDashboards[pluginDashboard.PluginId] = append(pluginDashboards[pluginDashboard.PluginId], &dashboards.Dashboard{
PluginID: pluginDashboard.PluginId,
})
}
@@ -554,7 +554,7 @@ func scenario(t *testing.T, desc string, input scenarioInput, f func(ctx *scenar
for _, d := range input.pluginDashboards {
if d.PluginId == req.PluginID && req.Reference == d.Reference {
return &plugindashboards.LoadPluginDashboardResponse{
Dashboard: &models.Dashboard{},
Dashboard: &dashboards.Dashboard{},
}, nil
}
}

View File

@@ -6,7 +6,6 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
pluginDashboardsManager "github.com/grafana/grafana/pkg/plugins/manager/dashboards"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/plugindashboards"
@@ -42,7 +41,7 @@ func (s Service) ListPluginDashboards(ctx context.Context, req *plugindashboards
result := make([]*plugindashboards.PluginDashboard, 0)
// load current dashboards
query := models.GetDashboardsByPluginIdQuery{OrgId: req.OrgID, PluginId: req.PluginID}
query := dashboards.GetDashboardsByPluginIDQuery{OrgID: req.OrgID, PluginID: req.PluginID}
if err := s.dashboardPluginService.GetDashboardsByPluginID(ctx, &query); err != nil {
return nil, err
}
@@ -61,7 +60,7 @@ func (s Service) ListPluginDashboards(ctx context.Context, req *plugindashboards
dashboard := loadResp.Dashboard
res := &plugindashboards.PluginDashboard{}
res.UID = dashboard.Uid
res.UID = dashboard.UID
res.Reference = reference
res.PluginId = req.PluginID
res.Title = dashboard.Title
@@ -70,13 +69,13 @@ func (s Service) ListPluginDashboards(ctx context.Context, req *plugindashboards
// find existing dashboard
for _, existingDash := range query.Result {
if existingDash.Slug == dashboard.Slug {
res.UID = existingDash.Uid
res.DashboardId = existingDash.Id
res.UID = existingDash.UID
res.DashboardId = existingDash.ID
res.Imported = true
res.ImportedUri = "db/" + existingDash.Slug
res.ImportedUrl = existingDash.GetUrl()
res.ImportedUrl = existingDash.GetURL()
res.ImportedRevision = existingDash.Data.Get("revision").MustInt64(1)
existingMatches[existingDash.Id] = true
existingMatches[existingDash.ID] = true
break
}
}
@@ -86,11 +85,11 @@ func (s Service) ListPluginDashboards(ctx context.Context, req *plugindashboards
// find deleted dashboards
for _, dash := range query.Result {
if _, exists := existingMatches[dash.Id]; !exists {
if _, exists := existingMatches[dash.ID]; !exists {
result = append(result, &plugindashboards.PluginDashboard{
UID: dash.Uid,
UID: dash.UID,
Slug: dash.Slug,
DashboardId: dash.Id,
DashboardId: dash.ID,
Removed: true,
})
}
@@ -127,7 +126,7 @@ func (s Service) LoadPluginDashboard(ctx context.Context, req *plugindashboards.
}
return &plugindashboards.LoadPluginDashboardResponse{
Dashboard: models.NewDashboardFromJson(data),
Dashboard: dashboards.NewDashboardFromJson(data),
}, nil
}

View File

@@ -9,9 +9,9 @@ import (
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/plugins/manager/dashboards"
dashmodels "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/plugindashboards"
"github.com/stretchr/testify/require"
)
@@ -39,10 +39,10 @@ func TestGetPluginDashboards(t *testing.T) {
},
}
dashboardPluginService := &dashboardPluginServiceMock{
pluginDashboards: map[string][]*models.Dashboard{
pluginDashboards: map[string][]*dashmodels.Dashboard{
"test-app": {
models.NewDashboardFromJson(testDashboardOld),
models.NewDashboardFromJson(testDashboardDeleted),
dashmodels.NewDashboardFromJson(testDashboardOld),
dashmodels.NewDashboardFromJson(testDashboardDeleted),
},
},
}
@@ -203,19 +203,19 @@ func (m pluginDashboardStoreMock) GetPluginDashboardFileContents(ctx context.Con
}
type dashboardPluginServiceMock struct {
pluginDashboards map[string][]*models.Dashboard
args []*models.GetDashboardsByPluginIdQuery
pluginDashboards map[string][]*dashmodels.Dashboard
args []*dashmodels.GetDashboardsByPluginIDQuery
}
func (d *dashboardPluginServiceMock) GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error {
query.Result = []*models.Dashboard{}
func (d *dashboardPluginServiceMock) GetDashboardsByPluginID(ctx context.Context, query *dashmodels.GetDashboardsByPluginIDQuery) error {
query.Result = []*dashmodels.Dashboard{}
if dashboards, exists := d.pluginDashboards[query.PluginId]; exists {
if dashboards, exists := d.pluginDashboards[query.PluginID]; exists {
query.Result = dashboards
}
if d.args == nil {
d.args = []*models.GetDashboardsByPluginIdQuery{}
d.args = []*dashmodels.GetDashboardsByPluginIDQuery{}
}
d.args = append(d.args, query)

View File

@@ -6,7 +6,6 @@ import (
"os"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/provisioning/utils"
@@ -91,7 +90,7 @@ func (provider *Provisioner) CleanUpOrphanedDashboards(ctx context.Context) {
currentReaders[index] = reader.Cfg.Name
}
if err := provider.provisioner.DeleteOrphanedProvisionedDashboards(ctx, &models.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: currentReaders}); err != nil {
if err := provider.provisioner.DeleteOrphanedProvisionedDashboards(ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: currentReaders}); err != nil {
provider.log.Warn("Failed to delete orphaned provisioned dashboards", "err", err)
}
}

View File

@@ -14,7 +14,6 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/provisioning/utils"
@@ -141,7 +140,7 @@ func (fr *FileReader) isDatabaseAccessRestricted() bool {
// storeDashboardsInFolder saves dashboards from the filesystem on disk to the folder from config
func (fr *FileReader) storeDashboardsInFolder(ctx context.Context, filesFoundOnDisk map[string]os.FileInfo,
dashboardRefs map[string]*models.DashboardProvisioning, usageTracker *usageTracker) error {
dashboardRefs map[string]*dashboards.DashboardProvisioning, usageTracker *usageTracker) error {
folderID, err := fr.getOrCreateFolderID(ctx, fr.Cfg, fr.dashboardProvisioningService, fr.Cfg.Folder)
if err != nil && !errors.Is(err, ErrFolderNameMissing) {
return err
@@ -163,7 +162,7 @@ func (fr *FileReader) storeDashboardsInFolder(ctx context.Context, filesFoundOnD
// storeDashboardsInFoldersFromFilesystemStructure saves dashboards from the filesystem on disk to the same folder
// in Grafana as they are in on the filesystem.
func (fr *FileReader) storeDashboardsInFoldersFromFileStructure(ctx context.Context, filesFoundOnDisk map[string]os.FileInfo,
dashboardRefs map[string]*models.DashboardProvisioning, resolvedPath string, usageTracker *usageTracker) error {
dashboardRefs map[string]*dashboards.DashboardProvisioning, resolvedPath string, usageTracker *usageTracker) error {
for path, fileInfo := range filesFoundOnDisk {
folderName := ""
@@ -187,14 +186,14 @@ func (fr *FileReader) storeDashboardsInFoldersFromFileStructure(ctx context.Cont
}
// handleMissingDashboardFiles will unprovision or delete dashboards which are missing on disk.
func (fr *FileReader) handleMissingDashboardFiles(ctx context.Context, provisionedDashboardRefs map[string]*models.DashboardProvisioning,
func (fr *FileReader) handleMissingDashboardFiles(ctx context.Context, provisionedDashboardRefs map[string]*dashboards.DashboardProvisioning,
filesFoundOnDisk map[string]os.FileInfo) {
// find dashboards to delete since json file is missing
var dashboardsToDelete []int64
for path, provisioningData := range provisionedDashboardRefs {
_, existsOnDisk := filesFoundOnDisk[path]
if !existsOnDisk {
dashboardsToDelete = append(dashboardsToDelete, provisioningData.DashboardId)
dashboardsToDelete = append(dashboardsToDelete, provisioningData.DashboardID)
}
}
@@ -222,7 +221,7 @@ func (fr *FileReader) handleMissingDashboardFiles(ctx context.Context, provision
// saveDashboard saves or updates the dashboard provisioning file at path.
func (fr *FileReader) saveDashboard(ctx context.Context, path string, folderID int64, fileInfo os.FileInfo,
provisionedDashboardRefs map[string]*models.DashboardProvisioning) (provisioningMetadata, error) {
provisionedDashboardRefs map[string]*dashboards.DashboardProvisioning) (provisioningMetadata, error) {
provisioningMetadata := provisioningMetadata{}
resolvedFileInfo, err := resolveSymlink(fileInfo, path)
if err != nil {
@@ -257,7 +256,7 @@ func (fr *FileReader) saveDashboard(ctx context.Context, path string, folderID i
}
if alreadyProvisioned {
dash.Dashboard.SetID(provisionedData.DashboardId)
dash.Dashboard.SetID(provisionedData.DashboardID)
}
if !fr.isDatabaseAccessRestricted() {
@@ -281,15 +280,15 @@ func (fr *FileReader) saveDashboard(ctx context.Context, path string, folderID i
}
func getProvisionedDashboardsByPath(ctx context.Context, service dashboards.DashboardProvisioningService, name string) (
map[string]*models.DashboardProvisioning, error) {
map[string]*dashboards.DashboardProvisioning, error) {
arr, err := service.GetProvisionedDashboardData(ctx, name)
if err != nil {
return nil, err
}
byPath := map[string]*models.DashboardProvisioning{}
byPath := map[string]*dashboards.DashboardProvisioning{}
for _, pd := range arr {
byPath[pd.ExternalId] = pd
byPath[pd.ExternalID] = pd
}
return byPath, nil

View File

@@ -13,7 +13,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/util"
)
@@ -163,10 +162,10 @@ func TestDashboardFileReader(t *testing.T) {
checksum, err := util.Md5Sum(file)
require.NoError(t, err)
provisionedDashboard := []*models.DashboardProvisioning{
provisionedDashboard := []*dashboards.DashboardProvisioning{
{
Name: "Default",
ExternalId: absPath,
ExternalID: absPath,
Updated: stat.ModTime().AddDate(0, 0, +1).Unix(),
CheckSum: checksum,
},
@@ -190,10 +189,10 @@ func TestDashboardFileReader(t *testing.T) {
stat, err := os.Stat(oneDashboard + "/dashboard1.json")
require.NoError(t, err)
provisionedDashboard := []*models.DashboardProvisioning{
provisionedDashboard := []*dashboards.DashboardProvisioning{
{
Name: "Default",
ExternalId: absPath,
ExternalID: absPath,
Updated: stat.ModTime().AddDate(0, 0, +1).Unix(),
CheckSum: "fakechecksum",
},
@@ -226,10 +225,10 @@ func TestDashboardFileReader(t *testing.T) {
checksum, err := util.Md5Sum(file)
require.NoError(t, err)
provisionedDashboard := []*models.DashboardProvisioning{
provisionedDashboard := []*dashboards.DashboardProvisioning{
{
Name: "Default",
ExternalId: absPath,
ExternalID: absPath,
Updated: stat.ModTime().AddDate(0, 0, -1).Unix(),
CheckSum: checksum,
},
@@ -253,10 +252,10 @@ func TestDashboardFileReader(t *testing.T) {
stat, err := os.Stat(oneDashboard + "/dashboard1.json")
require.NoError(t, err)
provisionedDashboard := []*models.DashboardProvisioning{
provisionedDashboard := []*dashboards.DashboardProvisioning{
{
Name: "Default",
ExternalId: absPath,
ExternalID: absPath,
Updated: stat.ModTime().AddDate(0, 0, -1).Unix(),
CheckSum: "fakechecksum",
},
@@ -431,9 +430,9 @@ func TestDashboardFileReader(t *testing.T) {
absPath2, err := filepath.Abs(unprovision + "/dashboard2.json")
require.NoError(t, err)
provisionedDashboard := []*models.DashboardProvisioning{
{DashboardId: 1, Name: "Default", ExternalId: absPath1},
{DashboardId: 2, Name: "Default", ExternalId: absPath2},
provisionedDashboard := []*dashboards.DashboardProvisioning{
{DashboardID: 1, Name: "Default", ExternalID: absPath1},
{DashboardID: 2, Name: "Default", ExternalID: absPath2},
}
setupFakeService := func() {

View File

@@ -9,7 +9,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
)
@@ -38,7 +37,7 @@ func TestDuplicatesValidator(t *testing.T) {
r, err := NewDashboardFileReader(cfg, logger, nil, fakeStore)
require.NoError(t, err)
fakeService.On("SaveFolderForProvisionedDashboards", mock.Anything, mock.Anything).Return(&dashboards.Dashboard{}, nil).Times(6)
fakeService.On("GetProvisionedDashboardData", mock.Anything, mock.AnythingOfType("string")).Return([]*models.DashboardProvisioning{}, nil).Times(4)
fakeService.On("GetProvisionedDashboardData", mock.Anything, mock.AnythingOfType("string")).Return([]*dashboards.DashboardProvisioning{}, nil).Times(4)
fakeService.On("SaveProvisionedDashboard", mock.Anything, mock.Anything, mock.Anything).Return(&dashboards.Dashboard{}, nil).Times(5)
folderID, err := r.getOrCreateFolderID(context.Background(), cfg, fakeService, folderName)
require.NoError(t, err)
@@ -152,7 +151,7 @@ func TestDuplicatesValidator(t *testing.T) {
t.Run("Duplicates validator should restrict write access only for readers with duplicates", func(t *testing.T) {
fakeService.On("SaveFolderForProvisionedDashboards", mock.Anything, mock.Anything).Return(&dashboards.Dashboard{}, nil).Times(5)
fakeService.On("GetProvisionedDashboardData", mock.Anything, mock.AnythingOfType("string")).Return([]*models.DashboardProvisioning{}, nil).Times(3)
fakeService.On("GetProvisionedDashboardData", mock.Anything, mock.AnythingOfType("string")).Return([]*dashboards.DashboardProvisioning{}, nil).Times(3)
fakeService.On("SaveProvisionedDashboard", mock.Anything, mock.Anything, mock.Anything).Return(&dashboards.Dashboard{}, nil).Times(5)
fakeStore := &fakeDashboardStore{}

View File

@@ -7,6 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/publicdashboards/internal/tokens"
. "github.com/grafana/grafana/pkg/services/publicdashboards/models"
"github.com/grafana/grafana/pkg/web"
@@ -30,7 +31,7 @@ func (api *Api) ViewPublicDashboard(c *models.ReqContext) response.Response {
meta := dtos.DashboardMeta{
Slug: dash.Slug,
Type: models.DashTypeDB,
Type: dashboards.DashTypeDB,
CanStar: false,
CanSave: false,
CanEdit: false,

View File

@@ -15,6 +15,7 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources"
ngModels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/org"
@@ -671,12 +672,12 @@ func createAlert(t *testing.T, orgId int64, dashboardId int64, panelsId int64, n
}
// createDashboard creates a dashboard for inserting into the test database.
func createDashboard(t *testing.T, id int64, orgId int64, uid string) *models.Dashboard {
func createDashboard(t *testing.T, id int64, orgId int64, uid string) *dashboards.Dashboard {
t.Helper()
return &models.Dashboard{
Id: id,
OrgId: orgId,
Uid: uid,
return &dashboards.Dashboard{
ID: id,
OrgID: orgId,
UID: uid,
Created: now,
Updated: now,
Title: uid, // Not tested, needed to satisfy contraint.
@@ -744,7 +745,7 @@ func setupLegacyAlertsTables(t *testing.T, x *xorm.Engine, legacyChannels []*mod
}
// Setup dashboards.
dashboards := []models.Dashboard{
dashboards := []dashboards.Dashboard{
*createDashboard(t, 1, 1, "dash1-1"),
*createDashboard(t, 2, 1, "dash2-1"),
*createDashboard(t, 3, 2, "dash3-2"),

View File

@@ -144,7 +144,7 @@ func (m *folderHelper) generateNewDashboardUid(orgId int64) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
exists, err := m.sess.Where("org_id=? AND uid=?", orgId, uid).Get(&models.Dashboard{})
exists, err := m.sess.Where("org_id=? AND uid=?", orgId, uid).Get(&dashboards.Dashboard{})
if err != nil {
return "", err
}
@@ -252,7 +252,7 @@ func (m *folderHelper) setACL(orgID int64, dashboardID int64, items []*dashboard
}
// Update dashboard HasACL flag
dashboard := models.Dashboard{HasACL: true}
dashboard := dashboards.Dashboard{HasACL: true}
_, err := m.sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
}

View File

@@ -148,13 +148,13 @@ func TestIntegration_DashboardPermissionFilter(t *testing.T) {
func setupTest(t *testing.T, numFolders, numDashboards int, permissions []accesscontrol.Permission) db.DB {
store := db.InitTestDB(t)
err := store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
dashes := make([]models.Dashboard, 0, numFolders+numDashboards)
dashes := make([]dashboards.Dashboard, 0, numFolders+numDashboards)
for i := 1; i <= numFolders; i++ {
str := strconv.Itoa(i)
dashes = append(dashes, models.Dashboard{
OrgId: 1,
dashes = append(dashes, dashboards.Dashboard{
OrgID: 1,
Slug: str,
Uid: str,
UID: str,
Title: str,
IsFolder: true,
Data: simplejson.New(),
@@ -169,11 +169,11 @@ func setupTest(t *testing.T, numFolders, numDashboards int, permissions []access
if i%numFolders != 0 {
folderID = i % numFolders
}
dashes = append(dashes, models.Dashboard{
OrgId: 1,
dashes = append(dashes, dashboards.Dashboard{
OrgID: 1,
IsFolder: false,
FolderId: int64(folderID),
Uid: str,
FolderID: int64(folderID),
UID: str,
Slug: str,
Title: str,
Data: simplejson.New(),

View File

@@ -41,13 +41,13 @@ func setupBenchMark(b *testing.B, numUsers, numDashboards int) db.DB {
store := db.InitTestDB(b)
now := time.Now()
err := store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
dashes := make([]models.Dashboard, 0, numDashboards)
dashes := make([]dashboards.Dashboard, 0, numDashboards)
for i := 1; i <= numDashboards; i++ {
str := strconv.Itoa(i)
dashes = append(dashes, models.Dashboard{
OrgId: 1,
dashes = append(dashes, dashboards.Dashboard{
OrgID: 1,
IsFolder: false,
Uid: str,
UID: str,
Slug: str,
Title: str,
Data: simplejson.New(),
@@ -82,7 +82,7 @@ func setupBenchMark(b *testing.B, numUsers, numDashboards int) db.DB {
permissions = append(permissions, accesscontrol.Permission{
RoleID: int64(i),
Action: dashboards.ActionDashboardsRead,
Scope: dashboards.ScopeDashboardsProvider.GetResourceScopeUID(dash.Uid),
Scope: dashboards.ScopeDashboardsProvider.GetResourceScopeUID(dash.UID),
Updated: now,
Created: now,
})

View File

@@ -173,11 +173,11 @@ func createDashboards(t *testing.T, store db.DB, startID, endID int, orgID int64
}`))
require.NoError(t, err)
var dash *models.Dashboard
var dash *dashboards.Dashboard
err = store.WithDbSession(context.Background(), func(sess *db.Session) error {
dash = models.NewDashboardFromJson(dashboard)
dash.OrgId = orgID
dash.Uid = util.GenerateShortUID()
dash = dashboards.NewDashboardFromJson(dashboard)
dash.OrgID = orgID
dash.UID = util.GenerateShortUID()
dash.CreatedBy = 1
dash.UpdatedBy = 1
_, err := sess.Insert(dash)
@@ -186,7 +186,7 @@ func createDashboards(t *testing.T, store db.DB, startID, endID int, orgID int64
tags := dash.GetTags()
if len(tags) > 0 {
for _, tag := range tags {
if _, err := sess.Insert(&DashboardTag{DashboardId: dash.Id, Term: tag}); err != nil {
if _, err := sess.Insert(&DashboardTag{DashboardId: dash.ID, Term: tag}); err != nil {
return err
}
}
@@ -196,7 +196,7 @@ func createDashboards(t *testing.T, store db.DB, startID, endID int, orgID int64
})
require.NoError(t, err)
createdIds = append(createdIds, dash.Id)
createdIds = append(createdIds, dash.ID)
}
return createdIds

View File

@@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotaimpl"
"github.com/grafana/grafana/pkg/services/serviceaccounts"
@@ -643,7 +644,7 @@ func updateDashboardACL(t *testing.T, sqlStore *sqlstore.SQLStore, dashboardID i
}
// Update dashboard HasACL flag
dashboard := models.Dashboard{HasACL: true}
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})

View File

@@ -15,6 +15,7 @@ import (
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/live"
"github.com/grafana/grafana/pkg/services/rendering"
)
@@ -286,7 +287,7 @@ func (r *simpleCrawler) walk(ctx context.Context, id int) {
break
}
url := models.GetKioskModeDashboardUrl(item.Uid, item.Slug, r.opts.Theme)
url := dashboards.GetKioskModeDashboardURL(item.Uid, item.Slug, r.opts.Theme)
r.log.Info("Getting dashboard thumbnail", "walkerId", id, "dashboardUID", item.Uid, "url", url)
dsUids, err := r.dsUidsLookup(ctx, item.Uid, item.OrgId)

View File

@@ -25,7 +25,7 @@ func TestIntegrationSqlStorage(t *testing.T) {
}
var sqlStore db.DB
var store store
var savedFolder *models.Dashboard
var savedFolder *dashboards.Dashboard
setup := func() {
sqlStore = db.InitTestDB(t)
@@ -35,9 +35,9 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should insert dashboard in default state", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
thumb := getThumbnail(t, store, dash.Uid, dash.OrgId)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
thumb := getThumbnail(t, store, dash.UID, dash.OrgID)
require.Positive(t, thumb.Id)
require.Equal(t, thumbs.ThumbnailStateDefault, thumb.State)
@@ -46,23 +46,23 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should be able to update the thumbnail", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
thumb := getThumbnail(t, store, dash.Uid, dash.OrgId)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
thumb := getThumbnail(t, store, dash.UID, dash.OrgID)
insertedThumbnailId := thumb.Id
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version+1)
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version+1)
updatedThumb := getThumbnail(t, store, dash.Uid, dash.OrgId)
updatedThumb := getThumbnail(t, store, dash.UID, dash.OrgID)
require.Equal(t, insertedThumbnailId, updatedThumb.Id)
require.Equal(t, dash.Version+1, updatedThumb.DashboardVersion)
})
t.Run("Should return empty array if all dashboards have thumbnails", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
cmd := thumbs.FindDashboardsWithStaleThumbnailsCommand{
Kind: kind,
@@ -75,9 +75,9 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should return dashboards with thumbnails with empty ds_uids array", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
cmd := thumbs.FindDashboardsWithStaleThumbnailsCommand{
Kind: kind,
@@ -87,14 +87,14 @@ func TestIntegrationSqlStorage(t *testing.T) {
res, err := store.FindDashboardsWithStaleThumbnails(context.Background(), &cmd)
require.NoError(t, err)
require.Len(t, res, 1)
require.Equal(t, dash.Id, res[0].Id)
require.Equal(t, dash.ID, res[0].Id)
})
t.Run("Should return dashboards with thumbnails marked as stale", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
updateThumbnailState(t, store, dash.Uid, dash.OrgId, thumbs.ThumbnailStateStale)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
updateThumbnailState(t, store, dash.UID, dash.OrgID, thumbs.ThumbnailStateStale)
cmd := thumbs.FindDashboardsWithStaleThumbnailsCommand{
Kind: kind,
@@ -103,15 +103,15 @@ func TestIntegrationSqlStorage(t *testing.T) {
res, err := store.FindDashboardsWithStaleThumbnails(context.Background(), &cmd)
require.NoError(t, err)
require.Len(t, res, 1)
require.Equal(t, dash.Id, res[0].Id)
require.Equal(t, dash.ID, res[0].Id)
})
t.Run("Should not return dashboards with updated thumbnails that had been marked as stale", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
updateThumbnailState(t, store, dash.Uid, dash.OrgId, thumbs.ThumbnailStateStale)
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
updateThumbnailState(t, store, dash.UID, dash.OrgID, thumbs.ThumbnailStateStale)
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
cmd := thumbs.FindDashboardsWithStaleThumbnailsCommand{
Kind: kind,
@@ -124,7 +124,7 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should find dashboards without thumbnails", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
cmd := thumbs.FindDashboardsWithStaleThumbnailsCommand{
Kind: kind,
@@ -133,13 +133,13 @@ func TestIntegrationSqlStorage(t *testing.T) {
res, err := store.FindDashboardsWithStaleThumbnails(context.Background(), &cmd)
require.NoError(t, err)
require.Len(t, res, 1)
require.Equal(t, dash.Id, res[0].Id)
require.Equal(t, dash.ID, res[0].Id)
})
t.Run("Should find dashboards with outdated thumbnails", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
updateTestDashboard(t, sqlStore, dash, map[string]interface{}{
"tags": "different-tag",
@@ -152,14 +152,14 @@ func TestIntegrationSqlStorage(t *testing.T) {
res, err := store.FindDashboardsWithStaleThumbnails(context.Background(), &cmd)
require.NoError(t, err)
require.Len(t, res, 1)
require.Equal(t, dash.Id, res[0].Id)
require.Equal(t, dash.ID, res[0].Id)
})
t.Run("Should not return dashboards with locked thumbnails even if they are outdated", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, dash.Version)
updateThumbnailState(t, store, dash.Uid, dash.OrgId, thumbs.ThumbnailStateLocked)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, dash.Version)
updateThumbnailState(t, store, dash.UID, dash.OrgID, thumbs.ThumbnailStateLocked)
updateTestDashboard(t, sqlStore, dash, map[string]interface{}{
"tags": "different-tag",
@@ -176,8 +176,8 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should not return dashboards with manually uploaded thumbnails by default", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, thumbs.DashboardVersionForManualThumbnailUpload)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, thumbs.DashboardVersionForManualThumbnailUpload)
updateTestDashboard(t, sqlStore, dash, map[string]interface{}{
"tags": "different-tag",
@@ -194,8 +194,8 @@ func TestIntegrationSqlStorage(t *testing.T) {
t.Run("Should return dashboards with manually uploaded thumbnails if requested", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, thumbs.DashboardVersionForManualThumbnailUpload)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, thumbs.DashboardVersionForManualThumbnailUpload)
updateTestDashboard(t, sqlStore, dash, map[string]interface{}{
"tags": "different-tag",
@@ -209,15 +209,15 @@ func TestIntegrationSqlStorage(t *testing.T) {
res, err := store.FindDashboardsWithStaleThumbnails(context.Background(), &cmd)
require.NoError(t, err)
require.Len(t, res, 1)
require.Equal(t, dash.Id, res[0].Id)
require.Equal(t, dash.ID, res[0].Id)
})
t.Run("Should count all dashboard thumbnails", func(t *testing.T) {
setup()
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.Uid, dash.OrgId, 1)
dash2 := insertTestDashboard(t, sqlStore, "test dash 23", 2, savedFolder.Id, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash2.Uid, dash2.OrgId, 1)
dash := insertTestDashboard(t, sqlStore, "test dash 23", 1, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash.UID, dash.OrgID, 1)
dash2 := insertTestDashboard(t, sqlStore, "test dash 23", 2, savedFolder.ID, false, "prod", "webapp")
upsertTestDashboardThumbnail(t, store, dash2.UID, dash2.OrgID, 1)
updateTestDashboard(t, sqlStore, dash, map[string]interface{}{
"tags": "different-tag",
@@ -284,23 +284,23 @@ func updateThumbnailState(t *testing.T, store store, dashboardUID string, orgId
require.NoError(t, err)
}
func updateTestDashboard(t *testing.T, sqlStore db.DB, dashModel *models.Dashboard, data map[string]interface{}) {
func updateTestDashboard(t *testing.T, sqlStore db.DB, dashModel *dashboards.Dashboard, data map[string]interface{}) {
t.Helper()
data["id"] = dashModel.Id
data["id"] = dashModel.ID
parentVersion := dashModel.Version
cmd := models.SaveDashboardCommand{
OrgId: dashModel.OrgId,
cmd := dashboards.SaveDashboardCommand{
OrgID: dashModel.OrgID,
Overwrite: true,
Dashboard: simplejson.NewFromAny(data),
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
var existing models.Dashboard
var existing dashboards.Dashboard
dash = cmd.GetDashboardModel()
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.Id, dash.OrgId).Get(&existing)
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.ID, dash.OrgID).Get(&existing)
require.NoError(t, err)
require.True(t, dashWithIdExists)
@@ -312,10 +312,10 @@ func updateTestDashboard(t *testing.T, sqlStore db.DB, dashModel *models.Dashboa
dash.SetVersion(dash.Version + 1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Id = dashModel.Id
dash.Uid = util.GenerateShortUID()
dash.ID = dashModel.ID
dash.UID = util.GenerateShortUID()
_, err = sess.MustCols("folder_id").ID(dash.Id).Update(dash)
_, err = sess.MustCols("folder_id").ID(dash.ID).Update(dash)
return err
})
@@ -323,7 +323,7 @@ func updateTestDashboard(t *testing.T, sqlStore db.DB, dashModel *models.Dashboa
err = sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: parentVersion,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,
@@ -346,11 +346,11 @@ func updateTestDashboard(t *testing.T, sqlStore db.DB, dashModel *models.Dashboa
}
func insertTestDashboard(t *testing.T, sqlStore db.DB, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
folderId int64, isFolder bool, tags ...interface{}) *dashboards.Dashboard {
t.Helper()
cmd := models.SaveDashboardCommand{
OrgId: orgId,
FolderId: folderId,
cmd := dashboards.SaveDashboardCommand{
OrgID: orgId,
FolderID: folderId,
IsFolder: isFolder,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": nil,
@@ -359,25 +359,25 @@ func insertTestDashboard(t *testing.T, sqlStore db.DB, title string, orgId int64
}),
}
var dash *models.Dashboard
var dash *dashboards.Dashboard
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dash = cmd.GetDashboardModel()
dash.SetVersion(1)
dash.Created = time.Now()
dash.Updated = time.Now()
dash.Uid = util.GenerateShortUID()
dash.UID = util.GenerateShortUID()
_, err := sess.Insert(dash)
return err
})
require.NoError(t, err)
require.NotNil(t, dash)
dash.Data.Set("id", dash.Id)
dash.Data.Set("uid", dash.Uid)
dash.Data.Set("id", dash.ID)
dash.Data.Set("uid", dash.UID)
err = sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
DashboardID: dash.ID,
ParentVersion: dash.Version,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,

View File

@@ -12,6 +12,7 @@ import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotaimpl"
@@ -844,7 +845,7 @@ func updateDashboardACL(t *testing.T, sqlStore db.DB, dashboardID int64, items .
}
// Update dashboard HasACL flag
dashboard := models.Dashboard{HasACL: true}
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})

View File

@@ -220,7 +220,7 @@ providers:
dashboardData, err := simplejson.NewJson([]byte(tc.dashboardData))
require.NoError(t, err)
buf := &bytes.Buffer{}
err = json.NewEncoder(buf).Encode(models.SaveDashboardCommand{
err = json.NewEncoder(buf).Encode(dashboards.SaveDashboardCommand{
Dashboard: dashboardData,
})
require.NoError(t, err)