mirror of
https://github.com/retailcrm/mg-transport-core.git
synced 2024-11-22 13:16:04 +03:00
statements executor (can simplify migrations)
This commit is contained in:
parent
27aee62487
commit
a2db1e41b2
14
core/db/query_executor.go
Normal file
14
core/db/query_executor.go
Normal 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
|
||||||
|
}
|
36
core/db/query_executor_test.go
Normal file
36
core/db/query_executor_test.go
Normal 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())
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user