Chore: Move library elements models to library elements service (#62507)

* Chore: Move library elements models to library elements service

* Fix stat import

* Fix faulty error assignment
This commit is contained in:
idafurjes 2023-02-01 17:32:05 +01:00 committed by GitHub
parent 8ff19bd901
commit 2c50c44d89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 370 additions and 370 deletions

View File

@ -40,7 +40,7 @@ import (
"github.com/grafana/grafana/pkg/services/folder/folderimpl"
"github.com/grafana/grafana/pkg/services/folder/foldertest"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/libraryelements"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/live"
"github.com/grafana/grafana/pkg/services/org"
pref "github.com/grafana/grafana/pkg/services/preference"
@ -1239,18 +1239,18 @@ func (m *mockLibraryPanelService) ImportLibraryPanelsForDashboard(c context.Cont
type mockLibraryElementService struct {
}
func (l *mockLibraryElementService) CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd libraryelements.CreateLibraryElementCommand) (libraryelements.LibraryElementDTO, error) {
return libraryelements.LibraryElementDTO{}, nil
func (l *mockLibraryElementService) CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd model.CreateLibraryElementCommand) (model.LibraryElementDTO, error) {
return model.LibraryElementDTO{}, nil
}
// GetElement gets an element from a UID.
func (l *mockLibraryElementService) GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (libraryelements.LibraryElementDTO, error) {
return libraryelements.LibraryElementDTO{}, nil
func (l *mockLibraryElementService) GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (model.LibraryElementDTO, error) {
return model.LibraryElementDTO{}, nil
}
// GetElementsForDashboard gets all connected elements for a specific dashboard.
func (l *mockLibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]libraryelements.LibraryElementDTO, error) {
return map[string]libraryelements.LibraryElementDTO{}, nil
func (l *mockLibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]model.LibraryElementDTO, error) {
return map[string]model.LibraryElementDTO{}, nil
}
// ConnectElementsToDashboard connects elements to a specific dashboard.

View File

@ -15,7 +15,7 @@ import (
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/libraryelements"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/services/user"
@ -277,7 +277,7 @@ func (hs *HTTPServer) UpdateFolder(c *contextmodel.ReqContext) response.Response
func (hs *HTTPServer) DeleteFolder(c *contextmodel.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed
err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c.Req.Context(), c.SignedInUser, web.Params(c.Req)[":uid"])
if err != nil {
if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) {
if errors.Is(err, model.ErrFolderHasConnectedLibraryElements) {
return response.Error(403, "Folder could not be deleted because it contains library elements in use", err)
}
return apierrors.ToFolderErrorResponse(err)

View File

@ -1,13 +0,0 @@
package models
// LibraryElementKind is used for the kind of library element
type LibraryElementKind int
const (
// PanelElement is used for library elements that are of the Panel kind
PanelElement LibraryElementKind = iota + 1
// VariableElement is used for library elements that are of the Variable kind
VariableElement
)
const LibraryElementConnectionTableName = "library_element_connection"

View File

@ -10,6 +10,7 @@ import (
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/web"
)
@ -39,7 +40,7 @@ func (l *LibraryElementService) registerAPIEndpoints() {
// 404: notFoundError
// 500: internalServerError
func (l *LibraryElementService) createHandler(c *contextmodel.ReqContext) response.Response {
cmd := CreateLibraryElementCommand{}
cmd := model.CreateLibraryElementCommand{}
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
@ -55,7 +56,6 @@ func (l *LibraryElementService) createHandler(c *contextmodel.ReqContext) respon
cmd.FolderID = folder.ID
}
}
element, err := l.createLibraryElement(c.Req.Context(), c.SignedInUser, cmd)
if err != nil {
return toLibraryElementError(err, "Failed to create library element")
@ -71,7 +71,7 @@ func (l *LibraryElementService) createHandler(c *contextmodel.ReqContext) respon
element.Meta.FolderName = folder.Title
}
return response.JSON(http.StatusOK, LibraryElementResponse{Result: element})
return response.JSON(http.StatusOK, model.LibraryElementResponse{Result: element})
}
// swagger:route DELETE /library-elements/{library_element_uid} library_elements deleteLibraryElementByUID
@ -94,7 +94,7 @@ func (l *LibraryElementService) deleteHandler(c *contextmodel.ReqContext) respon
return toLibraryElementError(err, "Failed to delete library element")
}
return response.JSON(http.StatusOK, DeleteLibraryElementResponse{
return response.JSON(http.StatusOK, model.DeleteLibraryElementResponse{
Message: "Library element deleted",
ID: id,
})
@ -117,7 +117,7 @@ func (l *LibraryElementService) getHandler(c *contextmodel.ReqContext) response.
return toLibraryElementError(err, "Failed to get library element")
}
return response.JSON(http.StatusOK, LibraryElementResponse{Result: element})
return response.JSON(http.StatusOK, model.LibraryElementResponse{Result: element})
}
// swagger:route GET /library-elements library_elements getLibraryElements
@ -133,23 +133,23 @@ func (l *LibraryElementService) getHandler(c *contextmodel.ReqContext) response.
// 401: unauthorisedError
// 500: internalServerError
func (l *LibraryElementService) getAllHandler(c *contextmodel.ReqContext) response.Response {
query := searchLibraryElementsQuery{
perPage: c.QueryInt("perPage"),
page: c.QueryInt("page"),
searchString: c.Query("searchString"),
sortDirection: c.Query("sortDirection"),
kind: c.QueryInt("kind"),
typeFilter: c.Query("typeFilter"),
excludeUID: c.Query("excludeUid"),
folderFilter: c.Query("folderFilter"),
folderFilterUIDs: c.Query("folderFilterUIDs"),
query := model.SearchLibraryElementsQuery{
PerPage: c.QueryInt("perPage"),
Page: c.QueryInt("page"),
SearchString: c.Query("searchString"),
SortDirection: c.Query("sortDirection"),
Kind: c.QueryInt("kind"),
TypeFilter: c.Query("typeFilter"),
ExcludeUID: c.Query("excludeUid"),
FolderFilter: c.Query("folderFilter"),
FolderFilterUIDs: c.Query("folderFilterUIDs"),
}
elementsResult, err := l.getAllLibraryElements(c.Req.Context(), c.SignedInUser, query)
if err != nil {
return toLibraryElementError(err, "Failed to get library elements")
}
return response.JSON(http.StatusOK, LibraryElementSearchResponse{Result: elementsResult})
return response.JSON(http.StatusOK, model.LibraryElementSearchResponse{Result: elementsResult})
}
// swagger:route PATCH /library-elements/{library_element_uid} library_elements updateLibraryElement
@ -167,7 +167,7 @@ func (l *LibraryElementService) getAllHandler(c *contextmodel.ReqContext) respon
// 412: preconditionFailedError
// 500: internalServerError
func (l *LibraryElementService) patchHandler(c *contextmodel.ReqContext) response.Response {
cmd := PatchLibraryElementCommand{}
cmd := model.PatchLibraryElementCommand{}
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
@ -199,7 +199,7 @@ func (l *LibraryElementService) patchHandler(c *contextmodel.ReqContext) respons
element.Meta.FolderName = folder.Title
}
return response.JSON(http.StatusOK, LibraryElementResponse{Result: element})
return response.JSON(http.StatusOK, model.LibraryElementResponse{Result: element})
}
// swagger:route GET /library-elements/{library_element_uid}/connections/ library_elements getLibraryElementConnections
@ -219,7 +219,7 @@ func (l *LibraryElementService) getConnectionsHandler(c *contextmodel.ReqContext
return toLibraryElementError(err, "Failed to get connections")
}
return response.JSON(http.StatusOK, LibraryElementConnectionsResponse{Result: connections})
return response.JSON(http.StatusOK, model.LibraryElementConnectionsResponse{Result: connections})
}
// swagger:route GET /library-elements/name/{library_element_name} library_elements getLibraryElementByName
@ -239,21 +239,21 @@ func (l *LibraryElementService) getByNameHandler(c *contextmodel.ReqContext) res
return toLibraryElementError(err, "Failed to get library element")
}
return response.JSON(http.StatusOK, LibraryElementArrayResponse{Result: elements})
return response.JSON(http.StatusOK, model.LibraryElementArrayResponse{Result: elements})
}
func toLibraryElementError(err error, message string) response.Response {
if errors.Is(err, errLibraryElementAlreadyExists) {
return response.Error(400, errLibraryElementAlreadyExists.Error(), err)
if errors.Is(err, model.ErrLibraryElementAlreadyExists) {
return response.Error(400, model.ErrLibraryElementAlreadyExists.Error(), err)
}
if errors.Is(err, ErrLibraryElementNotFound) {
return response.Error(404, ErrLibraryElementNotFound.Error(), err)
if errors.Is(err, model.ErrLibraryElementNotFound) {
return response.Error(404, model.ErrLibraryElementNotFound.Error(), err)
}
if errors.Is(err, errLibraryElementDashboardNotFound) {
return response.Error(404, errLibraryElementDashboardNotFound.Error(), err)
if errors.Is(err, model.ErrLibraryElementDashboardNotFound) {
return response.Error(404, model.ErrLibraryElementDashboardNotFound.Error(), err)
}
if errors.Is(err, errLibraryElementVersionMismatch) {
return response.Error(412, errLibraryElementVersionMismatch.Error(), err)
if errors.Is(err, model.ErrLibraryElementVersionMismatch) {
return response.Error(412, model.ErrLibraryElementVersionMismatch.Error(), err)
}
if errors.Is(err, dashboards.ErrFolderNotFound) {
return response.Error(404, dashboards.ErrFolderNotFound.Error(), err)
@ -261,14 +261,14 @@ func toLibraryElementError(err error, message string) response.Response {
if errors.Is(err, dashboards.ErrFolderAccessDenied) {
return response.Error(403, dashboards.ErrFolderAccessDenied.Error(), err)
}
if errors.Is(err, errLibraryElementHasConnections) {
return response.Error(403, errLibraryElementHasConnections.Error(), err)
if errors.Is(err, model.ErrLibraryElementHasConnections) {
return response.Error(403, model.ErrLibraryElementHasConnections.Error(), err)
}
if errors.Is(err, errLibraryElementInvalidUID) {
return response.Error(400, errLibraryElementInvalidUID.Error(), err)
if errors.Is(err, model.ErrLibraryElementInvalidUID) {
return response.Error(400, model.ErrLibraryElementInvalidUID.Error(), err)
}
if errors.Is(err, errLibraryElementUIDTooLong) {
return response.Error(400, errLibraryElementUIDTooLong.Error(), err)
if errors.Is(err, model.ErrLibraryElementUIDTooLong) {
return response.Error(400, model.ErrLibraryElementUIDTooLong.Error(), err)
}
return response.ErrOrFallback(http.StatusInternalServerError, message, err)
}
@ -358,14 +358,14 @@ type GetLibraryElementsParams struct {
type CreateLibraryElementParams struct {
// in:body
// required:true
Body CreateLibraryElementCommand `json:"body"`
Body model.CreateLibraryElementCommand `json:"body"`
}
// swagger:parameters updateLibraryElement
type UpdateLibraryElementParam struct {
// in:body
// required:true
Body PatchLibraryElementCommand `json:"body"`
Body model.PatchLibraryElementCommand `json:"body"`
// in:path
// required:true
UID string `json:"library_element_uid"`
@ -374,17 +374,17 @@ type UpdateLibraryElementParam struct {
// swagger:response getLibraryElementsResponse
type GetLibraryElementsResponse struct {
// in: body
Body LibraryElementSearchResponse `json:"body"`
Body model.LibraryElementSearchResponse `json:"body"`
}
// swagger:response getLibraryElementResponse
type GetLibraryElementResponse struct {
// in: body
Body LibraryElementResponse `json:"body"`
Body model.LibraryElementResponse `json:"body"`
}
// swagger:response getLibraryElementConnectionsResponse
type GetLibraryElementConnectionsResponse struct {
// in: body
Body LibraryElementConnectionsResponse `json:"body"`
Body model.LibraryElementConnectionsResponse `json:"body"`
}

View File

@ -11,8 +11,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
@ -29,7 +29,7 @@ SELECT DISTINCT
, u1.email AS created_by_email
, u2.login AS updated_by_name
, u2.email AS updated_by_email
, (SELECT COUNT(connection_id) FROM ` + models.LibraryElementConnectionTableName + ` WHERE element_id = le.id AND kind=1) AS connected_dashboards`
, (SELECT COUNT(connection_id) FROM ` + model.LibraryElementConnectionTableName + ` WHERE element_id = le.id AND kind=1) AS connected_dashboards`
)
// redundant SELECT to trick mysql's optimizer
@ -52,26 +52,26 @@ LEFT JOIN ` + user + ` AS u2 ON le.updated_by = u2.id
return userJoin
}
func syncFieldsWithModel(libraryElement *LibraryElement) error {
var model map[string]interface{}
if err := json.Unmarshal(libraryElement.Model, &model); err != nil {
func syncFieldsWithModel(libraryElement *model.LibraryElement) error {
var modelLibraryElement map[string]interface{}
if err := json.Unmarshal(libraryElement.Model, &modelLibraryElement); err != nil {
return err
}
if models.LibraryElementKind(libraryElement.Kind) == models.VariableElement {
model["name"] = libraryElement.Name
if model.LibraryElementKind(libraryElement.Kind) == model.VariableElement {
modelLibraryElement["name"] = libraryElement.Name
}
if model["type"] != nil {
libraryElement.Type = model["type"].(string)
if modelLibraryElement["type"] != nil {
libraryElement.Type = modelLibraryElement["type"].(string)
} else {
model["type"] = libraryElement.Type
modelLibraryElement["type"] = libraryElement.Type
}
if model["description"] != nil {
libraryElement.Description = model["description"].(string)
if modelLibraryElement["description"] != nil {
libraryElement.Description = modelLibraryElement["description"].(string)
} else {
model["description"] = libraryElement.Description
modelLibraryElement["description"] = libraryElement.Description
}
syncedModel, err := json.Marshal(&model)
syncedModel, err := json.Marshal(&modelLibraryElement)
if err != nil {
return err
}
@ -81,8 +81,8 @@ func syncFieldsWithModel(libraryElement *LibraryElement) error {
return nil
}
func getLibraryElement(dialect migrator.Dialect, session *db.Session, uid string, orgID int64) (LibraryElementWithMeta, error) {
elements := make([]LibraryElementWithMeta, 0)
func getLibraryElement(dialect migrator.Dialect, session *db.Session, uid string, orgID int64) (model.LibraryElementWithMeta, error) {
elements := make([]model.LibraryElementWithMeta, 0)
sql := selectLibraryElementDTOWithMeta +
", coalesce(dashboard.title, 'General') AS folder_name" +
", coalesce(dashboard.uid, '') AS folder_uid" +
@ -92,34 +92,34 @@ func getLibraryElement(dialect migrator.Dialect, session *db.Session, uid string
sess := session.SQL(sql, uid, orgID)
err := sess.Find(&elements)
if err != nil {
return LibraryElementWithMeta{}, err
return model.LibraryElementWithMeta{}, err
}
if len(elements) == 0 {
return LibraryElementWithMeta{}, ErrLibraryElementNotFound
return model.LibraryElementWithMeta{}, model.ErrLibraryElementNotFound
}
if len(elements) > 1 {
return LibraryElementWithMeta{}, fmt.Errorf("found %d elements, while expecting at most one", len(elements))
return model.LibraryElementWithMeta{}, fmt.Errorf("found %d elements, while expecting at most one", len(elements))
}
return elements[0], nil
}
// createLibraryElement adds a library element.
func (l *LibraryElementService) createLibraryElement(c context.Context, signedInUser *user.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) {
func (l *LibraryElementService) createLibraryElement(c context.Context, signedInUser *user.SignedInUser, cmd model.CreateLibraryElementCommand) (model.LibraryElementDTO, error) {
if err := l.requireSupportedElementKind(cmd.Kind); err != nil {
return LibraryElementDTO{}, err
return model.LibraryElementDTO{}, err
}
createUID := cmd.UID
if len(createUID) == 0 {
createUID = util.GenerateShortUID()
} else {
if !util.IsValidShortUID(createUID) {
return LibraryElementDTO{}, errLibraryElementInvalidUID
return model.LibraryElementDTO{}, model.ErrLibraryElementInvalidUID
} else if util.IsShortUIDTooLong(createUID) {
return LibraryElementDTO{}, errLibraryElementUIDTooLong
return model.LibraryElementDTO{}, model.ErrLibraryElementUIDTooLong
}
}
element := LibraryElement{
element := model.LibraryElement{
OrgID: signedInUser.OrgID,
FolderID: cmd.FolderID,
UID: createUID,
@ -136,7 +136,7 @@ func (l *LibraryElementService) createLibraryElement(c context.Context, signedIn
}
if err := syncFieldsWithModel(&element); err != nil {
return LibraryElementDTO{}, err
return model.LibraryElementDTO{}, err
}
err := l.SQLStore.WithTransactionalDbSession(c, func(session *db.Session) error {
@ -145,14 +145,14 @@ func (l *LibraryElementService) createLibraryElement(c context.Context, signedIn
}
if _, err := session.Insert(&element); err != nil {
if l.SQLStore.GetDialect().IsUniqueConstraintViolation(err) {
return errLibraryElementAlreadyExists
return model.ErrLibraryElementAlreadyExists
}
return err
}
return nil
})
dto := LibraryElementDTO{
dto := model.LibraryElementDTO{
ID: element.ID,
OrgID: element.OrgID,
FolderID: element.FolderID,
@ -163,7 +163,7 @@ func (l *LibraryElementService) createLibraryElement(c context.Context, signedIn
Description: element.Description,
Model: element.Model,
Version: element.Version,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
ConnectedDashboards: 0,
Created: element.Created,
Updated: element.Updated,
@ -207,7 +207,7 @@ func (l *LibraryElementService) deleteLibraryElement(c context.Context, signedIn
if err := session.SQL(sql, element.ID).Find(&connectionIDs); err != nil {
return err
} else if len(connectionIDs) > 0 {
return errLibraryElementHasConnections
return model.ErrLibraryElementHasConnections
}
result, err := session.Exec("DELETE FROM library_element WHERE id=?", element.ID)
@ -217,7 +217,7 @@ func (l *LibraryElementService) deleteLibraryElement(c context.Context, signedIn
if rowsAffected, err := result.RowsAffected(); err != nil {
return err
} else if rowsAffected != 1 {
return ErrLibraryElementNotFound
return model.ErrLibraryElementNotFound
}
elementID = element.ID
@ -227,8 +227,8 @@ func (l *LibraryElementService) deleteLibraryElement(c context.Context, signedIn
}
// getLibraryElements gets a Library Element where param == value
func getLibraryElements(c context.Context, store db.DB, cfg *setting.Cfg, signedInUser *user.SignedInUser, params []Pair) ([]LibraryElementDTO, error) {
libraryElements := make([]LibraryElementWithMeta, 0)
func getLibraryElements(c context.Context, store db.DB, cfg *setting.Cfg, signedInUser *user.SignedInUser, params []Pair) ([]model.LibraryElementDTO, error) {
libraryElements := make([]model.LibraryElementWithMeta, 0)
err := store.WithDbSession(c, func(session *db.Session) error {
builder := db.NewSqlBuilder(cfg, store.GetDialect())
builder.Write(selectLibraryElementDTOWithMeta)
@ -251,18 +251,18 @@ func getLibraryElements(c context.Context, store db.DB, cfg *setting.Cfg, signed
return err
}
if len(libraryElements) == 0 {
return ErrLibraryElementNotFound
return model.ErrLibraryElementNotFound
}
return nil
})
if err != nil {
return []LibraryElementDTO{}, err
return []model.LibraryElementDTO{}, err
}
leDtos := make([]LibraryElementDTO, len(libraryElements))
leDtos := make([]model.LibraryElementDTO, len(libraryElements))
for i, libraryElement := range libraryElements {
leDtos[i] = LibraryElementDTO{
leDtos[i] = model.LibraryElementDTO{
ID: libraryElement.ID,
OrgID: libraryElement.OrgID,
FolderID: libraryElement.FolderID,
@ -274,7 +274,7 @@ func getLibraryElements(c context.Context, store db.DB, cfg *setting.Cfg, signed
Description: libraryElement.Description,
Model: libraryElement.Model,
Version: libraryElement.Version,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: libraryElement.FolderName,
FolderUID: libraryElement.FolderUID,
ConnectedDashboards: libraryElement.ConnectedDashboards,
@ -298,40 +298,40 @@ func getLibraryElements(c context.Context, store db.DB, cfg *setting.Cfg, signed
}
// getLibraryElementByUid gets a Library Element by uid.
func (l *LibraryElementService) getLibraryElementByUid(c context.Context, signedInUser *user.SignedInUser, UID string) (LibraryElementDTO, error) {
func (l *LibraryElementService) getLibraryElementByUid(c context.Context, signedInUser *user.SignedInUser, UID string) (model.LibraryElementDTO, error) {
libraryElements, err := getLibraryElements(c, l.SQLStore, l.Cfg, signedInUser, []Pair{{key: "org_id", value: signedInUser.OrgID}, {key: "uid", value: UID}})
if err != nil {
return LibraryElementDTO{}, err
return model.LibraryElementDTO{}, err
}
if len(libraryElements) > 1 {
return LibraryElementDTO{}, fmt.Errorf("found %d elements, while expecting at most one", len(libraryElements))
return model.LibraryElementDTO{}, fmt.Errorf("found %d elements, while expecting at most one", len(libraryElements))
}
return libraryElements[0], nil
}
// getLibraryElementByName gets a Library Element by name.
func (l *LibraryElementService) getLibraryElementsByName(c context.Context, signedInUser *user.SignedInUser, name string) ([]LibraryElementDTO, error) {
func (l *LibraryElementService) getLibraryElementsByName(c context.Context, signedInUser *user.SignedInUser, name string) ([]model.LibraryElementDTO, error) {
return getLibraryElements(c, l.SQLStore, l.Cfg, signedInUser, []Pair{{"org_id", signedInUser.OrgID}, {"name", name}})
}
// getAllLibraryElements gets all Library Elements.
func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedInUser *user.SignedInUser, query searchLibraryElementsQuery) (LibraryElementSearchResult, error) {
elements := make([]LibraryElementWithMeta, 0)
result := LibraryElementSearchResult{}
if query.perPage <= 0 {
query.perPage = 100
func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedInUser *user.SignedInUser, query model.SearchLibraryElementsQuery) (model.LibraryElementSearchResult, error) {
elements := make([]model.LibraryElementWithMeta, 0)
result := model.LibraryElementSearchResult{}
if query.PerPage <= 0 {
query.PerPage = 100
}
if query.page <= 0 {
query.page = 1
if query.Page <= 0 {
query.Page = 1
}
var typeFilter []string
if len(strings.TrimSpace(query.typeFilter)) > 0 {
typeFilter = strings.Split(query.typeFilter, ",")
if len(strings.TrimSpace(query.TypeFilter)) > 0 {
typeFilter = strings.Split(query.TypeFilter, ",")
}
folderFilter := parseFolderFilter(query)
if folderFilter.parseError != nil {
return LibraryElementSearchResult{}, folderFilter.parseError
return model.LibraryElementSearchResult{}, folderFilter.parseError
}
err := l.SQLStore.WithDbSession(c, func(session *db.Session) error {
builder := db.NewSqlBuilder(l.Cfg, l.SQLStore.GetDialect())
@ -363,7 +363,7 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
if signedInUser.OrgRole != org.RoleAdmin {
builder.WriteDashboardPermissionFilter(signedInUser, dashboards.PERMISSION_VIEW)
}
if query.sortDirection == search.SortAlphaDesc.Name {
if query.SortDirection == search.SortAlphaDesc.Name {
builder.Write(" ORDER BY 1 DESC")
} else {
builder.Write(" ORDER BY 1 ASC")
@ -373,9 +373,9 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
return err
}
retDTOs := make([]LibraryElementDTO, 0)
retDTOs := make([]model.LibraryElementDTO, 0)
for _, element := range elements {
retDTOs = append(retDTOs, LibraryElementDTO{
retDTOs = append(retDTOs, model.LibraryElementDTO{
ID: element.ID,
OrgID: element.OrgID,
FolderID: element.FolderID,
@ -387,7 +387,7 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
Description: element.Description,
Model: element.Model,
Version: element.Version,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: element.FolderName,
FolderUID: element.FolderUID,
ConnectedDashboards: element.ConnectedDashboards,
@ -407,7 +407,7 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
})
}
var libraryElements []LibraryElement
var libraryElements []model.LibraryElement
countBuilder := db.SQLBuilder{}
countBuilder.Write("SELECT * FROM library_element AS le")
countBuilder.Write(" INNER JOIN dashboard AS dashboard on le.folder_id = dashboard.id")
@ -423,11 +423,11 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
return err
}
result = LibraryElementSearchResult{
result = model.LibraryElementSearchResult{
TotalCount: int64(len(libraryElements)),
Elements: retDTOs,
Page: query.page,
PerPage: query.perPage,
Page: query.Page,
PerPage: query.PerPage,
}
return nil
@ -436,7 +436,7 @@ func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedI
return result, err
}
func (l *LibraryElementService) handleFolderIDPatches(ctx context.Context, elementToPatch *LibraryElement, fromFolderID int64, toFolderID int64, user *user.SignedInUser) error {
func (l *LibraryElementService) handleFolderIDPatches(ctx context.Context, elementToPatch *model.LibraryElement, fromFolderID int64, toFolderID int64, user *user.SignedInUser) error {
// FolderID was not provided in the PATCH request
if toFolderID == -1 {
toFolderID = fromFolderID
@ -460,10 +460,10 @@ func (l *LibraryElementService) handleFolderIDPatches(ctx context.Context, eleme
}
// patchLibraryElement updates a Library Element.
func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInUser *user.SignedInUser, cmd PatchLibraryElementCommand, uid string) (LibraryElementDTO, error) {
var dto LibraryElementDTO
func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInUser *user.SignedInUser, cmd model.PatchLibraryElementCommand, uid string) (model.LibraryElementDTO, error) {
var dto model.LibraryElementDTO
if err := l.requireSupportedElementKind(cmd.Kind); err != nil {
return LibraryElementDTO{}, err
return model.LibraryElementDTO{}, err
}
err := l.SQLStore.WithTransactionalDbSession(c, func(session *db.Session) error {
elementInDB, err := getLibraryElement(l.SQLStore.GetDialect(), session, uid, signedInUser.OrgID)
@ -471,25 +471,25 @@ func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInU
return err
}
if elementInDB.Version != cmd.Version {
return errLibraryElementVersionMismatch
return model.ErrLibraryElementVersionMismatch
}
updateUID := cmd.UID
if len(updateUID) == 0 {
updateUID = uid
} else if updateUID != uid {
if !util.IsValidShortUID(updateUID) {
return errLibraryElementInvalidUID
return model.ErrLibraryElementInvalidUID
} else if util.IsShortUIDTooLong(updateUID) {
return errLibraryElementUIDTooLong
return model.ErrLibraryElementUIDTooLong
}
_, err := getLibraryElement(l.SQLStore.GetDialect(), session, updateUID, signedInUser.OrgID)
if !errors.Is(err, ErrLibraryElementNotFound) {
return errLibraryElementAlreadyExists
if !errors.Is(err, model.ErrLibraryElementNotFound) {
return model.ErrLibraryElementAlreadyExists
}
}
var libraryElement = LibraryElement{
var libraryElement = model.LibraryElement{
ID: elementInDB.ID,
OrgID: signedInUser.OrgID,
FolderID: cmd.FolderID,
@ -520,14 +520,14 @@ func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInU
}
if rowsAffected, err := session.ID(elementInDB.ID).Update(&libraryElement); err != nil {
if l.SQLStore.GetDialect().IsUniqueConstraintViolation(err) {
return errLibraryElementAlreadyExists
return model.ErrLibraryElementAlreadyExists
}
return err
} else if rowsAffected != 1 {
return ErrLibraryElementNotFound
return model.ErrLibraryElementNotFound
}
dto = LibraryElementDTO{
dto = model.LibraryElementDTO{
ID: libraryElement.ID,
OrgID: libraryElement.OrgID,
FolderID: libraryElement.FolderID,
@ -538,7 +538,7 @@ func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInU
Description: libraryElement.Description,
Model: libraryElement.Model,
Version: libraryElement.Version,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
ConnectedDashboards: elementInDB.ConnectedDashboards,
Created: libraryElement.Created,
Updated: libraryElement.Updated,
@ -561,17 +561,17 @@ func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInU
}
// getConnections gets all connections for a Library Element.
func (l *LibraryElementService) getConnections(c context.Context, signedInUser *user.SignedInUser, uid string) ([]LibraryElementConnectionDTO, error) {
connections := make([]LibraryElementConnectionDTO, 0)
func (l *LibraryElementService) getConnections(c context.Context, signedInUser *user.SignedInUser, uid string) ([]model.LibraryElementConnectionDTO, error) {
connections := make([]model.LibraryElementConnectionDTO, 0)
err := l.SQLStore.WithDbSession(c, func(session *db.Session) error {
element, err := getLibraryElement(l.SQLStore.GetDialect(), session, uid, signedInUser.OrgID)
if err != nil {
return err
}
var libraryElementConnections []libraryElementConnectionWithMeta
var libraryElementConnections []model.LibraryElementConnectionWithMeta
builder := db.NewSqlBuilder(l.Cfg, l.SQLStore.GetDialect())
builder.Write("SELECT lec.*, u1.login AS created_by_name, u1.email AS created_by_email, dashboard.uid AS connection_uid")
builder.Write(" FROM " + models.LibraryElementConnectionTableName + " AS lec")
builder.Write(" FROM " + model.LibraryElementConnectionTableName + " AS lec")
builder.Write(" LEFT JOIN " + l.SQLStore.GetDialect().Quote("user") + " AS u1 ON lec.created_by = u1.id")
builder.Write(" INNER JOIN dashboard AS dashboard on lec.connection_id = dashboard.id")
builder.Write(` WHERE lec.element_id=?`, element.ID)
@ -583,7 +583,7 @@ func (l *LibraryElementService) getConnections(c context.Context, signedInUser *
}
for _, connection := range libraryElementConnections {
connections = append(connections, LibraryElementConnectionDTO{
connections = append(connections, model.LibraryElementConnectionDTO{
ID: connection.ID,
Kind: connection.Kind,
ElementID: connection.ElementID,
@ -605,16 +605,16 @@ func (l *LibraryElementService) getConnections(c context.Context, signedInUser *
}
// getElementsForDashboardID gets all elements for a specific dashboard
func (l *LibraryElementService) getElementsForDashboardID(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) {
libraryElementMap := make(map[string]LibraryElementDTO)
func (l *LibraryElementService) getElementsForDashboardID(c context.Context, dashboardID int64) (map[string]model.LibraryElementDTO, error) {
libraryElementMap := make(map[string]model.LibraryElementDTO)
err := l.SQLStore.WithDbSession(c, func(session *db.Session) error {
var libraryElements []LibraryElementWithMeta
var libraryElements []model.LibraryElementWithMeta
sql := selectLibraryElementDTOWithMeta +
", coalesce(dashboard.title, 'General') AS folder_name" +
", coalesce(dashboard.uid, '') AS folder_uid" +
getFromLibraryElementDTOWithMeta(l.SQLStore.GetDialect()) +
" LEFT JOIN dashboard AS dashboard ON dashboard.id = le.folder_id" +
" INNER JOIN " + models.LibraryElementConnectionTableName + " AS lce ON lce.element_id = le.id AND lce.kind=1 AND lce.connection_id=?"
" INNER JOIN " + model.LibraryElementConnectionTableName + " AS lce ON lce.element_id = le.id AND lce.kind=1 AND lce.connection_id=?"
sess := session.SQL(sql, dashboardID)
err := sess.Find(&libraryElements)
if err != nil {
@ -622,7 +622,7 @@ func (l *LibraryElementService) getElementsForDashboardID(c context.Context, das
}
for _, element := range libraryElements {
libraryElementMap[element.UID] = LibraryElementDTO{
libraryElementMap[element.UID] = model.LibraryElementDTO{
ID: element.ID,
OrgID: element.OrgID,
FolderID: element.FolderID,
@ -633,7 +633,7 @@ func (l *LibraryElementService) getElementsForDashboardID(c context.Context, das
Description: element.Description,
Model: element.Model,
Version: element.Version,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: element.FolderName,
FolderUID: element.FolderUID,
ConnectedDashboards: element.ConnectedDashboards,
@ -662,7 +662,7 @@ func (l *LibraryElementService) getElementsForDashboardID(c context.Context, das
// connectElementsToDashboardID adds connections for all elements Library Elements in a Dashboard.
func (l *LibraryElementService) connectElementsToDashboardID(c context.Context, signedInUser *user.SignedInUser, elementUIDs []string, dashboardID int64) error {
err := l.SQLStore.WithTransactionalDbSession(c, func(session *db.Session) error {
_, err := session.Exec("DELETE FROM "+models.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID)
_, err := session.Exec("DELETE FROM "+model.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID)
if err != nil {
return err
}
@ -675,7 +675,7 @@ func (l *LibraryElementService) connectElementsToDashboardID(c context.Context,
return err
}
connection := libraryElementConnection{
connection := model.LibraryElementConnection{
ElementID: element.ID,
Kind: 1,
ConnectionID: dashboardID,
@ -698,7 +698,7 @@ func (l *LibraryElementService) connectElementsToDashboardID(c context.Context,
// disconnectElementsFromDashboardID deletes connections for all Library Elements in a Dashboard.
func (l *LibraryElementService) disconnectElementsFromDashboardID(c context.Context, dashboardID int64) error {
return l.SQLStore.WithTransactionalDbSession(c, func(session *db.Session) error {
_, err := session.Exec("DELETE FROM "+models.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID)
_, err := session.Exec("DELETE FROM "+model.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID)
if err != nil {
return err
}
@ -734,14 +734,14 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c context.Conte
ConnectionID int64 `xorm:"connection_id"`
}
sql := "SELECT lec.connection_id FROM library_element AS le"
sql += " INNER JOIN " + models.LibraryElementConnectionTableName + " AS lec on le.id = lec.element_id"
sql += " INNER JOIN " + model.LibraryElementConnectionTableName + " AS lec on le.id = lec.element_id"
sql += " WHERE le.folder_id=? AND le.org_id=?"
err = session.SQL(sql, folderID, signedInUser.OrgID).Find(&connectionIDs)
if err != nil {
return err
}
if len(connectionIDs) > 0 {
return ErrFolderHasConnectedLibraryElements
return model.ErrFolderHasConnectedLibraryElements
}
var elementIDs []struct {
@ -752,7 +752,7 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c context.Conte
return err
}
for _, elementID := range elementIDs {
_, err := session.Exec("DELETE FROM "+models.LibraryElementConnectionTableName+" WHERE element_id=?", elementID.ID)
_, err := session.Exec("DELETE FROM "+model.LibraryElementConnectionTableName+" WHERE element_id=?", elementID.ID)
if err != nil {
return err
}

View File

@ -3,10 +3,10 @@ package libraryelements
import (
"context"
"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/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user"
)
@ -20,14 +20,14 @@ func isUIDGeneralFolder(folderUID string) bool {
}
func (l *LibraryElementService) requireSupportedElementKind(kindAsInt int64) error {
kind := models.LibraryElementKind(kindAsInt)
kind := model.LibraryElementKind(kindAsInt)
switch kind {
case models.PanelElement:
case model.PanelElement:
return nil
case models.VariableElement:
case model.VariableElement:
return nil
default:
return errLibraryElementUnSupportedElementKind
return model.ErrLibraryElementUnSupportedElementKind
}
}

View File

@ -7,6 +7,7 @@ import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
@ -25,9 +26,9 @@ func ProvideService(cfg *setting.Cfg, sqlStore db.DB, routeRegister routing.Rout
// Service is a service for operating on library elements.
type Service interface {
CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error)
GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (LibraryElementDTO, error)
GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error)
CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd model.CreateLibraryElementCommand) (model.LibraryElementDTO, error)
GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (model.LibraryElementDTO, error)
GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]model.LibraryElementDTO, error)
ConnectElementsToDashboard(c context.Context, signedInUser *user.SignedInUser, elementUIDs []string, dashboardID int64) error
DisconnectElementsFromDashboard(c context.Context, dashboardID int64) error
DeleteLibraryElementsInFolder(c context.Context, signedInUser *user.SignedInUser, folderUID string) error
@ -43,17 +44,17 @@ type LibraryElementService struct {
}
// CreateElement creates a Library Element.
func (l *LibraryElementService) CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) {
func (l *LibraryElementService) CreateElement(c context.Context, signedInUser *user.SignedInUser, cmd model.CreateLibraryElementCommand) (model.LibraryElementDTO, error) {
return l.createLibraryElement(c, signedInUser, cmd)
}
// GetElement gets an element from a UID.
func (l *LibraryElementService) GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (LibraryElementDTO, error) {
func (l *LibraryElementService) GetElement(c context.Context, signedInUser *user.SignedInUser, UID string) (model.LibraryElementDTO, error) {
return l.getLibraryElementByUid(c, signedInUser, UID)
}
// GetElementsForDashboard gets all connected elements for a specific dashboard.
func (l *LibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) {
func (l *LibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]model.LibraryElementDTO, error) {
return l.getElementsForDashboardID(c, dashboardID)
}

View File

@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/util"
)
@ -29,7 +29,7 @@ func TestCreateLibraryElement(t *testing.T) {
FolderID: 1,
UID: sc.initialResult.Result.UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -40,7 +40,7 @@ func TestCreateLibraryElement(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: "ScenarioFolder",
ConnectedDashboards: 0,
@ -78,7 +78,7 @@ func TestCreateLibraryElement(t *testing.T) {
FolderID: 1,
UID: command.UID,
Name: "Nonexistent UID",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -89,7 +89,7 @@ func TestCreateLibraryElement(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: "ScenarioFolder",
ConnectedDashboards: 0,
@ -153,7 +153,7 @@ func TestCreateLibraryElement(t *testing.T) {
FolderID: 1,
UID: result.Result.UID,
Name: "Library Panel Name",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -164,7 +164,7 @@ func TestCreateLibraryElement(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: "ScenarioFolder",
ConnectedDashboards: 0,

View File

@ -6,6 +6,7 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/require"
@ -24,7 +25,7 @@ func TestDeleteLibraryElement(t *testing.T) {
resp := sc.service.deleteHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
var result DeleteLibraryElementResponse
var result model.DeleteLibraryElementResponse
err := json.Unmarshal(resp.Body(), &result)
require.NoError(t, err)

View File

@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/search"
)
@ -45,7 +45,7 @@ func TestGetAllLibraryElements(t *testing.T) {
err := sc.reqContext.Req.ParseForm()
require.NoError(t, err)
sc.reqContext.Req.Form.Add("kind", strconv.FormatInt(int64(models.PanelElement), 10))
sc.reqContext.Req.Form.Add("kind", strconv.FormatInt(int64(model.PanelElement), 10))
resp = sc.service.getAllHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
@ -65,7 +65,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -76,7 +76,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -111,7 +111,7 @@ func TestGetAllLibraryElements(t *testing.T) {
err := sc.reqContext.Req.ParseForm()
require.NoError(t, err)
sc.reqContext.Req.Form.Add("kind", strconv.FormatInt(int64(models.VariableElement), 10))
sc.reqContext.Req.Form.Add("kind", strconv.FormatInt(int64(model.VariableElement), 10))
resp = sc.service.getAllHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
@ -131,7 +131,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "query0",
Kind: int64(models.VariableElement),
Kind: int64(model.VariableElement),
Type: "query",
Description: "A description",
Model: map[string]interface{}{
@ -141,7 +141,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"description": "A description",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -192,7 +192,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -203,7 +203,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -227,7 +227,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[1].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -238,7 +238,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -292,7 +292,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -303,7 +303,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -327,7 +327,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[1].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -338,7 +338,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -366,7 +366,7 @@ func TestGetAllLibraryElements(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to get all library panels and two exist and typeFilter is set to existing types, it should succeed and the result should be correct",
func(t *testing.T, sc scenarioContext) {
command := getCreateCommandWithModel(sc.folder.ID, "Gauge - Library Panel", models.PanelElement, []byte(`
command := getCreateCommandWithModel(sc.folder.ID, "Gauge - Library Panel", model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -379,7 +379,7 @@ func TestGetAllLibraryElements(t *testing.T) {
resp := sc.service.createHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
command = getCreateCommandWithModel(sc.folder.ID, "BarGauge - Library Panel", models.PanelElement, []byte(`
command = getCreateCommandWithModel(sc.folder.ID, "BarGauge - Library Panel", model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -413,7 +413,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "BarGauge - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "bargauge",
Description: "BarGauge description",
Model: map[string]interface{}{
@ -424,7 +424,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "bargauge",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -448,7 +448,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[1].UID,
Name: "Gauge - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "gauge",
Description: "Gauge description",
Model: map[string]interface{}{
@ -459,7 +459,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"description": "Gauge description",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -487,7 +487,7 @@ func TestGetAllLibraryElements(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to get all library panels and two exist and typeFilter is set to a nonexistent type, it should succeed and the result should be correct",
func(t *testing.T, sc scenarioContext) {
command := getCreateCommandWithModel(sc.folder.ID, "Gauge - Library Panel", models.PanelElement, []byte(`
command := getCreateCommandWithModel(sc.folder.ID, "Gauge - Library Panel", model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -552,7 +552,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: newFolder.ID,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -563,7 +563,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "NewFolder",
FolderUID: newFolder.UID,
ConnectedDashboards: 0,
@ -649,7 +649,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -660,7 +660,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -684,7 +684,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[1].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -695,7 +695,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -749,7 +749,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -760,7 +760,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -814,7 +814,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -825,7 +825,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -880,7 +880,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -891,7 +891,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -919,7 +919,7 @@ func TestGetAllLibraryElements(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to get all library panels and two exist and searchString exists in the description, it should succeed and the result should be correct",
func(t *testing.T, sc scenarioContext) {
command := getCreateCommandWithModel(sc.folder.ID, "Text - Library Panel2", models.PanelElement, []byte(`
command := getCreateCommandWithModel(sc.folder.ID, "Text - Library Panel2", model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -955,7 +955,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -966,7 +966,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -994,7 +994,7 @@ func TestGetAllLibraryElements(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to get all library panels and two exist and searchString exists in both name and description, it should succeed and the result should be correct",
func(t *testing.T, sc scenarioContext) {
command := getCreateCommandWithModel(sc.folder.ID, "Some Other", models.PanelElement, []byte(`
command := getCreateCommandWithModel(sc.folder.ID, "Some Other", model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -1028,7 +1028,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Some Other",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A Library Panel",
Model: map[string]interface{}{
@ -1039,7 +1039,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -1063,7 +1063,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[1].UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -1074,7 +1074,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -1130,7 +1130,7 @@ func TestGetAllLibraryElements(t *testing.T) {
FolderID: 1,
UID: result.Result.Elements[0].UID,
Name: "Text - Library Panel2",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -1141,7 +1141,7 @@ func TestGetAllLibraryElements(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,

View File

@ -7,11 +7,10 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models"
)
func TestGetLibraryElement(t *testing.T) {
@ -38,7 +37,7 @@ func TestGetLibraryElement(t *testing.T) {
FolderID: 1,
UID: res.Result.UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -49,7 +48,7 @@ func TestGetLibraryElement(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 0,
@ -133,7 +132,7 @@ func TestGetLibraryElement(t *testing.T) {
FolderID: 1,
UID: res.Result.UID,
Name: "Text - Library Panel",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "text",
Description: "A description",
Model: map[string]interface{}{
@ -144,7 +143,7 @@ func TestGetLibraryElement(t *testing.T) {
"type": "text",
},
Version: 1,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "ScenarioFolder",
FolderUID: sc.folder.UID,
ConnectedDashboards: 1,

View File

@ -4,10 +4,10 @@ import (
"testing"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/util"
"github.com/google/go-cmp/cmp"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/require"
)
@ -15,7 +15,7 @@ import (
func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel that does not exist, it should fail",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{Kind: int64(models.PanelElement), Version: 1}
cmd := model.PatchLibraryElementCommand{Kind: int64(model.PanelElement), Version: 1}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": "unknown"})
sc.reqContext.Req.Body = mockRequestBody(cmd)
resp := sc.service.patchHandler(sc.reqContext)
@ -25,7 +25,7 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel that exists, it should succeed",
func(t *testing.T, sc scenarioContext) {
newFolder := createFolderWithACL(t, sc.sqlStore, "NewFolder", sc.user, []folderACLItem{})
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: newFolder.ID,
Name: "Panel - New name",
Model: []byte(`
@ -37,7 +37,7 @@ func TestPatchLibraryElement(t *testing.T) {
"type": "graph"
}
`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -52,7 +52,7 @@ func TestPatchLibraryElement(t *testing.T) {
FolderID: newFolder.ID,
UID: sc.initialResult.Result.UID,
Name: "Panel - New name",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Type: "graph",
Description: "An updated description",
Model: map[string]interface{}{
@ -63,7 +63,7 @@ func TestPatchLibraryElement(t *testing.T) {
"type": "graph",
},
Version: 2,
Meta: LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "NewFolder",
FolderUID: "NewFolder",
ConnectedDashboards: 0,
@ -90,9 +90,9 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with folder only, it should change folder successfully and return correct result",
func(t *testing.T, sc scenarioContext) {
newFolder := createFolderWithACL(t, sc.sqlStore, "NewFolder", sc.user, []folderACLItem{})
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: newFolder.ID,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -114,10 +114,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with name only, it should change name successfully and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
Name: "New Name",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -137,10 +137,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with a nonexistent UID, it should change UID successfully and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
UID: util.GenerateShortUID(),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -160,10 +160,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with an invalid UID, it should fail",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
UID: "Testing an invalid UID",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -174,10 +174,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with an UID that is too long, it should fail",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
UID: "j6T00KRZzj6T00KRZzj6T00KRZzj6T00KRZzj6T00K",
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -193,10 +193,10 @@ func TestPatchLibraryElement(t *testing.T) {
sc.reqContext.Req.Body = mockRequestBody(command)
resp := sc.service.createHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
UID: command.UID,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -207,10 +207,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with model only, it should change model successfully, sync type and description fields and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
Model: []byte(`{ "title": "New Model Title", "name": "New Model Name", "type":"graph", "description": "New description" }`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -236,10 +236,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with model.description only, it should change model successfully, sync type and description fields and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
Model: []byte(`{ "description": "New description" }`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -263,10 +263,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with model.type only, it should change model successfully, sync type and description fields and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: -1,
Model: []byte(`{ "type": "graph" }`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
Version: 1,
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -290,7 +290,7 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When another admin tries to patch a library panel, it should change UpdatedBy successfully and return correct result",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{FolderID: -1, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: -1, Version: 1, Kind: int64(model.PanelElement)}
sc.reqContext.UserID = 2
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
@ -312,10 +312,10 @@ func TestPatchLibraryElement(t *testing.T) {
sc.ctx.Req.Body = mockRequestBody(command)
resp := sc.service.createHandler(sc.reqContext)
var result = validateAndUnMarshalResponse(t, resp)
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
Name: "Text - Library Panel",
Version: 1,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
@ -330,10 +330,10 @@ func TestPatchLibraryElement(t *testing.T) {
sc.ctx.Req.Body = mockRequestBody(command)
resp := sc.service.createHandler(sc.reqContext)
var result = validateAndUnMarshalResponse(t, resp)
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: 1,
Version: 1,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
@ -343,10 +343,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel in another org, it should fail",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: sc.folder.ID,
Version: 1,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
sc.reqContext.OrgID = 2
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
@ -357,10 +357,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with an old version number, it should fail",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: sc.folder.ID,
Version: 1,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
@ -373,10 +373,10 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel with an other kind, it should succeed but panel should not change",
func(t *testing.T, sc scenarioContext) {
cmd := PatchLibraryElementCommand{
cmd := model.PatchLibraryElementCommand{
FolderID: sc.folder.ID,
Version: 1,
Kind: int64(models.VariableElement),
Kind: int64(model.VariableElement),
}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
@ -384,7 +384,7 @@ func TestPatchLibraryElement(t *testing.T) {
require.Equal(t, 200, resp.Status())
var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Type = "text"
sc.initialResult.Result.Kind = int64(models.PanelElement)
sc.initialResult.Result.Kind = int64(model.PanelElement)
sc.initialResult.Result.Description = "A description"
sc.initialResult.Result.Model = map[string]interface{}{
"datasource": "${DS_GDEV-TESTDATA}",

View File

@ -8,8 +8,8 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/web"
)
@ -91,7 +91,7 @@ func TestLibraryElementPermissions(t *testing.T) {
toFolder := createFolderWithACL(t, sc.sqlStore, "Folder", sc.user, testCase.items)
sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := PatchLibraryElementCommand{FolderID: toFolder.ID, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: toFolder.ID, Version: 1, Kind: int64(model.PanelElement)}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.reqContext.Req.Body = mockRequestBody(cmd)
resp = sc.service.patchHandler(sc.reqContext)
@ -108,7 +108,7 @@ func TestLibraryElementPermissions(t *testing.T) {
toFolder := createFolderWithACL(t, sc.sqlStore, "Folder", sc.user, everyonePermissions)
sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := PatchLibraryElementCommand{FolderID: toFolder.ID, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: toFolder.ID, Version: 1, Kind: int64(model.PanelElement)}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.reqContext.Req.Body = mockRequestBody(cmd)
resp = sc.service.patchHandler(sc.reqContext)
@ -159,7 +159,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result := validateAndUnMarshalResponse(t, resp)
sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := PatchLibraryElementCommand{FolderID: 0, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: 0, Version: 1, Kind: int64(model.PanelElement)}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
resp = sc.service.patchHandler(sc.reqContext)
@ -175,7 +175,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result := validateAndUnMarshalResponse(t, resp)
sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := PatchLibraryElementCommand{FolderID: folder.ID, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: folder.ID, Version: 1, Kind: int64(model.PanelElement)}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.ctx.Req.Body = mockRequestBody(cmd)
resp = sc.service.patchHandler(sc.reqContext)
@ -224,7 +224,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result := validateAndUnMarshalResponse(t, resp)
sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := PatchLibraryElementCommand{FolderID: -100, Version: 1, Kind: int64(models.PanelElement)}
cmd := model.PatchLibraryElementCommand{FolderID: -100, Version: 1, Kind: int64(model.PanelElement)}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
sc.reqContext.Req.Body = mockRequestBody(cmd)
resp = sc.service.patchHandler(sc.reqContext)

View File

@ -20,7 +20,6 @@ import (
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/models"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/alerting"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
@ -32,6 +31,7 @@ import (
"github.com/grafana/grafana/pkg/services/folder/folderimpl"
"github.com/grafana/grafana/pkg/services/folder/foldertest"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotatest"
@ -84,7 +84,7 @@ func TestDeleteLibraryPanelsInFolder(t *testing.T) {
require.NoError(t, err)
err = sc.service.DeleteLibraryElementsInFolder(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, sc.folder.UID)
require.EqualError(t, err, ErrFolderHasConnectedLibraryElements.Error())
require.EqualError(t, err, model.ErrFolderHasConnectedLibraryElements.Error())
})
scenarioWithPanel(t, "When an admin tries to delete a folder uid that doesn't exist, it should fail",
@ -156,9 +156,9 @@ func TestGetLibraryPanelConnections(t *testing.T) {
err := sc.service.ConnectElementsToDashboard(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, []string{sc.initialResult.Result.UID}, dashInDB.ID)
require.NoError(t, err)
var expected = func(res LibraryElementConnectionsResponse) LibraryElementConnectionsResponse {
return LibraryElementConnectionsResponse{
Result: []LibraryElementConnectionDTO{
var expected = func(res model.LibraryElementConnectionsResponse) model.LibraryElementConnectionsResponse {
return model.LibraryElementConnectionsResponse{
Result: []model.LibraryElementConnectionDTO{
{
ID: sc.initialResult.Result.ID,
Kind: sc.initialResult.Result.Kind,
@ -187,17 +187,17 @@ func TestGetLibraryPanelConnections(t *testing.T) {
}
type libraryElement struct {
ID int64 `json:"id"`
OrgID int64 `json:"orgId"`
FolderID int64 `json:"folderId"`
UID string `json:"uid"`
Name string `json:"name"`
Kind int64 `json:"kind"`
Type string `json:"type"`
Description string `json:"description"`
Model map[string]interface{} `json:"model"`
Version int64 `json:"version"`
Meta LibraryElementDTOMeta `json:"meta"`
ID int64 `json:"id"`
OrgID int64 `json:"orgId"`
FolderID int64 `json:"folderId"`
UID string `json:"uid"`
Name string `json:"name"`
Kind int64 `json:"kind"`
Type string `json:"type"`
Description string `json:"description"`
Model map[string]interface{} `json:"model"`
Version int64 `json:"version"`
Meta model.LibraryElementDTOMeta `json:"meta"`
}
type libraryElementResult struct {
@ -219,8 +219,8 @@ type libraryElementsSearchResult struct {
PerPage int `json:"perPage"`
}
func getCreatePanelCommand(folderID int64, name string) CreateLibraryElementCommand {
command := getCreateCommandWithModel(folderID, name, models.PanelElement, []byte(`
func getCreatePanelCommand(folderID int64, name string) model.CreateLibraryElementCommand {
command := getCreateCommandWithModel(folderID, name, model.PanelElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"id": 1,
@ -233,8 +233,8 @@ func getCreatePanelCommand(folderID int64, name string) CreateLibraryElementComm
return command
}
func getCreateVariableCommand(folderID int64, name string) CreateLibraryElementCommand {
command := getCreateCommandWithModel(folderID, name, models.VariableElement, []byte(`
func getCreateVariableCommand(folderID int64, name string) model.CreateLibraryElementCommand {
command := getCreateCommandWithModel(folderID, name, model.VariableElement, []byte(`
{
"datasource": "${DS_GDEV-TESTDATA}",
"name": "query0",
@ -246,11 +246,11 @@ func getCreateVariableCommand(folderID int64, name string) CreateLibraryElementC
return command
}
func getCreateCommandWithModel(folderID int64, name string, kind models.LibraryElementKind, model []byte) CreateLibraryElementCommand {
command := CreateLibraryElementCommand{
func getCreateCommandWithModel(folderID int64, name string, kind model.LibraryElementKind, byteModel []byte) model.CreateLibraryElementCommand {
command := model.CreateLibraryElementCommand{
FolderID: folderID,
Name: name,
Model: model,
Model: byteModel,
Kind: int64(kind),
}
@ -368,10 +368,10 @@ func validateAndUnMarshalResponse(t *testing.T, resp response.Response) libraryE
return result
}
func validateAndUnMarshalConnectionResponse(t *testing.T, resp response.Response) LibraryElementConnectionsResponse {
func validateAndUnMarshalConnectionResponse(t *testing.T, resp response.Response) model.LibraryElementConnectionsResponse {
t.Helper()
require.Equal(t, 200, resp.Status())
var result = LibraryElementConnectionsResponse{}
var result = model.LibraryElementConnectionsResponse{}
err := json.Unmarshal(resp.Body(), &result)
require.NoError(t, err)
return result

View File

@ -1,4 +1,4 @@
package libraryelements
package model
import (
"encoding/json"
@ -100,7 +100,7 @@ type LibraryElementDTOMeta struct {
}
// libraryElementConnection is the model for library element connections.
type libraryElementConnection struct {
type LibraryElementConnection struct {
ID int64 `xorm:"pk autoincr 'id'"`
ElementID int64 `xorm:"element_id"`
Kind int64 `xorm:"kind"`
@ -110,7 +110,7 @@ type libraryElementConnection struct {
}
// libraryElementConnectionWithMeta is the model for library element connections with meta.
type libraryElementConnectionWithMeta struct {
type LibraryElementConnectionWithMeta struct {
ID int64 `xorm:"pk autoincr 'id'"`
ElementID int64 `xorm:"element_id"`
Kind int64 `xorm:"kind"`
@ -135,23 +135,23 @@ type LibraryElementConnectionDTO struct {
var (
// errLibraryElementAlreadyExists is an error for when the user tries to add a library element that already exists.
errLibraryElementAlreadyExists = errors.New("library element with that name or UID already exists")
ErrLibraryElementAlreadyExists = errors.New("library element with that name or UID already exists")
// ErrLibraryElementNotFound is an error for when a library element can't be found.
ErrLibraryElementNotFound = errors.New("library element could not be found")
// errLibraryElementDashboardNotFound is an error for when a library element connection can't be found.
errLibraryElementDashboardNotFound = errors.New("library element connection could not be found")
// errLibraryElementHasConnections is an error for when an user deletes a library element that is connected.
errLibraryElementHasConnections = errors.New("the library element has connections")
ErrLibraryElementDashboardNotFound = errors.New("library element connection could not be found")
// ErrLibraryElementHasConnections is an error for when an user deletes a library element that is connected.
ErrLibraryElementHasConnections = errors.New("the library element has connections")
// errLibraryElementVersionMismatch is an error for when a library element has been changed by someone else.
errLibraryElementVersionMismatch = errors.New("the library element has been changed by someone else")
ErrLibraryElementVersionMismatch = errors.New("the library element has been changed by someone else")
// errLibraryElementUnSupportedElementKind is an error for when the kind is unsupported.
errLibraryElementUnSupportedElementKind = errors.New("the element kind is not supported")
ErrLibraryElementUnSupportedElementKind = errors.New("the element kind is not supported")
// ErrFolderHasConnectedLibraryElements is an error for when a user deletes a folder that contains connected library elements.
ErrFolderHasConnectedLibraryElements = errors.New("folder contains library elements that are linked in use")
// errLibraryElementInvalidUID is an error for when the uid of a library element is invalid
errLibraryElementInvalidUID = errors.New("uid contains illegal characters")
ErrLibraryElementInvalidUID = errors.New("uid contains illegal characters")
// errLibraryElementUIDTooLong is an error for when the uid of a library element is invalid
errLibraryElementUIDTooLong = errors.New("uid too long, max 40 characters")
ErrLibraryElementUIDTooLong = errors.New("uid too long, max 40 characters")
)
// Commands
@ -200,17 +200,17 @@ type PatchLibraryElementCommand struct {
UID string `json:"uid"`
}
// searchLibraryElementsQuery is the query used for searching for Elements
type searchLibraryElementsQuery struct {
perPage int
page int
searchString string
sortDirection string
kind int
typeFilter string
excludeUID string
folderFilter string
folderFilterUIDs string
// SearchLibraryElementsQuery is the query used for searching for Elements
type SearchLibraryElementsQuery struct {
PerPage int
Page int
SearchString string
SortDirection string
Kind int
TypeFilter string
ExcludeUID string
FolderFilter string
FolderFilterUIDs string
}
// LibraryElementResponse is a response struct for LibraryElementDTO.
@ -238,3 +238,15 @@ type DeleteLibraryElementResponse struct {
ID int64 `json:"id"`
Message string `json:"message"`
}
// LibraryElementKind is used for the kind of library element
type LibraryElementKind int
const (
// PanelElement is used for library elements that are of the Panel kind
PanelElement LibraryElementKind = iota + 1
// VariableElement is used for library elements that are of the Variable kind
VariableElement
)
const LibraryElementConnectionTableName = "library_element_connection"

View File

@ -7,7 +7,7 @@ import (
"strings"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
)
type Pair struct {
@ -32,16 +32,16 @@ func writeParamSelectorSQL(builder *db.SQLBuilder, params ...Pair) {
}
}
func writePerPageSQL(query searchLibraryElementsQuery, sqlStore db.DB, builder *db.SQLBuilder) {
if query.perPage != 0 {
offset := query.perPage * (query.page - 1)
builder.Write(sqlStore.GetDialect().LimitOffset(int64(query.perPage), int64(offset)))
func writePerPageSQL(query model.SearchLibraryElementsQuery, sqlStore db.DB, builder *db.SQLBuilder) {
if query.PerPage != 0 {
offset := query.PerPage * (query.Page - 1)
builder.Write(sqlStore.GetDialect().LimitOffset(int64(query.PerPage), int64(offset)))
}
}
func writeKindSQL(query searchLibraryElementsQuery, builder *db.SQLBuilder) {
if models.LibraryElementKind(query.kind) == models.PanelElement || models.LibraryElementKind(query.kind) == models.VariableElement {
builder.Write(" AND le.kind = ?", query.kind)
func writeKindSQL(query model.SearchLibraryElementsQuery, builder *db.SQLBuilder) {
if model.LibraryElementKind(query.Kind) == model.PanelElement || model.LibraryElementKind(query.Kind) == model.VariableElement {
builder.Write(" AND le.kind = ?", query.Kind)
}
}
@ -57,16 +57,16 @@ func writeTypeFilterSQL(typeFilter []string, builder *db.SQLBuilder) {
}
}
func writeSearchStringSQL(query searchLibraryElementsQuery, sqlStore db.DB, builder *db.SQLBuilder) {
if len(strings.TrimSpace(query.searchString)) > 0 {
builder.Write(" AND (le.name "+sqlStore.GetDialect().LikeStr()+" ?", "%"+query.searchString+"%")
builder.Write(" OR le.description "+sqlStore.GetDialect().LikeStr()+" ?)", "%"+query.searchString+"%")
func writeSearchStringSQL(query model.SearchLibraryElementsQuery, sqlStore db.DB, builder *db.SQLBuilder) {
if len(strings.TrimSpace(query.SearchString)) > 0 {
builder.Write(" AND (le.name "+sqlStore.GetDialect().LikeStr()+" ?", "%"+query.SearchString+"%")
builder.Write(" OR le.description "+sqlStore.GetDialect().LikeStr()+" ?)", "%"+query.SearchString+"%")
}
}
func writeExcludeSQL(query searchLibraryElementsQuery, builder *db.SQLBuilder) {
if len(strings.TrimSpace(query.excludeUID)) > 0 {
builder.Write(" AND le.uid <> ?", query.excludeUID)
func writeExcludeSQL(query model.SearchLibraryElementsQuery, builder *db.SQLBuilder) {
if len(strings.TrimSpace(query.ExcludeUID)) > 0 {
builder.Write(" AND le.uid <> ?", query.ExcludeUID)
}
}
@ -77,11 +77,11 @@ type FolderFilter struct {
parseError error
}
func parseFolderFilter(query searchLibraryElementsQuery) FolderFilter {
func parseFolderFilter(query model.SearchLibraryElementsQuery) FolderFilter {
folderIDs := make([]string, 0)
folderUIDs := make([]string, 0)
hasFolderFilter := len(strings.TrimSpace(query.folderFilter)) > 0
hasFolderFilterUID := len(strings.TrimSpace(query.folderFilterUIDs)) > 0
hasFolderFilter := len(strings.TrimSpace(query.FolderFilter)) > 0
hasFolderFilterUID := len(strings.TrimSpace(query.FolderFilterUIDs)) > 0
result := FolderFilter{
includeGeneralFolder: true,
@ -97,7 +97,7 @@ func parseFolderFilter(query searchLibraryElementsQuery) FolderFilter {
if hasFolderFilter {
result.includeGeneralFolder = false
folderIDs = strings.Split(query.folderFilter, ",")
folderIDs = strings.Split(query.FolderFilter, ",")
result.folderIDs = folderIDs
for _, filter := range folderIDs {
folderID, err := strconv.ParseInt(filter, 10, 64)
@ -113,7 +113,7 @@ func parseFolderFilter(query searchLibraryElementsQuery) FolderFilter {
if hasFolderFilterUID {
result.includeGeneralFolder = false
folderUIDs = strings.Split(query.folderFilterUIDs, ",")
folderUIDs = strings.Split(query.FolderFilterUIDs, ",")
result.folderUIDs = folderUIDs
for _, folderUID := range folderUIDs {

View File

@ -9,9 +9,9 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"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/libraryelements"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
@ -135,7 +135,7 @@ func importLibraryPanelsRecursively(c context.Context, service libraryelements.S
continue
}
if errors.Is(err, libraryelements.ErrLibraryElementNotFound) {
if errors.Is(err, model.ErrLibraryElementNotFound) {
name := libraryPanel.Get("name").MustString()
if len(name) == 0 {
return errLibraryPanelHeaderNameMissing
@ -151,11 +151,11 @@ func importLibraryPanelsRecursively(c context.Context, service libraryelements.S
return err
}
var cmd = libraryelements.CreateLibraryElementCommand{
var cmd = model.CreateLibraryElementCommand{
FolderID: folderID,
Name: name,
Model: Model,
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
UID: UID,
}
_, err = service.CreateElement(c, signedInUser, cmd)

View File

@ -19,7 +19,6 @@ import (
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/kinds/librarypanel"
"github.com/grafana/grafana/pkg/models"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
@ -31,6 +30,7 @@ import (
"github.com/grafana/grafana/pkg/services/folder/foldertest"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/libraryelements"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotatest"
@ -92,7 +92,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) {
scenarioWithLibraryPanel(t, "When an admin tries to store a dashboard with library panels inside and outside of rows, it should connect all",
func(t *testing.T, sc scenarioContext) {
cmd := libraryelements.CreateLibraryElementCommand{
cmd := model.CreateLibraryElementCommand{
FolderID: sc.initialResult.Result.FolderID,
Name: "Outside row",
Model: []byte(`
@ -104,7 +104,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) {
"description": "A description"
}
`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
outsidePanel, err := sc.elementService.CreateElement(sc.ctx, sc.user, cmd)
require.NoError(t, err)
@ -231,7 +231,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) {
scenarioWithLibraryPanel(t, "When an admin tries to store a dashboard with unused/removed library panels, it should disconnect unused/removed library panels",
func(t *testing.T, sc scenarioContext) {
unused, err := sc.elementService.CreateElement(sc.ctx, sc.user, libraryelements.CreateLibraryElementCommand{
unused, err := sc.elementService.CreateElement(sc.ctx, sc.user, model.CreateLibraryElementCommand{
FolderID: sc.folder.ID,
Name: "Unused Libray Panel",
Model: []byte(`
@ -243,7 +243,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) {
"description": "Unused description"
}
`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
})
require.NoError(t, err)
dashJSON := map[string]interface{}{
@ -368,7 +368,7 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) {
_, err := sc.elementService.GetElement(sc.ctx, sc.user, missingUID)
require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error())
require.EqualError(t, err, model.ErrLibraryElementNotFound.Error())
err = sc.service.ImportLibraryPanelsForDashboard(sc.ctx, sc.user, simplejson.NewFromAny(libraryElements), panels, 0)
require.NoError(t, err)
@ -520,9 +520,9 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) {
}
_, err := sc.elementService.GetElement(sc.ctx, sc.user, outsideUID)
require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error())
require.EqualError(t, err, model.ErrLibraryElementNotFound.Error())
_, err = sc.elementService.GetElement(sc.ctx, sc.user, insideUID)
require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error())
require.EqualError(t, err, model.ErrLibraryElementNotFound.Error())
err = sc.service.ImportLibraryPanelsForDashboard(sc.ctx, sc.user, simplejson.NewFromAny(libraryElements), panels, 0)
require.NoError(t, err)
@ -555,7 +555,7 @@ type libraryPanel struct {
Description string
Model map[string]interface{}
Version int64
Meta libraryelements.LibraryElementDTOMeta
Meta model.LibraryElementDTOMeta
}
type libraryElementGridPos struct {
@ -581,17 +581,17 @@ type libraryElementModel struct {
}
type libraryElement struct {
ID int64 `json:"id"`
OrgID int64 `json:"orgId"`
FolderID int64 `json:"folderId"`
UID string `json:"uid"`
Name string `json:"name"`
Kind int64 `json:"kind"`
Type string `json:"type"`
Description string `json:"description"`
Model libraryElementModel `json:"model"`
Version int64 `json:"version"`
Meta libraryelements.LibraryElementDTOMeta `json:"meta"`
ID int64 `json:"id"`
OrgID int64 `json:"orgId"`
FolderID int64 `json:"folderId"`
UID string `json:"uid"`
Name string `json:"name"`
Kind int64 `json:"kind"`
Type string `json:"type"`
Description string `json:"description"`
Model libraryElementModel `json:"model"`
Version int64 `json:"version"`
Meta model.LibraryElementDTOMeta `json:"meta"`
}
type libraryPanelResult struct {
@ -613,9 +613,9 @@ type folderACLItem struct {
permission dashboards.PermissionType
}
func toLibraryElement(t *testing.T, res libraryelements.LibraryElementDTO) libraryElement {
var model = libraryElementModel{}
err := json.Unmarshal(res.Model, &model)
func toLibraryElement(t *testing.T, res model.LibraryElementDTO) libraryElement {
var libraryElementModel = libraryElementModel{}
err := json.Unmarshal(res.Model, &libraryElementModel)
require.NoError(t, err)
return libraryElement{
@ -627,9 +627,9 @@ func toLibraryElement(t *testing.T, res libraryelements.LibraryElementDTO) libra
Type: res.Type,
Description: res.Description,
Kind: res.Kind,
Model: model,
Model: libraryElementModel,
Version: res.Version,
Meta: libraryelements.LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: res.Meta.FolderName,
FolderUID: res.Meta.FolderUID,
ConnectedDashboards: res.Meta.ConnectedDashboards,
@ -649,8 +649,8 @@ func toLibraryElement(t *testing.T, res libraryelements.LibraryElementDTO) libra
}
}
func getExpected(t *testing.T, res libraryelements.LibraryElementDTO, UID string, name string, model map[string]interface{}) libraryElement {
marshalled, err := json.Marshal(model)
func getExpected(t *testing.T, res model.LibraryElementDTO, UID string, name string, lEModel map[string]interface{}) libraryElement {
marshalled, err := json.Marshal(lEModel)
require.NoError(t, err)
var libModel libraryElementModel
err = json.Unmarshal(marshalled, &libModel)
@ -667,7 +667,7 @@ func getExpected(t *testing.T, res libraryelements.LibraryElementDTO, UID string
Kind: 1,
Model: libModel,
Version: 1,
Meta: libraryelements.LibraryElementDTOMeta{
Meta: model.LibraryElementDTOMeta{
FolderName: "General",
FolderUID: "",
ConnectedDashboards: 0,
@ -782,7 +782,7 @@ func scenarioWithLibraryPanel(t *testing.T, desc string, fn func(t *testing.T, s
t.Helper()
testScenario(t, desc, func(t *testing.T, sc scenarioContext) {
command := libraryelements.CreateLibraryElementCommand{
command := model.CreateLibraryElementCommand{
FolderID: sc.folder.ID,
Name: "Text - Library Panel",
Model: []byte(`
@ -794,7 +794,7 @@ func scenarioWithLibraryPanel(t *testing.T, desc string, fn func(t *testing.T, s
"description": "A description"
}
`),
Kind: int64(models.PanelElement),
Kind: int64(model.PanelElement),
}
resp, err := sc.elementService.CreateElement(sc.ctx, sc.user, command)
require.NoError(t, err)

View File

@ -1,7 +1,7 @@
package migrations
import (
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/libraryelements/model"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
@ -34,7 +34,7 @@ func addLibraryElementsMigrations(mg *migrator.Migrator) {
mg.AddMigration("add index library_element org_id-folder_id-name-kind", migrator.NewAddIndexMigration(libraryElementsV1, libraryElementsV1.Indices[0]))
libraryElementConnectionV1 := migrator.Table{
Name: models.LibraryElementConnectionTableName,
Name: model.LibraryElementConnectionTableName,
Columns: []*migrator.Column{
{Name: "id", Type: migrator.DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
{Name: "element_id", Type: migrator.DB_BigInt, Nullable: false},
@ -48,8 +48,8 @@ func addLibraryElementsMigrations(mg *migrator.Migrator) {
},
}
mg.AddMigration("create "+models.LibraryElementConnectionTableName+" table v1", migrator.NewAddTableMigration(libraryElementConnectionV1))
mg.AddMigration("add index "+models.LibraryElementConnectionTableName+" element_id-kind-connection_id", migrator.NewAddIndexMigration(libraryElementConnectionV1, libraryElementConnectionV1.Indices[0]))
mg.AddMigration("create "+model.LibraryElementConnectionTableName+" table v1", migrator.NewAddTableMigration(libraryElementConnectionV1))
mg.AddMigration("add index "+model.LibraryElementConnectionTableName+" element_id-kind-connection_id", migrator.NewAddIndexMigration(libraryElementConnectionV1, libraryElementConnectionV1.Indices[0]))
mg.AddMigration("add unique index library_element org_id_uid", migrator.NewAddIndexMigration(libraryElementsV1, &migrator.Index{
Cols: []string{"org_id", "uid"}, Type: migrator.UniqueIndex,

View File

@ -6,8 +6,8 @@ import (
"time"
"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/libraryelements/model"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/stats"
@ -111,8 +111,8 @@ func (ss *sqlStatsService) GetSystemStats(ctx context.Context, query *stats.GetS
sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("user_auth_token") + `) AS auth_tokens,`)
sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("alert_rule") + `) AS alert_rules,`)
sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("api_key") + `WHERE service_account_id IS NULL) AS api_keys,`)
sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_panels,`, models.PanelElement)
sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_variables,`, models.VariableElement)
sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_panels,`, model.PanelElement)
sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_variables,`, model.VariableElement)
sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("data_keys") + `) AS data_keys,`)
sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("data_keys") + `WHERE active = true) AS active_data_keys,`)