statements executor (can simplify migrations)

This commit is contained in:
Pavel 2022-06-15 17:24:50 +03:00 committed by GitHub
commit aaa0f81294
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 0 deletions

14
core/db/query_executor.go Normal file
View File

@ -0,0 +1,14 @@
package db
import "github.com/jinzhu/gorm"
// ExecStatements will execute a list of statements for the provided *gorm.DB.
// This method can be used to simplify migrations. Any other usage is discouraged.
func ExecStatements(db *gorm.DB, statements []string) error {
for _, stmt := range statements {
if err := db.Exec(stmt).Error; err != nil {
return err
}
}
return nil
}

View File

@ -0,0 +1,36 @@
package db
import (
"regexp"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jinzhu/gorm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestExecStatements(t *testing.T) {
sqlDB, mock, err := sqlmock.New()
require.NoError(t, err)
db, err := gorm.Open("postgres", sqlDB)
require.NoError(t, err)
mock.
ExpectExec(regexp.QuoteMeta(`CREATE TABLE "test_users" ("username" varchar(255) NOT NULL, "id" serial, PRIMARY KEY ("id"))`)).
WillReturnResult(sqlmock.NewResult(1, 1))
mock.
ExpectExec(regexp.QuoteMeta(`INSERT INTO "test_users" ("username") VALUES ('username') RETURNING "test_users"."id"`)).
WillReturnResult(sqlmock.NewResult(1, 1))
mock.
ExpectExec(regexp.QuoteMeta(`DELETE FROM "test_users" WHERE (id = 1)`)).
WillReturnResult(sqlmock.NewResult(1, 1))
require.NoError(t, ExecStatements(db, []string{
`CREATE TABLE "test_users" ("username" varchar(255) NOT NULL, "id" serial, PRIMARY KEY ("id"))`,
`INSERT INTO "test_users" ("username") VALUES ('username') RETURNING "test_users"."id"`,
`DELETE FROM "test_users" WHERE (id = 1)`,
}))
assert.NoError(t, mock.ExpectationsWereMet())
}