chore: remove sqlstore & mockstore dependencies from (most) packages (#57087)

* chore: add alias for InitTestDB and Session

Adds an alias for the sqlstore InitTestDB and Session, and updates tests using these to reduce dependencies on the sqlstore.Store.

* next pass of removing sqlstore imports
* last little bit
* remove mockstore where possible
This commit is contained in:
Kristin Laemmert 2022-10-19 09:02:15 -04:00 committed by GitHub
parent 5285d34cc0
commit 05709ce411
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
273 changed files with 1595 additions and 1491 deletions

View File

@ -62,7 +62,7 @@ You can now make SQL queries in any of your [command handlers](communication.md#
```go
func (s *MyService) DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
if err := s.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
if err := s.SQLStore.WithDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Exec("DELETE FROM dashboards WHERE dashboard_id=?", cmd.DashboardID)
return err
})

View File

@ -19,11 +19,11 @@ package example
type Service struct {
logger log.Logger
cfg *setting.Cfg
sqlStore *sqlstore.SQLStore
sqlStore db.DB
}
// ProvideService provides Service as dependency for other services.
func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*Service, error) {
func ProvideService(cfg *setting.Cfg, sqlStore db.DB) (*Service, error) {
s := &Service{
logger: log.New("service"),
cfg: cfg,
@ -76,7 +76,7 @@ package server
import (
"github.com/google/wire"
"github.com/grafana/grafana/pkg/example"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
)
var wireBasicSet = wire.NewSet(
@ -98,7 +98,7 @@ func Initialize(cla setting.CommandLineArgs, opts Options, apiOpts api.ServerOpt
return &Server{}, nil
}
func InitializeForTest(cla setting.CommandLineArgs, opts Options, apiOpts api.ServerOptions, sqlStore *sqlstore.SQLStore) (*Server, error) {
func InitializeForTest(cla setting.CommandLineArgs, opts Options, apiOpts api.ServerOptions, sqlStore db.DB) (*Server, error) {
wire.Build(wireExtsTestSet)
return &Server{}, nil
}

View File

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
@ -28,7 +29,7 @@ import (
func TestAnnotationsAPIEndpoint(t *testing.T) {
hs := setupSimpleHTTPServer(nil)
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
store.Cfg = hs.Cfg
hs.SQLStore = store
@ -309,7 +310,7 @@ func putAnnotationScenario(t *testing.T, desc string, url string, routePattern s
cmd dtos.UpdateAnnotationsCmd, fn scenarioFunc) {
t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) {
hs := setupSimpleHTTPServer(nil)
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
store.Cfg = hs.Cfg
hs.SQLStore = store
@ -334,7 +335,7 @@ func putAnnotationScenario(t *testing.T, desc string, url string, routePattern s
func patchAnnotationScenario(t *testing.T, desc string, url string, routePattern string, role org.RoleType, cmd dtos.PatchAnnotationsCmd, fn scenarioFunc) {
t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) {
hs := setupSimpleHTTPServer(nil)
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
store.Cfg = hs.Cfg
hs.SQLStore = store

View File

@ -16,6 +16,7 @@ import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/fs"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
@ -201,7 +202,7 @@ func getContextHandler(t *testing.T, cfg *setting.Cfg) *contexthandler.ContextHa
cfg = setting.NewCfg()
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
remoteCacheSvc := &remotecache.RemoteCache{}
cfg.RemoteCacheOptions = &setting.RemoteCacheOptions{
Name: "database",
@ -249,7 +250,7 @@ func (s *fakeRenderService) Init() error {
func setupAccessControlScenarioContext(t *testing.T, cfg *setting.Cfg, url string, permissions []accesscontrol.Permission) (*scenarioContext, *HTTPServer) {
cfg.Quota.Enabled = false
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: cfg,
Live: newTestLive(t, store),
@ -357,7 +358,7 @@ func setupHTTPServer(t *testing.T, useFakeAccessControl bool, options ...APITest
}
func setupHTTPServerWithCfg(t *testing.T, useFakeAccessControl bool, cfg *setting.Cfg, options ...APITestServerOption) accessControlScenarioContext {
db := sqlstore.InitTestDB(t, sqlstore.InitTestDBOpt{})
db := db.InitTestDB(t, db.InitTestDBOpt{})
return setupHTTPServerWithCfgDb(t, useFakeAccessControl, cfg, db, db, featuremgmt.WithFeatures(), options...)
}

View File

@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/framework/coremodel/registry"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
@ -40,7 +41,6 @@ import (
"github.com/grafana/grafana/pkg/services/provisioning"
"github.com/grafana/grafana/pkg/services/quota/quotaimpl"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
"github.com/grafana/grafana/pkg/services/team/teamtest"
@ -259,7 +259,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
mockSQLStore := mockstore.NewSQLStoreMock()
cfg := setting.NewCfg()
sql := sqlstore.InitTestDB(t)
sql := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: cfg,
@ -991,7 +991,7 @@ func getDashboardShouldReturn200WithConfig(t *testing.T, sc *scenarioContext, pr
}
if dashboardStore == nil {
sql := sqlstore.InitTestDB(t)
sql := db.InitTestDB(t)
dashboardStore = database.ProvideDashboardStore(sql, sql.Cfg, featuremgmt.WithFeatures(), tagimpl.ProvideService(sql, sql.Cfg))
}
@ -1079,7 +1079,7 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s
hs := HTTPServer{
Cfg: cfg,
ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()),
Live: newTestLive(t, sqlstore.InitTestDB(t)),
Live: newTestLive(t, db.InitTestDB(t)),
QuotaService: &quotaimpl.Service{
Cfg: cfg,
},
@ -1115,7 +1115,7 @@ func postValidateScenario(t *testing.T, desc string, url string, routePattern st
hs := HTTPServer{
Cfg: cfg,
ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()),
Live: newTestLive(t, sqlstore.InitTestDB(t)),
Live: newTestLive(t, db.InitTestDB(t)),
QuotaService: &quotaimpl.Service{Cfg: cfg},
LibraryPanelService: &mockLibraryPanelService{},
LibraryElementService: &mockLibraryElementService{},
@ -1151,7 +1151,7 @@ func postDiffScenario(t *testing.T, desc string, url string, routePattern string
hs := HTTPServer{
Cfg: cfg,
ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()),
Live: newTestLive(t, sqlstore.InitTestDB(t)),
Live: newTestLive(t, db.InitTestDB(t)),
QuotaService: &quotaimpl.Service{Cfg: cfg},
LibraryPanelService: &mockLibraryPanelService{},
LibraryElementService: &mockLibraryElementService{},
@ -1189,7 +1189,7 @@ func restoreDashboardVersionScenario(t *testing.T, desc string, url string, rout
hs := HTTPServer{
Cfg: cfg,
ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()),
Live: newTestLive(t, sqlstore.InitTestDB(t)),
Live: newTestLive(t, db.InitTestDB(t)),
QuotaService: &quotaimpl.Service{Cfg: cfg},
LibraryPanelService: &mockLibraryPanelService{},
LibraryElementService: &mockLibraryElementService{},

View File

@ -7,6 +7,10 @@ import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/plugins"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/featuremgmt"
@ -15,17 +19,14 @@ import (
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/updatechecker"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTestEnvironment(t *testing.T, cfg *setting.Cfg, features *featuremgmt.FeatureManager) (*web.Mux, *HTTPServer) {
t.Helper()
sqlstore.InitTestDB(t)
db.InitTestDB(t)
cfg.IsFeatureToggleEnabled = features.IsEnabled
{
@ -39,7 +40,7 @@ func setupTestEnvironment(t *testing.T, cfg *setting.Cfg, features *featuremgmt.
})
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsManager.SetupTestService(t, fakes.NewFakeSecretsStore())
hs := &HTTPServer{

View File

@ -9,6 +9,7 @@ import (
"path/filepath"
"testing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
"github.com/stretchr/testify/assert"
@ -17,7 +18,6 @@ import (
"github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/services/hooks"
"github.com/grafana/grafana/pkg/services/licensing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
)
@ -30,7 +30,7 @@ func setupOAuthTest(t *testing.T, cfg *setting.Cfg) *web.Mux {
}
cfg.ErrTemplateName = "error-template"
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: cfg,

View File

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
@ -47,7 +48,7 @@ func TestOrgUsersAPIEndpoint_userLoggedIn(t *testing.T) {
hs := setupSimpleHTTPServer(featuremgmt.WithFeatures())
settings := hs.Cfg
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
sqlStore.Cfg = settings
hs.SQLStore = sqlStore
orgService := orgtest.NewOrgServiceFake()

View File

@ -20,6 +20,7 @@ import (
"github.com/grafana/grafana/pkg/api/datasource"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/httpclient"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/tracing"
@ -35,7 +36,6 @@ import (
"github.com/grafana/grafana/pkg/services/secrets/fakes"
secretskvs "github.com/grafana/grafana/pkg/services/secrets/kvstore"
secretsmng "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
@ -98,7 +98,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
})
setting.SecretKey = "password" //nolint:goconst
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
key, err := secretsService.Encrypt(context.Background(), []byte("123"), secrets.WithoutScope())
@ -252,7 +252,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
})
setting.SecretKey = "password"
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
key, err := secretsService.Encrypt(context.Background(), []byte("123"), secrets.WithoutScope())
@ -352,7 +352,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
ds := &datasources.DataSource{Url: "htttp://graphite:8080", Type: datasources.DS_GRAPHITE}
ctx := &models.ReqContext{}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -379,7 +379,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
ctx := &models.ReqContext{}
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -405,7 +405,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
ctx := &models.ReqContext{}
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -435,7 +435,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
ctx := &models.ReqContext{}
var pluginRoutes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -460,7 +460,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
}
ctx := &models.ReqContext{}
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -511,7 +511,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
}
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -566,7 +566,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
})
t.Run("When proxying data source proxy should handle authentication", func(t *testing.T) {
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
@ -648,7 +648,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
t.Run("When response header Set-Cookie is not set should remove proxied Set-Cookie header", func(t *testing.T) {
ctx, ds := setUp(t)
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -668,7 +668,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
},
})
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -684,7 +684,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
t.Run("When response should set Content-Security-Policy header", func(t *testing.T) {
ctx, ds := setUp(t)
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -708,7 +708,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
},
})
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -735,7 +735,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
ctx.Req = httptest.NewRequest("GET", "/api/datasources/proxy/1/path/%2Ftest%2Ftest%2F?query=%2Ftest%2Ftest%2F", nil)
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -761,7 +761,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
ctx.Req = httptest.NewRequest("GET", "/api/datasources/proxy/1/path/%2Ftest%2Ftest%2F?query=%2Ftest%2Ftest%2F", nil)
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -787,7 +787,7 @@ func TestNewDataSourceProxy_InvalidURL(t *testing.T) {
cfg := &setting.Cfg{}
tracer := tracing.InitializeTracerForTest()
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -809,7 +809,7 @@ func TestNewDataSourceProxy_ProtocolLessURL(t *testing.T) {
tracer := tracing.InitializeTracerForTest()
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -853,7 +853,7 @@ func TestNewDataSourceProxy_MSSQL(t *testing.T) {
}
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -881,7 +881,7 @@ func getDatasourceProxiedRequest(t *testing.T, ctx *models.ReqContext, cfg *sett
tracer := tracing.InitializeTracerForTest()
var routes []*plugins.Route
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())
@ -1042,7 +1042,7 @@ func Test_PathCheck(t *testing.T) {
return ctx, req
}
ctx, _ := setUp()
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger"))
dsService := datasourceservice.ProvideService(nil, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService())

View File

@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/licensing"
@ -60,7 +61,7 @@ func setUpGetTeamMembersHandler(t *testing.T, sqlStore *sqlstore.SQLStore) {
func TestTeamMembersAPIEndpoint_userLoggedIn(t *testing.T) {
hs := setupSimpleHTTPServer(nil)
settings := hs.Cfg
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
sqlStore.Cfg = settings
hs.SQLStore = sqlStore

View File

@ -11,13 +11,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log/logtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org"
pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/services/preference/preftest"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/team/teamimpl"
"github.com/grafana/grafana/pkg/services/team/teamtest"
@ -30,7 +30,7 @@ func TestTeamAPIEndpoint(t *testing.T) {
t.Run("Given two teams", func(t *testing.T) {
hs := setupSimpleHTTPServer(nil)
hs.Cfg.EditorsCanAdmin = true
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
store.Cfg = hs.Cfg
hs.teamService = teamimpl.ProvideService(store, hs.Cfg)
hs.SQLStore = store
@ -262,7 +262,7 @@ func TestTeamAPIEndpoint_SearchTeams_RBAC(t *testing.T) {
func TestTeamAPIEndpoint_GetTeamByID_RBAC(t *testing.T) {
sc := setupHTTPServer(t, true)
sc.db = sqlstore.InitTestDB(t)
sc.db = db.InitTestDB(t)
_, err := sc.teamService.CreateTeam("team1", "team1@example.org", 1)
require.NoError(t, err)
@ -292,7 +292,7 @@ func TestTeamAPIEndpoint_GetTeamByID_RBAC(t *testing.T) {
// else return 403
func TestTeamAPIEndpoint_UpdateTeam_RBAC(t *testing.T) {
sc := setupHTTPServer(t, true)
sc.db = sqlstore.InitTestDB(t)
sc.db = db.InitTestDB(t)
_, err := sc.teamService.CreateTeam("team1", "", 1)
require.NoError(t, err)
@ -341,7 +341,7 @@ func TestTeamAPIEndpoint_UpdateTeam_RBAC(t *testing.T) {
// else return 403
func TestTeamAPIEndpoint_DeleteTeam_RBAC(t *testing.T) {
sc := setupHTTPServer(t, true)
sc.db = sqlstore.InitTestDB(t)
sc.db = db.InitTestDB(t)
_, err := sc.teamService.CreateTeam("team1", "", 1)
require.NoError(t, err)
@ -373,7 +373,7 @@ func TestTeamAPIEndpoint_DeleteTeam_RBAC(t *testing.T) {
// else return 403
func TestTeamAPIEndpoint_GetTeamPreferences_RBAC(t *testing.T) {
sc := setupHTTPServer(t, true)
sc.db = sqlstore.InitTestDB(t)
sc.db = db.InitTestDB(t)
_, err := sc.teamService.CreateTeam("team1", "", 1)
sqlstore := mockstore.NewSQLStoreMock()
@ -406,7 +406,7 @@ func TestTeamAPIEndpoint_GetTeamPreferences_RBAC(t *testing.T) {
// else return 403
func TestTeamAPIEndpoint_UpdateTeamPreferences_RBAC(t *testing.T) {
sc := setupHTTPServer(t, true)
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
sc.db = sqlStore
prefService := preftest.NewPreferenceServiceFake()

View File

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/models"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
@ -23,7 +24,6 @@ import (
"github.com/grafana/grafana/pkg/services/searchusers/filters"
"github.com/grafana/grafana/pkg/services/secrets/database"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/userimpl"
@ -33,7 +33,7 @@ import (
func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
settings := setting.NewCfg()
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: settings,
SQLStore: sqlStore,

View File

@ -5,6 +5,8 @@ import (
"strings"
"github.com/fatih/color"
"github.com/urfave/cli/v2"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/commands/datamigrations"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/commands/secretsmigrations"
@ -12,11 +14,10 @@ import (
"github.com/grafana/grafana/pkg/cmd/grafana-cli/runner"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/services"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/migrations"
"github.com/grafana/grafana/pkg/setting"
"github.com/urfave/cli/v2"
)
func runRunnerCommand(command func(commandLine utils.CommandLine, runner runner.Runner) error) func(context *cli.Context) error {
@ -42,7 +43,7 @@ func runRunnerCommand(command func(commandLine utils.CommandLine, runner runner.
}
}
func runDbCommand(command func(commandLine utils.CommandLine, sqlStore *sqlstore.SQLStore) error) func(context *cli.Context) error {
func runDbCommand(command func(commandLine utils.CommandLine, sqlStore db.DB) error) func(context *cli.Context) error {
return func(context *cli.Context) error {
cmd := &utils.ContextCommandLine{Context: context}
@ -58,7 +59,7 @@ func runDbCommand(command func(commandLine utils.CommandLine, sqlStore *sqlstore
bus := bus.ProvideBus(tracer)
sqlStore, err := sqlstore.ProvideService(cfg, nil, &migrations.OSSMigrations{}, bus, tracer)
sqlStore, err := db.ProvideService(cfg, nil, &migrations.OSSMigrations{}, bus, tracer)
if err != nil {
return fmt.Errorf("%v: %w", "failed to initialize SQL store", err)
}

View File

@ -11,18 +11,19 @@ import (
"strings"
"github.com/fatih/color"
"github.com/urfave/cli/v2"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/migrations"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/userimpl"
"github.com/grafana/grafana/pkg/setting"
"github.com/urfave/cli/v2"
)
func initConflictCfg(cmd *utils.ContextCommandLine) (*setting.Cfg, error) {
@ -283,7 +284,7 @@ func (r *ConflictResolver) MergeConflictingUsers(ctx context.Context) error {
// creating a session for each block of users
// we want to rollback incase something happens during update / delete
if err := r.Store.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
if err := r.Store.WithDbSession(ctx, func(sess *db.Session) error {
err := sess.Begin()
if err != nil {
return fmt.Errorf("could not open a db session: %w", err)
@ -607,7 +608,7 @@ func (c *ConflictingUser) Marshal(filerow string) error {
func GetUsersWithConflictingEmailsOrLogins(ctx *cli.Context, s *sqlstore.SQLStore) (ConflictingUsers, error) {
queryUsers := make([]ConflictingUser, 0)
outerErr := s.WithDbSession(ctx.Context, func(dbSession *sqlstore.DBSession) error {
outerErr := s.WithDbSession(ctx.Context, func(dbSession *db.Session) error {
rawSQL := conflictingUserEntriesSQL(s)
err := dbSession.SQL(rawSQL).Find(&queryUsers)
return err

View File

@ -5,17 +5,16 @@ import (
"fmt"
"os"
"sort"
"testing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/team/teamimpl"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/team/teamimpl"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
// "Skipping conflicting users test for mysql as it does make unique constraint case insensitive by default
@ -100,7 +99,7 @@ func TestBuildConflictBlock(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
if sqlStore.GetDialect().DriverName() != ignoredDatabase {
for _, u := range tc.users {
@ -205,7 +204,7 @@ conflict: test2
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
if sqlStore.GetDialect().DriverName() != ignoredDatabase {
for _, u := range tc.users {
@ -383,7 +382,7 @@ func TestGetConflictingUsers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
if sqlStore.GetDialect().DriverName() != ignoredDatabase {
for _, u := range tc.users {
cmd := user.CreateUserCommand{
@ -491,7 +490,7 @@ func TestGenerateConflictingUsersFile(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
if sqlStore.GetDialect().DriverName() != ignoredDatabase {
for _, u := range tc.users {
cmd := user.CreateUserCommand{
@ -541,7 +540,7 @@ func TestGenerateConflictingUsersFile(t *testing.T) {
func TestRunValidateConflictUserFile(t *testing.T) {
t.Run("should validate file thats gets created", func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
const testOrgID int64 = 1
if sqlStore.GetDialect().DriverName() != ignoredDatabase {
// add additional user with conflicting login where DOMAIN is upper case
@ -581,7 +580,7 @@ func TestRunValidateConflictUserFile(t *testing.T) {
func TestMergeUser(t *testing.T) {
t.Run("should be able to merge user", func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
teamSvc := teamimpl.ProvideService(sqlStore, setting.NewCfg())
team1, err := teamSvc.CreateTeam("team1 name", "", 1)
require.Nil(t, err)
@ -641,7 +640,7 @@ func TestMergeUser(t *testing.T) {
func TestMergeUserFromNewFileInput(t *testing.T) {
t.Run("should be able to merge users after choosing a different user to keep", func(t *testing.T) {
// Restore after destructive operation
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
type testBuildConflictBlock struct {
desc string

View File

@ -6,10 +6,10 @@ import (
"fmt"
"github.com/fatih/color"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
@ -27,8 +27,8 @@ var (
// EncryptDatasourcePasswords migrates unencrypted secrets on datasources
// to the secureJson Column.
func EncryptDatasourcePasswords(c utils.CommandLine, sqlStore *sqlstore.SQLStore) error {
return sqlStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
func EncryptDatasourcePasswords(c utils.CommandLine, sqlStore db.DB) error {
return sqlStore.WithDbSession(context.Background(), func(session *db.Session) error {
passwordsUpdated, err := migrateColumn(session, "password")
if err != nil {
return err
@ -61,7 +61,7 @@ func EncryptDatasourcePasswords(c utils.CommandLine, sqlStore *sqlstore.SQLStore
})
}
func migrateColumn(session *sqlstore.DBSession, column string) (int, error) {
func migrateColumn(session *db.Session, column string) (int, error) {
var rows []map[string][]byte
session.Cols("id", column, "secure_json_data")
@ -81,7 +81,7 @@ func migrateColumn(session *sqlstore.DBSession, column string) (int, error) {
return rowsUpdated, err
}
func updateRows(session *sqlstore.DBSession, rows []map[string][]byte, passwordFieldName string) (int, error) {
func updateRows(session *db.Session, rows []map[string][]byte, passwordFieldName string) (int, error) {
var rowsUpdated int
for _, row := range rows {

View File

@ -9,23 +9,23 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/commands/commandstest"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func TestPasswordMigrationCommand(t *testing.T) {
// setup datasources with password, basic_auth and none
store := sqlstore.InitTestDB(t)
err := store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
store := db.InitTestDB(t)
err := store.WithDbSession(context.Background(), func(sess *db.Session) error {
passwordMigration(t, sess, store)
return nil
})
require.NoError(t, err)
}
func passwordMigration(t *testing.T, session *sqlstore.DBSession, sqlstore *sqlstore.SQLStore) {
func passwordMigration(t *testing.T, session *db.Session, sqlstore db.DB) {
ds := []*datasources.DataSource{
{Type: "influxdb", Name: "influxdb", Password: "foobar", Uid: "influx"},
{Type: "graphite", Name: "graphite", BasicAuthPassword: "foobar", Uid: "graphite"},

View File

@ -1,18 +1,18 @@
package runner
import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/encryption"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/secrets"
"github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
type Runner struct {
Cfg *setting.Cfg
SQLStore *sqlstore.SQLStore
SQLStore db.DB
SettingsProvider setting.Provider
Features featuremgmt.FeatureToggles
EncryptionService encryption.Internal
@ -21,7 +21,7 @@ type Runner struct {
UserService user.Service
}
func New(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore, settingsProvider setting.Provider,
func New(cfg *setting.Cfg, sqlStore db.DB, settingsProvider setting.Provider,
encryptionService encryption.Internal, features featuremgmt.FeatureToggles,
secretsService *manager.SecretsService, secretsMigrator secrets.Migrator,
userService user.Service,

View File

@ -16,6 +16,8 @@ import (
"github.com/grafana/grafana/pkg/cuectx"
"github.com/grafana/grafana/pkg/expr"
cmreg "github.com/grafana/grafana/pkg/framework/coremodel/registry"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/httpclient"
"github.com/grafana/grafana/pkg/infra/httpclient/httpclientprovider"
"github.com/grafana/grafana/pkg/infra/kvstore"
@ -111,8 +113,6 @@ import (
serviceaccountsmanager "github.com/grafana/grafana/pkg/services/serviceaccounts/manager"
"github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/star/starimpl"
"github.com/grafana/grafana/pkg/services/store"
"github.com/grafana/grafana/pkg/services/store/sanitizer"
@ -155,7 +155,7 @@ var wireSet = wire.NewSet(
featuremgmt.ProvideManagerService,
featuremgmt.ProvideToggles,
wire.Bind(new(bus.Bus), new(*bus.InProcBus)),
sqlstore.ProvideService,
db.ProvideService,
wire.InterfaceValue(new(usagestats.Service), noOpUsageStats{}),
wire.InterfaceValue(new(routing.RouteRegister), noOpRouteRegister{}),
encryptionservice.ProvideEncryptionService,
@ -324,13 +324,13 @@ var wireSet = wire.NewSet(
userauthimpl.ProvideService,
ngmetrics.ProvideServiceForTest,
notifications.MockNotificationService,
wire.Bind(new(notifications.TempUserStore), new(*mockstore.SQLStoreMock)),
wire.Bind(new(notifications.TempUserStore), new(*dbtest.FakeDB)),
wire.Bind(new(notifications.Service), new(*notifications.NotificationServiceMock)),
wire.Bind(new(notifications.WebhookSender), new(*notifications.NotificationServiceMock)),
wire.Bind(new(notifications.EmailSender), new(*notifications.NotificationServiceMock)),
mockstore.NewSQLStoreMock,
dbtest.NewFakeDB,
wire.Bind(new(sqlstore.Store), new(*sqlstore.SQLStore)),
wire.Bind(new(db.DB), new(*sqlstore.SQLStore)),
wire.Bind(new(db.DB), new(*dbtest.FakeDB)),
prefimpl.ProvideService,
opentsdb.ProvideService,
acimpl.ProvideAccessControl,

55
pkg/infra/db/db.go Normal file
View File

@ -0,0 +1,55 @@
package db
import (
"context"
"os"
"xorm.io/core"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/sqlstore/session"
)
type DB interface {
WithTransactionalDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error
WithDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error
WithNewDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error
GetDialect() migrator.Dialect
GetDBType() core.DbType
GetSqlxSession() *session.SessionDB
InTransaction(ctx context.Context, fn func(ctx context.Context) error) error
}
type Session = sqlstore.DBSession
type SQLBuilder = sqlstore.SQLBuilder
type InitTestDBOpt = sqlstore.InitTestDBOpt
var InitTestDB = sqlstore.InitTestDB
var InitTestDBwithCfg = sqlstore.InitTestDBWithCfg
var ProvideService = sqlstore.ProvideService
var NewSqlBuilder = sqlstore.NewSqlBuilder
func IsTestDbMySQL() bool {
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
return db == migrator.MySQL
}
return false
}
func IsTestDbPostgres() bool {
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
return db == migrator.Postgres
}
return false
}
func IsTestDBMSSQL() bool {
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
return db == migrator.MSSQL
}
return false
}

View File

@ -0,0 +1,53 @@
package dbtest
import (
"context"
"xorm.io/core"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/sqlstore/session"
)
type FakeDB struct {
ExpectedError error
}
func NewFakeDB() *FakeDB {
return &FakeDB{}
}
func (f *FakeDB) WithTransactionalDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error {
return f.ExpectedError
}
func (f *FakeDB) WithDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error {
return f.ExpectedError
}
func (f *FakeDB) WithNewDbSession(ctx context.Context, callback sqlstore.DBTransactionFunc) error {
return f.ExpectedError
}
func (f *FakeDB) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
return f.ExpectedError
}
func (f *FakeDB) GetDBType() core.DbType {
return ""
}
func (f *FakeDB) GetDialect() migrator.Dialect {
return nil
}
func (f *FakeDB) GetSqlxSession() *session.SessionDB {
return nil
}
// TODO: service-specific methods not yet split out ; to be removed
func (f *FakeDB) UpdateTempUserWithEmailSent(ctx context.Context, cmd *models.UpdateTempUserWithEmailSentCommand) error {
return f.ExpectedError
}

View File

@ -14,9 +14,8 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
@ -71,7 +70,7 @@ func NewDbStorage(log log.Logger, db db.DB, filter PathFilter, rootFolder string
}, filter, rootFolder)
}
func (s dbFileStorage) getProperties(sess *sqlstore.DBSession, pathHashes []string) (map[string]map[string]string, error) {
func (s dbFileStorage) getProperties(sess *db.Session, pathHashes []string) (map[string]map[string]string, error) {
attributesByPath := make(map[string]map[string]string)
entities := make([]*fileMeta, 0)
@ -96,7 +95,7 @@ func (s dbFileStorage) Get(ctx context.Context, path string, options *GetFileOpt
if err != nil {
return nil, false, err
}
err = s.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.db.WithDbSession(ctx, func(sess *db.Session) error {
table := &file{}
sess.Table("file")
@ -150,7 +149,7 @@ func (s dbFileStorage) Delete(ctx context.Context, filePath string) error {
if err != nil {
return err
}
err = s.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
deletedFilesCount, err := sess.Table("file").Where("path_hash = ?", pathHash).Delete(&file{})
if err != nil {
return err
@ -179,7 +178,7 @@ func (s dbFileStorage) Upsert(ctx context.Context, cmd *UpsertFileCommand) error
return err
}
err = s.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existing := &file{}
exists, err := sess.Table("file").Where("path_hash = ?", pathHash).Get(existing)
if err != nil {
@ -247,7 +246,7 @@ func (s dbFileStorage) Upsert(ctx context.Context, cmd *UpsertFileCommand) error
return err
}
func upsertProperties(dialect migrator.Dialect, sess *sqlstore.DBSession, now time.Time, cmd *UpsertFileCommand, pathHash string) error {
func upsertProperties(dialect migrator.Dialect, sess *db.Session, now time.Time, cmd *UpsertFileCommand, pathHash string) error {
fileMeta := &fileMeta{}
_, err := sess.Table("file_meta").Where("path_hash = ?", pathHash).Delete(fileMeta)
if err != nil {
@ -262,7 +261,7 @@ func upsertProperties(dialect migrator.Dialect, sess *sqlstore.DBSession, now ti
return nil
}
func upsertProperty(dialect migrator.Dialect, sess *sqlstore.DBSession, now time.Time, pathHash string, key string, val string) error {
func upsertProperty(dialect migrator.Dialect, sess *db.Session, now time.Time, pathHash string, key string, val string) error {
existing := &fileMeta{}
keyEqualsCondition := fmt.Sprintf("%s = ?", dialect.Quote("key"))
@ -288,7 +287,7 @@ func upsertProperty(dialect migrator.Dialect, sess *sqlstore.DBSession, now time
func (s dbFileStorage) List(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) {
var resp *ListResponse
err := s.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.db.WithDbSession(ctx, func(sess *db.Session) error {
cursor := ""
if paging != nil && paging.After != "" {
pagingFolderPathHash, err := createPathHash(paging.After + Delimiter)
@ -438,7 +437,7 @@ func (s dbFileStorage) CreateFolder(ctx context.Context, path string) error {
now := time.Now()
precedingFolders := precedingFolders(path)
err := s.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var insertErr error
sess.MustLogSQL(true)
previousFolder := Delimiter
@ -516,7 +515,7 @@ func (s dbFileStorage) DeleteFolder(ctx context.Context, folderPath string, opti
return s.Delete(ctx, lowerFolderPath)
}
err := s.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var rawHashes []interface{}
// xorm does not support `.Delete()` with `.Join()`, so we first have to retrieve all path_hashes and then use them to filter `file_meta` table

View File

@ -8,9 +8,10 @@ import (
"path"
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
"gocloud.dev/blob"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@ -44,7 +45,7 @@ const (
func runTests(createCases func() []fsTestCase, t *testing.T) {
var testLogger log.Logger
var sqlStore *sqlstore.SQLStore
var sqlStore db.DB
var filestorage FileStorage
var ctx context.Context
var tempDir string
@ -74,13 +75,13 @@ func runTests(createCases func() []fsTestCase, t *testing.T) {
setupSqlFS := func() {
commonSetup()
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
filestorage = NewDbStorage(testLogger, sqlStore, nil, "/")
}
setupSqlFSNestedPath := func() {
commonSetup()
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
filestorage = NewDbStorage(testLogger, sqlStore, nil, "/5/dashboards/")
}

View File

@ -3,8 +3,8 @@ package kvstore
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
const (
@ -12,7 +12,7 @@ const (
AllOrganizations = -1
)
func ProvideService(sqlStore sqlstore.Store) KVStore {
func ProvideService(sqlStore db.DB) KVStore {
return &kvStoreSQL{
sqlStore: sqlStore,
log: log.New("infra.kvstore.sql"),

View File

@ -5,16 +5,17 @@ import (
"fmt"
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
)
func createTestableKVStore(t *testing.T) KVStore {
t.Helper()
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
kv := &kvStoreSQL{
sqlStore: sqlStore,

View File

@ -5,14 +5,14 @@ import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
// kvStoreSQL provides a key/value store backed by the Grafana database
type kvStoreSQL struct {
log log.Logger
sqlStore sqlstore.Store
sqlStore db.DB
}
// Get an item from the store
@ -24,7 +24,7 @@ func (kv *kvStoreSQL) Get(ctx context.Context, orgId int64, namespace string, ke
}
var itemFound bool
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *db.Session) error {
has, err := dbSession.Get(&item)
if err != nil {
kv.log.Debug("error getting kvstore value", "orgId", orgId, "namespace", namespace, "key", key, "err", err)
@ -44,7 +44,7 @@ func (kv *kvStoreSQL) Get(ctx context.Context, orgId int64, namespace string, ke
// Set an item in the store
func (kv *kvStoreSQL) Set(ctx context.Context, orgId int64, namespace string, key string, value string) error {
return kv.sqlStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return kv.sqlStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
item := Item{
OrgId: &orgId,
Namespace: &namespace,
@ -88,8 +88,8 @@ func (kv *kvStoreSQL) Set(ctx context.Context, orgId int64, namespace string, ke
// Del deletes an item from the store.
func (kv *kvStoreSQL) Del(ctx context.Context, orgId int64, namespace string, key string) error {
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
query := fmt.Sprintf("DELETE FROM kv_store WHERE org_id=? and namespace=? and %s=?", kv.sqlStore.Quote("key"))
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *db.Session) error {
query := fmt.Sprintf("DELETE FROM kv_store WHERE org_id=? and namespace=? and %s=?", kv.sqlStore.GetDialect().Quote("key"))
_, err := dbSession.Exec(query, orgId, namespace, key)
return err
})
@ -100,8 +100,8 @@ func (kv *kvStoreSQL) Del(ctx context.Context, orgId int64, namespace string, ke
// organizations the constant 'kvstore.AllOrganizations' can be passed as orgId.
func (kv *kvStoreSQL) Keys(ctx context.Context, orgId int64, namespace string, keyPrefix string) ([]Key, error) {
var keys []Key
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
query := dbSession.Where("namespace = ?", namespace).And(fmt.Sprintf("%s LIKE ?", kv.sqlStore.Quote("key")), keyPrefix+"%")
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *db.Session) error {
query := dbSession.Where("namespace = ?", namespace).And(fmt.Sprintf("%s LIKE ?", kv.sqlStore.GetDialect().Quote("key")), keyPrefix+"%")
if orgId != AllOrganizations {
query.And("org_id = ?", orgId)
}
@ -115,7 +115,7 @@ func (kv *kvStoreSQL) Keys(ctx context.Context, orgId int64, namespace string, k
// The map result is like map[orgId]map[key]value
func (kv *kvStoreSQL) GetAll(ctx context.Context, orgId int64, namespace string) (map[int64]map[string]string, error) {
var results []Item
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := kv.sqlStore.WithDbSession(ctx, func(dbSession *db.Session) error {
query := dbSession.Where("namespace = ?", namespace)
if orgId != AllOrganizations {
query.And("org_id = ?", orgId)

View File

@ -4,8 +4,8 @@ import (
"context"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
var getTime = time.Now
@ -13,11 +13,11 @@ var getTime = time.Now
const databaseCacheType = "database"
type databaseCache struct {
SQLStore *sqlstore.SQLStore
SQLStore db.DB
log log.Logger
}
func newDatabaseCache(sqlstore *sqlstore.SQLStore) *databaseCache {
func newDatabaseCache(sqlstore db.DB) *databaseCache {
dc := &databaseCache{
SQLStore: sqlstore,
log: log.New("remotecache.database"),
@ -39,7 +39,7 @@ func (dc *databaseCache) Run(ctx context.Context) error {
}
func (dc *databaseCache) internalRunGC() {
err := dc.SQLStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
err := dc.SQLStore.WithDbSession(context.Background(), func(session *db.Session) error {
now := getTime().Unix()
sql := `DELETE FROM cache_data WHERE (? - created_at) >= expires AND expires <> 0`
@ -56,7 +56,7 @@ func (dc *databaseCache) Get(ctx context.Context, key string) (interface{}, erro
cacheHit := CacheData{}
item := &cachedItem{}
err := dc.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
err := dc.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
exist, err := session.Where("cache_key= ?", key).Get(&cacheHit)
if err != nil {
@ -95,7 +95,7 @@ func (dc *databaseCache) Set(ctx context.Context, key string, value interface{},
return err
}
return dc.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return dc.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
var expiresInSeconds int64
if expire != 0 {
expiresInSeconds = int64(expire) / int64(time.Second)
@ -109,10 +109,10 @@ func (dc *databaseCache) Set(ctx context.Context, key string, value interface{},
// if the update fails propagate the error
// which eventually will result in a key that is not finally set
// but since it's a cache does not harm a lot
if dc.SQLStore.Dialect.IsUniqueConstraintViolation(err) || dc.SQLStore.Dialect.IsDeadlock(err) {
if dc.SQLStore.GetDialect().IsUniqueConstraintViolation(err) || dc.SQLStore.GetDialect().IsDeadlock(err) {
sql := `UPDATE cache_data SET data=?, created_at=?, expires=? WHERE cache_key=?`
_, err = session.Exec(sql, data, getTime().Unix(), expiresInSeconds, key)
if err != nil && dc.SQLStore.Dialect.IsDeadlock(err) {
if err != nil && dc.SQLStore.GetDialect().IsDeadlock(err) {
// most probably somebody else is upserting the key
// so it is safe enough not to propagate this error
return nil
@ -125,7 +125,7 @@ func (dc *databaseCache) Set(ctx context.Context, key string, value interface{},
}
func (dc *databaseCache) Delete(ctx context.Context, key string) error {
return dc.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return dc.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
sql := "DELETE FROM cache_data WHERE cache_key=?"
_, err := session.Exec(sql, key)

View File

@ -5,13 +5,14 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/stretchr/testify/assert"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
)
func TestDatabaseStorageGarbageCollection(t *testing.T) {
sqlstore := sqlstore.InitTestDB(t)
sqlstore := db.InitTestDB(t)
db := &databaseCache{
SQLStore: sqlstore,
@ -59,7 +60,7 @@ func TestDatabaseStorageGarbageCollection(t *testing.T) {
func TestSecondSet(t *testing.T) {
var err error
sqlstore := sqlstore.InitTestDB(t)
sqlstore := db.InitTestDB(t)
db := &databaseCache{
SQLStore: sqlstore,

View File

@ -9,9 +9,9 @@ import (
"github.com/go-kit/log"
"github.com/grafana/grafana/pkg/infra/db"
glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
)
@ -29,7 +29,7 @@ const (
ServiceName = "RemoteCache"
)
func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*RemoteCache, error) {
func ProvideService(cfg *setting.Cfg, sqlStore db.DB) (*RemoteCache, error) {
client, err := createClient(cfg.RemoteCacheOptions, sqlStore)
if err != nil {
return nil, err
@ -62,7 +62,7 @@ type CacheStorage interface {
type RemoteCache struct {
log log.Logger
client CacheStorage
SQLStore *sqlstore.SQLStore
SQLStore db.DB
Cfg *setting.Cfg
}
@ -97,7 +97,7 @@ func (ds *RemoteCache) Run(ctx context.Context) error {
return ctx.Err()
}
func createClient(opts *setting.RemoteCacheOptions, sqlstore *sqlstore.SQLStore) (CacheStorage, error) {
func createClient(opts *setting.RemoteCacheOptions, sqlstore db.DB) (CacheStorage, error) {
if opts.Name == redisCacheType {
return newRedisStorage(opts)
}

View File

@ -5,10 +5,11 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/setting"
)
type CacheableStruct struct {
@ -20,7 +21,7 @@ func init() {
Register(CacheableStruct{})
}
func createTestClient(t *testing.T, opts *setting.RemoteCacheOptions, sqlstore *sqlstore.SQLStore) CacheStorage {
func createTestClient(t *testing.T, opts *setting.RemoteCacheOptions, sqlstore db.DB) CacheStorage {
t.Helper()
cfg := &setting.Cfg{
@ -39,7 +40,7 @@ func TestCachedBasedOnConfig(t *testing.T) {
})
require.Nil(t, err, "Failed to load config")
client := createTestClient(t, cfg.RemoteCacheOptions, sqlstore.InitTestDB(t))
client := createTestClient(t, cfg.RemoteCacheOptions, db.InitTestDB(t))
runTestsForClient(t, client)
}

View File

@ -3,9 +3,10 @@ package remotecache
import (
"testing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/setting"
)
// NewFakeStore creates store for testing
@ -17,7 +18,7 @@ func NewFakeStore(t *testing.T) *RemoteCache {
ConnStr: "",
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
dc, err := ProvideService(&setting.Cfg{
RemoteCacheOptions: opts,

View File

@ -5,13 +5,14 @@ import (
"errors"
"time"
"go.opentelemetry.io/otel/attribute"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"go.opentelemetry.io/otel/attribute"
)
func ProvideService(sqlStore *sqlstore.SQLStore, tracer tracing.Tracer) *ServerLockService {
func ProvideService(sqlStore db.DB, tracer tracing.Tracer) *ServerLockService {
return &ServerLockService{
SQLStore: sqlStore,
tracer: tracer,
@ -23,7 +24,7 @@ func ProvideService(sqlStore *sqlstore.SQLStore, tracer tracing.Tracer) *ServerL
// It exposes 2 services LockAndExecute and LockExecuteAndRelease, which are intended to be used independently, don't mix
// them up (ie, use the same actionName for both of them).
type ServerLockService struct {
SQLStore *sqlstore.SQLStore
SQLStore db.DB
tracer tracing.Tracer
log log.Logger
}
@ -73,7 +74,7 @@ func (sl *ServerLockService) acquireLock(ctx context.Context, serverLock *server
defer span.End()
var result bool
err := sl.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := sl.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
newVersion := serverLock.Version + 1
sql := `UPDATE server_lock SET
version = ?,
@ -101,7 +102,7 @@ func (sl *ServerLockService) getOrCreate(ctx context.Context, actionName string)
var result *serverLock
err := sl.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := sl.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
lockRows := []*serverLock{}
err := dbSession.Where("operation_uid = ?", actionName).Find(&lockRows)
if err != nil {
@ -171,7 +172,7 @@ func (sl *ServerLockService) acquireForRelease(ctx context.Context, actionName s
defer span.End()
// getting the lock - as the action name has a Unique constraint, this will fail if the lock is already on the database
err := sl.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := sl.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
// we need to find if the lock is in the database
lockRows := []*serverLock{}
err := dbSession.Where("operation_uid = ?", actionName).Find(&lockRows)
@ -226,7 +227,7 @@ func (sl *ServerLockService) releaseLock(ctx context.Context, actionName string)
ctx, span := sl.tracer.Start(ctx, "ServerLockService.releaseLock")
defer span.End()
err := sl.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := sl.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `DELETE FROM server_lock WHERE operation_uid=? `
res, err := dbSession.Exec(sql, actionName)

View File

@ -8,15 +8,15 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
func createTestableServerLock(t *testing.T) *ServerLockService {
t.Helper()
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
return &ServerLockService{
SQLStore: store,
@ -105,7 +105,7 @@ func TestLockAndRelease(t *testing.T) {
}
// inserting a row with lock in the past
err := sl.SQLStore.WithTransactionalDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := sl.SQLStore.WithTransactionalDbSession(context.Background(), func(sess *db.Session) error {
r, err := sess.Insert(lock)
require.NoError(t, err)
require.Equal(t, int64(1), r)
@ -118,7 +118,7 @@ func TestLockAndRelease(t *testing.T) {
require.NoError(t, err)
//validate that the lock LastExecution was updated (at least different from the original)
err = sl.SQLStore.WithTransactionalDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = sl.SQLStore.WithTransactionalDbSession(context.Background(), func(sess *db.Session) error {
lockRows := []*serverLock{}
err := sess.Where("operation_uid = ?", operationUID).Find(&lockRows)
require.NoError(t, err)

View File

@ -12,17 +12,16 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/kvstore"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/setting"
)
@ -40,7 +39,7 @@ func Test_InterfaceContractValidity(t *testing.T) {
func TestMetrics(t *testing.T) {
const metricName = "stats.test_metric.count"
sqlStore := mockstore.NewSQLStoreMock()
sqlStore := dbtest.NewFakeDB()
uss := createService(t, setting.Cfg{}, sqlStore, false)
uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) {
@ -149,7 +148,7 @@ func TestMetrics(t *testing.T) {
}
func TestGetUsageReport_IncludesMetrics(t *testing.T) {
sqlStore := mockstore.NewSQLStoreMock()
sqlStore := dbtest.NewFakeDB()
uss := createService(t, setting.Cfg{}, sqlStore, true)
metricName := "stats.test_metric.count"
@ -167,7 +166,7 @@ func TestGetUsageReport_IncludesMetrics(t *testing.T) {
func TestRegisterMetrics(t *testing.T) {
const goodMetricName = "stats.test_external_metric.count"
sqlStore := mockstore.NewSQLStoreMock()
sqlStore := dbtest.NewFakeDB()
uss := createService(t, setting.Cfg{}, sqlStore, false)
metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2}
@ -209,10 +208,10 @@ type httpResp struct {
err error
}
func createService(t *testing.T, cfg setting.Cfg, sqlStore sqlstore.Store, withDB bool) *UsageStats {
func createService(t *testing.T, cfg setting.Cfg, sqlStore db.DB, withDB bool) *UsageStats {
t.Helper()
if withDB {
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
}
return ProvideService(

View File

@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
)
const concurrentUserStatsCacheLifetime = time.Hour
@ -32,7 +32,7 @@ func (s *Service) concurrentUsers(ctx context.Context) (*concurrentUsersStats, e
}
s.concurrentUserStatsCache.stats = &concurrentUsersStats{}
err := s.sqlstore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.sqlstore.WithDbSession(ctx, func(sess *db.Session) error {
// Retrieves concurrent users stats as a histogram. Buckets are accumulative and upper bound is inclusive.
rawSQL := `
SELECT

View File

@ -8,18 +8,16 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/util"
)
func TestConcurrentUsersMetrics(t *testing.T) {
sqlStore := sqlstore.InitTestDB(t)
s := createService(t, setting.NewCfg(), sqlStore)
sqlStore, cfg := db.InitTestDBwithCfg(t)
s := createService(t, cfg, sqlStore)
createConcurrentTokens(t, sqlStore)
@ -35,8 +33,8 @@ func TestConcurrentUsersMetrics(t *testing.T) {
}
func TestConcurrentUsersStats(t *testing.T) {
sqlStore := sqlstore.InitTestDB(t)
s := createService(t, setting.NewCfg(), sqlStore)
sqlStore, cfg := db.InitTestDBwithCfg(t)
s := createService(t, cfg, sqlStore)
createConcurrentTokens(t, sqlStore)
@ -82,7 +80,7 @@ func TestConcurrentUsersStats(t *testing.T) {
assert.Equal(t, expectedResult, actualResult)
}
func createConcurrentTokens(t *testing.T, sqlStore sqlstore.Store) {
func createConcurrentTokens(t *testing.T, sqlStore db.DB) {
t.Helper()
for u := 1; u <= 6; u++ {
for tkn := 1; tkn <= u*3; tkn++ {
@ -91,7 +89,7 @@ func createConcurrentTokens(t *testing.T, sqlStore sqlstore.Store) {
}
}
func createToken(t *testing.T, uID int, sqlStore sqlstore.Store) {
func createToken(t *testing.T, uID int, sqlStore db.DB) {
t.Helper()
token, err := util.RandomHex(16)
require.NoError(t, err)
@ -115,7 +113,7 @@ func createToken(t *testing.T, uID int, sqlStore sqlstore.Store) {
AuthTokenSeen: false,
}
err = sqlStore.WithDbSession(context.Background(), func(dbSession *sqlstore.DBSession) error {
err = sqlStore.WithDbSession(context.Background(), func(dbSession *db.Session) error {
_, err = dbSession.Insert(&userAuthToken)
return err
})

View File

@ -4,12 +4,12 @@ import (
"context"
"errors"
"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/ldap"
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/loginattempt"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
)
@ -39,7 +39,7 @@ type AuthenticatorService struct {
userService user.Service
}
func ProvideService(store sqlstore.Store, loginService login.Service, loginAttemptService loginattempt.Service, userService user.Service) *AuthenticatorService {
func ProvideService(store db.DB, loginService login.Service, loginAttemptService loginattempt.Service, userService user.Service) *AuthenticatorService {
a := &AuthenticatorService{
loginService: loginService,
loginAttemptService: loginAttemptService,

View File

@ -4,11 +4,12 @@ import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateLoginAttempts(t *testing.T) {

View File

@ -4,12 +4,14 @@ import (
"context"
"testing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
)
func TestLoginUsingGrafanaDB(t *testing.T) {
@ -55,7 +57,7 @@ func TestLoginUsingGrafanaDB(t *testing.T) {
}
type grafanaLoginScenarioContext struct {
store *mockstore.SQLStoreMock
store db.DB
userService *usertest.FakeUserService
loginUserQuery *models.LoginUserQuery
validatePasswordCalled bool
@ -70,7 +72,7 @@ func grafanaLoginScenario(t *testing.T, desc string, fn grafanaLoginScenarioFunc
origValidatePassword := validatePassword
sc := &grafanaLoginScenarioContext{
store: mockstore.NewSQLStoreMock(),
store: dbtest.NewFakeDB(),
loginUserQuery: &models.LoginUserQuery{
Username: "user",
Password: "pwd",
@ -100,11 +102,9 @@ func mockPasswordValidation(valid bool, sc *grafanaLoginScenarioContext) {
}
func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(usr *user.User) {
sc.store.ExpectedUser = usr
sc.userService = usertest.NewUserServiceFake()
sc.userService.ExpectedUser = usr
if usr == nil {
sc.store.ExpectedError = user.ErrUserNotFound
sc.userService.ExpectedError = user.ErrUserNotFound
}
}

View File

@ -7,11 +7,11 @@ import (
"strconv"
"strings"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/middleware/cookies"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/team"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
@ -194,7 +194,7 @@ func shouldForceLogin(c *models.ReqContext) bool {
return forceLogin
}
func OrgAdminDashOrFolderAdminOrTeamAdmin(ss sqlstore.Store, ds dashboards.DashboardService, ts team.Service) func(c *models.ReqContext) {
func OrgAdminDashOrFolderAdminOrTeamAdmin(ss db.DB, ds dashboards.DashboardService, ts team.Service) func(c *models.ReqContext) {
return func(c *models.ReqContext) {
if c.OrgRole == org.RoleAdmin {
return

View File

@ -4,11 +4,12 @@ import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMiddlewareAuth(t *testing.T) {
@ -39,7 +40,6 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and NoAnonynmous true", func(
t *testing.T, sc *scenarioContext) {
sc.mockSQLStore.ExpectedOrg = &models.Org{Id: orgID, Name: "test"}
sc.orgService.ExpectedOrg = &org.Org{ID: orgID, Name: "test"}
sc.m.Get("/api/secure", ReqSignedInNoAnonymous, sc.defaultHandler)
sc.fakeReq("GET", "/api/secure").exec()
@ -49,7 +49,6 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and request with forceLogin in query string", func(
t *testing.T, sc *scenarioContext) {
sc.mockSQLStore.ExpectedOrg = &models.Org{Id: orgID, Name: "test"}
sc.orgService.ExpectedOrg = &org.Org{ID: orgID, Name: "test"}
sc.m.Get("/secure", reqSignIn, sc.defaultHandler)
@ -63,7 +62,6 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and request with same org provided in query string", func(
t *testing.T, sc *scenarioContext) {
sc.mockSQLStore.ExpectedOrg = &models.Org{Id: 1, Name: sc.cfg.AnonymousOrgName}
sc.orgService.ExpectedOrg = &org.Org{ID: 1, Name: sc.cfg.AnonymousOrgName}
sc.m.Get("/secure", reqSignIn, sc.defaultHandler)
@ -75,7 +73,6 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and request with different org provided in query string", func(
t *testing.T, sc *scenarioContext) {
sc.mockSQLStore.ExpectedOrg = &models.Org{Id: 1, Name: sc.cfg.AnonymousOrgName}
sc.orgService.ExpectedOrg = &org.Org{ID: 1, Name: sc.cfg.AnonymousOrgName}
sc.m.Get("/secure", reqSignIn, sc.defaultHandler)

View File

@ -18,6 +18,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/fs"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache"
@ -35,7 +36,6 @@ import (
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/grafana/grafana/pkg/setting"
@ -458,7 +458,6 @@ func TestMiddlewareContext(t *testing.T) {
})
middlewareScenario(t, "When anonymous access is enabled", func(t *testing.T, sc *scenarioContext) {
sc.mockSQLStore.ExpectedOrg = &models.Org{Id: 1, Name: sc.cfg.AnonymousOrgName}
sc.orgService.ExpectedOrg = &org.Org{ID: 1, Name: sc.cfg.AnonymousOrgName}
sc.fakeReq("GET", "/").exec()
@ -768,7 +767,7 @@ func middlewareScenario(t *testing.T, desc string, fn scenarioFunc, cbs ...func(
sc.m.UseMiddleware(AddCSPHeader(cfg, logger))
sc.m.UseMiddleware(web.Renderer(viewsPath, "[[", "]]"))
sc.mockSQLStore = mockstore.NewSQLStoreMock()
sc.mockSQLStore = dbtest.NewFakeDB()
sc.loginService = &loginservice.LoginServiceMock{}
sc.userService = usertest.NewUserServiceFake()
sc.orgService = orgtest.NewOrgServiceFake()
@ -807,7 +806,7 @@ func middlewareScenario(t *testing.T, desc string, fn scenarioFunc, cbs ...func(
})
}
func getContextHandler(t *testing.T, cfg *setting.Cfg, mockSQLStore *mockstore.SQLStoreMock,
func getContextHandler(t *testing.T, cfg *setting.Cfg, mockSQLStore *dbtest.FakeDB,
loginService *loginservice.LoginServiceMock, apiKeyService *apikeytest.Service,
userService *usertest.FakeUserService, orgService *orgtest.FakeOrgService,
oauthTokenService *auth.FakeOAuthTokenService,

View File

@ -61,7 +61,7 @@ func TestMiddlewareQuota(t *testing.T) {
const quotaUsed = 4
setUp := func(sc *scenarioContext) {
sc.withTokenSessionCookie("token")
sc.mockSQLStore.ExpectedSignedInUser = &user.SignedInUser{UserID: 12}
sc.userService.ExpectedSignedInUser = &user.SignedInUser{UserID: 12}
sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*models.UserToken, error) {
return &models.UserToken{
UserId: 12,

View File

@ -6,6 +6,10 @@ import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/apikey/apikeytest"
@ -13,12 +17,9 @@ import (
"github.com/grafana/grafana/pkg/services/contexthandler"
"github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/require"
)
type scenarioContext struct {
@ -38,8 +39,8 @@ type scenarioContext struct {
jwtAuthService *models.FakeJWTService
remoteCacheService *remotecache.RemoteCache
cfg *setting.Cfg
sqlStore sqlstore.Store
mockSQLStore *mockstore.SQLStoreMock
sqlStore db.DB
mockSQLStore *dbtest.FakeDB
contextHandler *contexthandler.ContextHandler
loginService *loginservice.LoginServiceMock
apiKeyService *apikeytest.Service

View File

@ -14,6 +14,7 @@ import (
"github.com/stretchr/testify/require"
"gopkg.in/ini.v1"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/plugins/backendplugin/coreplugin"
@ -27,7 +28,6 @@ import (
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/licensing"
"github.com/grafana/grafana/pkg/services/searchV2"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb/azuremonitor"
"github.com/grafana/grafana/pkg/tsdb/cloudmonitoring"
@ -95,7 +95,7 @@ func TestIntegrationPluginManager(t *testing.T) {
pg := postgres.ProvideService(cfg)
my := mysql.ProvideService(cfg, hcp)
ms := mssql.ProvideService(cfg)
sv2 := searchV2.ProvideService(cfg, sqlstore.InitTestDB(t), nil, nil, tracer, features, nil, nil, nil)
sv2 := searchV2.ProvideService(cfg, db.InitTestDB(t), nil, nil, tracer, features, nil, nil, nil)
graf := grafanads.ProvideService(sv2, nil)
coreRegistry := coreplugin.ProvideCoreRegistry(am, cw, cm, es, grap, idb, lk, otsdb, pr, tmpo, td, pg, my, ms, graf)

View File

@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/cuectx"
"github.com/grafana/grafana/pkg/expr"
cmreg "github.com/grafana/grafana/pkg/framework/coremodel/registry"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/httpclient"
"github.com/grafana/grafana/pkg/infra/httpclient/httpclientprovider"
"github.com/grafana/grafana/pkg/infra/kvstore"
@ -121,7 +122,6 @@ import (
serviceaccountsmanager "github.com/grafana/grafana/pkg/services/serviceaccounts/manager"
"github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/services/star/starimpl"
"github.com/grafana/grafana/pkg/services/store"

View File

@ -8,6 +8,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics"
@ -15,7 +16,6 @@ import (
"github.com/grafana/grafana/pkg/services/accesscontrol/api"
"github.com/grafana/grafana/pkg/services/accesscontrol/database"
"github.com/grafana/grafana/pkg/services/accesscontrol/ossaccesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)

View File

@ -8,12 +8,12 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/database"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
)
@ -26,7 +26,7 @@ func setupTestEnv(t testing.TB) *Service {
cfg: cfg,
log: log.New("accesscontrol"),
registrations: accesscontrol.RegistrationList{},
store: database.ProvideService(sqlstore.InitTestDB(t)),
store: database.ProvideService(db.InitTestDB(t)),
roles: accesscontrol.BuildBasicRoleDefinitions(),
}
require.NoError(t, ac.RegisterFixedRoles(context.Background()))
@ -58,7 +58,7 @@ func TestUsageMetrics(t *testing.T) {
s, errInitAc := ProvideService(
cfg,
sqlstore.InitTestDB(t),
db.InitTestDB(t),
routing.NewRouteRegister(),
localcache.ProvideService(),
)

View File

@ -5,9 +5,8 @@ import (
"strconv"
"strings"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
)
const (
@ -24,7 +23,7 @@ type AccessControlStore struct {
func (s *AccessControlStore) GetUserPermissions(ctx context.Context, query accesscontrol.GetUserPermissionsQuery) ([]accesscontrol.Permission, error) {
result := make([]accesscontrol.Permission, 0)
err := s.sql.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.sql.WithDbSession(ctx, func(sess *db.Session) error {
if query.UserID == 0 && len(query.TeamIDs) == 0 && len(query.Roles) == 0 {
// no permission to fetch
return nil
@ -112,7 +111,7 @@ func userRolesFilter(orgID, userID int64, teamIDs []int64, roles []string) (stri
}
func (s *AccessControlStore) DeleteUserPermissions(ctx context.Context, orgID, userID int64) error {
err := s.sql.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.sql.WithDbSession(ctx, func(sess *db.Session) error {
roleDeleteQuery := "DELETE FROM user_role WHERE user_id = ?"
roleDeleteParams := []interface{}{roleDeleteQuery, userID}
if orgID != accesscontrol.GlobalOrgID {

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
rs "github.com/grafana/grafana/pkg/services/accesscontrol/resourcepermissions"
@ -243,9 +244,9 @@ func createUserAndTeam(t *testing.T, sql *sqlstore.SQLStore, teamSvc team.Servic
}
func setupTestEnv(t testing.TB) (*AccessControlStore, rs.Store, *sqlstore.SQLStore, team.Service) {
sql := sqlstore.InitTestDB(t)
sql, cfg := db.InitTestDBwithCfg(t)
acstore := ProvideService(sql)
permissionStore := rs.NewStore(sql)
teamService := teamimpl.ProvideService(sql, sql.Cfg)
teamService := teamimpl.ProvideService(sql, cfg)
return acstore, permissionStore, sql, teamService
}

View File

@ -8,11 +8,11 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/datasources"
dsService "github.com/grafana/grafana/pkg/services/datasources/service"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
)
@ -43,7 +43,7 @@ func benchmarkFilter(b *testing.B, numDs, numPermissions int) {
require.NoError(b, err)
var datasources []datasources.DataSource
err = store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = store.WithDbSession(context.Background(), func(sess *db.Session) error {
return sess.SQL(baseSql+acFilter.Where, acFilter.Args...).Find(&datasources)
})
require.NoError(b, err)
@ -51,9 +51,9 @@ func benchmarkFilter(b *testing.B, numDs, numPermissions int) {
}
}
func setupFilterBenchmark(b *testing.B, numDs, numPermissions int) (*sqlstore.SQLStore, []accesscontrol.Permission) {
func setupFilterBenchmark(b *testing.B, numDs, numPermissions int) (db.DB, []accesscontrol.Permission) {
b.Helper()
sqlStore := sqlstore.InitTestDB(b)
sqlStore := db.InitTestDB(b)
store := dsService.CreateStore(sqlStore, log.New("accesscontrol.test"))
for i := 1; i <= numDs; i++ {
err := store.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{

View File

@ -8,11 +8,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/datasources"
dsService "github.com/grafana/grafana/pkg/services/datasources/service"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
)
@ -166,9 +166,9 @@ func TestFilter_Datasources(t *testing.T) {
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
store := sqlstore.InitTestDB(t)
store := db.InitTestDB(t)
err := store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := store.WithDbSession(context.Background(), func(sess *db.Session) error {
// seed 10 data sources
for i := 1; i <= 10; i++ {
dsStore := dsService.CreateStore(store, log.New("accesscontrol.test"))

View File

@ -7,13 +7,12 @@ import (
"strconv"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/resourcepermissions"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/serviceaccounts"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/team"
"github.com/grafana/grafana/pkg/services/team/teamimpl"
"github.com/grafana/grafana/pkg/services/user"
@ -75,7 +74,7 @@ func ProvideTeamPermissions(
ReaderRoleName: "Team permission reader",
WriterRoleName: "Team permission writer",
RoleGroup: "Teams",
OnSetUser: func(session *sqlstore.DBSession, orgID int64, user accesscontrol.User, resourceID, permission string) error {
OnSetUser: func(session *db.Session, orgID int64, user accesscontrol.User, resourceID, permission string) error {
teamId, err := strconv.ParseInt(resourceID, 10, 64)
if err != nil {
return err

View File

@ -1,8 +1,8 @@
package resourcepermissions
import (
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
type ResourceHooks struct {
@ -11,9 +11,9 @@ type ResourceHooks struct {
BuiltInRole BuiltinResourceHookFunc
}
type UserResourceHookFunc func(session *sqlstore.DBSession, orgID int64, user accesscontrol.User, resourceID, permission string) error
type TeamResourceHookFunc func(session *sqlstore.DBSession, orgID, teamID int64, resourceID, permission string) error
type BuiltinResourceHookFunc func(session *sqlstore.DBSession, orgID int64, builtInRole, resourceID, permission string) error
type UserResourceHookFunc func(session *db.Session, orgID int64, user accesscontrol.User, resourceID, permission string) error
type TeamResourceHookFunc func(session *db.Session, orgID, teamID int64, resourceID, permission string) error
type BuiltinResourceHookFunc func(session *db.Session, orgID int64, builtInRole, resourceID, permission string) error
type User struct {
ID int64

View File

@ -3,8 +3,8 @@ package resourcepermissions
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
type ResourceValidator func(ctx context.Context, orgID int64, resourceID string) error
@ -32,11 +32,11 @@ type Options struct {
// RoleGroup is the group name for the generated fixed roles
RoleGroup string
// OnSetUser if configured will be called each time a permission is set for a user
OnSetUser func(session *sqlstore.DBSession, orgID int64, user accesscontrol.User, resourceID, permission string) error
OnSetUser func(session *db.Session, orgID int64, user accesscontrol.User, resourceID, permission string) error
// OnSetTeam if configured will be called each time a permission is set for a team
OnSetTeam func(session *sqlstore.DBSession, orgID, teamID int64, resourceID, permission string) error
OnSetTeam func(session *db.Session, orgID, teamID int64, resourceID, permission string) error
// OnSetBuiltInRole if configured will be called each time a permission is set for a built-in role
OnSetBuiltInRole func(session *sqlstore.DBSession, orgID int64, builtInRole, resourceID, permission string) error
OnSetBuiltInRole func(session *db.Session, orgID int64, builtInRole, resourceID, permission string) error
// InheritedScopesSolver if configured can generate additional scopes that will be used when fetching permissions for a resource
InheritedScopesSolver InheritedScopesSolver
}

View File

@ -6,10 +6,10 @@ import (
"sort"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/team"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"

View File

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/licensing/licensingtest"
@ -50,7 +51,7 @@ func TestService_SetUserPermission(t *testing.T) {
var hookCalled bool
if tt.callHook {
service.options.OnSetUser = func(session *sqlstore.DBSession, orgID int64, user accesscontrol.User, resourceID, permission string) error {
service.options.OnSetUser = func(session *db.Session, orgID int64, user accesscontrol.User, resourceID, permission string) error {
hookCalled = true
return nil
}
@ -94,7 +95,7 @@ func TestService_SetTeamPermission(t *testing.T) {
var hookCalled bool
if tt.callHook {
service.options.OnSetTeam = func(session *sqlstore.DBSession, orgID, teamID int64, resourceID, permission string) error {
service.options.OnSetTeam = func(session *db.Session, orgID, teamID int64, resourceID, permission string) error {
hookCalled = true
return nil
}
@ -134,7 +135,7 @@ func TestService_SetBuiltInRolePermission(t *testing.T) {
var hookCalled bool
if tt.callHook {
service.options.OnSetBuiltInRole = func(session *sqlstore.DBSession, orgID int64, builtInRole, resourceID, permission string) error {
service.options.OnSetBuiltInRole = func(session *db.Session, orgID int64, builtInRole, resourceID, permission string) error {
hookCalled = true
return nil
}
@ -221,7 +222,7 @@ func TestService_SetPermissions(t *testing.T) {
func setupTestEnvironment(t *testing.T, permissions []accesscontrol.Permission, ops Options) (*Service, *sqlstore.SQLStore, team.Service) {
t.Helper()
sql := sqlstore.InitTestDB(t)
sql := db.InitTestDB(t)
cfg := setting.NewCfg()
teamSvc := teamimpl.ProvideService(sql, cfg)
userSvc := userimpl.ProvideService(sql, nil, cfg, teamimpl.ProvideService(sql, cfg), nil)

View File

@ -6,11 +6,10 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util"
)
@ -58,7 +57,7 @@ func (s *store) SetUserResourcePermission(
var err error
var permission *accesscontrol.ResourcePermission
err = s.sql.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.sql.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
permission, err = s.setUserResourcePermission(sess, orgID, usr, cmd, hook)
return err
})
@ -66,7 +65,7 @@ func (s *store) SetUserResourcePermission(
return permission, err
}
func (s *store) setUserResourcePermission(
sess *sqlstore.DBSession, orgID int64, user accesscontrol.User,
sess *db.Session, orgID int64, user accesscontrol.User,
cmd SetResourcePermissionCommand,
hook UserResourceHookFunc,
) (*accesscontrol.ResourcePermission, error) {
@ -96,7 +95,7 @@ func (s *store) SetTeamResourcePermission(
var err error
var permission *accesscontrol.ResourcePermission
err = s.sql.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.sql.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
permission, err = s.setTeamResourcePermission(sess, orgID, teamID, cmd, hook)
return err
})
@ -105,7 +104,7 @@ func (s *store) SetTeamResourcePermission(
}
func (s *store) setTeamResourcePermission(
sess *sqlstore.DBSession, orgID, teamID int64,
sess *db.Session, orgID, teamID int64,
cmd SetResourcePermissionCommand,
hook TeamResourceHookFunc,
) (*accesscontrol.ResourcePermission, error) {
@ -135,7 +134,7 @@ func (s *store) SetBuiltInResourcePermission(
var err error
var permission *accesscontrol.ResourcePermission
err = s.sql.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.sql.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
permission, err = s.setBuiltInResourcePermission(sess, orgID, builtInRole, cmd, hook)
return err
})
@ -148,7 +147,7 @@ func (s *store) SetBuiltInResourcePermission(
}
func (s *store) setBuiltInResourcePermission(
sess *sqlstore.DBSession, orgID int64, builtInRole string,
sess *db.Session, orgID int64, builtInRole string,
cmd SetResourcePermissionCommand,
hook BuiltinResourceHookFunc,
) (*accesscontrol.ResourcePermission, error) {
@ -174,7 +173,7 @@ func (s *store) SetResourcePermissions(
var err error
var permissions []accesscontrol.ResourcePermission
err = s.sql.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err = s.sql.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
for _, cmd := range commands {
var p *accesscontrol.ResourcePermission
if cmd.User.ID != 0 {
@ -201,7 +200,7 @@ func (s *store) SetResourcePermissions(
type roleAdder func(roleID int64) error
func (s *store) setResourcePermission(
sess *sqlstore.DBSession, orgID int64, roleName string, adder roleAdder, cmd SetResourcePermissionCommand,
sess *db.Session, orgID int64, roleName string, adder roleAdder, cmd SetResourcePermissionCommand,
) (*accesscontrol.ResourcePermission, error) {
role, err := s.getOrCreateManagedRole(sess, orgID, roleName, adder)
if err != nil {
@ -254,7 +253,7 @@ func (s *store) setResourcePermission(
func (s *store) GetResourcePermissions(ctx context.Context, orgID int64, query GetResourcePermissionsQuery) ([]accesscontrol.ResourcePermission, error) {
var result []accesscontrol.ResourcePermission
err := s.sql.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := s.sql.WithDbSession(ctx, func(sess *db.Session) error {
var err error
result, err = s.getResourcePermissions(sess, orgID, query)
return err
@ -263,7 +262,7 @@ func (s *store) GetResourcePermissions(ctx context.Context, orgID int64, query G
return result, err
}
func (s *store) getResourcePermissions(sess *sqlstore.DBSession, orgID int64, query GetResourcePermissionsQuery) ([]accesscontrol.ResourcePermission, error) {
func (s *store) getResourcePermissions(sess *db.Session, orgID int64, query GetResourcePermissionsQuery) ([]accesscontrol.ResourcePermission, error) {
if len(query.Actions) == 0 {
return nil, nil
}
@ -463,7 +462,7 @@ func flatPermissionsToResourcePermission(scope string, permissions []flatResourc
}
}
func (s *store) userAdder(sess *sqlstore.DBSession, orgID, userID int64) roleAdder {
func (s *store) userAdder(sess *db.Session, orgID, userID int64) roleAdder {
return func(roleID int64) error {
if res, err := sess.Query("SELECT 1 FROM user_role WHERE org_id=? AND user_id=? AND role_id=?", orgID, userID, roleID); err != nil {
return err
@ -484,7 +483,7 @@ func (s *store) userAdder(sess *sqlstore.DBSession, orgID, userID int64) roleAdd
}
}
func (s *store) teamAdder(sess *sqlstore.DBSession, orgID, teamID int64) roleAdder {
func (s *store) teamAdder(sess *db.Session, orgID, teamID int64) roleAdder {
return func(roleID int64) error {
if res, err := sess.Query("SELECT 1 FROM team_role WHERE org_id=? AND team_id=? AND role_id=?", orgID, teamID, roleID); err != nil {
return err
@ -504,7 +503,7 @@ func (s *store) teamAdder(sess *sqlstore.DBSession, orgID, teamID int64) roleAdd
}
}
func (s *store) builtInRoleAdder(sess *sqlstore.DBSession, orgID int64, builtinRole string) roleAdder {
func (s *store) builtInRoleAdder(sess *db.Session, orgID int64, builtinRole string) roleAdder {
return func(roleID int64) error {
if res, err := sess.Query("SELECT 1 FROM builtin_role WHERE role_id=? AND role=? AND org_id=?", roleID, builtinRole, orgID); err != nil {
return err
@ -524,7 +523,7 @@ func (s *store) builtInRoleAdder(sess *sqlstore.DBSession, orgID int64, builtinR
}
}
func (s *store) getOrCreateManagedRole(sess *sqlstore.DBSession, orgID int64, name string, add roleAdder) (*accesscontrol.Role, error) {
func (s *store) getOrCreateManagedRole(sess *db.Session, orgID int64, name string, add roleAdder) (*accesscontrol.Role, error) {
role := accesscontrol.Role{OrgID: orgID, Name: name}
has, err := sess.Where("org_id = ? AND name = ?", orgID, name).Get(&role)
@ -559,7 +558,7 @@ func (s *store) getOrCreateManagedRole(sess *sqlstore.DBSession, orgID int64, na
return &role, nil
}
func generateNewRoleUID(sess *sqlstore.DBSession, orgID int64) (string, error) {
func generateNewRoleUID(sess *db.Session, orgID int64) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
@ -576,7 +575,7 @@ func generateNewRoleUID(sess *sqlstore.DBSession, orgID int64) (string, error) {
return "", fmt.Errorf("failed to generate uid")
}
func (s *store) getPermissions(sess *sqlstore.DBSession, resource, resourceID, resourceAttribute string, roleID int64) ([]flatResourcePermission, error) {
func (s *store) getPermissions(sess *db.Session, resource, resourceID, resourceAttribute string, roleID int64) ([]flatResourcePermission, error) {
var result []flatResourcePermission
rawSql := `
SELECT
@ -605,7 +604,7 @@ func (s *store) getPermissions(sess *sqlstore.DBSession, resource, resourceID, r
return result, nil
}
func (s *store) createPermissions(sess *sqlstore.DBSession, roleID int64, resource, resourceID, resourceAttribute string, actions map[string]struct{}) error {
func (s *store) createPermissions(sess *db.Session, roleID int64, resource, resourceID, resourceAttribute string, actions map[string]struct{}) error {
if len(actions) == 0 {
return nil
}
@ -624,7 +623,7 @@ func (s *store) createPermissions(sess *sqlstore.DBSession, roleID int64, resour
return nil
}
func deletePermissions(sess *sqlstore.DBSession, ids []int64) error {
func deletePermissions(sess *db.Session, ids []int64) error {
if len(ids) == 0 {
return nil
}

View File

@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore"
@ -420,7 +421,7 @@ func TestIntegrationStore_GetResourcePermissions(t *testing.T) {
t.Run(tt.desc, func(t *testing.T) {
store, sql := setupTestEnv(t)
err := sql.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := sql.WithDbSession(context.Background(), func(sess *db.Session) error {
role := &accesscontrol.Role{
OrgID: tt.user.OrgID,
UID: "seeded",
@ -492,6 +493,6 @@ func seedResourcePermissions(t *testing.T, store *store, sql *sqlstore.SQLStore,
}
func setupTestEnv(t testing.TB) (*store, *sqlstore.SQLStore) {
sql := sqlstore.InitTestDB(t)
sql := db.InitTestDB(t)
return NewStore(sql), sql
}

View File

@ -11,10 +11,10 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/datasources/permissions"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
)
@ -200,7 +200,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Alert notifications are in DB", func(t *testing.T) {
sqlStore := sqlStore{db: sqlstore.InitTestDB(t)}
sqlStore := sqlStore{db: db.InitTestDB(t)}
firstNotification := models.CreateAlertNotificationCommand{Uid: "notifier1", OrgId: 1, Name: "1"}
err = sqlStore.CreateAlertNotificationCommand(context.Background(), &firstNotification)

View File

@ -6,13 +6,14 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/tsdb/legacydata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/tsdb/legacydata"
)
type FakeCondition struct{}
@ -85,7 +86,7 @@ func TestAlertRuleForParsing(t *testing.T) {
}
func TestAlertRuleModel(t *testing.T) {
sqlStore := &sqlStore{db: sqlstore.InitTestDB(t), cache: localcache.New(time.Minute, time.Minute)}
sqlStore := &sqlStore{db: db.InitTestDB(t), cache: localcache.New(time.Minute, time.Minute)}
RegisterCondition("test", func(model *simplejson.Json, index int) (Condition, error) {
return &FakeCondition{}, nil
})

View File

@ -4,10 +4,10 @@ import (
"context"
"fmt"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption"
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)

View File

@ -6,7 +6,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/usagestats"
@ -14,14 +17,12 @@ import (
encryptionprovider "github.com/grafana/grafana/pkg/services/encryption/provider"
encryptionservice "github.com/grafana/grafana/pkg/services/encryption/service"
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/require"
)
func TestService(t *testing.T) {
sqlStore := &sqlStore{
db: sqlstore.InitTestDB(t),
db: db.InitTestDB(t),
log: &log.ConcreteLogger{},
cache: localcache.New(time.Minute, time.Minute),
}

View File

@ -6,12 +6,11 @@ import (
"fmt"
"strings"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/tag"
"github.com/grafana/grafana/pkg/setting"
)
@ -54,7 +53,7 @@ func ProvideAlertStore(
}
func (ss *sqlStore) GetAlertById(ctx context.Context, query *models.GetAlertByIdQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
alert := models.Alert{}
has, err := sess.ID(query.Id).Get(&alert)
if !has {
@ -70,7 +69,7 @@ func (ss *sqlStore) GetAlertById(ctx context.Context, query *models.GetAlertById
}
func (ss *sqlStore) GetAllAlertQueryHandler(ctx context.Context, query *models.GetAllAlertsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var alerts []*models.Alert
err := sess.SQL("select * from alert").Find(&alerts)
if err != nil {
@ -82,7 +81,7 @@ func (ss *sqlStore) GetAllAlertQueryHandler(ctx context.Context, query *models.G
})
}
func deleteAlertByIdInternal(alertId int64, reason string, sess *sqlstore.DBSession, log *log.ConcreteLogger) error {
func deleteAlertByIdInternal(alertId int64, reason string, sess *db.Session, log *log.ConcreteLogger) error {
log.Debug("Deleting alert", "id", alertId, "reason", reason)
if _, err := sess.Exec("DELETE FROM alert WHERE id = ?", alertId); err != nil {
@ -105,8 +104,8 @@ func deleteAlertByIdInternal(alertId int64, reason string, sess *sqlstore.DBSess
}
func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *models.GetAlertsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
builder := sqlstore.NewSqlBuilder(ss.cfg)
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
builder := db.NewSqlBuilder(ss.cfg)
builder.Write(`SELECT
alert.id,
@ -185,7 +184,7 @@ func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *models.GetAler
}
func (ss *sqlStore) SaveAlerts(ctx context.Context, dashID int64, alerts []*models.Alert) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existingAlerts, err := GetAlertsByDashboardId2(dashID, sess)
if err != nil {
return err
@ -203,7 +202,7 @@ func (ss *sqlStore) SaveAlerts(ctx context.Context, dashID int64, alerts []*mode
})
}
func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*models.Alert, alerts []*models.Alert, sess *sqlstore.DBSession, log *log.ConcreteLogger) error {
func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*models.Alert, alerts []*models.Alert, sess *db.Session, log *log.ConcreteLogger) error {
for _, alert := range alerts {
update := false
var alertToUpdate *models.Alert
@ -263,7 +262,7 @@ func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*models.A
return nil
}
func deleteMissingAlerts(alerts []*models.Alert, existingAlerts []*models.Alert, sess *sqlstore.DBSession, log *log.ConcreteLogger) error {
func deleteMissingAlerts(alerts []*models.Alert, existingAlerts []*models.Alert, sess *db.Session, log *log.ConcreteLogger) error {
for _, missingAlert := range alerts {
missing := true
@ -286,7 +285,7 @@ func deleteMissingAlerts(alerts []*models.Alert, existingAlerts []*models.Alert,
return nil
}
func GetAlertsByDashboardId2(dashboardId int64, sess *sqlstore.DBSession) ([]*models.Alert, error) {
func GetAlertsByDashboardId2(dashboardId int64, sess *db.Session) ([]*models.Alert, error) {
alerts := make([]*models.Alert, 0)
err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)
@ -298,7 +297,7 @@ func GetAlertsByDashboardId2(dashboardId int64, sess *sqlstore.DBSession) ([]*mo
}
func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *models.SetAlertStateCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
alert := models.Alert{}
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
@ -337,7 +336,7 @@ func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *models.SetAlertState
}
func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *models.PauseAlertCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
if len(cmd.AlertIds) == 0 {
return fmt.Errorf("command contains no alertids")
}
@ -371,7 +370,7 @@ func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *models.PauseAlertComman
}
func (ss *sqlStore) PauseAllAlerts(ctx context.Context, cmd *models.PauseAllAlertCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var newState string
if cmd.Paused {
newState = string(models.AlertStatePaused)
@ -389,7 +388,7 @@ func (ss *sqlStore) PauseAllAlerts(ctx context.Context, cmd *models.PauseAllAler
}
func (ss *sqlStore) GetAlertStatesForDashboard(ctx context.Context, query *models.GetAlertStatesForDashboardQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var rawSQL = `SELECT
id,
dashboard_id,

View File

@ -8,8 +8,8 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/util"
)
@ -33,7 +33,7 @@ type AlertNotificationStore interface {
var timeNow = time.Now
func (ss *sqlStore) DeleteAlertNotification(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
sql := "DELETE FROM alert_notification WHERE alert_notification.org_id = ? AND alert_notification.id = ?"
res, err := sess.Exec(sql, cmd.OrgId, cmd.Id)
if err != nil {
@ -58,7 +58,7 @@ func (ss *sqlStore) DeleteAlertNotification(ctx context.Context, cmd *models.Del
func (ss *sqlStore) DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error {
existingNotification := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
if err := ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, existingNotification, sess)
}); err != nil {
return err
@ -81,7 +81,7 @@ func (ss *sqlStore) DeleteAlertNotificationWithUid(ctx context.Context, cmd *mod
}
func (ss *sqlStore) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationInternal(ctx, query, sess)
})
}
@ -94,7 +94,7 @@ func (ss *sqlStore) GetAlertNotificationUidWithId(ctx context.Context, query *mo
return nil
}
if err := ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationUidInternal(ctx, query, sess)
}); err != nil {
return err
@ -110,13 +110,13 @@ func newAlertNotificationUidCacheKey(orgID, notificationId int64) string {
}
func (ss *sqlStore) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, query, sess)
})
}
func (ss *sqlStore) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
results := make([]*models.AlertNotification, 0)
if err := sess.Where("org_id = ?", query.OrgId).Asc("name").Find(&results); err != nil {
return err
@ -128,7 +128,7 @@ func (ss *sqlStore) GetAllAlertNotifications(ctx context.Context, query *models.
}
func (ss *sqlStore) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -173,7 +173,7 @@ func (ss *sqlStore) GetAlertNotificationsWithUidToSend(ctx context.Context, quer
})
}
func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlertNotificationUidQuery, sess *sqlstore.DBSession) error {
func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlertNotificationUidQuery, sess *db.Session) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -202,7 +202,7 @@ func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlert
return nil
}
func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNotificationsQuery, sess *sqlstore.DBSession) error {
func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNotificationsQuery, sess *db.Session) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -252,7 +252,7 @@ func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNot
return nil
}
func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery, sess *sqlstore.DBSession) error {
func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery, sess *db.Session) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -291,7 +291,7 @@ func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetA
}
func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
if cmd.Uid == "" {
uid, uidGenerationErr := generateNewAlertNotificationUid(ctx, sess, cmd.OrgId)
if uidGenerationErr != nil {
@ -364,7 +364,7 @@ func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *mod
})
}
func generateNewAlertNotificationUid(ctx context.Context, sess *sqlstore.DBSession, orgId int64) (string, error) {
func generateNewAlertNotificationUid(ctx context.Context, sess *db.Session, orgId int64) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
exists, err := sess.Where("org_id=? AND uid=?", orgId, uid).Get(&models.AlertNotification{})
@ -381,7 +381,7 @@ func generateNewAlertNotificationUid(ctx context.Context, sess *sqlstore.DBSessi
}
func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) (err error) {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) (err error) {
current := models.AlertNotification{}
if _, err = sess.ID(cmd.Id).Get(&current); err != nil {
@ -451,7 +451,7 @@ func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.Upd
func (ss *sqlStore) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error {
getAlertNotificationWithUidQuery := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
if err := ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, getAlertNotificationWithUidQuery, sess)
}); err != nil {
return err
@ -492,7 +492,7 @@ func (ss *sqlStore) UpdateAlertNotificationWithUid(ctx context.Context, cmd *mod
}
func (ss *sqlStore) SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
version := cmd.Version
var current models.AlertNotificationState
if _, err := sess.ID(cmd.Id).Get(&current); err != nil {
@ -521,7 +521,7 @@ func (ss *sqlStore) SetAlertNotificationStateToCompleteCommand(ctx context.Conte
}
func (ss *sqlStore) SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
newVersion := cmd.Version + 1
sql := `UPDATE alert_notification_state SET
state = ?,
@ -557,7 +557,7 @@ func (ss *sqlStore) SetAlertNotificationStateToPendingCommand(ctx context.Contex
}
func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
nj := &models.AlertNotificationState{}
exist, err := getAlertNotificationState(ctx, sess, cmd, nj)
@ -604,7 +604,7 @@ func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *
})
}
func getAlertNotificationState(ctx context.Context, sess *sqlstore.DBSession, cmd *models.GetOrCreateNotificationStateQuery, nj *models.AlertNotificationState) (bool, error) {
func getAlertNotificationState(ctx context.Context, sess *db.Session, cmd *models.GetOrCreateNotificationStateQuery, nj *models.AlertNotificationState) (bool, error) {
return sess.
Where("alert_notification_state.org_id = ?", cmd.OrgId).
Where("alert_notification_state.alert_id = ?", cmd.AlertId).

View File

@ -8,10 +8,10 @@ import (
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/stretchr/testify/require"
)
@ -23,7 +23,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
var store *sqlStore
setup := func() {
store = &sqlStore{
db: sqlstore.InitTestDB(t),
db: db.InitTestDB(t),
log: log.New(),
cache: localcache.New(time.Minute, time.Minute)}
}

View File

@ -5,20 +5,19 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"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"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
"github.com/stretchr/testify/require"
)
func mockTimeNow() {
@ -47,7 +46,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
var items []*models.Alert
setup := func(t *testing.T) {
ss := sqlstore.InitTestDB(t)
ss := db.InitTestDB(t)
tagService := tagimpl.ProvideService(ss, ss.Cfg)
cfg := setting.NewCfg()
cfg.RBACEnabled = false
@ -264,7 +263,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
err := store.SaveAlerts(context.Background(), testDash.Id, items)
require.Nil(t, err)
err = store.db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = store.db.WithDbSession(context.Background(), func(sess *db.Session) error {
dash := models.Dashboard{Id: testDash.Id, OrgId: 1}
_, err := sess.Delete(dash)
return err
@ -289,7 +288,7 @@ func TestIntegrationPausingAlerts(t *testing.T) {
defer resetTimeNow()
t.Run("Given an alert", func(t *testing.T) {
ss := sqlstore.InitTestDB(t)
ss := db.InitTestDB(t)
sqlStore := sqlStore{db: ss, log: log.New(), tagService: tagimpl.ProvideService(ss, ss.Cfg)}
testDash := insertTestDashboard(t, sqlStore.db, "dashboard with alerts", 1, 0, false, "alert")
@ -380,7 +379,7 @@ func (ss *sqlStore) pauseAllAlerts(t *testing.T, pauseState bool) error {
return err
}
func insertTestDashboard(t *testing.T, db db.DB, title string, orgId int64,
func insertTestDashboard(t *testing.T, store db.DB, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
t.Helper()
cmd := models.SaveDashboardCommand{
@ -395,7 +394,7 @@ func insertTestDashboard(t *testing.T, db db.DB, title string, orgId int64,
}
var dash *models.Dashboard
err := db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := store.WithDbSession(context.Background(), func(sess *db.Session) error {
dash = cmd.GetDashboardModel()
dash.SetVersion(1)
dash.Created = time.Now()
@ -410,7 +409,7 @@ func insertTestDashboard(t *testing.T, db db.DB, title string, orgId int64,
dash.Data.Set("id", dash.Id)
dash.Data.Set("uid", dash.Uid)
err = db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = store.WithDbSession(context.Background(), func(sess *db.Session) error {
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.Id,
ParentVersion: dash.Version,

View File

@ -3,9 +3,9 @@ package annotationsimpl
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/tag"
"github.com/grafana/grafana/pkg/setting"
)

View File

@ -3,8 +3,8 @@ package annotationsimpl
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/setting"
)

View File

@ -5,19 +5,20 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/setting"
)
func TestAnnotationCleanUp(t *testing.T) {
fakeSQL := sqlstore.InitTestDB(t)
fakeSQL := db.InitTestDB(t)
t.Cleanup(func() {
err := fakeSQL.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(session *db.Session) error {
_, err := session.Exec("DELETE FROM annotation")
return err
})
@ -111,10 +112,10 @@ func TestAnnotationCleanUp(t *testing.T) {
}
func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
fakeSQL := sqlstore.InitTestDB(t)
fakeSQL := db.InitTestDB(t)
t.Cleanup(func() {
err := fakeSQL.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(session *db.Session) error {
_, err := session.Exec("DELETE FROM annotation")
return err
})
@ -132,7 +133,7 @@ func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
Created: time.Now().AddDate(-10, 0, -10).UnixNano() / int64(time.Millisecond),
}
err := fakeSQL.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(sess *db.Session) error {
_, err := sess.Insert(a)
require.NoError(t, err, "cannot insert annotation")
_, err = sess.Insert(a)
@ -163,10 +164,10 @@ func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
require.NoError(t, err)
}
func assertAnnotationCount(t *testing.T, fakeSQL *sqlstore.SQLStore, sql string, expectedCount int64) {
func assertAnnotationCount(t *testing.T, fakeSQL db.DB, sql string, expectedCount int64) {
t.Helper()
err := fakeSQL.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(sess *db.Session) error {
count, err := sess.Where(sql).Count(&annotations.Item{})
require.NoError(t, err)
require.Equal(t, expectedCount, count)
@ -175,10 +176,10 @@ func assertAnnotationCount(t *testing.T, fakeSQL *sqlstore.SQLStore, sql string,
require.NoError(t, err)
}
func assertAnnotationTagCount(t *testing.T, fakeSQL *sqlstore.SQLStore, expectedCount int64) {
func assertAnnotationTagCount(t *testing.T, fakeSQL db.DB, expectedCount int64) {
t.Helper()
err := fakeSQL.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(sess *db.Session) error {
count, err := sess.SQL("select count(*) from annotation_tag").Count()
require.NoError(t, err)
require.Equal(t, expectedCount, count)
@ -187,7 +188,7 @@ func assertAnnotationTagCount(t *testing.T, fakeSQL *sqlstore.SQLStore, expected
require.NoError(t, err)
}
func createTestAnnotations(t *testing.T, store *sqlstore.SQLStore, expectedCount int, oldAnnotations int) {
func createTestAnnotations(t *testing.T, store db.DB, expectedCount int, oldAnnotations int) {
t.Helper()
cutoffDate := time.Now()
@ -221,7 +222,7 @@ func createTestAnnotations(t *testing.T, store *sqlstore.SQLStore, expectedCount
a.Created = cutoffDate.AddDate(-10, 0, -10).UnixNano() / int64(time.Millisecond)
}
err := store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := store.WithDbSession(context.Background(), func(sess *db.Session) error {
_, err := sess.Insert(a)
require.NoError(t, err, "should be able to save annotation", err)

View File

@ -8,12 +8,11 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/permissions"
"github.com/grafana/grafana/pkg/services/sqlstore/searchstore"
"github.com/grafana/grafana/pkg/services/tag"
@ -60,7 +59,7 @@ func (r *xormRepositoryImpl) Add(ctx context.Context, item *annotations.Item) er
return err
}
return r.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return r.db.WithDbSession(ctx, func(sess *db.Session) error {
if _, err := sess.Table("annotation").Insert(item); err != nil {
return err
}
@ -81,7 +80,7 @@ func (r *xormRepositoryImpl) Add(ctx context.Context, item *annotations.Item) er
}
func (r *xormRepositoryImpl) Update(ctx context.Context, item *annotations.Item) error {
return r.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return r.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var (
isExist bool
err error
@ -137,7 +136,7 @@ func (r *xormRepositoryImpl) Get(ctx context.Context, query *annotations.ItemQue
var sql bytes.Buffer
params := make([]interface{}, 0)
items := make([]*annotations.ItemDTO, 0)
err := r.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := r.db.WithDbSession(ctx, func(sess *db.Session) error {
sql.WriteString(`
SELECT
annotation.id,
@ -293,7 +292,7 @@ func getAccessControlFilter(user *user.SignedInUser) (string, []interface{}, err
}
func (r *xormRepositoryImpl) Delete(ctx context.Context, params *annotations.DeleteParams) error {
return r.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return r.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var (
sql string
annoTagSQL string
@ -330,7 +329,7 @@ func (r *xormRepositoryImpl) Delete(ctx context.Context, params *annotations.Del
func (r *xormRepositoryImpl) GetTags(ctx context.Context, query *annotations.TagsQuery) (annotations.FindTagsResult, error) {
var items []*annotations.Tag
err := r.db.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := r.db.WithDbSession(ctx, func(dbSession *db.Session) error {
if query.Limit == 0 {
query.Limit = 100
}
@ -446,7 +445,7 @@ func (r *xormRepositoryImpl) executeUntilDoneOrCancelled(ctx context.Context, sq
return totalAffected, ctx.Err()
default:
var affected int64
err := r.db.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
err := r.db.WithDbSession(ctx, func(session *db.Session) error {
res, err := session.Exec(sql)
if err != nil {
return err

View File

@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/require"
"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/accesscontrol"
@ -17,7 +18,6 @@ import (
"github.com/grafana/grafana/pkg/services/dashboards"
dashboardstore "github.com/grafana/grafana/pkg/services/dashboards/database"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
@ -27,7 +27,7 @@ func TestIntegrationAnnotations(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sql := sqlstore.InitTestDB(t)
sql := db.InitTestDB(t)
var maximumTagsLength int64 = 60
repo := xormRepositoryImpl{db: sql, cfg: setting.NewCfg(), log: log.New("annotation.test"), tagService: tagimpl.ProvideService(sql, sql.Cfg), maximumTagsLength: maximumTagsLength}
@ -43,7 +43,7 @@ func TestIntegrationAnnotations(t *testing.T) {
t.Run("Testing annotation create, read, update and delete", func(t *testing.T) {
t.Cleanup(func() {
err := sql.WithDbSession(context.Background(), func(dbSession *sqlstore.DBSession) error {
err := sql.WithDbSession(context.Background(), func(dbSession *db.Session) error {
_, err := dbSession.Exec("DELETE FROM annotation WHERE 1=1")
if err != nil {
return err
@ -406,7 +406,7 @@ func TestIntegrationAnnotationListingWithRBAC(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sql := sqlstore.InitTestDB(t, sqlstore.InitTestDBOpt{})
sql := db.InitTestDB(t)
var maximumTagsLength int64 = 60
repo := xormRepositoryImpl{db: sql, cfg: setting.NewCfg(), log: log.New("annotation.test"), tagService: tagimpl.ProvideService(sql, sql.Cfg), maximumTagsLength: maximumTagsLength}
dashboardStore := dashboardstore.ProvideDashboardStore(sql, sql.Cfg, featuremgmt.WithFeatures(), tagimpl.ProvideService(sql, sql.Cfg))

View File

@ -3,8 +3,8 @@ package apikeyimpl
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/setting"
)

View File

@ -3,11 +3,12 @@ package apikeyimpl
import (
"testing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/setting"
)
func TestIntegrationSQLxApiKeyDataAccess(t *testing.T) {
testIntegrationApiKeyDataAccess(t, func(ss *sqlstore.SQLStore) store {
return &sqlxStore{sess: ss.GetSqlxSession(), cfg: ss.Cfg}
testIntegrationApiKeyDataAccess(t, func(ss db.DB, cfg *setting.Cfg) store {
return &sqlxStore{sess: ss.GetSqlxSession(), cfg: cfg}
})
}

View File

@ -9,13 +9,14 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
type getStore func(*sqlstore.SQLStore) store
type getStore func(db.DB, *setting.Cfg) store
type getApiKeysTestCase struct {
desc string
@ -59,8 +60,8 @@ func testIntegrationApiKeyDataAccess(t *testing.T, fn getStore) {
defer resetTimeNow()
t.Run("Testing API Key data access", func(t *testing.T) {
db := sqlstore.InitTestDB(t)
ss := fn(db)
db := db.InitTestDB(t)
ss := fn(db, db.Cfg)
t.Run("Given saved api key", func(t *testing.T) {
cmd := apikey.AddCommand{OrgId: 1, Name: "hello", Key: "asd"}
@ -198,8 +199,8 @@ func testIntegrationApiKeyDataAccess(t *testing.T, fn getStore) {
})
t.Run("Testing API Key errors", func(t *testing.T) {
db := sqlstore.InitTestDB(t)
ss := fn(db)
db := db.InitTestDB(t)
ss := fn(db, db.Cfg)
t.Run("Delete non-existing key should return error", func(t *testing.T) {
cmd := apikey.DeleteCommand{Id: 1}
@ -253,8 +254,8 @@ func testIntegrationApiKeyDataAccess(t *testing.T, fn getStore) {
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
db := sqlstore.InitTestDB(t, sqlstore.InitTestDBOpt{})
store := fn(db)
db := db.InitTestDB(t, db.InitTestDBOpt{})
store := fn(db, db.Cfg)
seedApiKeys(t, store, 10)
query := &apikey.GetApiKeysQuery{OrgId: 1, User: tt.user}

View File

@ -5,13 +5,13 @@ import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/setting"
"github.com/pkg/errors"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/setting"
)
type sqlStore struct {
@ -23,7 +23,7 @@ type sqlStore struct {
var timeNow = time.Now
func (ss *sqlStore) GetAPIKeys(ctx context.Context, query *apikey.GetApiKeysQuery) error {
return ss.db.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(dbSession *db.Session) error {
var sess *xorm.Session
if query.IncludeExpired {
@ -53,7 +53,7 @@ func (ss *sqlStore) GetAPIKeys(ctx context.Context, query *apikey.GetApiKeysQuer
func (ss *sqlStore) GetAllAPIKeys(ctx context.Context, orgID int64) ([]*apikey.APIKey, error) {
result := make([]*apikey.APIKey, 0)
err := ss.db.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := ss.db.WithDbSession(ctx, func(dbSession *db.Session) error {
sess := dbSession.Where("service_account_id IS NULL").Asc("name")
if orgID != -1 {
sess = sess.Where("org_id=?", orgID)
@ -64,7 +64,7 @@ func (ss *sqlStore) GetAllAPIKeys(ctx context.Context, orgID int64) ([]*apikey.A
}
func (ss *sqlStore) DeleteApiKey(ctx context.Context, cmd *apikey.DeleteCommand) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
rawSQL := "DELETE FROM api_key WHERE id=? and org_id=? and service_account_id IS NULL"
result, err := sess.Exec(rawSQL, cmd.Id, cmd.OrgId)
if err != nil {
@ -81,7 +81,7 @@ func (ss *sqlStore) DeleteApiKey(ctx context.Context, cmd *apikey.DeleteCommand)
}
func (ss *sqlStore) AddAPIKey(ctx context.Context, cmd *apikey.AddCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
key := apikey.APIKey{OrgId: cmd.OrgId, Name: cmd.Name}
exists, _ := sess.Get(&key)
if exists {
@ -119,7 +119,7 @@ func (ss *sqlStore) AddAPIKey(ctx context.Context, cmd *apikey.AddCommand) error
}
func (ss *sqlStore) GetApiKeyById(ctx context.Context, query *apikey.GetByIDQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var key apikey.APIKey
has, err := sess.ID(query.ApiKeyId).Get(&key)
@ -135,7 +135,7 @@ func (ss *sqlStore) GetApiKeyById(ctx context.Context, query *apikey.GetByIDQuer
}
func (ss *sqlStore) GetApiKeyByName(ctx context.Context, query *apikey.GetByNameQuery) error {
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var key apikey.APIKey
has, err := sess.Where("org_id=? AND name=?", query.OrgId, query.KeyName).Get(&key)
@ -152,7 +152,7 @@ func (ss *sqlStore) GetApiKeyByName(ctx context.Context, query *apikey.GetByName
func (ss *sqlStore) GetAPIKeyByHash(ctx context.Context, hash string) (*apikey.APIKey, error) {
var key apikey.APIKey
err := ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table("api_key").Where(fmt.Sprintf("%s = ?", ss.db.GetDialect().Quote("key")), hash).Get(&key)
if err != nil {
return err
@ -166,7 +166,7 @@ func (ss *sqlStore) GetAPIKeyByHash(ctx context.Context, hash string) (*apikey.A
func (ss *sqlStore) UpdateAPIKeyLastUsedDate(ctx context.Context, tokenID int64) error {
now := timeNow()
return ss.db.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
if _, err := sess.Table("api_key").ID(tokenID).Cols("last_used_at").Update(&apikey.APIKey{LastUsedAt: &now}); err != nil {
return err
}

View File

@ -3,11 +3,12 @@ package apikeyimpl
import (
"testing"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/setting"
)
func TestIntegrationXORMApiKeyDataAccess(t *testing.T) {
testIntegrationApiKeyDataAccess(t, func(ss *sqlstore.SQLStore) store {
return &sqlStore{db: ss, cfg: ss.Cfg}
testIntegrationApiKeyDataAccess(t, func(ss db.DB, cfg *setting.Cfg) store {
return &sqlStore{db: ss, cfg: cfg}
})
}

View File

@ -8,11 +8,10 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/serverlock"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/serverlock"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
@ -24,7 +23,7 @@ var getTime = time.Now
const urgentRotateTime = 1 * time.Minute
func ProvideUserAuthTokenService(sqlStore *sqlstore.SQLStore, serverLockService *serverlock.ServerLockService,
func ProvideUserAuthTokenService(sqlStore db.DB, serverLockService *serverlock.ServerLockService,
cfg *setting.Cfg) *UserAuthTokenService {
s := &UserAuthTokenService{
SQLStore: sqlStore,
@ -36,7 +35,7 @@ func ProvideUserAuthTokenService(sqlStore *sqlstore.SQLStore, serverLockService
}
type UserAuthTokenService struct {
SQLStore *sqlstore.SQLStore
SQLStore db.DB
ServerLockService *serverlock.ServerLockService
Cfg *setting.Cfg
log log.Logger
@ -44,10 +43,10 @@ type UserAuthTokenService struct {
type ActiveAuthTokenService struct {
cfg *setting.Cfg
sqlStore sqlstore.Store
sqlStore db.DB
}
func ProvideActiveAuthTokenService(cfg *setting.Cfg, sqlStore sqlstore.Store) *ActiveAuthTokenService {
func ProvideActiveAuthTokenService(cfg *setting.Cfg, sqlStore db.DB) *ActiveAuthTokenService {
return &ActiveAuthTokenService{
cfg: cfg,
sqlStore: sqlStore,
@ -57,7 +56,7 @@ func ProvideActiveAuthTokenService(cfg *setting.Cfg, sqlStore sqlstore.Store) *A
func (a *ActiveAuthTokenService) ActiveTokenCount(ctx context.Context) (int64, error) {
var count int64
var err error
err = a.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = a.sqlStore.WithDbSession(ctx, func(dbSession *db.Session) error {
var model userAuthToken
count, err = dbSession.Where(`created_at > ? AND rotated_at > ? AND revoked_at = 0`,
getTime().Add(-a.cfg.LoginMaxLifetime).Unix(),
@ -98,7 +97,7 @@ func (s *UserAuthTokenService) CreateToken(ctx context.Context, user *user.User,
AuthTokenSeen: false,
}
err = s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
_, err = dbSession.Insert(&userAuthToken)
return err
})
@ -123,7 +122,7 @@ func (s *UserAuthTokenService) LookupToken(ctx context.Context, unhashedToken st
var model userAuthToken
var exists bool
var err error
err = s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
exists, err = dbSession.Where("(auth_token = ? OR prev_auth_token = ?)",
hashedToken,
hashedToken).
@ -163,7 +162,7 @@ func (s *UserAuthTokenService) LookupToken(ctx context.Context, unhashedToken st
expireBefore := getTime().Add(-urgentRotateTime).Unix()
var affectedRows int64
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
affectedRows, err = dbSession.Where("id = ? AND prev_auth_token = ? AND rotated_at < ?",
modelCopy.Id,
modelCopy.PrevAuthToken,
@ -190,7 +189,7 @@ func (s *UserAuthTokenService) LookupToken(ctx context.Context, unhashedToken st
modelCopy.SeenAt = getTime().Unix()
var affectedRows int64
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
affectedRows, err = dbSession.Where("id = ? AND auth_token = ?",
modelCopy.Id,
modelCopy.AuthToken).
@ -274,9 +273,9 @@ func (s *UserAuthTokenService) TryRotateToken(ctx context.Context, token *models
WHERE id = ? AND (auth_token_seen = ? OR rotated_at < ?)`
var affected int64
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
res, err := dbSession.Exec(sql, userAgent, clientIPStr, s.SQLStore.Dialect.BooleanStr(true), hashedToken,
s.SQLStore.Dialect.BooleanStr(false), now.Unix(), model.Id, s.SQLStore.Dialect.BooleanStr(true),
err = s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
res, err := dbSession.Exec(sql, userAgent, clientIPStr, s.SQLStore.GetDialect().BooleanStr(true), hashedToken,
s.SQLStore.GetDialect().BooleanStr(false), now.Unix(), model.Id, s.SQLStore.GetDialect().BooleanStr(true),
now.Add(-30*time.Second).Unix())
if err != nil {
return err
@ -316,12 +315,12 @@ func (s *UserAuthTokenService) RevokeToken(ctx context.Context, token *models.Us
if soft {
model.RevokedAt = getTime().Unix()
err = s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
rowsAffected, err = dbSession.ID(model.Id).Update(model)
return err
})
} else {
err = s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err = s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
rowsAffected, err = dbSession.Delete(model)
return err
})
@ -344,7 +343,7 @@ func (s *UserAuthTokenService) RevokeToken(ctx context.Context, token *models.Us
}
func (s *UserAuthTokenService) RevokeAllUserTokens(ctx context.Context, userId int64) error {
return s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `DELETE from user_auth_token WHERE user_id = ?`
res, err := dbSession.Exec(sql, userId)
if err != nil {
@ -363,7 +362,7 @@ func (s *UserAuthTokenService) RevokeAllUserTokens(ctx context.Context, userId i
}
func (s *UserAuthTokenService) BatchRevokeAllUserTokens(ctx context.Context, userIds []int64) error {
return s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
if len(userIds) == 0 {
return nil
}
@ -394,7 +393,7 @@ func (s *UserAuthTokenService) BatchRevokeAllUserTokens(ctx context.Context, use
func (s *UserAuthTokenService) GetUserToken(ctx context.Context, userId, userTokenId int64) (*models.UserToken, error) {
var result models.UserToken
err := s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
var token userAuthToken
exists, err := dbSession.Where("id = ? AND user_id = ?", userTokenId, userId).Get(&token)
if err != nil {
@ -413,7 +412,7 @@ func (s *UserAuthTokenService) GetUserToken(ctx context.Context, userId, userTok
func (s *UserAuthTokenService) GetUserTokens(ctx context.Context, userId int64) ([]*models.UserToken, error) {
result := []*models.UserToken{}
err := s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
var tokens []*userAuthToken
err := dbSession.Where("user_id = ? AND created_at > ? AND rotated_at > ? AND revoked_at = 0",
userId,
@ -440,7 +439,7 @@ func (s *UserAuthTokenService) GetUserTokens(ctx context.Context, userId int64)
func (s *UserAuthTokenService) GetUserRevokedTokens(ctx context.Context, userId int64) ([]*models.UserToken, error) {
result := []*models.UserToken{}
err := s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
var tokens []*userAuthToken
err := dbSession.Where("user_id = ? AND revoked_at > 0", userId).Find(&tokens)
if err != nil {

View File

@ -8,15 +8,14 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/require"
"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/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/setting"
)
func TestUserAuthToken(t *testing.T) {
@ -533,7 +532,7 @@ func createTestContext(t *testing.T) *testContext {
t.Helper()
maxInactiveDurationVal, _ := time.ParseDuration("168h")
maxLifetimeDurationVal, _ := time.ParseDuration("720h")
sqlstore := sqlstore.InitTestDB(t)
sqlstore := db.InitTestDB(t)
cfg := &setting.Cfg{
LoginMaxInactiveLifetime: maxInactiveDurationVal,
@ -560,14 +559,14 @@ func createTestContext(t *testing.T) *testContext {
}
type testContext struct {
sqlstore *sqlstore.SQLStore
sqlstore db.DB
tokenService *UserAuthTokenService
activeTokenService *ActiveAuthTokenService
}
func (c *testContext) getAuthTokenByID(id int64) (*userAuthToken, error) {
var res *userAuthToken
err := c.sqlstore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := c.sqlstore.WithDbSession(context.Background(), func(sess *db.Session) error {
var t userAuthToken
found, err := sess.ID(id).Get(&t)
if err != nil || !found {
@ -583,8 +582,8 @@ func (c *testContext) getAuthTokenByID(id int64) (*userAuthToken, error) {
func (c *testContext) markAuthTokenAsSeen(id int64) (bool, error) {
hasRowsAffected := false
err := c.sqlstore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
res, err := sess.Exec("UPDATE user_auth_token SET auth_token_seen = ? WHERE id = ?", c.sqlstore.Dialect.BooleanStr(true), id)
err := c.sqlstore.WithDbSession(context.Background(), func(sess *db.Session) error {
res, err := sess.Exec("UPDATE user_auth_token SET auth_token_seen = ? WHERE id = ?", c.sqlstore.GetDialect().BooleanStr(true), id)
if err != nil {
return err
}
@ -601,7 +600,7 @@ func (c *testContext) markAuthTokenAsSeen(id int64) (bool, error) {
func (c *testContext) updateRotatedAt(id, rotatedAt int64) (bool, error) {
hasRowsAffected := false
err := c.sqlstore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := c.sqlstore.WithDbSession(context.Background(), func(sess *db.Session) error {
res, err := sess.Exec("UPDATE user_auth_token SET rotated_at = ? WHERE id = ?", rotatedAt, id)
if err != nil {
return err

View File

@ -4,7 +4,7 @@ import (
"context"
"time"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/infra/db"
)
func (s *UserAuthTokenService) Run(ctx context.Context) error {
@ -46,7 +46,7 @@ func (s *UserAuthTokenService) deleteExpiredTokens(ctx context.Context, maxInact
s.log.Debug("starting cleanup of expired auth tokens", "createdBefore", createdBefore, "rotatedBefore", rotatedBefore)
var affected int64
err := s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `DELETE from user_auth_token WHERE created_at <= ? OR rotated_at <= ?`
res, err := dbSession.Exec(sql, createdBefore.Unix(), rotatedBefore.Unix())
if err != nil {

View File

@ -6,8 +6,9 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
)
func TestUserAuthTokenCleanup(t *testing.T) {
@ -22,7 +23,7 @@ func TestUserAuthTokenCleanup(t *testing.T) {
insertToken := func(ctx *testContext, token string, prev string, createdAt, rotatedAt int64) {
ut := userAuthToken{AuthToken: token, PrevAuthToken: prev, CreatedAt: createdAt, RotatedAt: rotatedAt, UserAgent: "", ClientIp: ""}
err := ctx.sqlstore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err := ctx.sqlstore.WithDbSession(context.Background(), func(sess *db.Session) error {
_, err := sess.Insert(&ut)
require.Nil(t, err)
return nil

View File

@ -12,6 +12,7 @@ import (
"go.opentelemetry.io/otel/attribute"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/serverlock"
"github.com/grafana/grafana/pkg/infra/tracing"
@ -23,13 +24,12 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/image"
"github.com/grafana/grafana/pkg/services/queryhistory"
"github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/services/sqlstore"
tempuser "github.com/grafana/grafana/pkg/services/temp_user"
"github.com/grafana/grafana/pkg/setting"
)
func ProvideService(cfg *setting.Cfg, serverLockService *serverlock.ServerLockService,
shortURLService shorturls.Service, sqlstore *sqlstore.SQLStore, queryHistoryService queryhistory.Service,
shortURLService shorturls.Service, sqlstore db.DB, queryHistoryService queryhistory.Service,
dashboardVersionService dashver.Service, dashSnapSvc dashboardsnapshots.Service, deleteExpiredImageService *image.DeleteExpiredService,
loginAttemptService loginattempt.Service, tempUserService tempuser.Service, tracer tracing.Tracer, annotationCleaner annotations.Cleaner) *CleanUpService {
s := &CleanUpService{
@ -53,7 +53,7 @@ func ProvideService(cfg *setting.Cfg, serverLockService *serverlock.ServerLockSe
type CleanUpService struct {
log log.Logger
tracer tracing.Tracer
store sqlstore.Store
store db.DB
Cfg *setting.Cfg
ServerLockService *serverlock.ServerLockService
ShortURLService shorturls.Service

View File

@ -4,13 +4,13 @@ import (
"context"
"strconv"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/user"
)

View File

@ -3,13 +3,13 @@ package comments
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/comments/commentmodel"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/live"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
@ -17,13 +17,13 @@ import (
type Service struct {
cfg *setting.Cfg
live *live.GrafanaLive
sqlStore *sqlstore.SQLStore
sqlStore db.DB
storage Storage
permissions *commentmodel.PermissionChecker
userService user.Service
}
func ProvideService(cfg *setting.Cfg, store *sqlstore.SQLStore, live *live.GrafanaLive,
func ProvideService(cfg *setting.Cfg, store db.DB, live *live.GrafanaLive,
features featuremgmt.FeatureToggles, accessControl accesscontrol.AccessControl,
dashboardService dashboards.DashboardService, userService user.Service, annotationsRepo annotations.Repository) *Service {
s := &Service{

View File

@ -4,9 +4,8 @@ import (
"context"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/comments/commentmodel"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
)
type sqlStorage struct {
@ -35,7 +34,7 @@ func (s *sqlStorage) Create(ctx context.Context, orgID int64, objectType string,
var result *commentmodel.Comment
return result, s.sql.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return result, s.sql.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
var group commentmodel.CommentGroup
has, err := dbSession.NoAutoCondition().Where(
"org_id=? AND object_type=? AND object_id=?",
@ -97,7 +96,7 @@ func (s *sqlStorage) Get(ctx context.Context, orgID int64, objectType string, ob
}
}
return result, s.sql.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return result, s.sql.WithTransactionalDbSession(ctx, func(dbSession *db.Session) error {
var group commentmodel.CommentGroup
has, err := dbSession.NoAutoCondition().Where(
"org_id=? AND object_type=? AND object_id=?",

View File

@ -5,15 +5,15 @@ import (
"strconv"
"testing"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/comments/commentmodel"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/stretchr/testify/require"
)
func createSqlStorage(t *testing.T) Storage {
t.Helper()
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
return &sqlStorage{
sql: sqlStore,
}

View File

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/infra/tracing"
@ -17,7 +18,6 @@ import (
"github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/grafana/grafana/pkg/setting"
@ -69,7 +69,7 @@ type fakeRenderService struct {
func getContextHandler(t *testing.T) *ContextHandler {
t.Helper()
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
cfg := setting.NewCfg()
cfg.RemoteCacheOptions = &setting.RemoteCacheOptions{
@ -108,7 +108,7 @@ func getContextHandler(t *testing.T) *ContextHandler {
}
type FakeGetSignUserStore struct {
sqlstore.Store
db.DB
}
func (f *FakeGetSignUserStore) GetSignedInUser(ctx context.Context, query *models.GetSignedInUserQuery) error {

View File

@ -13,6 +13,7 @@ import (
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models"
@ -20,7 +21,6 @@ import (
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/multildap"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
@ -55,13 +55,13 @@ type AuthProxy struct {
cfg *setting.Cfg
remoteCache *remotecache.RemoteCache
loginService login.Service
sqlStore sqlstore.Store
sqlStore db.DB
userService user.Service
logger log.Logger
}
func ProvideAuthProxy(cfg *setting.Cfg, remoteCache *remotecache.RemoteCache, loginService login.Service, userService user.Service, sqlStore sqlstore.Store) *AuthProxy {
func ProvideAuthProxy(cfg *setting.Cfg, remoteCache *remotecache.RemoteCache, loginService login.Service, userService user.Service, sqlStore db.DB) *AuthProxy {
return &AuthProxy{
cfg: cfg,
remoteCache: remoteCache,

View File

@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/components/apikeygen"
apikeygenprefix "github.com/grafana/grafana/pkg/components/apikeygenprefixed"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/network"
"github.com/grafana/grafana/pkg/infra/remotecache"
@ -27,7 +28,6 @@ import (
"github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
@ -43,7 +43,7 @@ const (
const ServiceName = "ContextHandler"
func ProvideService(cfg *setting.Cfg, tokenService models.UserTokenService, jwtService models.JWTService,
remoteCache *remotecache.RemoteCache, renderService rendering.Service, sqlStore sqlstore.Store,
remoteCache *remotecache.RemoteCache, renderService rendering.Service, sqlStore db.DB,
tracer tracing.Tracer, authProxy *authproxy.AuthProxy, loginService login.Service,
apiKeyService apikey.Service, authenticator loginpkg.Authenticator, userService user.Service,
orgService org.Service, oauthTokenService oauthtoken.OAuthTokenService,
@ -73,7 +73,7 @@ type ContextHandler struct {
JWTAuthService models.JWTService
RemoteCache *remotecache.RemoteCache
RenderService rendering.Service
SQLStore sqlstore.Store
SQLStore db.DB
tracer tracing.Tracer
authProxy *authproxy.AuthProxy
authenticator loginpkg.Authenticator

View File

@ -7,10 +7,10 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
)
func ProvideService(sqlStore db.DB, routeRegister routing.RouteRegister, ds datasources.DataSourceService, ac accesscontrol.AccessControl, bus bus.Bus) *CorrelationsService {

View File

@ -3,8 +3,8 @@ package correlations
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/util"
)
@ -19,7 +19,7 @@ func (s CorrelationsService) createCorrelation(ctx context.Context, cmd CreateCo
Config: cmd.Config,
}
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *sqlstore.DBSession) error {
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
var err error
query := &datasources.GetDataSourceQuery{
@ -59,7 +59,7 @@ func (s CorrelationsService) createCorrelation(ctx context.Context, cmd CreateCo
}
func (s CorrelationsService) deleteCorrelation(ctx context.Context, cmd DeleteCorrelationCommand) error {
return s.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
query := &datasources.GetDataSourceQuery{
OrgId: cmd.OrgId,
Uid: cmd.SourceUID,
@ -86,7 +86,7 @@ func (s CorrelationsService) updateCorrelation(ctx context.Context, cmd UpdateCo
SourceUID: cmd.SourceUID,
}
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *sqlstore.DBSession) error {
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
query := &datasources.GetDataSourceQuery{
OrgId: cmd.OrgId,
Uid: cmd.SourceUID,
@ -148,7 +148,7 @@ func (s CorrelationsService) getCorrelation(ctx context.Context, cmd GetCorrelat
SourceUID: cmd.SourceUID,
}
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *sqlstore.DBSession) error {
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
query := &datasources.GetDataSourceQuery{
OrgId: cmd.OrgId,
Uid: cmd.SourceUID,
@ -174,7 +174,7 @@ func (s CorrelationsService) getCorrelation(ctx context.Context, cmd GetCorrelat
func (s CorrelationsService) getCorrelationsBySourceUID(ctx context.Context, cmd GetCorrelationsBySourceUIDQuery) ([]Correlation, error) {
correlations := make([]Correlation, 0)
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *sqlstore.DBSession) error {
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
query := &datasources.GetDataSourceQuery{
OrgId: cmd.OrgId,
Uid: cmd.SourceUID,
@ -196,7 +196,7 @@ func (s CorrelationsService) getCorrelationsBySourceUID(ctx context.Context, cmd
func (s CorrelationsService) getCorrelations(ctx context.Context, cmd GetCorrelationsQuery) ([]Correlation, error) {
correlations := make([]Correlation, 0)
err := s.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
return session.Select("correlation.*").Join("", "data_source AS dss", "correlation.source_uid = dss.uid and dss.org_id = ?", cmd.OrgId).Join("", "data_source AS dst", "correlation.target_uid = dst.uid and dst.org_id = ?", cmd.OrgId).Find(&correlations)
})
if err != nil {
@ -207,14 +207,14 @@ func (s CorrelationsService) getCorrelations(ctx context.Context, cmd GetCorrela
}
func (s CorrelationsService) deleteCorrelationsBySourceUID(ctx context.Context, cmd DeleteCorrelationsBySourceUIDCommand) error {
return s.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
_, err := session.Delete(&Correlation{SourceUID: cmd.SourceUID})
return err
})
}
func (s CorrelationsService) deleteCorrelationsByTargetUID(ctx context.Context, cmd DeleteCorrelationsByTargetUIDCommand) error {
return s.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
_, err := session.Delete(&Correlation{TargetUID: &cmd.TargetUID})
return err
})

View File

@ -3,9 +3,9 @@ package database
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
// GetDashboardACLInfoList returns a list of permissions for a dashboard. They can be fetched from three
@ -14,9 +14,9 @@ import (
// 2) permissions for its parent folder
// 3) if no specific permissions have been set for the dashboard or its parent folder then get the default permissions
func (d *DashboardStore) GetDashboardACLInfoList(ctx context.Context, query *models.GetDashboardACLInfoListQuery) error {
outerErr := d.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
outerErr := d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
query.Result = make([]*models.DashboardACLInfoDTO, 0)
falseStr := d.sqlStore.GetDialect().BooleanStr(false)
falseStr := d.store.GetDialect().BooleanStr(false)
if query.DashboardID == 0 {
sql := `SELECT
@ -62,7 +62,7 @@ func (d *DashboardStore) GetDashboardACLInfoList(ctx context.Context, query *mod
d.slug,
d.uid,
d.is_folder,
CASE WHEN (da.dashboard_id = -1 AND d.folder_id > 0) OR da.dashboard_id = d.folder_id THEN ` + d.sqlStore.GetDialect().BooleanStr(true) + ` ELSE ` + falseStr + ` END AS inherited
CASE WHEN (da.dashboard_id = -1 AND d.folder_id > 0) OR da.dashboard_id = d.folder_id THEN ` + d.store.GetDialect().BooleanStr(true) + ` ELSE ` + falseStr + ` END AS inherited
FROM dashboard as d
LEFT JOIN dashboard folder on folder.id = d.folder_id
LEFT JOIN dashboard_acl AS da ON
@ -75,7 +75,7 @@ func (d *DashboardStore) GetDashboardACLInfoList(ctx context.Context, query *mod
(folder.id IS NULL AND d.has_acl = ` + falseStr + `)
)
)
LEFT JOIN ` + d.sqlStore.GetDialect().Quote("user") + ` AS u ON u.id = da.user_id
LEFT JOIN ` + d.store.GetDialect().Quote("user") + ` AS u ON u.id = da.user_id
LEFT JOIN team ug on ug.id = da.team_id
WHERE d.org_id = ? AND d.id = ? AND da.id IS NOT NULL
ORDER BY da.id ASC
@ -97,15 +97,15 @@ func (d *DashboardStore) GetDashboardACLInfoList(ctx context.Context, query *mod
// HasEditPermissionInFolders validates that an user have access to a certain folder
func (d *DashboardStore) HasEditPermissionInFolders(ctx context.Context, query *models.HasEditPermissionInFoldersQuery) error {
return d.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
if query.SignedInUser.HasRole(org.RoleEditor) {
query.Result = true
return nil
}
builder := sqlstore.NewSqlBuilder(d.cfg)
builder := db.NewSqlBuilder(d.cfg)
builder.Write("SELECT COUNT(dashboard.id) AS count FROM dashboard WHERE dashboard.org_id = ? AND dashboard.is_folder = ?",
query.SignedInUser.OrgID, d.sqlStore.GetDialect().BooleanStr(true))
query.SignedInUser.OrgID, d.store.GetDialect().BooleanStr(true))
builder.WriteDashboardPermissionFilter(query.SignedInUser, models.PERMISSION_EDIT)
type folderCount struct {
@ -125,13 +125,13 @@ func (d *DashboardStore) HasEditPermissionInFolders(ctx context.Context, query *
}
func (d *DashboardStore) HasAdminPermissionInDashboardsOrFolders(ctx context.Context, query *models.HasAdminPermissionInDashboardsOrFoldersQuery) error {
return d.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
if query.SignedInUser.HasRole(org.RoleAdmin) {
query.Result = true
return nil
}
builder := sqlstore.NewSqlBuilder(d.cfg)
builder := db.NewSqlBuilder(d.cfg)
builder.Write("SELECT COUNT(dashboard.id) AS count FROM dashboard WHERE dashboard.org_id = ?", query.SignedInUser.OrgID)
builder.WriteDashboardPermissionFilter(query.SignedInUser, models.PERMISSION_ADMIN)
@ -151,7 +151,7 @@ func (d *DashboardStore) HasAdminPermissionInDashboardsOrFolders(ctx context.Con
}
func (d *DashboardStore) DeleteACLByUser(ctx context.Context, userID int64) error {
return d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var rawSQL = "DELETE FROM dashboard_acl WHERE user_id = ?"
_, err := sess.Exec(rawSQL, userID)
return err

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
@ -24,7 +25,7 @@ func TestIntegrationDashboardACLDataAccess(t *testing.T) {
var dashboardStore *DashboardStore
setup := func(t *testing.T) {
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
dashboardStore = ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
currentUser = createUser(t, sqlStore, "viewer", "Viewer", false)
savedFolder = insertTestDashboard(t, dashboardStore, "1 test dash folder", 1, 0, true, "prod", "webapp")
@ -237,7 +238,7 @@ func TestIntegrationDashboardACLDataAccess(t *testing.T) {
t.Run("Default permissions for root folder dashboards", func(t *testing.T) {
setup(t)
var rootFolderId int64 = 0
//sqlStore := sqlstore.InitTestDB(t)
//sqlStore := db.InitTestDB(t)
query := models.GetDashboardACLInfoListQuery{DashboardID: rootFolderId, OrgID: 1}

View File

@ -8,6 +8,7 @@ import (
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
@ -15,8 +16,6 @@ import (
"github.com/grafana/grafana/pkg/services/dashboards"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/sqlstore/permissions"
"github.com/grafana/grafana/pkg/services/sqlstore/searchstore"
@ -27,18 +26,24 @@ import (
)
type DashboardStore struct {
sqlStore db.DB
store db.DB
cfg *setting.Cfg
log log.Logger
features featuremgmt.FeatureToggles
tagService tag.Service
}
type DashboardTag struct {
Id int64
DashboardId int64
Term string
}
// DashboardStore implements the Store interface
var _ dashboards.Store = (*DashboardStore)(nil)
func ProvideDashboardStore(sqlStore db.DB, cfg *setting.Cfg, features featuremgmt.FeatureToggles, tagService tag.Service) *DashboardStore {
return &DashboardStore{sqlStore: sqlStore, cfg: cfg, log: log.New("dashboard-store"), features: features, tagService: tagService}
return &DashboardStore{store: sqlStore, cfg: cfg, log: log.New("dashboard-store"), features: features, tagService: tagService}
}
func (d *DashboardStore) emitEntityEvent() bool {
@ -47,14 +52,14 @@ func (d *DashboardStore) emitEntityEvent() bool {
func (d *DashboardStore) ValidateDashboardBeforeSave(ctx context.Context, dashboard *models.Dashboard, overwrite bool) (bool, error) {
isParentFolderChanged := false
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var err error
isParentFolderChanged, err = getExistingDashboardByIdOrUidForUpdate(sess, dashboard, d.sqlStore.GetDialect(), overwrite)
isParentFolderChanged, err = getExistingDashboardByIdOrUidForUpdate(sess, dashboard, d.store.GetDialect(), overwrite)
if err != nil {
return err
}
isParentFolderChanged, err = getExistingDashboardByTitleAndFolder(sess, dashboard, d.sqlStore.GetDialect(), overwrite,
isParentFolderChanged, err = getExistingDashboardByTitleAndFolder(sess, dashboard, d.store.GetDialect(), overwrite,
isParentFolderChanged)
if err != nil {
return err
@ -77,8 +82,8 @@ func (d *DashboardStore) GetFolderByTitle(ctx context.Context, orgID int64, titl
// there is a unique constraint on org_id, folder_id, title
// there are no nested folders so the parent folder id is always 0
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Title: title}
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.sqlStore.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
@ -94,8 +99,8 @@ func (d *DashboardStore) GetFolderByTitle(ctx context.Context, orgID int64, titl
func (d *DashboardStore) GetFolderByID(ctx context.Context, orgID int64, id int64) (*models.Folder, error) {
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Id: id}
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.sqlStore.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
@ -118,8 +123,8 @@ func (d *DashboardStore) GetFolderByUID(ctx context.Context, orgID int64, uid st
}
dashboard := models.Dashboard{OrgId: orgID, FolderId: 0, Uid: uid}
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.sqlStore.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
has, err := sess.Table(&models.Dashboard{}).Where("is_folder = " + d.store.GetDialect().BooleanStr(true)).Where("folder_id=0").Get(&dashboard)
if err != nil {
return err
}
@ -138,7 +143,7 @@ func (d *DashboardStore) GetFolderByUID(ctx context.Context, orgID int64, uid st
func (d *DashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*models.DashboardProvisioning, error) {
var data models.DashboardProvisioning
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", dashboardID).Get(&data)
return err
})
@ -151,7 +156,7 @@ func (d *DashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, da
func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*models.DashboardProvisioning, error) {
var provisionedDashboard models.DashboardProvisioning
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var dashboard models.Dashboard
exists, err := sess.Where("org_id = ? AND uid = ?", orgID, dashboardUID).Get(&dashboard)
if err != nil {
@ -174,14 +179,14 @@ func (d *DashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, o
func (d *DashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*models.DashboardProvisioning, error) {
var result []*models.DashboardProvisioning
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return sess.Where("name = ?", name).Find(&result)
})
return result, err
}
func (d *DashboardStore) SaveProvisionedDashboard(ctx context.Context, cmd models.SaveDashboardCommand, provisioning *models.DashboardProvisioning) (*models.Dashboard, error) {
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
if err := saveDashboard(sess, &cmd, d.emitEntityEvent()); err != nil {
return err
}
@ -197,14 +202,14 @@ func (d *DashboardStore) SaveProvisionedDashboard(ctx context.Context, cmd model
}
func (d *DashboardStore) SaveDashboard(ctx context.Context, cmd models.SaveDashboardCommand) (*models.Dashboard, error) {
err := d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return saveDashboard(sess, &cmd, d.emitEntityEvent())
})
return cmd.Result, err
}
func (d *DashboardStore) UpdateDashboardACL(ctx context.Context, dashboardID int64, items []*models.DashboardACL) error {
return d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
// delete existing items
_, err := sess.Exec("DELETE FROM dashboard_acl WHERE dashboard_id=?", dashboardID)
if err != nil {
@ -234,7 +239,7 @@ func (d *DashboardStore) UpdateDashboardACL(ctx context.Context, dashboardID int
}
func (d *DashboardStore) SaveAlerts(ctx context.Context, dashID int64, alerts []*models.Alert) error {
return d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existingAlerts, err := GetAlertsByDashboardId2(dashID, sess)
if err != nil {
return err
@ -255,14 +260,14 @@ func (d *DashboardStore) SaveAlerts(ctx context.Context, dashID int64, alerts []
// UnprovisionDashboard removes row in dashboard_provisioning for the dashboard making it seem as if manually created.
// The dashboard will still have `created_by = -1` to see it was not created by any particular user.
func (d *DashboardStore) UnprovisionDashboard(ctx context.Context, id int64) error {
return d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", id).Delete(&models.DashboardProvisioning{})
return err
})
}
func (d *DashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error {
return d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
var result []*models.DashboardProvisioning
convertedReaderNames := make([]interface{}, len(cmd.ReaderNames))
@ -286,7 +291,7 @@ func (d *DashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context
})
}
func getExistingDashboardByIdOrUidForUpdate(sess *sqlstore.DBSession, dash *models.Dashboard, dialect migrator.Dialect, overwrite bool) (bool, error) {
func getExistingDashboardByIdOrUidForUpdate(sess *db.Session, dash *models.Dashboard, dialect migrator.Dialect, overwrite bool) (bool, error) {
dashWithIdExists := false
isParentFolderChanged := false
var existingById models.Dashboard
@ -373,7 +378,7 @@ func getExistingDashboardByIdOrUidForUpdate(sess *sqlstore.DBSession, dash *mode
return isParentFolderChanged, nil
}
func getExistingDashboardByTitleAndFolder(sess *sqlstore.DBSession, dash *models.Dashboard, dialect migrator.Dialect, overwrite,
func getExistingDashboardByTitleAndFolder(sess *db.Session, dash *models.Dashboard, dialect migrator.Dialect, overwrite,
isParentFolderChanged bool) (bool, error) {
var existing models.Dashboard
exists, err := sess.Where("org_id=? AND slug=? AND (is_folder=? OR folder_id=?)", dash.OrgId, dash.Slug,
@ -407,7 +412,7 @@ func getExistingDashboardByTitleAndFolder(sess *sqlstore.DBSession, dash *models
return isParentFolderChanged, nil
}
func saveDashboard(sess *sqlstore.DBSession, cmd *models.SaveDashboardCommand, emitEntityEvent bool) error {
func saveDashboard(sess *db.Session, cmd *models.SaveDashboardCommand, emitEntityEvent bool) error {
dash := cmd.GetDashboardModel()
userId := cmd.UserId
@ -510,7 +515,7 @@ func saveDashboard(sess *sqlstore.DBSession, cmd *models.SaveDashboardCommand, e
tags := dash.GetTags()
if len(tags) > 0 {
for _, tag := range tags {
if _, err := sess.Insert(&sqlstore.DashboardTag{DashboardId: dash.Id, Term: tag}); err != nil {
if _, err := sess.Insert(DashboardTag{DashboardId: dash.Id, Term: tag}); err != nil {
return err
}
}
@ -527,7 +532,7 @@ func saveDashboard(sess *sqlstore.DBSession, cmd *models.SaveDashboardCommand, e
return nil
}
func generateNewDashboardUid(sess *sqlstore.DBSession, orgId int64) (string, error) {
func generateNewDashboardUid(sess *db.Session, orgId int64) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
@ -544,7 +549,7 @@ func generateNewDashboardUid(sess *sqlstore.DBSession, orgId int64) (string, err
return "", dashboards.ErrDashboardFailedGenerateUniqueUid
}
func saveProvisionedData(sess *sqlstore.DBSession, provisioning *models.DashboardProvisioning, dashboard *models.Dashboard) error {
func saveProvisionedData(sess *db.Session, provisioning *models.DashboardProvisioning, dashboard *models.Dashboard) error {
result := &models.DashboardProvisioning{}
exist, err := sess.Where("dashboard_id=? AND name = ?", dashboard.Id, provisioning.Name).Get(result)
@ -564,7 +569,7 @@ func saveProvisionedData(sess *sqlstore.DBSession, provisioning *models.Dashboar
return err
}
func GetAlertsByDashboardId2(dashboardId int64, sess *sqlstore.DBSession) ([]*models.Alert, error) {
func GetAlertsByDashboardId2(dashboardId int64, sess *db.Session) ([]*models.Alert, error) {
alerts := make([]*models.Alert, 0)
err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)
@ -576,7 +581,7 @@ func GetAlertsByDashboardId2(dashboardId int64, sess *sqlstore.DBSession) ([]*mo
}
func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*models.Alert, alerts []*models.Alert, log log.Logger) error {
return d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
for _, alert := range alerts {
update := false
var alertToUpdate *models.Alert
@ -636,7 +641,7 @@ func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*mod
})
}
func (d *DashboardStore) deleteMissingAlerts(alerts []*models.Alert, existingAlerts []*models.Alert, sess *sqlstore.DBSession) error {
func (d *DashboardStore) deleteMissingAlerts(alerts []*models.Alert, existingAlerts []*models.Alert, sess *db.Session) error {
for _, missingAlert := range alerts {
missing := true
@ -659,7 +664,7 @@ func (d *DashboardStore) deleteMissingAlerts(alerts []*models.Alert, existingAle
return nil
}
func (d *DashboardStore) deleteAlertByIdInternal(alertId int64, reason string, sess *sqlstore.DBSession) error {
func (d *DashboardStore) deleteAlertByIdInternal(alertId int64, reason string, sess *db.Session) error {
d.log.Debug("Deleting alert", "id", alertId, "reason", reason)
if _, err := sess.Exec("DELETE FROM alert WHERE id = ?", alertId); err != nil {
@ -682,9 +687,9 @@ func (d *DashboardStore) deleteAlertByIdInternal(alertId int64, reason string, s
}
func (d *DashboardStore) GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error {
return d.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
var dashboards = make([]*models.Dashboard, 0)
whereExpr := "org_id=? AND plugin_id=? AND is_folder=" + d.sqlStore.GetDialect().BooleanStr(false)
whereExpr := "org_id=? AND plugin_id=? AND is_folder=" + d.store.GetDialect().BooleanStr(false)
err := dbSession.Where(whereExpr, query.OrgId, query.PluginId).Find(&dashboards)
query.Result = dashboards
@ -693,12 +698,12 @@ func (d *DashboardStore) GetDashboardsByPluginID(ctx context.Context, query *mod
}
func (d *DashboardStore) DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
return d.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return d.deleteDashboard(cmd, sess, d.emitEntityEvent())
})
}
func (d *DashboardStore) deleteDashboard(cmd *models.DeleteDashboardCommand, sess *sqlstore.DBSession, emitEntityEvent bool) error {
func (d *DashboardStore) deleteDashboard(cmd *models.DeleteDashboardCommand, sess *db.Session, emitEntityEvent bool) error {
dashboard := models.Dashboard{Id: cmd.Id, OrgId: cmd.OrgId}
has, err := sess.Get(&dashboard)
if err != nil {
@ -835,7 +840,7 @@ func createEntityEvent(dashboard *models.Dashboard, eventType store.EntityEventT
return entityEvent
}
func (d *DashboardStore) deleteAlertDefinition(dashboardId int64, sess *sqlstore.DBSession) error {
func (d *DashboardStore) deleteAlertDefinition(dashboardId int64, sess *db.Session) error {
alerts := make([]*models.Alert, 0)
if err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts); err != nil {
return err
@ -853,7 +858,7 @@ func (d *DashboardStore) deleteAlertDefinition(dashboardId int64, sess *sqlstore
}
func (d *DashboardStore) GetDashboard(ctx context.Context, query *models.GetDashboardQuery) (*models.Dashboard, error) {
err := d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
if query.Id == 0 && len(query.Slug) == 0 && len(query.Uid) == 0 {
return dashboards.ErrDashboardIdentifierNotSet
}
@ -877,7 +882,7 @@ func (d *DashboardStore) GetDashboard(ctx context.Context, query *models.GetDash
}
func (d *DashboardStore) GetDashboardUIDById(ctx context.Context, query *models.GetDashboardRefByIdQuery) error {
return d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
var rawSQL = `SELECT uid, slug from dashboard WHERE Id=?`
us := &models.DashboardRef{}
exists, err := sess.SQL(rawSQL, query.Id).Get(us)
@ -892,7 +897,7 @@ func (d *DashboardStore) GetDashboardUIDById(ctx context.Context, query *models.
}
func (d *DashboardStore) GetDashboards(ctx context.Context, query *models.GetDashboardsQuery) error {
return d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
if len(query.DashboardIds) == 0 && len(query.DashboardUIds) == 0 {
return models.ErrCommandValidationFailed
}
@ -916,7 +921,7 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
permissions.DashboardPermissionFilter{
OrgRole: query.SignedInUser.OrgRole,
OrgId: query.SignedInUser.OrgID,
Dialect: d.sqlStore.GetDialect(),
Dialect: d.store.GetDialect(),
UserId: query.SignedInUser.UserID,
PermissionLevel: query.Permission,
},
@ -956,11 +961,11 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
}
if len(query.Title) > 0 {
filters = append(filters, searchstore.TitleFilter{Dialect: d.sqlStore.GetDialect(), Title: query.Title})
filters = append(filters, searchstore.TitleFilter{Dialect: d.store.GetDialect(), Title: query.Title})
}
if len(query.Type) > 0 {
filters = append(filters, searchstore.TypeFilter{Dialect: d.sqlStore.GetDialect(), Type: query.Type})
filters = append(filters, searchstore.TypeFilter{Dialect: d.store.GetDialect(), Type: query.Type})
}
if len(query.FolderIds) > 0 {
@ -968,7 +973,7 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
}
var res []dashboards.DashboardSearchProjection
sb := &searchstore.Builder{Dialect: d.sqlStore.GetDialect(), Filters: filters}
sb := &searchstore.Builder{Dialect: d.store.GetDialect(), Filters: filters}
limit := query.Limit
if limit < 1 {
@ -982,7 +987,7 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
sql, params := sb.ToSQL(limit, page)
err := d.sqlStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
return sess.SQL(sql, params...).Find(&res)
})
@ -994,7 +999,7 @@ func (d *DashboardStore) FindDashboards(ctx context.Context, query *models.FindP
}
func (d *DashboardStore) GetDashboardTags(ctx context.Context, query *models.GetDashboardTagsQuery) error {
return d.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `SELECT
COUNT(*) as count,
term

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
@ -30,7 +31,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
var dashboardStore *DashboardStore
setup := func() {
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
sqlStore.Cfg.RBACEnabled = false
dashboardStore = ProvideDashboardStore(sqlStore, &setting.Cfg{}, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder = insertTestDashboard(t, dashboardStore, "1 test dash folder", 1, 0, true, "prod", "webapp")
@ -184,7 +185,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
var rootFolderId int64 = 0
setup2 := func() {
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder1 = insertTestDashboard(t, dashboardStore, "1 test dash folder", 1, 0, true, "prod")
folder2 = insertTestDashboard(t, dashboardStore, "2 test dash folder", 1, 0, true, "prod")
@ -289,7 +290,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
var adminUser, editorUser, viewerUser user.User
setup3 := func() {
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder1 = insertTestDashboard(t, dashboardStore, "1 test dash folder", 1, 0, true, "prod")
folder2 = insertTestDashboard(t, dashboardStore, "2 test dash folder", 1, 0, true, "prod")
@ -471,7 +472,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
title := "Very Unique Name"
var sqlStore *sqlstore.SQLStore
var folder1, folder2 *models.Dashboard
sqlStore = sqlstore.InitTestDB(t)
sqlStore = db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder2 = insertTestDashboard(t, dashboardStore, "TEST", orgId, 0, true, "prod")
_ = insertTestDashboard(t, dashboardStore, title, orgId, folder2.Id, false, "prod")
@ -486,7 +487,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
t.Run("GetFolderByUID", func(t *testing.T) {
var orgId int64 = 1
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder := insertTestDashboard(t, dashboardStore, "TEST", orgId, 0, true, "prod")
dash := insertTestDashboard(t, dashboardStore, "Very Unique Name", orgId, folder.Id, false, "prod")
@ -510,7 +511,7 @@ func TestIntegrationDashboardFolderDataAccess(t *testing.T) {
t.Run("GetFolderByID", func(t *testing.T) {
var orgId int64 = 1
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folder := insertTestDashboard(t, dashboardStore, "TEST", orgId, 0, true, "prod")
dash := insertTestDashboard(t, dashboardStore, "Very Unique Name", orgId, folder.Id, false, "prod")

View File

@ -8,8 +8,8 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
)
@ -17,7 +17,7 @@ func TestIntegrationDashboardProvisioningTest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
dashboardStore := ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
folderCmd := models.SaveDashboardCommand{

View File

@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
@ -29,14 +30,15 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
t.Skip("skipping integration test")
}
var sqlStore *sqlstore.SQLStore
var cfg *setting.Cfg
var savedFolder, savedDash, savedDash2 *models.Dashboard
var dashboardStore *DashboardStore
var starService star.Service
setup := func() {
sqlStore = sqlstore.InitTestDB(t)
starService = starimpl.ProvideService(sqlStore, sqlStore.Cfg)
dashboardStore = ProvideDashboardStore(sqlStore, sqlStore.Cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, sqlStore.Cfg))
sqlStore, cfg = db.InitTestDBwithCfg(t)
starService = starimpl.ProvideService(sqlStore, cfg)
dashboardStore = ProvideDashboardStore(sqlStore, cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, cfg))
savedFolder = insertTestDashboard(t, dashboardStore, "1 test dash folder", 1, 0, true, "prod", "webapp")
savedDash = insertTestDashboard(t, dashboardStore, "test dash 23", 1, savedFolder.Id, false, "prod", "webapp")
insertTestDashboard(t, dashboardStore, "test dash 45", 1, savedFolder.Id, false, "prod")
@ -249,7 +251,7 @@ func TestIntegrationDashboardDataAccess(t *testing.T) {
require.NoError(t, err)
require.Equal(t, len(res), 0)
err = sqlStore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
var existingRuleID int64
exists, err := sess.Table("alert_rule").Where("namespace_uid = (SELECT uid FROM dashboard WHERE id = ?)", savedFolder.Id).Cols("id").Get(&existingRuleID)
require.NoError(t, err)
@ -486,7 +488,7 @@ func TestIntegrationDashboardDataAccessGivenPluginWithImportedDashboards(t *test
if testing.Short() {
t.Skip("skipping integration test")
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
cfg := setting.NewCfg()
cfg.IsFeatureToggleEnabled = func(key string) bool { return false }
dashboardStore := ProvideDashboardStore(sqlStore, &setting.Cfg{}, testFeatureToggles, tagimpl.ProvideService(sqlStore, cfg))
@ -510,7 +512,7 @@ func TestIntegrationDashboard_SortingOptions(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
cfg := setting.NewCfg()
cfg.IsFeatureToggleEnabled = func(key string) bool { return false }
dashboardStore := ProvideDashboardStore(sqlStore, &setting.Cfg{}, testFeatureToggles, tagimpl.ProvideService(sqlStore, cfg))
@ -561,7 +563,7 @@ func TestIntegrationDashboard_Filter(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
cfg := setting.NewCfg()
cfg.IsFeatureToggleEnabled = func(key string) bool { return false }
dashboardStore := ProvideDashboardStore(sqlStore, cfg, testFeatureToggles, tagimpl.ProvideService(sqlStore, cfg))
@ -603,8 +605,8 @@ func TestIntegrationDashboard_Filter(t *testing.T) {
assert.Equal(t, dashB.Id, results[0].ID)
}
func insertTestRule(t *testing.T, sqlStore *sqlstore.SQLStore, foderOrgID int64, folderUID string) {
err := sqlStore.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
func insertTestRule(t *testing.T, sqlStore sqlstore.Store, foderOrgID int64, folderUID string) {
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
type alertQuery struct {
RefID string
DatasourceUID string
@ -683,6 +685,7 @@ func CreateUser(t *testing.T, sqlStore *sqlstore.SQLStore, name string, role str
sqlStore.Cfg.AutoAssignOrgRole = role
currentUserCmd := user.CreateUserCommand{Login: name, Email: name + "@test.com", Name: "a " + name, IsAdmin: isAdmin}
currentUser, err := sqlStore.CreateUser(context.Background(), currentUserCmd)
require.NoError(t, err)
q1 := models.GetUserOrgListQuery{UserId: currentUser.ID}
err = sqlStore.GetUserOrgList(context.Background(), &q1)

View File

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/models"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/alerting"
@ -16,8 +17,6 @@ import (
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/services/tag/tagimpl"
"github.com/grafana/grafana/pkg/services/team/teamtest"
"github.com/grafana/grafana/pkg/services/user"
@ -95,7 +94,7 @@ func TestIntegrationIntegratedDashboardService(t *testing.T) {
permissionScenario(t, "When creating a new dashboard in the General folder", canSave,
func(t *testing.T, sc *permissionScenarioContext) {
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
cmd := models.SaveDashboardCommand{
OrgId: testOrgID,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
@ -821,7 +820,7 @@ func permissionScenario(t *testing.T, desc string, canSave bool, fn permissionSc
cfg := setting.NewCfg()
cfg.RBACEnabled = false
cfg.IsFeatureToggleEnabled = featuremgmt.WithFeatures().IsEnabled
sqlStore := sqlstore.InitTestDB(t)
sqlStore := db.InitTestDB(t)
dashboardStore := database.ProvideDashboardStore(sqlStore, cfg, featuremgmt.WithFeatures(), tagimpl.ProvideService(sqlStore, cfg))
service := ProvideDashboardService(
cfg, dashboardStore, &dummyDashAlertExtractor{},

View File

@ -5,11 +5,10 @@ import (
"time"
"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/services/dashboardsnapshots"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/db"
"github.com/grafana/grafana/pkg/setting"
)
@ -29,7 +28,7 @@ func ProvideStore(db db.DB) *DashboardSnapshotStore {
// SnapShotRemoveExpired is deprecated and should be removed in the future.
// Snapshot expiry is decided by the user when they share the snapshot.
func (d *DashboardSnapshotStore) DeleteExpiredSnapshots(ctx context.Context, cmd *dashboardsnapshots.DeleteExpiredSnapshotsCommand) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
if !setting.SnapShotRemoveExpired {
d.log.Warn("[Deprecated] The snapshot_remove_expired setting is outdated. Please remove from your config.")
return nil
@ -47,7 +46,7 @@ func (d *DashboardSnapshotStore) DeleteExpiredSnapshots(ctx context.Context, cmd
}
func (d *DashboardSnapshotStore) CreateDashboardSnapshot(ctx context.Context, cmd *dashboardsnapshots.CreateDashboardSnapshotCommand) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var expires = time.Now().Add(time.Hour * 24 * 365 * 50)
if cmd.Expires > 0 {
expires = time.Now().Add(time.Second * time.Duration(cmd.Expires))
@ -76,7 +75,7 @@ func (d *DashboardSnapshotStore) CreateDashboardSnapshot(ctx context.Context, cm
}
func (d *DashboardSnapshotStore) DeleteDashboardSnapshot(ctx context.Context, cmd *dashboardsnapshots.DeleteDashboardSnapshotCommand) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var rawSQL = "DELETE FROM dashboard_snapshot WHERE delete_key=?"
_, err := sess.Exec(rawSQL, cmd.DeleteKey)
return err
@ -84,7 +83,7 @@ func (d *DashboardSnapshotStore) DeleteDashboardSnapshot(ctx context.Context, cm
}
func (d *DashboardSnapshotStore) GetDashboardSnapshot(ctx context.Context, query *dashboardsnapshots.GetDashboardSnapshotQuery) error {
return d.store.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
snapshot := dashboardsnapshots.DashboardSnapshot{Key: query.Key, DeleteKey: query.DeleteKey}
has, err := sess.Get(&snapshot)
@ -102,7 +101,7 @@ func (d *DashboardSnapshotStore) GetDashboardSnapshot(ctx context.Context, query
// SearchDashboardSnapshots returns a list of all snapshots for admins
// for other roles, it returns snapshots created by the user
func (d *DashboardSnapshotStore) SearchDashboardSnapshots(ctx context.Context, query *dashboardsnapshots.GetDashboardSnapshotsQuery) error {
return d.store.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
var snapshots = make(dashboardsnapshots.DashboardSnapshotsList, 0)
if query.Limit > 0 {
sess.Limit(query.Limit)

View File

@ -9,11 +9,11 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/dashboardsnapshots"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/secrets"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
@ -22,7 +22,7 @@ func TestIntegrationDashboardSnapshotDBAccess(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sqlstore := sqlstore.InitTestDB(t)
sqlstore := db.InitTestDB(t)
dashStore := ProvideStore(sqlstore)
origSecret := setting.SecretKey
@ -153,7 +153,7 @@ func TestIntegrationDeleteExpiredSnapshots(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sqlstore := sqlstore.InitTestDB(t)
sqlstore := db.InitTestDB(t)
dashStore := ProvideStore(sqlstore)
t.Run("Testing dashboard snapshots clean up", func(t *testing.T) {
@ -208,7 +208,7 @@ func createTestSnapshot(t *testing.T, dashStore *DashboardSnapshotStore, key str
// Set expiry date manually - to be able to create expired snapshots
if expires < 0 {
expireDate := time.Now().Add(time.Second * time.Duration(expires))
err = dashStore.store.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
err = dashStore.store.WithDbSession(context.Background(), func(sess *db.Session) error {
_, err := sess.Exec("UPDATE dashboard_snapshot SET expires = ? WHERE id = ?", expireDate, cmd.Result.Id)
return err
})

Some files were not shown because too many files have changed in this diff Show More