forked from go-gorm/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add
Connection
to execute multiple commands in a single conne…
…ction; (go-gorm#4982)
- Loading branch information
kinggo
authored
Jan 7, 2022
1 parent
f757b8f
commit 0df42e9
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package tests_test | ||
|
||
import ( | ||
"fmt" | ||
"gorm.io/driver/mysql" | ||
"gorm.io/gorm" | ||
"testing" | ||
) | ||
|
||
func TestWithSingleConnection(t *testing.T) { | ||
|
||
var expectedName = "test" | ||
var actualName string | ||
|
||
setSQL, getSQL := getSetSQL(DB.Dialector.Name()) | ||
if len(setSQL) == 0 || len(getSQL) == 0 { | ||
return | ||
} | ||
|
||
err := DB.Connection(func(tx *gorm.DB) error { | ||
if err := tx.Exec(setSQL, expectedName).Error; err != nil { | ||
return err | ||
} | ||
|
||
if err := tx.Raw(getSQL).Scan(&actualName).Error; err != nil { | ||
return err | ||
} | ||
return nil | ||
}) | ||
|
||
if err != nil { | ||
t.Errorf(fmt.Sprintf("WithSingleConnection should work, but got err %v", err)) | ||
} | ||
|
||
if actualName != expectedName { | ||
t.Errorf("WithSingleConnection() method should get correct value, expect: %v, got %v", expectedName, actualName) | ||
} | ||
|
||
} | ||
|
||
func getSetSQL(driverName string) (string, string) { | ||
switch driverName { | ||
case mysql.Dialector{}.Name(): | ||
return "SET @testName := ?", "SELECT @testName" | ||
default: | ||
return "", "" | ||
} | ||
} |