SQLStore: Run tests as integration tests (#28265)

* sqlstore: Run tests as integration tests

* Truncate database instead of re-creating it on each test

* Fix test description

See https://github.com/grafana/grafana/pull/12129

* Fix lint issues

* Fix postgres dialect after review suggestion

* Rename and document functions after review suggestion

* Add periods

* Fix auto-increment value for mysql dialect

Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
This commit is contained in:
Sofia Papagiannaki
2020-10-16 10:46:14 +03:00
committed by GitHub
parent c07896063b
commit 4937f0daab
33 changed files with 222 additions and 53 deletions

View File

@ -140,6 +140,37 @@ func (db *Postgres) CleanDB() error {
return nil
}
// TruncateDBTables truncates all the tables.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *Postgres) TruncateDBTables() error {
sess := db.engine.NewSession()
defer sess.Close()
for _, table := range db.engine.Tables {
switch table.Name {
case "":
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 errutil.Wrapf(err, "failed to truncate table %q", table.Name)
}
if _, err := sess.Exec(fmt.Sprintf("ALTER SEQUENCE %v RESTART WITH 3;", db.Quote(fmt.Sprintf("%v_id_seq", table.Name)))); err != nil {
return errutil.Wrapf(err, "failed to reset table %q", table.Name)
}
default:
if _, err := sess.Exec(fmt.Sprintf("TRUNCATE TABLE %v RESTART IDENTITY CASCADE;", db.Quote(table.Name))); err != nil {
if db.isUndefinedTable(err) {
continue
}
return errutil.Wrapf(err, "failed to truncate table %q", table.Name)
}
}
}
return nil
}
func (db *Postgres) isThisError(err error, errcode string) bool {
if driverErr, ok := err.(*pq.Error); ok {
if string(driverErr.Code) == errcode {
@ -157,6 +188,10 @@ func (db *Postgres) ErrorMessage(err error) string {
return ""
}
func (db *Postgres) isUndefinedTable(err error) bool {
return db.isThisError(err, "42P01")
}
func (db *Postgres) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, "23505")
}