grafana/pkg/services/sqlstore/migrator/mysql_dialect.go

326 lines
8.9 KiB
Go
Raw Normal View History

package migrator
import (
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"github.com/VividCortex/mysqlerr"
"github.com/go-sql-driver/mysql"
"github.com/golang-migrate/migrate/v4/database"
"xorm.io/xorm"
)
type MySQLDialect struct {
BaseDialect
}
func NewMysqlDialect(engine *xorm.Engine) Dialect {
d := MySQLDialect{}
d.BaseDialect.dialect = &d
d.BaseDialect.engine = engine
d.BaseDialect.driverName = MySQL
return &d
}
func (db *MySQLDialect) SupportEngine() bool {
return true
}
func (db *MySQLDialect) Quote(name string) string {
return "`" + name + "`"
}
func (db *MySQLDialect) AutoIncrStr() string {
return "AUTO_INCREMENT"
}
func (db *MySQLDialect) BooleanStr(value bool) string {
2016-10-25 07:52:20 -05:00
if value {
2016-12-13 21:15:35 -06:00
return "1"
}
return "0"
}
func (db *MySQLDialect) BatchSize() int {
return 1000
}
func (db *MySQLDialect) SQLType(c *Column) string {
var res string
switch c.Type {
case DB_Bool:
res = DB_TinyInt
c.Length = 1
case DB_Serial:
c.IsAutoIncrement = true
c.IsPrimaryKey = true
c.Nullable = false
res = DB_Int
case DB_BigSerial:
c.IsAutoIncrement = true
c.IsPrimaryKey = true
c.Nullable = false
res = DB_BigInt
case DB_Bytea:
res = DB_Blob
case DB_TimeStampz:
res = DB_Char
c.Length = 64
case DB_NVarchar:
res = DB_Varchar
default:
res = c.Type
}
Remove redundancy in variable declarations (golint) This commit fixes the following golint warnings: pkg/api/avatar/avatar.go:229:12: should omit type *http.Client from declaration of var client; it will be inferred from the right-hand side pkg/login/brute_force_login_protection.go:13:26: should omit type time.Duration from declaration of var loginAttemptsWindow; it will be inferred from the right-hand side pkg/metrics/graphitebridge/graphite.go:58:26: should omit type []string from declaration of var metricCategoryPrefix; it will be inferred from the right-hand side pkg/metrics/graphitebridge/graphite.go:69:22: should omit type []string from declaration of var trimMetricPrefix; it will be inferred from the right-hand side pkg/models/alert.go:37:36: should omit type error from declaration of var ErrCannotChangeStateOnPausedAlert; it will be inferred from the right-hand side pkg/models/alert.go:38:36: should omit type error from declaration of var ErrRequiresNewState; it will be inferred from the right-hand side pkg/models/datasource.go:61:28: should omit type map[string]bool from declaration of var knownDatasourcePlugins; it will be inferred from the right-hand side pkg/plugins/update_checker.go:16:13: should omit type http.Client from declaration of var httpClient; it will be inferred from the right-hand side pkg/services/alerting/engine.go:103:24: should omit type time.Duration from declaration of var unfinishedWorkTimeout; it will be inferred from the right-hand side pkg/services/alerting/engine.go:105:19: should omit type time.Duration from declaration of var alertTimeout; it will be inferred from the right-hand side pkg/services/alerting/engine.go:106:19: should omit type int from declaration of var alertMaxAttempts; it will be inferred from the right-hand side pkg/services/alerting/notifier.go:143:23: should omit type map[string]*NotifierPlugin from declaration of var notifierFactories; it will be inferred from the right-hand side pkg/services/alerting/rule.go:136:24: should omit type map[string]ConditionFactory from declaration of var conditionFactories; it will be inferred from the right-hand side pkg/services/alerting/conditions/evaluator.go:12:15: should omit type []string from declaration of var defaultTypes; it will be inferred from the right-hand side pkg/services/alerting/conditions/evaluator.go:13:15: should omit type []string from declaration of var rangedTypes; it will be inferred from the right-hand side pkg/services/alerting/notifiers/opsgenie.go:44:19: should omit type string from declaration of var opsgenieAlertURL; it will be inferred from the right-hand side pkg/services/alerting/notifiers/pagerduty.go:43:23: should omit type string from declaration of var pagerdutyEventApiUrl; it will be inferred from the right-hand side pkg/services/alerting/notifiers/telegram.go:21:17: should omit type string from declaration of var telegramApiUrl; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:11:24: should omit type string from declaration of var simpleDashboardConfig; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:12:24: should omit type string from declaration of var oldVersion; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:13:24: should omit type string from declaration of var brokenConfigs; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/file_reader.go:22:30: should omit type time.Duration from declaration of var checkDiskForChangesInterval; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/file_reader.go:24:23: should omit type error from declaration of var ErrFolderNameMissing; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:15:34: should omit type string from declaration of var twoDatasourcesConfig; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:16:34: should omit type string from declaration of var twoDatasourcesConfigPurgeOthers; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:17:34: should omit type string from declaration of var doubleDatasourcesConfig; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:18:34: should omit type string from declaration of var allProperties; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:19:34: should omit type string from declaration of var versionZero; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:20:34: should omit type string from declaration of var brokenYaml; it will be inferred from the right-hand side pkg/services/sqlstore/stats.go:16:25: should omit type time.Duration from declaration of var activeUserTimeLimit; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/mysql_dialect.go:69:14: should omit type bool from declaration of var hasLen1; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/mysql_dialect.go:70:14: should omit type bool from declaration of var hasLen2; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/postgres_dialect.go:95:14: should omit type bool from declaration of var hasLen1; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/postgres_dialect.go:96:14: should omit type bool from declaration of var hasLen2; it will be inferred from the right-hand side pkg/setting/setting.go:42:15: should omit type string from declaration of var Env; it will be inferred from the right-hand side pkg/setting/setting.go:161:18: should omit type bool from declaration of var LdapAllowSignup; it will be inferred from the right-hand side pkg/setting/setting.go:473:30: should omit type bool from declaration of var skipStaticRootValidation; it will be inferred from the right-hand side pkg/tsdb/interval.go:14:21: should omit type time.Duration from declaration of var defaultMinInterval; it will be inferred from the right-hand side pkg/tsdb/interval.go:15:21: should omit type time.Duration from declaration of var year; it will be inferred from the right-hand side pkg/tsdb/interval.go:16:21: should omit type time.Duration from declaration of var day; it will be inferred from the right-hand side pkg/tsdb/cloudwatch/credentials.go:26:24: should omit type map[string]cache from declaration of var awsCredentialCache; it will be inferred from the right-hand side pkg/tsdb/influxdb/query.go:15:27: should omit type *regexp.Regexp from declaration of var regexpOperatorPattern; it will be inferred from the right-hand side pkg/tsdb/influxdb/query.go:16:27: should omit type *regexp.Regexp from declaration of var regexpMeasurementPattern; it will be inferred from the right-hand side pkg/tsdb/mssql/mssql_test.go:25:14: should omit type string from declaration of var serverIP; it will be inferred from the right-hand side
2018-04-27 15:14:36 -05:00
var hasLen1 = (c.Length > 0)
var hasLen2 = (c.Length2 > 0)
if res == DB_BigInt && !hasLen1 && !hasLen2 {
c.Length = 20
hasLen1 = true
}
if hasLen2 {
res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
} else if hasLen1 {
res += "(" + strconv.Itoa(c.Length) + ")"
}
switch c.Type {
case DB_Char, DB_Varchar, DB_NVarchar, DB_TinyText, DB_Text, DB_MediumText, DB_LongText:
if c.IsLatin {
res += " CHARACTER SET latin1 COLLATE latin1_bin"
} else {
res += " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
}
}
return res
}
func (db *MySQLDialect) UpdateTableSQL(tableName string, columns []*Column) string {
var statements = []string{}
statements = append(statements, "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
for _, col := range columns {
statements = append(statements, "MODIFY "+col.StringNoPk(db))
}
return "ALTER TABLE " + db.Quote(tableName) + " " + strings.Join(statements, ", ") + ";"
}
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 *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 *MySQLDialect) RenameColumn(table Table, column *Column, newName string) string {
quote := db.dialect.Quote
return fmt.Sprintf(
"ALTER TABLE %s CHANGE %s %s %s",
quote(table.Name), quote(column.Name), quote(newName), db.SQLType(column),
)
}
func (db *MySQLDialect) CleanDB() error {
Chore: Enable PR testing in Drone (#26189) * Add Drone configuration Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add more steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add more steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Build front-end before testing it Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Upgrade grafana/build-container Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add packaging step Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Trigger on push Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove some steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Enable steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Install Dockerize Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use node image for test-frontend Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Increase number of test workers Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Make plugin installation depend on frontend tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Make integration tests depend on frontend tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use grafana/build-container also for front-end tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Upgrade dependencies in order to fix front-end tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Depend on es-check Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Dont' depend on tests before building front-end Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add more steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix packaging Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Simplify Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Try to build images Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix e2e tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove steps Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Install netcat Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Include golangci-lint with grafana/build-container Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Build storybook and docs website Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix e2e tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use build image with root user Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drop CircleCI dependencies Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix e2e tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix e2e under Drone Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Execute e2e server separately Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use own plugin for building Docker images Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use Starlark to configure Drone Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add enterprise steps to pipeline Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add more enterprise steps to pipeline Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Maintain Yarn cache Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Build enterprise Docker images Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Build Ubuntu Docker images Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Refactor Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add Postgres integration test Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Add MySQL integration test Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix integration tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Parameterize integration test DB connections Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Categorize integration tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use grabpl integration-tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove unintended change Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drone: Disable Ubuntu Docker images for PR pipeline Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Regenerate yarn.lock Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Upgrade grabpl Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Restore Yarn cache before installing in grafana-enterprise Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Use separate pipelines for OSS and enterprise Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Let OSS builds depend on tests Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Restore Go cache before building back-end Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Reduce number of variants built for PRs Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix building of Docker images Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drone: Simplify logic Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drone: Use Starlark Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drone: Fix syntax error Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Convert .drone.star to YAML Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Upgrade AWS Go SDK Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Drone: Fix Go linting Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Undo irrelevant changes Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Revert "Undo irrelevant changes" This reverts commit 5152f65972fc24f579f065beb43c2df929da1f19. * Undo irrelevant changes Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * e2e: Support Circle Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove unused script Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * TypeScript fixes Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * TypeScript fixes Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove unused script Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * More Drone support Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove unused script Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Fix build on Circle Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Remove TODO comment Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
2020-07-10 09:09:21 -05:00
tables, err := db.engine.DBMetas()
if err != nil {
return err
}
sess := db.engine.NewSession()
defer sess.Close()
for _, table := range tables {
switch table.Name {
default:
if _, err := sess.Exec("set foreign_key_checks = 0"); err != nil {
return fmt.Errorf("%v: %w", "failed to disable foreign key checks", err)
}
if _, err := sess.Exec("drop table " + table.Name + " ;"); err != nil {
return fmt.Errorf("failed to delete table %q: %w", table.Name, err)
}
if _, err := sess.Exec("set foreign_key_checks = 1"); err != nil {
return fmt.Errorf("%v: %w", "failed to disable foreign key checks", err)
}
}
}
return nil
}
// TruncateDBTables truncates all the tables.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *MySQLDialect) TruncateDBTables() error {
tables, err := db.engine.DBMetas()
if err != nil {
return err
}
sess := db.engine.NewSession()
defer sess.Close()
for _, table := range tables {
switch table.Name {
case "migration_log":
continue
case "dashboard_acl":
// keep default dashboard permissions
if _, err := sess.Exec(fmt.Sprintf("DELETE FROM %v WHERE dashboard_id != -1 AND org_id != -1;", db.Quote(table.Name))); err != nil {
return fmt.Errorf("failed to truncate table %q: %w", table.Name, err)
}
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE %v AUTO_INCREMENT = 3;", db.Quote(table.Name))); err != nil {
return fmt.Errorf("failed to reset table %q: %w", table.Name, err)
}
default:
if _, err := sess.Exec(fmt.Sprintf("TRUNCATE TABLE %v;", db.Quote(table.Name))); err != nil {
return fmt.Errorf("failed to truncate table %q: %w", table.Name, err)
}
}
}
return nil
}
func (db *MySQLDialect) isThisError(err error, errcode uint16) bool {
var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
if driverErr.Number == errcode {
return true
}
}
return false
}
func (db *MySQLDialect) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, mysqlerr.ER_DUP_ENTRY)
}
func (db *MySQLDialect) ErrorMessage(err error) string {
var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
return driverErr.Message
}
return ""
}
func (db *MySQLDialect) IsDeadlock(err error) bool {
return db.isThisError(err, mysqlerr.ER_LOCK_DEADLOCK)
}
// UpsertSQL returns the upsert sql statement for MySQL dialect
func (db *MySQLDialect) UpsertSQL(tableName string, keyCols, updateCols []string) string {
q, _ := db.UpsertMultipleSQL(tableName, keyCols, updateCols, 1)
return q
}
func (db *MySQLDialect) UpsertMultipleSQL(tableName string, keyCols, updateCols []string, count int) (string, error) {
if count < 1 {
return "", fmt.Errorf("upsert statement must have count >= 1. Got %v", count)
}
columnsStr := strings.Builder{}
colPlaceHoldersStr := strings.Builder{}
setStr := strings.Builder{}
separator := ", "
for i, c := range updateCols {
if i == len(updateCols)-1 {
separator = ""
}
columnsStr.WriteString(fmt.Sprintf("%s%s", db.Quote(c), separator))
colPlaceHoldersStr.WriteString(fmt.Sprintf("?%s", separator))
setStr.WriteString(fmt.Sprintf("%s=VALUES(%s)%s", db.Quote(c), db.Quote(c), separator))
}
valuesStr := strings.Builder{}
separator = ", "
colPlaceHolders := colPlaceHoldersStr.String()
for i := 0; i < count; i++ {
if i == count-1 {
separator = ""
}
valuesStr.WriteString(fmt.Sprintf("(%s)%s", colPlaceHolders, separator))
}
s := fmt.Sprintf(`INSERT INTO %s (%s) VALUES %s ON DUPLICATE KEY UPDATE %s`,
tableName,
columnsStr.String(),
valuesStr.String(),
setStr.String(),
)
return s, nil
}
func (db *MySQLDialect) Lock(cfg LockCfg) error {
query := "SELECT GET_LOCK(?, ?)"
var success sql.NullBool
lockName, err := db.getLockName()
if err != nil {
return fmt.Errorf("failed to generate lock name: %w", err)
}
// trying to obtain the lock with the specific name
// the lock is exclusive per session and is released explicitly by executing RELEASE_LOCK() or implicitly when the session terminates
// it returns 1 if the lock was obtained successfully,
// 0 if the attempt timed out (for example, because another client has previously locked the name),
// or NULL if an error occurred
// starting from MySQL 5.7 it is even possible for a given session to acquire multiple locks for the same name
// however other sessions cannot acquire a lock with that name until the acquiring session releases all its locks for the name.
_, err = cfg.Session.SQL(query, lockName, cfg.Timeout).Get(&success)
if err != nil {
return err
}
if !success.Valid || !success.Bool {
return ErrLockDB
}
return nil
}
func (db *MySQLDialect) Unlock(cfg LockCfg) error {
query := "SELECT RELEASE_LOCK(?)"
var success sql.NullBool
lockName, err := db.getLockName()
if err != nil {
return fmt.Errorf("failed to generate lock name: %w", err)
}
// trying to release the lock with the specific name
// it returns 1 if the lock was released,
// 0 if the lock was not established by this thread (in which case the lock is not released),
// and NULL if the named lock did not exist (it was never obtained by a call to GET_LOCK() or if it has previously been released)
_, err = cfg.Session.SQL(query, lockName).Get(&success)
if err != nil {
return err
}
if !success.Valid || !success.Bool {
return ErrReleaseLockDB
}
return nil
}
func (db *MySQLDialect) getLockName() (string, error) {
cfg, err := mysql.ParseDSN(db.engine.DataSourceName())
if err != nil {
return "", err
}
s, err := database.GenerateAdvisoryLockId(cfg.DBName)
if err != nil {
return "", fmt.Errorf("failed to generate advisory lock key: %w", err)
}
return s, nil
}