Chore: Fix SQL related Go variable naming (#28887)

* Chore: Fix variable naming

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Arve Knudsen 2020-11-11 06:21:08 +01:00 committed by GitHub
parent 7abf0506b1
commit b5379c5335
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 377 additions and 376 deletions

View File

@ -10,11 +10,11 @@ Grafana supports the [following databases](https://grafana.com/docs/installation
Grafana uses the [XORM](https://xorm.io) framework for persisting objects to the database. For more information on how to use XORM, refer to the [documentation](http://gobook.io/read/github.com/go-xorm/manual-en-US/).
[Services](services.md) don't use XORM directly. Instead, services use the _SQL store_, a special type of service that provides an abstraction for the database layer. There are two ways of using the `sqlstore`: using `sqlstore` handlers, and using the `SqlStore` instance.
[Services](services.md) don't use XORM directly. Instead, services use the _SQL store_, a special type of service that provides an abstraction for the database layer. There are two ways of using the `sqlstore`: using `sqlstore` handlers, and using the `SQLStore` instance.
## `sqlstore` handlers
> **Deprecated:** We are deprecating `sqlstore` handlers in favor of using the `SqlStore` object directly in each service. Since most services still use the `sqlstore` handlers, we still want to explain how they work.
> **Deprecated:** We are deprecating `sqlstore` handlers in favor of using the `SQLStore` object directly in each service. Since most services still use the `sqlstore` handlers, we still want to explain how they work.
The `sqlstore` package allows you to register [command handlers](communication.md#handle-commands) that either store, or retrieve objects from the database. `sqlstore` handlers are similar to services:
@ -46,15 +46,15 @@ func DeleteDashboard(cmd *models.DeleteDashboardCommand) error {
Here, `inTransaction` is a helper function in the `sqlstore` package that provides a session, that lets you execute SQL statements.
## `SqlStore`
## `SQLStore`
As opposed to a `sqlstore` handler, the `SqlStore` is a service itself. The `SqlStore` has the same responsibility however: to store and retrieve objects, to and from the database.
As opposed to a `sqlstore` handler, the `SQLStore` is a service itself. The `SQLStore` has the same responsibility however: to store and retrieve objects, to and from the database.
To use the `SqlStore`, inject the `SQLStore` in your service struct:
To use the `SQLStore`, inject it in your service struct:
```go
type MyService struct {
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
}
```

View File

@ -185,7 +185,7 @@ func GenerateError(c *models.ReqContext) Response {
// GET /api/tsdb/testdata/gensql
func GenerateSQLTestData(c *models.ReqContext) Response {
if err := bus.Dispatch(&models.InsertSqlTestDataCommand{}); err != nil {
if err := bus.Dispatch(&models.InsertSQLTestDataCommand{}); err != nil {
return Error(500, "Failed to insert test data", err)
}

View File

@ -14,7 +14,7 @@ import (
"github.com/urfave/cli/v2"
)
func runDbCommand(command func(commandLine utils.CommandLine, sqlStore *sqlstore.SqlStore) error) func(context *cli.Context) error {
func runDbCommand(command func(commandLine utils.CommandLine, sqlStore *sqlstore.SQLStore) error) func(context *cli.Context) error {
return func(context *cli.Context) error {
cmd := &utils.ContextCommandLine{Context: context}
debug := cmd.Bool("debug")
@ -34,7 +34,7 @@ func runDbCommand(command func(commandLine utils.CommandLine, sqlStore *sqlstore
cfg.LogConfigSources()
}
engine := &sqlstore.SqlStore{}
engine := &sqlstore.SQLStore{}
engine.Cfg = cfg
engine.Bus = bus.GetBus()
if err := engine.Init(); err != nil {

View File

@ -27,7 +27,7 @@ var (
// EncryptDatasourcePasswords migrates unencrypted secrets on datasources
// to the secureJson Column.
func EncryptDatasourcePasswords(c utils.CommandLine, sqlStore *sqlstore.SqlStore) error {
func EncryptDatasourcePasswords(c utils.CommandLine, sqlStore *sqlstore.SQLStore) error {
return sqlStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
passwordsUpdated, err := migrateColumn(session, "password")
if err != nil {

View File

@ -17,7 +17,7 @@ import (
const AdminUserId = 1
func resetPasswordCommand(c utils.CommandLine, sqlStore *sqlstore.SqlStore) error {
func resetPasswordCommand(c utils.CommandLine, sqlStore *sqlstore.SQLStore) error {
newPassword := ""
if c.Bool("password-from-stdin") {

View File

@ -13,11 +13,11 @@ var getTime = time.Now
const databaseCacheType = "database"
type databaseCache struct {
SQLStore *sqlstore.SqlStore
SQLStore *sqlstore.SQLStore
log log.Logger
}
func newDatabaseCache(sqlstore *sqlstore.SqlStore) *databaseCache {
func newDatabaseCache(sqlstore *sqlstore.SQLStore) *databaseCache {
dc := &databaseCache{
SQLStore: sqlstore,
log: log.New("remotecache.database"),

View File

@ -46,7 +46,7 @@ type CacheStorage interface {
type RemoteCache struct {
log log.Logger
client CacheStorage
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
Cfg *setting.Cfg `inject:""`
}
@ -89,7 +89,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 *sqlstore.SQLStore) (CacheStorage, error) {
if opts.Name == redisCacheType {
return newRedisStorage(opts)
}

View File

@ -19,7 +19,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 *sqlstore.SQLStore) CacheStorage {
t.Helper()
dc := &RemoteCache{

View File

@ -16,7 +16,7 @@ func init() {
// ServerLockService allows servers in HA mode to claim a lock
// and execute an function if the server was granted the lock
type ServerLockService struct {
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
log log.Logger
}

View File

@ -24,7 +24,7 @@ func init() {
type UsageStatsService struct {
Cfg *setting.Cfg `inject:""`
Bus bus.Bus `inject:""`
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
AlertingUsageStats alerting.UsageStatsQuerier `inject:""`
License models.Licensing `inject:""`

View File

@ -2,10 +2,10 @@ package models
import "time"
type InsertSqlTestDataCommand struct {
type InsertSQLTestDataCommand struct {
}
type SqlTestData struct {
type SQLTestData struct {
Id int64
Metric1 string
Metric2 string

View File

@ -26,7 +26,7 @@ var getTime = time.Now
const urgentRotateTime = 1 * time.Minute
type UserAuthTokenService struct {
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
ServerLockService *serverlock.ServerLockService `inject:""`
Cfg *setting.Cfg `inject:""`
log log.Logger

View File

@ -514,7 +514,7 @@ func createTestContext(t *testing.T) *testContext {
}
type testContext struct {
sqlstore *sqlstore.SqlStore
sqlstore *sqlstore.SQLStore
tokenService *UserAuthTokenService
}

View File

@ -16,7 +16,7 @@ type CacheService interface {
type CacheServiceImpl struct {
CacheService *localcache.CacheService `inject:""`
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
}
func init() {

View File

@ -17,7 +17,7 @@ func init() {
}
type ShortURLService struct {
SQLStore *sqlstore.SqlStore `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
}
func (s *ShortURLService) Init() error {

View File

@ -72,7 +72,7 @@ func deleteAlertByIdInternal(alertId int64, reason string, sess *DBSession) erro
}
func HandleAlertsQuery(query *models.GetAlertsQuery) error {
builder := SqlBuilder{}
builder := SQLBuilder{}
builder.Write(`SELECT
alert.id,
@ -135,7 +135,7 @@ func HandleAlertsQuery(query *models.GetAlertsQuery) error {
}
alerts := make([]*models.AlertListItemDTO, 0)
if err := x.SQL(builder.GetSqlString(), builder.params...).Find(&alerts); err != nil {
if err := x.SQL(builder.GetSQLString(), builder.params...).Find(&alerts); err != nil {
return err
}
@ -371,7 +371,7 @@ func PauseAllAlerts(cmd *models.PauseAllAlertCommand) error {
}
func GetAlertStatesForDashboard(query *models.GetAlertStatesForDashboardQuery) error {
var rawSql = `SELECT
var rawSQL = `SELECT
id,
dashboard_id,
panel_id,
@ -381,7 +381,7 @@ func GetAlertStatesForDashboard(query *models.GetAlertStatesForDashboardQuery) e
WHERE org_id = ? AND dashboard_id = ?`
query.Result = make([]*models.AlertStateInfoDTO, 0)
err := x.SQL(rawSql, query.OrgId, query.DashboardId).Find(&query.Result)
err := x.SQL(rawSQL, query.OrgId, query.DashboardId).Find(&query.Result)
return err
}

View File

@ -80,11 +80,11 @@ func GetAlertNotifications(query *models.GetAlertNotificationsQuery) error {
return getAlertNotificationInternal(query, newSession())
}
func (ss *SqlStore) addAlertNotificationUidByIdHandler() {
func (ss *SQLStore) addAlertNotificationUidByIdHandler() {
bus.AddHandler("sql", ss.GetAlertNotificationUidWithId)
}
func (ss *SqlStore) GetAlertNotificationUidWithId(query *models.GetAlertNotificationUidQuery) error {
func (ss *SQLStore) GetAlertNotificationUidWithId(query *models.GetAlertNotificationUidQuery) error {
cacheKey := newAlertNotificationUidCacheKey(query.OrgId, query.Id)
if cached, found := ss.CacheService.Get(cacheKey); found {

View File

@ -28,10 +28,10 @@ func validateTimeRange(item *annotations.Item) error {
return nil
}
type SqlAnnotationRepo struct {
type SQLAnnotationRepo struct {
}
func (r *SqlAnnotationRepo) Save(item *annotations.Item) error {
func (r *SQLAnnotationRepo) Save(item *annotations.Item) error {
return inTransaction(func(sess *DBSession) error {
tags := models.ParseTagPairs(item.Tags)
item.Tags = models.JoinTagPairs(tags)
@ -64,7 +64,7 @@ func (r *SqlAnnotationRepo) Save(item *annotations.Item) error {
})
}
func (r *SqlAnnotationRepo) Update(item *annotations.Item) error {
func (r *SQLAnnotationRepo) Update(item *annotations.Item) error {
return inTransaction(func(sess *DBSession) error {
var (
isExist bool
@ -117,7 +117,7 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error {
})
}
func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) {
func (r *SQLAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -234,26 +234,26 @@ func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.I
return items, nil
}
func (r *SqlAnnotationRepo) Delete(params *annotations.DeleteParams) error {
func (r *SQLAnnotationRepo) Delete(params *annotations.DeleteParams) error {
return inTransaction(func(sess *DBSession) error {
var (
sql string
annoTagSql string
annoTagSQL string
queryParams []interface{}
)
sqlog.Info("delete", "orgId", params.OrgId)
if params.Id != 0 {
annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE id = ? AND org_id = ?)"
annoTagSQL = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE id = ? AND org_id = ?)"
sql = "DELETE FROM annotation WHERE id = ? AND org_id = ?"
queryParams = []interface{}{params.Id, params.OrgId}
} else {
annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE dashboard_id = ? AND panel_id = ? AND org_id = ?)"
annoTagSQL = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE dashboard_id = ? AND panel_id = ? AND org_id = ?)"
sql = "DELETE FROM annotation WHERE dashboard_id = ? AND panel_id = ? AND org_id = ?"
queryParams = []interface{}{params.DashboardId, params.PanelId, params.OrgId}
}
sqlOrArgs := append([]interface{}{annoTagSql}, queryParams...)
sqlOrArgs := append([]interface{}{annoTagSQL}, queryParams...)
if _, err := sess.Exec(sqlOrArgs...); err != nil {
return err

View File

@ -8,6 +8,7 @@ import (
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -15,11 +16,11 @@ func TestAnnotationCleanUp(t *testing.T) {
fakeSQL := InitTestDB(t)
t.Cleanup(func() {
_ = fakeSQL.WithDbSession(context.Background(), func(session *DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(session *DBSession) error {
_, err := session.Exec("DELETE FROM annotation")
require.Nil(t, err, "cleaning up all annotations should not cause problems")
return err
})
assert.NoError(t, err)
})
createTestAnnotations(t, fakeSQL, 21, 6)
@ -95,11 +96,11 @@ func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
fakeSQL := InitTestDB(t)
t.Cleanup(func() {
_ = fakeSQL.WithDbSession(context.Background(), func(session *DBSession) error {
err := fakeSQL.WithDbSession(context.Background(), func(session *DBSession) error {
_, err := session.Exec("DELETE FROM annotation")
require.Nil(t, err, "cleaning up all annotations should not cause problems")
return err
})
assert.NoError(t, err)
})
// create some test annotations
@ -137,10 +138,10 @@ func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
countOld, err := session.Where("alert_id = 10").Count(&annotations.Item{})
require.NoError(t, err)
require.Equal(t, int64(0), countOld, "the two first annotations should have been deleted.")
require.Equal(t, int64(0), countOld, "the two first annotations should have been deleted")
}
func assertAnnotationCount(t *testing.T, fakeSQL *SqlStore, sql string, expectedCount int64) {
func assertAnnotationCount(t *testing.T, fakeSQL *SQLStore, sql string, expectedCount int64) {
t.Helper()
session := fakeSQL.NewSession()
@ -150,7 +151,7 @@ func assertAnnotationCount(t *testing.T, fakeSQL *SqlStore, sql string, expected
require.Equal(t, expectedCount, count)
}
func createTestAnnotations(t *testing.T, sqlstore *SqlStore, expectedCount int, oldAnnotations int) {
func createTestAnnotations(t *testing.T, sqlstore *SQLStore, expectedCount int, oldAnnotations int) {
t.Helper()
cutoffDate := time.Now()

View File

@ -15,7 +15,7 @@ func TestAnnotations(t *testing.T) {
mockTimeNow()
defer resetTimeNow()
InitTestDB(t)
repo := SqlAnnotationRepo{}
repo := SQLAnnotationRepo{}
t.Run("Testing annotation create, read, update and delete", func(t *testing.T) {
t.Cleanup(func() {

View File

@ -29,8 +29,8 @@ func GetApiKeys(query *models.GetApiKeysQuery) error {
func DeleteApiKeyCtx(ctx context.Context, cmd *models.DeleteApiKeyCommand) error {
return withDbSession(ctx, func(sess *DBSession) error {
var rawSql = "DELETE FROM api_key WHERE id=? and org_id=?"
_, err := sess.Exec(rawSql, cmd.Id, cmd.OrgId)
var rawSQL = "DELETE FROM api_key WHERE id=? and org_id=?"
_, err := sess.Exec(rawSQL, cmd.Id, cmd.OrgId)
return err
})
}

View File

@ -271,7 +271,7 @@ func findDashboards(query *search.FindPersistedDashboardsQuery) ([]DashboardSear
page = 1
}
sql, params := sb.ToSql(limit, page)
sql, params := sb.ToSQL(limit, page)
err := x.SQL(sql, params...).Find(&res)
if err != nil {
return nil, err
@ -522,10 +522,10 @@ type DashboardSlugDTO struct {
}
func GetDashboardSlugById(query *models.GetDashboardSlugByIdQuery) error {
var rawSql = `SELECT slug from dashboard WHERE Id=?`
var rawSQL = `SELECT slug from dashboard WHERE Id=?`
var slug = DashboardSlugDTO{}
exists, err := x.SQL(rawSql, query.Id).Get(&slug)
exists, err := x.SQL(rawSQL, query.Id).Get(&slug)
if err != nil {
return err
@ -549,11 +549,11 @@ func GetDashboardsBySlug(query *models.GetDashboardsBySlugQuery) error {
}
func GetDashboardUIDById(query *models.GetDashboardRefByIdQuery) error {
var rawSql = `SELECT uid, slug from dashboard WHERE Id=?`
var rawSQL = `SELECT uid, slug from dashboard WHERE Id=?`
us := &models.DashboardRef{}
exists, err := x.SQL(rawSql, query.Id).Get(us)
exists, err := x.SQL(rawSQL, query.Id).Get(us)
if err != nil {
return err
@ -710,7 +710,7 @@ func HasEditPermissionInFolders(query *models.HasEditPermissionInFoldersQuery) e
return nil
}
builder := &SqlBuilder{}
builder := &SQLBuilder{}
builder.Write("SELECT COUNT(dashboard.id) AS count FROM dashboard WHERE dashboard.org_id = ? AND dashboard.is_folder = ?", query.SignedInUser.OrgId, dialect.BooleanStr(true))
builder.writeDashboardPermissionFilter(query.SignedInUser, models.PERMISSION_EDIT)
@ -719,7 +719,7 @@ func HasEditPermissionInFolders(query *models.HasEditPermissionInFoldersQuery) e
}
resp := make([]*folderCount, 0)
if err := x.SQL(builder.GetSqlString(), builder.params...).Find(&resp); err != nil {
if err := x.SQL(builder.GetSQLString(), builder.params...).Find(&resp); err != nil {
return err
}
@ -734,7 +734,7 @@ func HasAdminPermissionInFolders(query *models.HasAdminPermissionInFoldersQuery)
return nil
}
builder := &SqlBuilder{}
builder := &SQLBuilder{}
builder.Write("SELECT COUNT(dashboard.id) AS count FROM dashboard WHERE dashboard.org_id = ? AND dashboard.is_folder = ?", query.SignedInUser.OrgId, dialect.BooleanStr(true))
builder.writeDashboardPermissionFilter(query.SignedInUser, models.PERMISSION_ADMIN)
@ -743,7 +743,7 @@ func HasAdminPermissionInFolders(query *models.HasAdminPermissionInFoldersQuery)
}
resp := make([]*folderCount, 0)
if err := x.SQL(builder.GetSqlString(), builder.params...).Find(&resp); err != nil {
if err := x.SQL(builder.GetSQLString(), builder.params...).Find(&resp); err != nil {
return err
}

View File

@ -28,8 +28,8 @@ func DeleteExpiredSnapshots(cmd *models.DeleteExpiredSnapshotsCommand) error {
return nil
}
deleteExpiredSql := "DELETE FROM dashboard_snapshot WHERE expires < ?"
expiredResponse, err := sess.Exec(deleteExpiredSql, time.Now())
deleteExpiredSQL := "DELETE FROM dashboard_snapshot WHERE expires < ?"
expiredResponse, err := sess.Exec(deleteExpiredSQL, time.Now())
if err != nil {
return err
}
@ -81,8 +81,8 @@ func CreateDashboardSnapshot(cmd *models.CreateDashboardSnapshotCommand) error {
func DeleteDashboardSnapshot(cmd *models.DeleteDashboardSnapshotCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM dashboard_snapshot WHERE delete_key=?"
_, err := sess.Exec(rawSql, cmd.DeleteKey)
var rawSQL = "DELETE FROM dashboard_snapshot WHERE delete_key=?"
_, err := sess.Exec(rawSQL, cmd.DeleteKey)
return err
})
}

View File

@ -165,7 +165,7 @@ func TestDeleteExpiredSnapshots(t *testing.T) {
})
}
func createTestSnapshot(t *testing.T, sqlstore *SqlStore, key string, expires int64) *models.DashboardSnapshot {
func createTestSnapshot(t *testing.T, sqlstore *SQLStore, key string, expires int64) *models.DashboardSnapshot {
cmd := models.CreateDashboardSnapshotCommand{
Key: key,
DeleteKey: "delete" + key,

View File

@ -108,8 +108,8 @@ func deleteExpiredVersions(cmd *models.DeleteExpiredVersionsCommand, perBatch in
return nil
}
deleteExpiredSql := `DELETE FROM dashboard_version WHERE id IN (?` + strings.Repeat(",?", len(versionIdsToDelete)-1) + `)`
sqlOrArgs := append([]interface{}{deleteExpiredSql}, versionIdsToDelete...)
deleteExpiredSQL := `DELETE FROM dashboard_version WHERE id IN (?` + strings.Repeat(",?", len(versionIdsToDelete)-1) + `)`
sqlOrArgs := append([]interface{}{deleteExpiredSQL}, versionIdsToDelete...)
expiredResponse, err := sess.Exec(sqlOrArgs...)
if err != nil {
return err

View File

@ -43,9 +43,9 @@ func init() {
// database queries.
func WrapDatabaseDriverWithHooks(dbType string) string {
drivers := map[string]driver.Driver{
migrator.SQLITE: &sqlite3.SQLiteDriver{},
migrator.MYSQL: &mysql.MySQLDriver{},
migrator.POSTGRES: &pq.Driver{},
migrator.SQLite: &sqlite3.SQLiteDriver{},
migrator.MySQL: &mysql.MySQLDriver{},
migrator.Postgres: &pq.Driver{},
}
d, exist := drivers[dbType]

View File

@ -44,7 +44,7 @@ func getDataSourceByID(id, orgID int64, engine *xorm.Engine) (*models.DataSource
return &datasource, nil
}
func (ss *SqlStore) GetDataSourceByID(id, orgID int64) (*models.DataSource, error) {
func (ss *SQLStore) GetDataSourceByID(id, orgID int64) (*models.DataSource, error) {
return getDataSourceByID(id, orgID, ss.engine)
}
@ -83,8 +83,8 @@ func GetAllDataSources(query *models.GetAllDataSourcesQuery) error {
func DeleteDataSourceById(cmd *models.DeleteDataSourceByIdCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM data_source WHERE id=? and org_id=?"
result, err := sess.Exec(rawSql, cmd.Id, cmd.OrgId)
var rawSQL = "DELETE FROM data_source WHERE id=? and org_id=?"
result, err := sess.Exec(rawSQL, cmd.Id, cmd.OrgId)
affected, _ := result.RowsAffected()
cmd.DeletedDatasourcesCount = affected
return err
@ -93,8 +93,8 @@ func DeleteDataSourceById(cmd *models.DeleteDataSourceByIdCommand) error {
func DeleteDataSourceByName(cmd *models.DeleteDataSourceByNameCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM data_source WHERE name=? and org_id=?"
result, err := sess.Exec(rawSql, cmd.Name, cmd.OrgId)
var rawSQL = "DELETE FROM data_source WHERE name=? and org_id=?"
result, err := sess.Exec(rawSQL, cmd.Name, cmd.OrgId)
affected, _ := result.RowsAffected()
cmd.DeletedDatasourcesCount = affected
return err
@ -163,8 +163,8 @@ func AddDataSource(cmd *models.AddDataSourceCommand) error {
func updateIsDefaultFlag(ds *models.DataSource, sess *DBSession) error {
// Handle is default flag
if ds.IsDefault {
rawSql := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
if _, err := sess.Exec(rawSql, false, ds.OrgId, ds.Id); err != nil {
rawSQL := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
if _, err := sess.Exec(rawSQL, false, ds.OrgId, ds.Id); err != nil {
return err
}
}

View File

@ -155,8 +155,8 @@ func addAlertMigrations(mg *Migrator) {
Name: "uid", Type: DB_NVarchar, Length: 40, Nullable: true,
}))
mg.AddMigration("Update uid column values in alert_notification", new(RawSqlMigration).
Sqlite("UPDATE alert_notification SET uid=printf('%09d',id) WHERE uid IS NULL;").
mg.AddMigration("Update uid column values in alert_notification", new(RawSQLMigration).
SQLite("UPDATE alert_notification SET uid=printf('%09d',id) WHERE uid IS NULL;").
Postgres("UPDATE alert_notification SET uid=lpad('' || id::text,9,'0') WHERE uid IS NULL;").
Mysql("UPDATE alert_notification SET uid=lpad(id,9,'0') WHERE uid IS NULL;"))
@ -173,7 +173,7 @@ func addAlertMigrations(mg *Migrator) {
}))
// change column type of alert.settings
mg.AddMigration("alter alert.settings to mediumtext", NewRawSqlMigration("").
mg.AddMigration("alter alert.settings to mediumtext", NewRawSQLMigration("").
Mysql("ALTER TABLE alert MODIFY settings MEDIUMTEXT;"))
mg.AddMigration("Add non-unique index alert_notification_state_alert_id", NewAddIndexMigration(alert_notification_state, &Index{

View File

@ -85,8 +85,8 @@ func addAnnotationMig(mg *Migrator) {
//
// clear alert text
//
updateTextFieldSql := "UPDATE annotation SET TEXT = '' WHERE alert_id > 0"
mg.AddMigration("Update alert annotations and set TEXT to empty", NewRawSqlMigration(updateTextFieldSql))
updateTextFieldSQL := "UPDATE annotation SET TEXT = '' WHERE alert_id > 0"
mg.AddMigration("Update alert annotations and set TEXT to empty", NewRawSQLMigration(updateTextFieldSQL))
//
// Add a 'created' & 'updated' column
@ -107,8 +107,8 @@ func addAnnotationMig(mg *Migrator) {
//
// Convert epoch saved as seconds to milliseconds
//
updateEpochSql := "UPDATE annotation SET epoch = (epoch*1000) where epoch < 9999999999"
mg.AddMigration("Convert existing annotations from seconds to milliseconds", NewRawSqlMigration(updateEpochSql))
updateEpochSQL := "UPDATE annotation SET epoch = (epoch*1000) where epoch < 9999999999"
mg.AddMigration("Convert existing annotations from seconds to milliseconds", NewRawSQLMigration(updateEpochSQL))
//
// 6.4: Make Regions a single annotation row
@ -119,7 +119,7 @@ func addAnnotationMig(mg *Migrator) {
mg.AddMigration("Add index for epoch_end", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "epoch", "epoch_end"}, Type: IndexType,
}))
mg.AddMigration("Make epoch_end the same as epoch", NewRawSqlMigration("UPDATE annotation SET epoch_end = epoch"))
mg.AddMigration("Make epoch_end the same as epoch", NewRawSQLMigration("UPDATE annotation SET epoch_end = epoch"))
mg.AddMigration("Move region to single row", &AddMakeRegionSingleRowMigration{})
//
@ -154,7 +154,7 @@ type AddMakeRegionSingleRowMigration struct {
MigrationBase
}
func (m *AddMakeRegionSingleRowMigration) Sql(dialect Dialect) string {
func (m *AddMakeRegionSingleRowMigration) SQL(dialect Dialect) string {
return "code migration"
}

View File

@ -45,8 +45,8 @@ INSERT INTO dashboard_acl
(-1,-1, 2,'Editor','2017-06-20','2017-06-20')
`
mg.AddMigration("save default acl rules in dashboard_acl table", NewRawSqlMigration(rawSQL))
mg.AddMigration("save default acl rules in dashboard_acl table", NewRawSQLMigration(rawSQL))
mg.AddMigration("delete acl rules for deleted dashboards and folders", NewRawSqlMigration(
mg.AddMigration("delete acl rules for deleted dashboards and folders", NewRawSQLMigration(
"DELETE FROM dashboard_acl WHERE dashboard_id NOT IN (SELECT id FROM dashboard) AND dashboard_id != -1"))
}

View File

@ -90,7 +90,7 @@ func addDashboardMigration(mg *Migrator) {
mg.AddMigration("drop table dashboard_v1", NewDropTableMigration("dashboard_v1"))
// change column type of dashboard.data
mg.AddMigration("alter dashboard.data to mediumtext v1", NewRawSqlMigration("").
mg.AddMigration("alter dashboard.data to mediumtext v1", NewRawSQLMigration("").
Mysql("ALTER TABLE dashboard MODIFY data MEDIUMTEXT;"))
// add column to store updater of a dashboard
@ -155,8 +155,8 @@ func addDashboardMigration(mg *Migrator) {
Name: "uid", Type: DB_NVarchar, Length: 40, Nullable: true,
}))
mg.AddMigration("Update uid column values in dashboard", NewRawSqlMigration("").
Sqlite("UPDATE dashboard SET uid=printf('%09d',id) WHERE uid IS NULL;").
mg.AddMigration("Update uid column values in dashboard", NewRawSQLMigration("").
SQLite("UPDATE dashboard SET uid=printf('%09d',id) WHERE uid IS NULL;").
Postgres("UPDATE dashboard SET uid=lpad('' || id::text,9,'0') WHERE uid IS NULL;").
Mysql("UPDATE dashboard SET uid=lpad(id,9,'0') WHERE uid IS NULL;"))
@ -220,9 +220,9 @@ func addDashboardMigration(mg *Migrator) {
Type: IndexType,
}))
mg.AddMigration("delete tags for deleted dashboards", NewRawSqlMigration(
mg.AddMigration("delete tags for deleted dashboards", NewRawSQLMigration(
"DELETE FROM dashboard_tag WHERE dashboard_id NOT IN (SELECT id FROM dashboard)"))
mg.AddMigration("delete stars for deleted dashboards", NewRawSqlMigration(
mg.AddMigration("delete stars for deleted dashboards", NewRawSQLMigration(
"DELETE FROM star WHERE dashboard_id NOT IN (SELECT id FROM dashboard)"))
}

View File

@ -50,7 +50,7 @@ func addDashboardSnapshotMigrations(mg *Migrator) {
addTableIndicesMigrations(mg, "v5", snapshotV5)
// change column type of dashboard
mg.AddMigration("alter dashboard_snapshot to mediumtext v2", NewRawSqlMigration("").
mg.AddMigration("alter dashboard_snapshot to mediumtext v2", NewRawSQLMigration("").
Mysql("ALTER TABLE dashboard_snapshot MODIFY dashboard MEDIUMTEXT;"))
mg.AddMigration("Update dashboard_snapshot table charset", NewTableCharsetMigration("dashboard_snapshot", []*Column{
@ -69,6 +69,6 @@ func addDashboardSnapshotMigrations(mg *Migrator) {
Name: "dashboard_encrypted", Type: DB_Blob, Nullable: true,
}))
mg.AddMigration("Change dashboard_encrypted column to MEDIUMBLOB", NewRawSqlMigration("").
mg.AddMigration("Change dashboard_encrypted column to MEDIUMBLOB", NewRawSQLMigration("").
Mysql("ALTER TABLE dashboard_snapshot MODIFY dashboard_encrypted MEDIUMBLOB;"))
}

View File

@ -28,7 +28,7 @@ func addDashboardVersionMigration(mg *Migrator) {
// before new dashboards where created with version 0, now they are always inserted with version 1
const setVersionTo1WhereZeroSQL = `UPDATE dashboard SET version = 1 WHERE version = 0`
mg.AddMigration("Set dashboard version to 1 where 0", NewRawSqlMigration(setVersionTo1WhereZeroSQL))
mg.AddMigration("Set dashboard version to 1 where 0", NewRawSQLMigration(setVersionTo1WhereZeroSQL))
const rawSQL = `INSERT INTO dashboard_version
(
@ -51,9 +51,9 @@ SELECT
'',
dashboard.data
FROM dashboard;`
mg.AddMigration("save existing dashboard data in dashboard_version table v1", NewRawSqlMigration(rawSQL))
mg.AddMigration("save existing dashboard data in dashboard_version table v1", NewRawSQLMigration(rawSQL))
// change column type of dashboard_version.data
mg.AddMigration("alter dashboard_version.data to mediumtext v1", NewRawSqlMigration("").
mg.AddMigration("alter dashboard_version.data to mediumtext v1", NewRawSQLMigration("").
Mysql("ALTER TABLE dashboard_version MODIFY data MEDIUMTEXT;"))
}

View File

@ -122,17 +122,17 @@ func addDataSourceMigration(mg *Migrator) {
}))
const setVersionToOneWhereZero = `UPDATE data_source SET version = 1 WHERE version = 0`
mg.AddMigration("Update initial version to 1", NewRawSqlMigration(setVersionToOneWhereZero))
mg.AddMigration("Update initial version to 1", NewRawSQLMigration(setVersionToOneWhereZero))
mg.AddMigration("Add read_only data column", NewAddColumnMigration(tableV2, &Column{
Name: "read_only", Type: DB_Bool, Nullable: true,
}))
const migrateLoggingToLoki = `UPDATE data_source SET type = 'loki' WHERE type = 'logging'`
mg.AddMigration("Migrate logging ds to loki ds", NewRawSqlMigration(migrateLoggingToLoki))
mg.AddMigration("Migrate logging ds to loki ds", NewRawSQLMigration(migrateLoggingToLoki))
const setEmptyJSONWhereNullJSON = `UPDATE data_source SET json_data = '{}' WHERE json_data is null`
mg.AddMigration("Update json_data with nulls", NewRawSqlMigration(setEmptyJSONWhereNullJSON))
mg.AddMigration("Update json_data with nulls", NewRawSQLMigration(setEmptyJSONWhereNullJSON))
// add column uid for linking
mg.AddMigration("Add uid column", NewAddColumnMigration(tableV2, &Column{
@ -142,8 +142,8 @@ func addDataSourceMigration(mg *Migrator) {
// Initialize as id as that is unique already
mg.AddMigration(
"Update uid value",
NewRawSqlMigration("").
Sqlite("UPDATE data_source SET uid=printf('%09d',id);").
NewRawSQLMigration("").
SQLite("UPDATE data_source SET uid=printf('%09d',id);").
Postgres("UPDATE data_source SET uid=lpad('' || id::text,9,'0');").
Mysql("UPDATE data_source SET uid=lpad(id,9,'0');"),
)

View File

@ -12,7 +12,7 @@ import (
func TestMigrations(t *testing.T) {
testDBs := []sqlutil.TestDB{
sqlutil.Sqlite3TestDB(),
sqlutil.SQLite3TestDB(),
}
for _, testDB := range testDBs {

View File

@ -64,5 +64,5 @@ func addOrgMigrations(mg *Migrator) {
}))
const migrateReadOnlyViewersToViewers = `UPDATE org_user SET role = 'Viewer' WHERE role = 'Read Only Editor'`
mg.AddMigration("Migrate all Read Only Viewers to Viewers", NewRawSqlMigration(migrateReadOnlyViewersToViewers))
mg.AddMigration("Migrate all Read Only Viewers to Viewers", NewRawSQLMigration(migrateReadOnlyViewersToViewers))
}

View File

@ -38,8 +38,8 @@ func addPreferencesMigrations(mg *Migrator) {
Name: "team_id", Type: DB_BigInt, Nullable: true,
}))
mg.AddMigration("Update team_id column values in preferences", NewRawSqlMigration("").
Sqlite("UPDATE preferences SET team_id=0 WHERE team_id IS NULL;").
mg.AddMigration("Update team_id column values in preferences", NewRawSQLMigration("").
SQLite("UPDATE preferences SET team_id=0 WHERE team_id IS NULL;").
Postgres("UPDATE preferences SET team_id=0 WHERE team_id IS NULL;").
Mysql("UPDATE preferences SET team_id=0 WHERE team_id IS NULL;"))
}

View File

@ -99,7 +99,7 @@ type SetCreatedForOutstandingInvites struct {
MigrationBase
}
func (m *SetCreatedForOutstandingInvites) Sql(dialect Dialect) string {
func (m *SetCreatedForOutstandingInvites) SQL(dialect Dialect) string {
return "code migration"
}

View File

@ -22,7 +22,7 @@ func addUserAuthMigrations(mg *Migrator) {
// add indices
addTableIndicesMigrations(mg, "v1", userAuthV1)
mg.AddMigration("alter user_auth.auth_id to length 190", NewRawSqlMigration("").
mg.AddMigration("alter user_auth.auth_id to length 190", NewRawSQLMigration("").
Postgres("ALTER TABLE user_auth ALTER COLUMN auth_id TYPE VARCHAR(190);").
Mysql("ALTER TABLE user_auth MODIFY auth_id VARCHAR(190);"))

View File

@ -132,7 +132,7 @@ type AddMissingUserSaltAndRandsMigration struct {
MigrationBase
}
func (m *AddMissingUserSaltAndRandsMigration) Sql(dialect Dialect) string {
func (m *AddMissingUserSaltAndRandsMigration) SQL(dialect Dialect) string {
return "code migration"
}

View File

@ -1,7 +1,7 @@
package migrator
type MigrationCondition interface {
Sql(dialect Dialect) (string, []interface{})
SQL(dialect Dialect) (string, []interface{})
IsFulfilled(results []map[string][]byte) bool
}
@ -23,8 +23,8 @@ type IfIndexExistsCondition struct {
IndexName string
}
func (c *IfIndexExistsCondition) Sql(dialect Dialect) (string, []interface{}) {
return dialect.IndexCheckSql(c.TableName, c.IndexName)
func (c *IfIndexExistsCondition) SQL(dialect Dialect) (string, []interface{}) {
return dialect.IndexCheckSQL(c.TableName, c.IndexName)
}
type IfIndexNotExistsCondition struct {
@ -33,8 +33,8 @@ type IfIndexNotExistsCondition struct {
IndexName string
}
func (c *IfIndexNotExistsCondition) Sql(dialect Dialect) (string, []interface{}) {
return dialect.IndexCheckSql(c.TableName, c.IndexName)
func (c *IfIndexNotExistsCondition) SQL(dialect Dialect) (string, []interface{}) {
return dialect.IndexCheckSQL(c.TableName, c.IndexName)
}
type IfColumnNotExistsCondition struct {
@ -43,6 +43,6 @@ type IfColumnNotExistsCondition struct {
ColumnName string
}
func (c *IfColumnNotExistsCondition) Sql(dialect Dialect) (string, []interface{}) {
return dialect.ColumnCheckSql(c.TableName, c.ColumnName)
func (c *IfColumnNotExistsCondition) SQL(dialect Dialect) (string, []interface{}) {
return dialect.ColumnCheckSQL(c.TableName, c.ColumnName)
}

View File

@ -15,25 +15,25 @@ type Dialect interface {
OrStr() string
EqStr() string
ShowCreateNull() bool
SqlType(col *Column) string
SQLType(col *Column) string
SupportEngine() bool
LikeStr() string
Default(col *Column) string
BooleanStr(bool) string
DateTimeFunc(string) string
CreateIndexSql(tableName string, index *Index) string
CreateTableSql(table *Table) string
AddColumnSql(tableName string, col *Column) string
CreateIndexSQL(tableName string, index *Index) string
CreateTableSQL(table *Table) string
AddColumnSQL(tableName string, col *Column) string
CopyTableData(sourceTable string, targetTable string, sourceCols []string, targetCols []string) string
DropTable(tableName string) string
DropIndexSql(tableName string, index *Index) string
DropIndexSQL(tableName string, index *Index) string
RenameTable(oldName string, newName string) string
UpdateTableSql(tableName string, columns []*Column) string
UpdateTableSQL(tableName string, columns []*Column) string
IndexCheckSql(tableName, indexName string) (string, []interface{})
ColumnCheckSql(tableName, columnName string) (string, []interface{})
IndexCheckSQL(tableName, indexName string) (string, []interface{})
ColumnCheckSQL(tableName, columnName string) (string, []interface{})
ColString(*Column) string
ColStringNoPk(*Column) string
@ -46,7 +46,7 @@ type Dialect interface {
CleanDB() error
TruncateDBTables() error
NoOpSql() string
NoOpSQL() string
IsUniqueConstraintViolation(err error) bool
ErrorMessage(err error) string
@ -56,12 +56,12 @@ type Dialect interface {
type dialectFunc func(*xorm.Engine) Dialect
var supportedDialects = map[string]dialectFunc{
MYSQL: NewMysqlDialect,
SQLITE: NewSqlite3Dialect,
POSTGRES: NewPostgresDialect,
MYSQL + "WithHooks": NewMysqlDialect,
SQLITE + "WithHooks": NewSqlite3Dialect,
POSTGRES + "WithHooks": NewPostgresDialect,
MySQL: NewMysqlDialect,
SQLite: NewSQLite3Dialect,
Postgres: NewPostgresDialect,
MySQL + "WithHooks": NewMysqlDialect,
SQLite + "WithHooks": NewSQLite3Dialect,
Postgres + "WithHooks": NewPostgresDialect,
}
func NewDialect(engine *xorm.Engine) Dialect {
@ -111,7 +111,7 @@ func (b *BaseDialect) DateTimeFunc(value string) string {
return value
}
func (b *BaseDialect) CreateTableSql(table *Table) string {
func (b *BaseDialect) CreateTableSQL(table *Table) string {
sql := "CREATE TABLE IF NOT EXISTS "
sql += b.dialect.Quote(table.Name) + " (\n"
@ -145,11 +145,11 @@ func (b *BaseDialect) CreateTableSql(table *Table) string {
return sql
}
func (b *BaseDialect) AddColumnSql(tableName string, col *Column) string {
func (b *BaseDialect) AddColumnSQL(tableName string, col *Column) string {
return fmt.Sprintf("alter table %s ADD COLUMN %s", b.dialect.Quote(tableName), col.StringNoPk(b.dialect))
}
func (b *BaseDialect) CreateIndexSql(tableName string, index *Index) string {
func (b *BaseDialect) CreateIndexSQL(tableName string, index *Index) string {
quote := b.dialect.Quote
var unique string
if index.Type == UniqueIndex {
@ -167,20 +167,20 @@ func (b *BaseDialect) CreateIndexSql(tableName string, index *Index) string {
}
func (b *BaseDialect) QuoteColList(cols []string) string {
var sourceColsSql = ""
var sourceColsSQL = ""
for _, col := range cols {
sourceColsSql += b.dialect.Quote(col)
sourceColsSql += "\n, "
sourceColsSQL += b.dialect.Quote(col)
sourceColsSQL += "\n, "
}
return strings.TrimSuffix(sourceColsSql, "\n, ")
return strings.TrimSuffix(sourceColsSQL, "\n, ")
}
func (b *BaseDialect) CopyTableData(sourceTable string, targetTable string, sourceCols []string, targetCols []string) string {
sourceColsSql := b.QuoteColList(sourceCols)
targetColsSql := b.QuoteColList(targetCols)
sourceColsSQL := b.QuoteColList(sourceCols)
targetColsSQL := b.QuoteColList(targetCols)
quote := b.dialect.Quote
return fmt.Sprintf("INSERT INTO %s (%s) SELECT %s FROM %s", quote(targetTable), targetColsSql, sourceColsSql, quote(sourceTable))
return fmt.Sprintf("INSERT INTO %s (%s) SELECT %s FROM %s", quote(targetTable), targetColsSQL, sourceColsSQL, quote(sourceTable))
}
func (b *BaseDialect) DropTable(tableName string) string {
@ -193,24 +193,24 @@ func (b *BaseDialect) RenameTable(oldName string, newName string) string {
return fmt.Sprintf("ALTER TABLE %s RENAME TO %s", quote(oldName), quote(newName))
}
func (b *BaseDialect) ColumnCheckSql(tableName, columnName string) (string, []interface{}) {
func (b *BaseDialect) ColumnCheckSQL(tableName, columnName string) (string, []interface{}) {
return "", nil
}
func (b *BaseDialect) DropIndexSql(tableName string, index *Index) string {
func (b *BaseDialect) DropIndexSQL(tableName string, index *Index) string {
quote := b.dialect.Quote
name := index.XName(tableName)
return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName))
}
func (b *BaseDialect) UpdateTableSql(tableName string, columns []*Column) string {
func (b *BaseDialect) UpdateTableSQL(tableName string, columns []*Column) string {
return "-- NOT REQUIRED"
}
func (b *BaseDialect) ColString(col *Column) string {
sql := b.dialect.Quote(col.Name) + " "
sql += b.dialect.SqlType(col) + " "
sql += b.dialect.SQLType(col) + " "
if col.IsPrimaryKey {
sql += "PRIMARY KEY "
@ -237,7 +237,7 @@ func (b *BaseDialect) ColString(col *Column) string {
func (b *BaseDialect) ColStringNoPk(col *Column) string {
sql := b.dialect.Quote(col.Name) + " "
sql += b.dialect.SqlType(col) + " "
sql += b.dialect.SQLType(col) + " "
if b.dialect.ShowCreateNull() {
if col.Nullable {
@ -274,7 +274,7 @@ func (b *BaseDialect) CleanDB() error {
return nil
}
func (b *BaseDialect) NoOpSql() string {
func (b *BaseDialect) NoOpSQL() string {
return "SELECT 0;"
}

View File

@ -21,21 +21,21 @@ func (m *MigrationBase) GetCondition() MigrationCondition {
return m.Condition
}
type RawSqlMigration struct {
type RawSQLMigration struct {
MigrationBase
sql map[string]string
}
func NewRawSqlMigration(sql string) *RawSqlMigration {
m := &RawSqlMigration{}
func NewRawSQLMigration(sql string) *RawSQLMigration {
m := &RawSQLMigration{}
if sql != "" {
m.Default(sql)
}
return m
}
func (m *RawSqlMigration) Sql(dialect Dialect) string {
func (m *RawSQLMigration) SQL(dialect Dialect) string {
if m.sql != nil {
if val := m.sql[dialect.DriverName()]; val != "" {
return val
@ -46,10 +46,10 @@ func (m *RawSqlMigration) Sql(dialect Dialect) string {
}
}
return dialect.NoOpSql()
return dialect.NoOpSQL()
}
func (m *RawSqlMigration) Set(dialect string, sql string) *RawSqlMigration {
func (m *RawSQLMigration) Set(dialect string, sql string) *RawSQLMigration {
if m.sql == nil {
m.sql = make(map[string]string)
}
@ -58,23 +58,23 @@ func (m *RawSqlMigration) Set(dialect string, sql string) *RawSqlMigration {
return m
}
func (m *RawSqlMigration) Default(sql string) *RawSqlMigration {
func (m *RawSQLMigration) Default(sql string) *RawSQLMigration {
return m.Set("default", sql)
}
func (m *RawSqlMigration) Sqlite(sql string) *RawSqlMigration {
return m.Set(SQLITE, sql)
func (m *RawSQLMigration) SQLite(sql string) *RawSQLMigration {
return m.Set(SQLite, sql)
}
func (m *RawSqlMigration) Mysql(sql string) *RawSqlMigration {
return m.Set(MYSQL, sql)
func (m *RawSQLMigration) Mysql(sql string) *RawSQLMigration {
return m.Set(MySQL, sql)
}
func (m *RawSqlMigration) Postgres(sql string) *RawSqlMigration {
return m.Set(POSTGRES, sql)
func (m *RawSQLMigration) Postgres(sql string) *RawSQLMigration {
return m.Set(Postgres, sql)
}
func (m *RawSqlMigration) Mssql(sql string) *RawSqlMigration {
func (m *RawSQLMigration) Mssql(sql string) *RawSQLMigration {
return m.Set(MSSQL, sql)
}
@ -100,8 +100,8 @@ func (m *AddColumnMigration) Column(col *Column) *AddColumnMigration {
return m
}
func (m *AddColumnMigration) Sql(dialect Dialect) string {
return dialect.AddColumnSql(m.tableName, m.column)
func (m *AddColumnMigration) SQL(dialect Dialect) string {
return dialect.AddColumnSQL(m.tableName, m.column)
}
type AddIndexMigration struct {
@ -121,8 +121,8 @@ func (m *AddIndexMigration) Table(tableName string) *AddIndexMigration {
return m
}
func (m *AddIndexMigration) Sql(dialect Dialect) string {
return dialect.CreateIndexSql(m.tableName, m.index)
func (m *AddIndexMigration) SQL(dialect Dialect) string {
return dialect.CreateIndexSQL(m.tableName, m.index)
}
type DropIndexMigration struct {
@ -137,11 +137,11 @@ func NewDropIndexMigration(table Table, index *Index) *DropIndexMigration {
return m
}
func (m *DropIndexMigration) Sql(dialect Dialect) string {
func (m *DropIndexMigration) SQL(dialect Dialect) string {
if m.index.Name == "" {
m.index.Name = strings.Join(m.index.Cols, "_")
}
return dialect.DropIndexSql(m.tableName, m.index)
return dialect.DropIndexSQL(m.tableName, m.index)
}
type AddTableMigration struct {
@ -158,8 +158,8 @@ func NewAddTableMigration(table Table) *AddTableMigration {
return &AddTableMigration{table: table}
}
func (m *AddTableMigration) Sql(d Dialect) string {
return d.CreateTableSql(&m.table)
func (m *AddTableMigration) SQL(d Dialect) string {
return d.CreateTableSQL(&m.table)
}
type DropTableMigration struct {
@ -171,7 +171,7 @@ func NewDropTableMigration(tableName string) *DropTableMigration {
return &DropTableMigration{tableName: tableName}
}
func (m *DropTableMigration) Sql(d Dialect) string {
func (m *DropTableMigration) SQL(d Dialect) string {
return d.DropTable(m.tableName)
}
@ -191,7 +191,7 @@ func (m *RenameTableMigration) Rename(oldName string, newName string) *RenameTab
return m
}
func (m *RenameTableMigration) Sql(d Dialect) string {
func (m *RenameTableMigration) SQL(d Dialect) string {
return d.RenameTable(m.oldName, m.newName)
}
@ -213,7 +213,7 @@ func NewCopyTableDataMigration(targetTable string, sourceTable string, colMap ma
return m
}
func (m *CopyTableDataMigration) Sql(d Dialect) string {
func (m *CopyTableDataMigration) SQL(d Dialect) string {
return d.CopyTableData(m.sourceTable, m.targetTable, m.sourceCols, m.targetCols)
}
@ -227,6 +227,6 @@ func NewTableCharsetMigration(tableName string, columns []*Column) *TableCharset
return &TableCharsetMigration{tableName: tableName, columns: columns}
}
func (m *TableCharsetMigration) Sql(d Dialect) string {
return d.UpdateTableSql(m.tableName, m.columns)
func (m *TableCharsetMigration) SQL(d Dialect) string {
return d.UpdateTableSQL(m.tableName, m.columns)
}

View File

@ -20,8 +20,8 @@ type Migrator struct {
type MigrationLog struct {
Id int64
MigrationId string
Sql string
MigrationID string `xorm:"migration_id"`
SQL string `xorm:"sql"`
Success bool
Error string
Timestamp time.Time
@ -65,7 +65,7 @@ func (mg *Migrator) GetMigrationLog() (map[string]MigrationLog, error) {
if !logItem.Success {
continue
}
logMap[logItem.MigrationId] = logItem
logMap[logItem.MigrationID] = logItem
}
return logMap, nil
@ -87,11 +87,11 @@ func (mg *Migrator) Start() error {
continue
}
sql := m.Sql(mg.Dialect)
sql := m.SQL(mg.Dialect)
record := MigrationLog{
MigrationId: m.Id(),
Sql: sql,
MigrationID: m.Id(),
SQL: sql,
Timestamp: time.Now(),
}
@ -122,7 +122,7 @@ func (mg *Migrator) exec(m Migration, sess *xorm.Session) error {
condition := m.GetCondition()
if condition != nil {
sql, args := condition.Sql(mg.Dialect)
sql, args := condition.SQL(mg.Dialect)
if sql != "" {
mg.Logger.Debug("Executing migration condition sql", "id", m.Id(), "sql", sql, "args", args)
@ -144,7 +144,7 @@ func (mg *Migrator) exec(m Migration, sess *xorm.Session) error {
mg.Logger.Debug("Executing code migration", "id", m.Id())
err = codeMigration.Exec(sess, mg)
} else {
sql := m.Sql(mg.Dialect)
sql := m.SQL(mg.Dialect)
mg.Logger.Debug("Executing sql migration", "id", m.Id(), "sql", sql)
_, err = sess.Exec(sql)
}

View File

@ -11,38 +11,38 @@ import (
"xorm.io/xorm"
)
type Mysql struct {
type MySQLDialect struct {
BaseDialect
}
func NewMysqlDialect(engine *xorm.Engine) Dialect {
d := Mysql{}
d := MySQLDialect{}
d.BaseDialect.dialect = &d
d.BaseDialect.engine = engine
d.BaseDialect.driverName = MYSQL
d.BaseDialect.driverName = MySQL
return &d
}
func (db *Mysql) SupportEngine() bool {
func (db *MySQLDialect) SupportEngine() bool {
return true
}
func (db *Mysql) Quote(name string) string {
func (db *MySQLDialect) Quote(name string) string {
return "`" + name + "`"
}
func (db *Mysql) AutoIncrStr() string {
func (db *MySQLDialect) AutoIncrStr() string {
return "AUTO_INCREMENT"
}
func (db *Mysql) BooleanStr(value bool) string {
func (db *MySQLDialect) BooleanStr(value bool) string {
if value {
return "1"
}
return "0"
}
func (db *Mysql) SqlType(c *Column) string {
func (db *MySQLDialect) SQLType(c *Column) string {
var res string
switch c.Type {
case DB_Bool:
@ -91,7 +91,7 @@ func (db *Mysql) SqlType(c *Column) string {
return res
}
func (db *Mysql) UpdateTableSql(tableName string, columns []*Column) string {
func (db *MySQLDialect) UpdateTableSQL(tableName string, columns []*Column) string {
var statements = []string{}
statements = append(statements, "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@ -103,19 +103,19 @@ func (db *Mysql) UpdateTableSql(tableName string, columns []*Column) string {
return "ALTER TABLE " + db.Quote(tableName) + " " + strings.Join(statements, ", ") + ";"
}
func (db *Mysql) IndexCheckSql(tableName, indexName string) (string, []interface{}) {
func (db *MySQLDialect) IndexCheckSQL(tableName, indexName string) (string, []interface{}) {
args := []interface{}{tableName, indexName}
sql := "SELECT 1 FROM " + db.Quote("INFORMATION_SCHEMA") + "." + db.Quote("STATISTICS") + " WHERE " + db.Quote("TABLE_SCHEMA") + " = DATABASE() AND " + db.Quote("TABLE_NAME") + "=? AND " + db.Quote("INDEX_NAME") + "=?"
return sql, args
}
func (db *Mysql) ColumnCheckSql(tableName, columnName string) (string, []interface{}) {
func (db *MySQLDialect) ColumnCheckSQL(tableName, columnName string) (string, []interface{}) {
args := []interface{}{tableName, columnName}
sql := "SELECT 1 FROM " + db.Quote("INFORMATION_SCHEMA") + "." + db.Quote("COLUMNS") + " WHERE " + db.Quote("TABLE_SCHEMA") + " = DATABASE() AND " + db.Quote("TABLE_NAME") + "=? AND " + db.Quote("COLUMN_NAME") + "=?"
return sql, args
}
func (db *Mysql) CleanDB() error {
func (db *MySQLDialect) CleanDB() error {
tables, err := db.engine.DBMetas()
if err != nil {
return err
@ -140,7 +140,7 @@ func (db *Mysql) CleanDB() error {
// TruncateDBTables truncates all the tables.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *Mysql) TruncateDBTables() error {
func (db *MySQLDialect) TruncateDBTables() error {
tables, err := db.engine.DBMetas()
if err != nil {
return err
@ -168,7 +168,7 @@ func (db *Mysql) TruncateDBTables() error {
return nil
}
func (db *Mysql) isThisError(err error, errcode uint16) bool {
func (db *MySQLDialect) isThisError(err error, errcode uint16) bool {
if driverErr, ok := err.(*mysql.MySQLError); ok {
if driverErr.Number == errcode {
return true
@ -178,17 +178,17 @@ func (db *Mysql) isThisError(err error, errcode uint16) bool {
return false
}
func (db *Mysql) IsUniqueConstraintViolation(err error) bool {
func (db *MySQLDialect) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, mysqlerr.ER_DUP_ENTRY)
}
func (db *Mysql) ErrorMessage(err error) string {
func (db *MySQLDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*mysql.MySQLError); ok {
return driverErr.Message
}
return ""
}
func (db *Mysql) IsDeadlock(err error) bool {
func (db *MySQLDialect) IsDeadlock(err error) bool {
return db.isThisError(err, mysqlerr.ER_LOCK_DEADLOCK)
}

View File

@ -11,39 +11,39 @@ import (
"xorm.io/xorm"
)
type Postgres struct {
type PostgresDialect struct {
BaseDialect
}
func NewPostgresDialect(engine *xorm.Engine) Dialect {
d := Postgres{}
d := PostgresDialect{}
d.BaseDialect.dialect = &d
d.BaseDialect.engine = engine
d.BaseDialect.driverName = POSTGRES
d.BaseDialect.driverName = Postgres
return &d
}
func (db *Postgres) SupportEngine() bool {
func (db *PostgresDialect) SupportEngine() bool {
return false
}
func (db *Postgres) Quote(name string) string {
func (db *PostgresDialect) Quote(name string) string {
return "\"" + name + "\""
}
func (db *Postgres) LikeStr() string {
func (db *PostgresDialect) LikeStr() string {
return "ILIKE"
}
func (db *Postgres) AutoIncrStr() string {
func (db *PostgresDialect) AutoIncrStr() string {
return ""
}
func (db *Postgres) BooleanStr(value bool) string {
func (db *PostgresDialect) BooleanStr(value bool) string {
return strconv.FormatBool(value)
}
func (db *Postgres) Default(col *Column) string {
func (db *PostgresDialect) Default(col *Column) string {
if col.Type == DB_Bool {
if col.Default == "0" {
return "FALSE"
@ -53,7 +53,7 @@ func (db *Postgres) Default(col *Column) string {
return col.Default
}
func (db *Postgres) SqlType(c *Column) string {
func (db *PostgresDialect) SQLType(c *Column) string {
var res string
switch t := c.Type; t {
case DB_TinyInt:
@ -103,29 +103,29 @@ func (db *Postgres) SqlType(c *Column) string {
return res
}
func (db *Postgres) IndexCheckSql(tableName, indexName string) (string, []interface{}) {
func (db *PostgresDialect) IndexCheckSQL(tableName, indexName string) (string, []interface{}) {
args := []interface{}{tableName, indexName}
sql := "SELECT 1 FROM " + db.Quote("pg_indexes") + " WHERE" + db.Quote("tablename") + "=? AND " + db.Quote("indexname") + "=?"
return sql, args
}
func (db *Postgres) DropIndexSql(tableName string, index *Index) string {
func (db *PostgresDialect) DropIndexSQL(tableName string, index *Index) string {
quote := db.Quote
idxName := index.XName(tableName)
return fmt.Sprintf("DROP INDEX %v CASCADE", quote(idxName))
}
func (db *Postgres) UpdateTableSql(tableName string, columns []*Column) string {
func (db *PostgresDialect) UpdateTableSQL(tableName string, columns []*Column) string {
var statements = []string{}
for _, col := range columns {
statements = append(statements, "ALTER "+db.Quote(col.Name)+" TYPE "+db.SqlType(col))
statements = append(statements, "ALTER "+db.Quote(col.Name)+" TYPE "+db.SQLType(col))
}
return "ALTER TABLE " + db.Quote(tableName) + " " + strings.Join(statements, ", ") + ";"
}
func (db *Postgres) CleanDB() error {
func (db *PostgresDialect) CleanDB() error {
sess := db.engine.NewSession()
defer sess.Close()
@ -142,7 +142,7 @@ func (db *Postgres) CleanDB() error {
// TruncateDBTables truncates all the tables.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *Postgres) TruncateDBTables() error {
func (db *PostgresDialect) TruncateDBTables() error {
sess := db.engine.NewSession()
defer sess.Close()
@ -171,7 +171,7 @@ func (db *Postgres) TruncateDBTables() error {
return nil
}
func (db *Postgres) isThisError(err error, errcode string) bool {
func (db *PostgresDialect) isThisError(err error, errcode string) bool {
if driverErr, ok := err.(*pq.Error); ok {
if string(driverErr.Code) == errcode {
return true
@ -181,26 +181,26 @@ func (db *Postgres) isThisError(err error, errcode string) bool {
return false
}
func (db *Postgres) ErrorMessage(err error) string {
func (db *PostgresDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*pq.Error); ok {
return driverErr.Message
}
return ""
}
func (db *Postgres) isUndefinedTable(err error) bool {
func (db *PostgresDialect) isUndefinedTable(err error) bool {
return db.isThisError(err, "42P01")
}
func (db *Postgres) IsUniqueConstraintViolation(err error) bool {
func (db *PostgresDialect) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, "23505")
}
func (db *Postgres) IsDeadlock(err error) bool {
func (db *PostgresDialect) IsDeadlock(err error) bool {
return db.isThisError(err, "40P01")
}
func (db *Postgres) PostInsertId(table string, sess *xorm.Session) error {
func (db *PostgresDialect) PostInsertId(table string, sess *xorm.Session) error {
if table != "org" {
return nil
}

View File

@ -8,42 +8,42 @@ import (
"xorm.io/xorm"
)
type Sqlite3 struct {
type SQLite3 struct {
BaseDialect
}
func NewSqlite3Dialect(engine *xorm.Engine) Dialect {
d := Sqlite3{}
func NewSQLite3Dialect(engine *xorm.Engine) Dialect {
d := SQLite3{}
d.BaseDialect.dialect = &d
d.BaseDialect.engine = engine
d.BaseDialect.driverName = SQLITE
d.BaseDialect.driverName = SQLite
return &d
}
func (db *Sqlite3) SupportEngine() bool {
func (db *SQLite3) SupportEngine() bool {
return false
}
func (db *Sqlite3) Quote(name string) string {
func (db *SQLite3) Quote(name string) string {
return "`" + name + "`"
}
func (db *Sqlite3) AutoIncrStr() string {
func (db *SQLite3) AutoIncrStr() string {
return "AUTOINCREMENT"
}
func (db *Sqlite3) BooleanStr(value bool) string {
func (db *SQLite3) BooleanStr(value bool) string {
if value {
return "1"
}
return "0"
}
func (db *Sqlite3) DateTimeFunc(value string) string {
func (db *SQLite3) DateTimeFunc(value string) string {
return "datetime(" + value + ")"
}
func (db *Sqlite3) SqlType(c *Column) string {
func (db *SQLite3) SQLType(c *Column) string {
switch c.Type {
case DB_Date, DB_DateTime, DB_TimeStamp, DB_Time:
return DB_DateTime
@ -69,26 +69,26 @@ func (db *Sqlite3) SqlType(c *Column) string {
}
}
func (db *Sqlite3) IndexCheckSql(tableName, indexName string) (string, []interface{}) {
func (db *SQLite3) IndexCheckSQL(tableName, indexName string) (string, []interface{}) {
args := []interface{}{tableName, indexName}
sql := "SELECT 1 FROM " + db.Quote("sqlite_master") + " WHERE " + db.Quote("type") + "='index' AND " + db.Quote("tbl_name") + "=? AND " + db.Quote("name") + "=?"
return sql, args
}
func (db *Sqlite3) DropIndexSql(tableName string, index *Index) string {
func (db *SQLite3) DropIndexSQL(tableName string, index *Index) string {
quote := db.Quote
// var unique string
idxName := index.XName(tableName)
return fmt.Sprintf("DROP INDEX %v", quote(idxName))
}
func (db *Sqlite3) CleanDB() error {
func (db *SQLite3) CleanDB() error {
return nil
}
// TruncateDBTables deletes all data from all the tables and resets the sequences.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *Sqlite3) TruncateDBTables() error {
func (db *SQLite3) TruncateDBTables() error {
tables, err := db.engine.DBMetas()
if err != nil {
return err
@ -119,7 +119,7 @@ func (db *Sqlite3) TruncateDBTables() error {
return nil
}
func (db *Sqlite3) isThisError(err error, errcode int) bool {
func (db *SQLite3) isThisError(err error, errcode int) bool {
if driverErr, ok := err.(sqlite3.Error); ok {
if int(driverErr.ExtendedCode) == errcode {
return true
@ -129,17 +129,17 @@ func (db *Sqlite3) isThisError(err error, errcode int) bool {
return false
}
func (db *Sqlite3) ErrorMessage(err error) string {
func (db *SQLite3) ErrorMessage(err error) string {
if driverErr, ok := err.(sqlite3.Error); ok {
return driverErr.Error()
}
return ""
}
func (db *Sqlite3) IsUniqueConstraintViolation(err error) bool {
func (db *SQLite3) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, int(sqlite3.ErrConstraintUnique))
}
func (db *Sqlite3) IsDeadlock(err error) bool {
func (db *SQLite3) IsDeadlock(err error) bool {
return false // No deadlock
}

View File

@ -8,14 +8,14 @@ import (
)
const (
POSTGRES = "postgres"
SQLITE = "sqlite3"
MYSQL = "mysql"
Postgres = "postgres"
SQLite = "sqlite3"
MySQL = "mysql"
MSSQL = "mssql"
)
type Migration interface {
Sql(dialect Dialect) string
SQL(dialect Dialect) string
Id() string
SetId(string)
GetCondition() MigrationCondition

View File

@ -70,8 +70,8 @@ func UpdatePlaylist(cmd *models.UpdatePlaylistCommand) error {
return err
}
rawSql := "DELETE FROM playlist_item WHERE playlist_id = ?"
_, err = x.Exec(rawSql, cmd.Id)
rawSQL := "DELETE FROM playlist_item WHERE playlist_id = ?"
_, err = x.Exec(rawSQL, cmd.Id)
if err != nil {
return err
@ -113,15 +113,15 @@ func DeletePlaylist(cmd *models.DeletePlaylistCommand) error {
}
return inTransaction(func(sess *DBSession) error {
var rawPlaylistSql = "DELETE FROM playlist WHERE id = ? and org_id = ?"
_, err := sess.Exec(rawPlaylistSql, cmd.Id, cmd.OrgId)
var rawPlaylistSQL = "DELETE FROM playlist WHERE id = ? and org_id = ?"
_, err := sess.Exec(rawPlaylistSQL, cmd.Id, cmd.OrgId)
if err != nil {
return err
}
var rawItemSql = "DELETE FROM playlist_item WHERE playlist_id = ?"
_, err2 := sess.Exec(rawItemSql, cmd.Id)
var rawItemSQL = "DELETE FROM playlist_item WHERE playlist_id = ?"
_, err2 := sess.Exec(rawItemSQL, cmd.Id)
return err2
})

View File

@ -10,13 +10,13 @@ import (
"github.com/grafana/grafana/pkg/setting"
)
func (ss *SqlStore) addPreferencesQueryAndCommandHandlers() {
func (ss *SQLStore) addPreferencesQueryAndCommandHandlers() {
bus.AddHandler("sql", GetPreferences)
bus.AddHandler("sql", ss.GetPreferencesWithDefaults)
bus.AddHandler("sql", SavePreferences)
}
func (ss *SqlStore) GetPreferencesWithDefaults(query *models.GetPreferencesWithDefaultsQuery) error {
func (ss *SQLStore) GetPreferencesWithDefaults(query *models.GetPreferencesWithDefaultsQuery) error {
params := make([]interface{}, 0)
filter := ""

View File

@ -36,9 +36,9 @@ func GetOrgQuotaByTarget(query *models.GetOrgQuotaByTargetQuery) error {
}
// get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(query.Target))
rawSQL := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(query.Target))
resp := make([]*targetCount, 0)
if err := x.SQL(rawSql, query.OrgId).Find(&resp); err != nil {
if err := x.SQL(rawSQL, query.OrgId).Find(&resp); err != nil {
return err
}
@ -79,9 +79,9 @@ func GetOrgQuotas(query *models.GetOrgQuotasQuery) error {
result := make([]*models.OrgQuotaDTO, len(quotas))
for i, q := range quotas {
// get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(q.Target))
rawSQL := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(q.Target))
resp := make([]*targetCount, 0)
if err := x.SQL(rawSql, q.OrgId).Find(&resp); err != nil {
if err := x.SQL(rawSQL, q.OrgId).Find(&resp); err != nil {
return err
}
result[i] = &models.OrgQuotaDTO{
@ -139,9 +139,9 @@ func GetUserQuotaByTarget(query *models.GetUserQuotaByTargetQuery) error {
}
// get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(query.Target))
rawSQL := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(query.Target))
resp := make([]*targetCount, 0)
if err := x.SQL(rawSql, query.UserId).Find(&resp); err != nil {
if err := x.SQL(rawSQL, query.UserId).Find(&resp); err != nil {
return err
}
@ -182,9 +182,9 @@ func GetUserQuotas(query *models.GetUserQuotasQuery) error {
result := make([]*models.UserQuotaDTO, len(quotas))
for i, q := range quotas {
// get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(q.Target))
rawSQL := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(q.Target))
resp := make([]*targetCount, 0)
if err := x.SQL(rawSql, q.UserId).Find(&resp); err != nil {
if err := x.SQL(rawSQL, q.UserId).Find(&resp); err != nil {
return err
}
result[i] = &models.UserQuotaDTO{
@ -231,9 +231,9 @@ func UpdateUserQuota(cmd *models.UpdateUserQuotaCmd) error {
func GetGlobalQuotaByTarget(query *models.GetGlobalQuotaByTargetQuery) error {
// get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s", dialect.Quote(query.Target))
rawSQL := fmt.Sprintf("SELECT COUNT(*) as count from %s", dialect.Quote(query.Target))
resp := make([]*targetCount, 0)
if err := x.SQL(rawSql).Find(&resp); err != nil {
if err := x.SQL(rawSQL).Find(&resp); err != nil {
return err
}

View File

@ -20,8 +20,8 @@ type Builder struct {
sql bytes.Buffer
}
// ToSql builds the SQL query and returns it as a string, together with the SQL parameters.
func (b *Builder) ToSql(limit, page int64) (string, []interface{}) {
// ToSQL builds the SQL query and returns it as a string, together with the SQL parameters.
func (b *Builder) ToSQL(limit, page int64) (string, []interface{}) {
b.params = make([]interface{}, 0)
b.sql = bytes.Buffer{}

View File

@ -7,7 +7,7 @@
// without fuzziness and in a single SQL query.
//
// Search queries are a combination of an outer query which Builder
// creates automatically when calling the Builder.ToSql method and an
// creates automatically when calling the Builder.ToSQL method and an
// inner query feeding that which lists the IDs of the dashboards that
// should be part of the result set. By default search will return all
// dashboards (behind pagination) but it is possible to dynamically add

View File

@ -52,7 +52,7 @@ func TestBuilder_EqualResults_Basic(t *testing.T) {
res := []sqlstore.DashboardSearchProjection{}
err = db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
sql, params := builder.ToSql(limit, page)
sql, params := builder.ToSQL(limit, page)
return sess.SQL(sql, params...).Find(&res)
})
require.NoError(t, err)
@ -92,18 +92,18 @@ func TestBuilder_Pagination(t *testing.T) {
resPg2 := []sqlstore.DashboardSearchProjection{}
resPg3 := []sqlstore.DashboardSearchProjection{}
err = db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
sql, params := builder.ToSql(15, 1)
sql, params := builder.ToSQL(15, 1)
err := sess.SQL(sql, params...).Find(&resPg1)
if err != nil {
return err
}
sql, params = builder.ToSql(15, 2)
sql, params = builder.ToSQL(15, 2)
err = sess.SQL(sql, params...).Find(&resPg2)
if err != nil {
return err
}
sql, params = builder.ToSql(15, 3)
sql, params = builder.ToSQL(15, 3)
return sess.SQL(sql, params...).Find(&resPg3)
})
require.NoError(t, err)
@ -146,7 +146,7 @@ func TestBuilder_Permissions(t *testing.T) {
res := []sqlstore.DashboardSearchProjection{}
err = db.WithDbSession(context.Background(), func(sess *sqlstore.DBSession) error {
sql, params := builder.ToSql(limit, page)
sql, params := builder.ToSQL(limit, page)
return sess.SQL(sql, params...).Find(&res)
})
require.NoError(t, err)
@ -154,7 +154,7 @@ func TestBuilder_Permissions(t *testing.T) {
assert.Len(t, res, 0)
}
func setupTestEnvironment(t *testing.T) *sqlstore.SqlStore {
func setupTestEnvironment(t *testing.T) *sqlstore.SQLStore {
t.Helper()
store := sqlstore.InitTestDB(t)
dialect = store.Dialect

View File

@ -19,7 +19,7 @@ func (sess *DBSession) publishAfterCommit(msg interface{}) {
}
// NewSession returns a new DBSession
func (ss *SqlStore) NewSession() *DBSession {
func (ss *SQLStore) NewSession() *DBSession {
return &DBSession{Session: ss.engine.NewSession()}
}
@ -47,7 +47,7 @@ func startSession(ctx context.Context, engine *xorm.Engine, beginTran bool) (*DB
}
// WithDbSession calls the callback with an session attached to the context.
func (ss *SqlStore) WithDbSession(ctx context.Context, callback dbTransactionFunc) error {
func (ss *SQLStore) WithDbSession(ctx context.Context, callback dbTransactionFunc) error {
sess, err := startSession(ctx, ss.engine, false)
if err != nil {
return err

View File

@ -9,7 +9,7 @@ import (
)
func init() {
bus.AddHandler("sql", InsertSqlTestData)
bus.AddHandler("sql", InsertSQLTestData)
}
func sqlRandomWalk(m1 string, m2 string, intWalker int64, floatWalker float64, sess *DBSession) error {
@ -17,7 +17,7 @@ func sqlRandomWalk(m1 string, m2 string, intWalker int64, floatWalker float64, s
now := time.Now().UTC()
step := time.Minute
row := &models.SqlTestData{
row := &models.SQLTestData{
Metric1: m1,
Metric2: m2,
TimeEpoch: timeWalker.Unix(),
@ -43,7 +43,7 @@ func sqlRandomWalk(m1 string, m2 string, intWalker int64, floatWalker float64, s
return nil
}
func InsertSqlTestData(cmd *models.InsertSqlTestDataCommand) error {
func InsertSQLTestData(cmd *models.InsertSQLTestDataCommand) error {
return inTransaction(func(sess *DBSession) error {
var err error

View File

@ -7,12 +7,12 @@ import (
"github.com/grafana/grafana/pkg/models"
)
type SqlBuilder struct {
type SQLBuilder struct {
sql bytes.Buffer
params []interface{}
}
func (sb *SqlBuilder) Write(sql string, params ...interface{}) {
func (sb *SQLBuilder) Write(sql string, params ...interface{}) {
sb.sql.WriteString(sql)
if len(params) > 0 {
@ -20,15 +20,15 @@ func (sb *SqlBuilder) Write(sql string, params ...interface{}) {
}
}
func (sb *SqlBuilder) GetSqlString() string {
func (sb *SQLBuilder) GetSQLString() string {
return sb.sql.String()
}
func (sb *SqlBuilder) AddParams(params ...interface{}) {
func (sb *SQLBuilder) AddParams(params ...interface{}) {
sb.params = append(sb.params, params...)
}
func (sb *SqlBuilder) writeDashboardPermissionFilter(user *models.SignedInUser, permission models.PermissionType) {
func (sb *SQLBuilder) writeDashboardPermissionFilter(user *models.SignedInUser, permission models.PermissionType) {
if user.OrgRole == models.ROLE_ADMIN {
return
}

View File

@ -14,7 +14,7 @@ import (
"github.com/stretchr/testify/assert"
)
func TestSqlBuilder(t *testing.T) {
func TestSQLBuilder(t *testing.T) {
t.Run("writeDashboardPermissionFilter", func(t *testing.T) {
t.Run("user ACL", func(t *testing.T) {
test(t,
@ -317,8 +317,8 @@ func createDummyAcl(dashboardPermission *DashboardPermission, search Search, das
return 0, err
}
func getDashboards(sqlStore *SqlStore, search Search, aclUserId int64) ([]*dashboardResponse, error) {
builder := &SqlBuilder{}
func getDashboards(sqlStore *SQLStore, search Search, aclUserId int64) ([]*dashboardResponse, error) {
builder := &SQLBuilder{}
signedInUser := &models.SignedInUser{
UserId: 9999999999,
}
@ -341,6 +341,6 @@ func getDashboards(sqlStore *SqlStore, search Search, aclUserId int64) ([]*dashb
var res []*dashboardResponse
builder.Write("SELECT * FROM dashboard WHERE true")
builder.writeDashboardPermissionFilter(signedInUser, search.RequiredPermission)
err := sqlStore.engine.SQL(builder.GetSqlString(), builder.params...).Find(&res)
err := sqlStore.engine.SQL(builder.GetSQLString(), builder.params...).Find(&res)
return res, err
}

View File

@ -46,13 +46,13 @@ func init() {
xorm.DefaultPostgresSchema = ""
registry.Register(&registry.Descriptor{
Name: "SqlStore",
Instance: &SqlStore{},
Name: "SQLStore",
Instance: &SQLStore{},
InitPriority: registry.High,
})
}
type SqlStore struct {
type SQLStore struct {
Cfg *setting.Cfg `inject:""`
Bus bus.Bus `inject:""`
CacheService *localcache.CacheService `inject:""`
@ -64,7 +64,7 @@ type SqlStore struct {
skipEnsureDefaultOrgAndUser bool
}
func (ss *SqlStore) Init() error {
func (ss *SQLStore) Init() error {
ss.log = log.New("sqlstore")
ss.readConfig()
@ -95,7 +95,7 @@ func (ss *SqlStore) Init() error {
}
// Init repo instances
annotations.SetRepository(&SqlAnnotationRepo{})
annotations.SetRepository(&SQLAnnotationRepo{})
annotations.SetAnnotationCleaner(&AnnotationCleanupService{batchSize: 100, log: log.New("annotationcleaner")})
ss.Bus.SetTransactionManager(ss)
@ -111,7 +111,7 @@ func (ss *SqlStore) Init() error {
return ss.ensureMainOrgAndAdminUser()
}
func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
func (ss *SQLStore) ensureMainOrgAndAdminUser() error {
err := ss.InTransaction(context.Background(), func(ctx context.Context) error {
systemUserCountQuery := models.GetSystemUserCountStatsQuery{}
err := bus.DispatchCtx(ctx, &systemUserCountQuery)
@ -151,7 +151,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
return err
}
func (ss *SqlStore) buildExtraConnectionString(sep rune) string {
func (ss *SQLStore) buildExtraConnectionString(sep rune) string {
if ss.dbCfg.UrlQueryParams == nil {
return ""
}
@ -168,7 +168,7 @@ func (ss *SqlStore) buildExtraConnectionString(sep rune) string {
return sb.String()
}
func (ss *SqlStore) buildConnectionString() (string, error) {
func (ss *SQLStore) buildConnectionString() (string, error) {
cnnstr := ss.dbCfg.ConnectionString
// special case used by integration tests
@ -177,7 +177,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
}
switch ss.dbCfg.Type {
case migrator.MYSQL:
case migrator.MySQL:
protocol := "tcp"
if strings.HasPrefix(ss.dbCfg.Host, "/") {
protocol = "unix"
@ -199,7 +199,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
}
cnnstr += ss.buildExtraConnectionString('&')
case migrator.POSTGRES:
case migrator.Postgres:
addr, err := util.SplitHostPortDefault(ss.dbCfg.Host, "127.0.0.1", "5432")
if err != nil {
return "", errutil.Wrapf(err, "Invalid host specifier '%s'", ss.dbCfg.Host)
@ -214,7 +214,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s sslcert=%s sslkey=%s sslrootcert=%s", ss.dbCfg.User, ss.dbCfg.Pwd, addr.Host, addr.Port, ss.dbCfg.Name, ss.dbCfg.SslMode, ss.dbCfg.ClientCertPath, ss.dbCfg.ClientKeyPath, ss.dbCfg.CaCertPath)
cnnstr += ss.buildExtraConnectionString(' ')
case migrator.SQLITE:
case migrator.SQLite:
// special case for tests
if !filepath.IsAbs(ss.dbCfg.Path) {
ss.dbCfg.Path = filepath.Join(ss.Cfg.DataPath, ss.dbCfg.Path)
@ -232,14 +232,14 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
return cnnstr, nil
}
func (ss *SqlStore) getEngine() (*xorm.Engine, error) {
func (ss *SQLStore) getEngine() (*xorm.Engine, error) {
connectionString, err := ss.buildConnectionString()
if err != nil {
return nil, err
}
sqlog.Info("Connecting to DB", "dbtype", ss.dbCfg.Type)
if ss.dbCfg.Type == migrator.SQLITE && strings.HasPrefix(connectionString, "file:") {
if ss.dbCfg.Type == migrator.SQLite && strings.HasPrefix(connectionString, "file:") {
exists, err := fs.Exists(ss.dbCfg.Path)
if err != nil {
return nil, errutil.Wrapf(err, "can't check for existence of %q", ss.dbCfg.Path)
@ -277,8 +277,8 @@ func (ss *SqlStore) getEngine() (*xorm.Engine, error) {
engine.SetConnMaxLifetime(time.Second * time.Duration(ss.dbCfg.ConnMaxLifetime))
// configure sql logging
debugSql := ss.Cfg.Raw.Section("database").Key("log_queries").MustBool(false)
if !debugSql {
debugSQL := ss.Cfg.Raw.Section("database").Key("log_queries").MustBool(false)
if !debugSQL {
engine.SetLogger(&xorm.DiscardLogger{})
} else {
engine.SetLogger(NewXormLogger(log.LvlInfo, log.New("sqlstore.xorm")))
@ -289,7 +289,7 @@ func (ss *SqlStore) getEngine() (*xorm.Engine, error) {
return engine, nil
}
func (ss *SqlStore) readConfig() {
func (ss *SQLStore) readConfig() {
sec := ss.Cfg.Raw.Section("database")
cfgURL := sec.Key("url").String()
@ -340,18 +340,18 @@ type ITestDB interface {
Logf(format string, args ...interface{})
}
var testSqlStore *SqlStore
var testSQLStore *SQLStore
// InitTestDB initializes the test DB.
func InitTestDB(t ITestDB) *SqlStore {
func InitTestDB(t ITestDB) *SQLStore {
t.Helper()
if testSqlStore == nil {
testSqlStore = &SqlStore{}
testSqlStore.Bus = bus.New()
testSqlStore.CacheService = localcache.New(5*time.Minute, 10*time.Minute)
testSqlStore.skipEnsureDefaultOrgAndUser = true
if testSQLStore == nil {
testSQLStore = &SQLStore{}
testSQLStore.Bus = bus.New()
testSQLStore.CacheService = localcache.New(5*time.Minute, 10*time.Minute)
testSQLStore.skipEnsureDefaultOrgAndUser = true
dbType := migrator.SQLITE
dbType := migrator.SQLite
// environment variable present for test db?
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
@ -360,8 +360,8 @@ func InitTestDB(t ITestDB) *SqlStore {
}
// set test db config
testSqlStore.Cfg = setting.NewCfg()
sec, err := testSqlStore.Cfg.Raw.NewSection("database")
testSQLStore.Cfg = setting.NewCfg()
sec, err := testSQLStore.Cfg.Raw.NewSection("database")
if err != nil {
t.Fatalf("Failed to create section: %s", err)
}
@ -379,7 +379,7 @@ func InitTestDB(t ITestDB) *SqlStore {
t.Fatalf("Failed to create key: %s", err)
}
default:
if _, err := sec.NewKey("connection_string", sqlutil.Sqlite3TestDB().ConnStr); err != nil {
if _, err := sec.NewKey("connection_string", sqlutil.SQLite3TestDB().ConnStr); err != nil {
t.Fatalf("Failed to create key: %s", err)
}
}
@ -391,34 +391,34 @@ func InitTestDB(t ITestDB) *SqlStore {
t.Fatalf("Failed to init test database: %v", err)
}
testSqlStore.Dialect = migrator.NewDialect(engine)
testSQLStore.Dialect = migrator.NewDialect(engine)
// temp global var until we get rid of global vars
dialect = testSqlStore.Dialect
dialect = testSQLStore.Dialect
t.Logf("Cleaning DB")
if err := dialect.CleanDB(); err != nil {
t.Fatalf("Failed to clean test db %v", err)
}
if err := testSqlStore.Init(); err != nil {
if err := testSQLStore.Init(); err != nil {
t.Fatalf("Failed to init test database: %v", err)
}
testSqlStore.engine.DatabaseTZ = time.UTC
testSqlStore.engine.TZLocation = time.UTC
testSQLStore.engine.DatabaseTZ = time.UTC
testSQLStore.engine.TZLocation = time.UTC
}
if err := dialect.TruncateDBTables(); err != nil {
t.Fatalf("Failed to truncate test db %v", err)
}
return testSqlStore
return testSQLStore
}
func IsTestDbMySql() bool {
func IsTestDbMySQL() bool {
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
return db == migrator.MYSQL
return db == migrator.MySQL
}
return false
@ -426,7 +426,7 @@ func IsTestDbMySql() bool {
func IsTestDbPostgres() bool {
if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
return db == migrator.POSTGRES
return db == migrator.Postgres
}
return false

View File

@ -68,14 +68,14 @@ var sqlStoreTestCases = []sqlStoreTest{
},
}
func TestSqlConnectionString(t *testing.T) {
func TestSQLConnectionString(t *testing.T) {
Convey("Testing SQL Connection Strings", t, func() {
t.Helper()
for _, testCase := range sqlStoreTestCases {
Convey(testCase.name, func() {
sqlstore := &SqlStore{}
sqlstore.Cfg = makeSqlStoreTestConfig(testCase.dbType, testCase.dbHost)
sqlstore := &SQLStore{}
sqlstore.Cfg = makeSQLStoreTestConfig(testCase.dbType, testCase.dbHost)
sqlstore.readConfig()
connStr, err := sqlstore.buildConnectionString()
@ -89,7 +89,7 @@ func TestSqlConnectionString(t *testing.T) {
})
}
func makeSqlStoreTestConfig(dbType string, host string) *setting.Cfg {
func makeSQLStoreTestConfig(dbType string, host string) *setting.Cfg {
cfg := setting.NewCfg()
sec, err := cfg.Raw.NewSection("database")

View File

@ -10,7 +10,7 @@ type TestDB struct {
ConnStr string
}
func Sqlite3TestDB() TestDB {
func SQLite3TestDB() TestDB {
// To run all tests in a local test database, set ConnStr to "grafana_test.db"
return TestDB{
DriverName: "sqlite3",

View File

@ -13,8 +13,8 @@ func init() {
}
func IsStarredByUser(query *models.IsStarredByUserQuery) error {
rawSql := "SELECT 1 from star where user_id=? and dashboard_id=?"
results, err := x.Query(rawSql, query.UserId, query.DashboardId)
rawSQL := "SELECT 1 from star where user_id=? and dashboard_id=?"
results, err := x.Query(rawSQL, query.UserId, query.DashboardId)
if err != nil {
return err
@ -51,8 +51,8 @@ func UnstarDashboard(cmd *models.UnstarDashboardCommand) error {
}
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM star WHERE user_id=? and dashboard_id=?"
_, err := sess.Exec(rawSql, cmd.UserId, cmd.DashboardId)
var rawSQL = "DELETE FROM star WHERE user_id=? and dashboard_id=?"
_, err := sess.Exec(rawSQL, cmd.UserId, cmd.DashboardId)
return err
})
}

View File

@ -22,28 +22,28 @@ func init() {
const activeUserTimeLimit = time.Hour * 24 * 30
func GetAlertNotifiersUsageStats(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error {
var rawSql = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("alert_notification") + ` GROUP BY type`
var rawSQL = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("alert_notification") + ` GROUP BY type`
query.Result = make([]*models.NotifierUsageStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
err := x.SQL(rawSQL).Find(&query.Result)
return err
}
func GetDataSourceStats(query *models.GetDataSourceStatsQuery) error {
var rawSql = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("data_source") + ` GROUP BY type`
var rawSQL = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("data_source") + ` GROUP BY type`
query.Result = make([]*models.DataSourceStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
err := x.SQL(rawSQL).Find(&query.Result)
return err
}
func GetDataSourceAccessStats(query *models.GetDataSourceAccessStatsQuery) error {
var rawSql = `SELECT COUNT(*) AS count, type, access FROM ` + dialect.Quote("data_source") + ` GROUP BY type, access`
var rawSQL = `SELECT COUNT(*) AS count, type, access FROM ` + dialect.Quote("data_source") + ` GROUP BY type, access`
query.Result = make([]*models.DataSourceAccessStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
err := x.SQL(rawSQL).Find(&query.Result)
return err
}
func GetSystemStats(query *models.GetSystemStatsQuery) error {
sb := &SqlBuilder{}
sb := &SQLBuilder{}
sb.Write("SELECT ")
sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("user") + `) AS users,`)
sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("org") + `) AS orgs,`)
@ -84,7 +84,7 @@ func GetSystemStats(query *models.GetSystemStatsQuery) error {
sb.Write(roleCounterSQL())
var stats models.SystemStats
_, err := x.SQL(sb.GetSqlString(), sb.params...).Get(&stats)
_, err := x.SQL(sb.GetSQLString(), sb.params...).Get(&stats)
if err != nil {
return err
}
@ -113,7 +113,7 @@ func roleCounterSQL() string {
func GetAdminStats(query *models.GetAdminStatsQuery) error {
activeEndDate := time.Now().Add(-activeUserTimeLimit)
var rawSql = `SELECT
var rawSQL = `SELECT
(
SELECT COUNT(*)
FROM ` + dialect.Quote("org") + `
@ -161,7 +161,7 @@ func GetAdminStats(query *models.GetAdminStatsQuery) error {
) AS active_sessions`
var stats models.AdminStats
_, err := x.SQL(rawSql, activeEndDate, activeEndDate.Unix()).Get(&stats)
_, err := x.SQL(rawSQL, activeEndDate, activeEndDate.Unix()).Get(&stats)
if err != nil {
return err
}
@ -172,9 +172,9 @@ func GetAdminStats(query *models.GetAdminStatsQuery) error {
func GetSystemUserCountStats(ctx context.Context, query *models.GetSystemUserCountStatsQuery) error {
return withDbSession(ctx, func(sess *DBSession) error {
var rawSql = `SELECT COUNT(id) AS Count FROM ` + dialect.Quote("user")
var rawSQL = `SELECT COUNT(id) AS Count FROM ` + dialect.Quote("user")
var stats models.SystemUserCountStats
_, err := sess.SQL(rawSql).Get(&stats)
_, err := sess.SQL(rawSQL).Get(&stats)
if err != nil {
return err
}

View File

@ -24,7 +24,7 @@ func init() {
bus.AddHandler("sql", IsAdminOfTeams)
}
func getTeamSearchSqlBase() string {
func getTeamSearchSQLBase() string {
return `SELECT
team.id as id,
team.org_id,
@ -36,7 +36,7 @@ func getTeamSearchSqlBase() string {
INNER JOIN team_member on team.id = team_member.team_id AND team_member.user_id = ? `
}
func getTeamSelectSqlBase() string {
func getTeamSelectSQLBase() string {
return `SELECT
team.id as id,
team.org_id,
@ -158,10 +158,10 @@ func SearchTeams(query *models.SearchTeamsQuery) error {
params := make([]interface{}, 0)
if query.UserIdFilter > 0 {
sql.WriteString(getTeamSearchSqlBase())
sql.WriteString(getTeamSearchSQLBase())
params = append(params, query.UserIdFilter)
} else {
sql.WriteString(getTeamSelectSqlBase())
sql.WriteString(getTeamSelectSQLBase())
}
sql.WriteString(` WHERE team.org_id = ?`)
@ -207,7 +207,7 @@ func SearchTeams(query *models.SearchTeamsQuery) error {
func GetTeamById(query *models.GetTeamByIdQuery) error {
var sql bytes.Buffer
sql.WriteString(getTeamSelectSqlBase())
sql.WriteString(getTeamSelectSQLBase())
sql.WriteString(` WHERE team.org_id = ? and team.id = ?`)
var team models.TeamDTO
@ -231,7 +231,7 @@ func GetTeamsByUser(query *models.GetTeamsByUserQuery) error {
var sql bytes.Buffer
sql.WriteString(getTeamSelectSqlBase())
sql.WriteString(getTeamSelectSQLBase())
sql.WriteString(` INNER JOIN team_member on team.id = team_member.team_id`)
sql.WriteString(` WHERE team.org_id = ? and team_member.user_id = ?`)
@ -268,9 +268,9 @@ func AddTeamMember(cmd *models.AddTeamMemberCommand) error {
}
func getTeamMember(sess *DBSession, orgId int64, teamId int64, userId int64) (models.TeamMember, error) {
rawSql := `SELECT * FROM team_member WHERE org_id=? and team_id=? and user_id=?`
rawSQL := `SELECT * FROM team_member WHERE org_id=? and team_id=? and user_id=?`
var member models.TeamMember
exists, err := sess.SQL(rawSql, orgId, teamId, userId).Get(&member)
exists, err := sess.SQL(rawSQL, orgId, teamId, userId).Get(&member)
if err != nil {
return member, err
@ -322,8 +322,8 @@ func RemoveTeamMember(cmd *models.RemoveTeamMemberCommand) error {
}
}
var rawSql = "DELETE FROM team_member WHERE org_id=? and team_id=? and user_id=?"
res, err := sess.Exec(rawSql, cmd.OrgId, cmd.TeamId, cmd.UserId)
var rawSQL = "DELETE FROM team_member WHERE org_id=? and team_id=? and user_id=?"
res, err := sess.Exec(rawSQL, cmd.OrgId, cmd.TeamId, cmd.UserId)
if err != nil {
return err
}
@ -337,9 +337,9 @@ func RemoveTeamMember(cmd *models.RemoveTeamMemberCommand) error {
}
func isLastAdmin(sess *DBSession, orgId int64, teamId int64, userId int64) (bool, error) {
rawSql := "SELECT user_id FROM team_member WHERE org_id=? and team_id=? and permission=?"
rawSQL := "SELECT user_id FROM team_member WHERE org_id=? and team_id=? and permission=?"
userIds := []*int64{}
err := sess.SQL(rawSql, orgId, teamId, models.PERMISSION_ADMIN).Find(&userIds)
err := sess.SQL(rawSQL, orgId, teamId, models.PERMISSION_ADMIN).Find(&userIds)
if err != nil {
return false, err
}
@ -403,7 +403,7 @@ func GetTeamMembers(query *models.GetTeamMembersQuery) error {
}
func IsAdminOfTeams(query *models.IsAdminOfTeamsQuery) error {
builder := &SqlBuilder{}
builder := &SQLBuilder{}
builder.Write("SELECT COUNT(team.id) AS count FROM team INNER JOIN team_member ON team_member.team_id = team.id WHERE team.org_id = ? AND team_member.user_id = ? AND team_member.permission = ?", query.SignedInUser.OrgId, query.SignedInUser.UserId, models.PERMISSION_ADMIN)
type teamCount struct {
@ -411,7 +411,7 @@ func IsAdminOfTeams(query *models.IsAdminOfTeamsQuery) error {
}
resp := make([]*teamCount, 0)
if err := x.SQL(builder.GetSqlString(), builder.params...).Find(&resp); err != nil {
if err := x.SQL(builder.GetSQLString(), builder.params...).Find(&resp); err != nil {
return err
}

View File

@ -18,8 +18,8 @@ func init() {
func UpdateTempUserStatus(cmd *models.UpdateTempUserStatusCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "UPDATE temp_user SET status=? WHERE code=?"
_, err := sess.Exec(rawSql, string(cmd.Status), cmd.Code)
var rawSQL = "UPDATE temp_user SET status=? WHERE code=?"
_, err := sess.Exec(rawSQL, string(cmd.Status), cmd.Code)
return err
})
}
@ -64,7 +64,7 @@ func UpdateTempUserWithEmailSent(cmd *models.UpdateTempUserWithEmailSentCommand)
}
func GetTempUsersQuery(query *models.GetTempUsersQuery) error {
rawSql := `SELECT
rawSQL := `SELECT
tu.id as id,
tu.org_id as org_id,
tu.email as email,
@ -84,25 +84,25 @@ func GetTempUsersQuery(query *models.GetTempUsersQuery) error {
params := []interface{}{string(query.Status)}
if query.OrgId > 0 {
rawSql += ` AND tu.org_id=?`
rawSQL += ` AND tu.org_id=?`
params = append(params, query.OrgId)
}
if query.Email != "" {
rawSql += ` AND tu.email=?`
rawSQL += ` AND tu.email=?`
params = append(params, query.Email)
}
rawSql += " ORDER BY tu.created desc"
rawSQL += " ORDER BY tu.created desc"
query.Result = make([]*models.TempUserDTO, 0)
sess := x.SQL(rawSql, params...)
sess := x.SQL(rawSQL, params...)
err := sess.Find(&query.Result)
return err
}
func GetTempUserByCode(query *models.GetTempUserByCodeQuery) error {
var rawSql = `SELECT
var rawSQL = `SELECT
tu.id as id,
tu.org_id as org_id,
tu.email as email,
@ -121,7 +121,7 @@ func GetTempUserByCode(query *models.GetTempUserByCodeQuery) error {
WHERE tu.code=?`
var tempUser models.TempUserDTO
sess := x.SQL(rawSql, query.Code)
sess := x.SQL(rawSQL, query.Code)
has, err := sess.Get(&tempUser)
if err != nil {
@ -136,8 +136,8 @@ func GetTempUserByCode(query *models.GetTempUserByCodeQuery) error {
func ExpireOldUserInvites(cmd *models.ExpireTempUsersCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "UPDATE temp_user SET status = ?, updated = ? WHERE created <= ? AND status in (?, ?)"
if result, err := sess.Exec(rawSql, string(models.TmpUserExpired), time.Now().Unix(), cmd.OlderThan.Unix(), string(models.TmpUserSignUpStarted), string(models.TmpUserInvitePending)); err != nil {
var rawSQL = "UPDATE temp_user SET status = ?, updated = ? WHERE created <= ? AND status in (?, ?)"
if result, err := sess.Exec(rawSQL, string(models.TmpUserExpired), time.Now().Unix(), cmd.OlderThan.Unix(), string(models.TmpUserSignUpStarted), string(models.TmpUserInvitePending)); err != nil {
return err
} else if cmd.NumExpired, err = result.RowsAffected(); err != nil {
return err

View File

@ -12,15 +12,15 @@ import (
)
// WithTransactionalDbSession calls the callback with a session within a transaction.
func (ss *SqlStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
func (ss *SQLStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
return inTransactionWithRetryCtx(ctx, ss.engine, callback, 0)
}
func (ss *SqlStore) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
func (ss *SQLStore) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
return ss.inTransactionWithRetry(ctx, fn, 0)
}
func (ss *SqlStore) inTransactionWithRetry(ctx context.Context, fn func(ctx context.Context) error, retry int) error {
func (ss *SQLStore) inTransactionWithRetry(ctx context.Context, fn func(ctx context.Context) error, retry int) error {
return inTransactionWithRetryCtx(ctx, ss.engine, func(sess *DBSession) error {
withValue := context.WithValue(ctx, ContextSessionKey{}, sess)
return fn(withValue)

View File

@ -15,7 +15,7 @@ import (
"github.com/grafana/grafana/pkg/util"
)
func (ss *SqlStore) addUserQueryAndCommandHandlers() {
func (ss *SQLStore) addUserQueryAndCommandHandlers() {
ss.Bus.AddHandler(ss.GetSignedInUserWithCache)
bus.AddHandler("sql", GetUserById)
@ -360,7 +360,7 @@ func newSignedInUserCacheKey(orgID, userID int64) string {
return fmt.Sprintf("signed-in-user-%d-%d", userID, orgID)
}
func (ss *SqlStore) GetSignedInUserWithCache(query *models.GetSignedInUserQuery) error {
func (ss *SQLStore) GetSignedInUserWithCache(query *models.GetSignedInUserQuery) error {
cacheKey := newSignedInUserCacheKey(query.OrgId, query.UserId)
if cached, found := ss.CacheService.Get(cacheKey); found {
query.Result = cached.(*models.SignedInUser)
@ -383,7 +383,7 @@ func GetSignedInUser(query *models.GetSignedInUserQuery) error {
orgId = strconv.FormatInt(query.OrgId, 10)
}
var rawSql = `SELECT
var rawSQL = `SELECT
u.id as user_id,
u.is_admin as is_grafana_admin,
u.email as email,
@ -402,11 +402,11 @@ func GetSignedInUser(query *models.GetSignedInUserQuery) error {
sess := x.Table("user")
switch {
case query.UserId > 0:
sess.SQL(rawSql+"WHERE u.id=?", query.UserId)
sess.SQL(rawSQL+"WHERE u.id=?", query.UserId)
case query.Login != "":
sess.SQL(rawSql+"WHERE u.login=?", query.Login)
sess.SQL(rawSQL+"WHERE u.login=?", query.Login)
case query.Email != "":
sess.SQL(rawSql+"WHERE u.email=?", query.Email)
sess.SQL(rawSQL+"WHERE u.email=?", query.Email)
}
var user models.SignedInUser

View File

@ -32,10 +32,10 @@ import (
// devenv/README.md for setup instructions.
func TestMySQL(t *testing.T) {
// change to true to run the MySQL tests
runMySqlTests := false
runMySQLTests := false
// runMySqlTests := true
if !(sqlstore.IsTestDbMySql() || runMySqlTests) {
if !(sqlstore.IsTestDbMySQL() || runMySQLTests) {
t.Skip()
}