From a2db1e41b28ca2c64bb95e5619e8b094ac346095 Mon Sep 17 00:00:00 2001 From: Neur0toxine Date: Wed, 15 Jun 2022 17:22:41 +0300 Subject: [PATCH] statements executor (can simplify migrations) --- core/db/query_executor.go | 14 +++++++++++++ core/db/query_executor_test.go | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 core/db/query_executor.go create mode 100644 core/db/query_executor_test.go diff --git a/core/db/query_executor.go b/core/db/query_executor.go new file mode 100644 index 0000000..e049f53 --- /dev/null +++ b/core/db/query_executor.go @@ -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 +} diff --git a/core/db/query_executor_test.go b/core/db/query_executor_test.go new file mode 100644 index 0000000..d52e898 --- /dev/null +++ b/core/db/query_executor_test.go @@ -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()) +}