Skip to content

Commit

Permalink
test: ExplainSQL using consecutive pairs of escaper in SQL string rep…
Browse files Browse the repository at this point in the history
…resents an escaper
  • Loading branch information
iTanken committed Dec 28, 2023
1 parent 1d7de79 commit a7d7d12
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
47 changes: 45 additions & 2 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,63 @@
package main

import (
"reflect"
"testing"
)

// GORM_REPO: https://github.com/go-gorm/gorm.git
// GORM_REPO: ./gorm
// GORM_BRANCH: master
// TEST_DRIVERS: sqlite, mysql, postgres, sqlserver

func TestGORM(t *testing.T) {
user := User{Name: "jinzhu"}
user := User{Name: `"jin'zhu"`} // string values contain single or double quotes

// SQLite:
// INSERT INTO `users` (`created_at`,`updated_at`,`deleted_at`,`name`,`age`,`birthday`,`company_id`,`manager_id`,`active`)
// VALUES ("2023-12-27 17:58:17.329","2023-12-27 17:58:17.329",NULL,
// """jin'zhu""",
// 0,NULL,NULL,NULL,false
// ) RETURNING `id`
DB.Create(&user)

var result User
if err := DB.First(&result, user.ID).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
}

func TestExplain(t *testing.T) {
type args struct {
prepareSql string
values []interface{}
}
tests := []struct {
name string
args args
wantSQL string
}{
{"mysql", args{"SELECT ? AS QUOTES_STR", []interface{}{"'"}}, `SELECT '''' AS QUOTES_STR`},
{"postgres", args{"SELECT $1 AS QUOTES_STR", []interface{}{"'"}}, `SELECT '''' AS QUOTES_STR`},
{"sqlserver", args{"SELECT @p1 AS QUOTES_STR", []interface{}{"'"}}, `SELECT '''' AS QUOTES_STR`},
{"sqlite", args{"SELECT ? AS QUOTES_STR", []interface{}{`"`}}, `SELECT """" AS QUOTES_STR`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if name := DB.Dialector.Name(); name != tt.name {
t.Logf("%s skip %s...", name, tt.name)
return
}
gotSQL := DB.Dialector.Explain(tt.args.prepareSql, tt.args.values...)
if reflect.DeepEqual(gotSQL, tt.wantSQL) {
var result string
if err := DB.Raw(gotSQL).Row().Scan(&result); err == nil {
t.Logf("exec `%s` result = `%s`", gotSQL, result)
} else {
t.Errorf("exec `%s` got error: %v", gotSQL, err)
}
} else {
t.Errorf("Explain gotSQL = %v, want %v", gotSQL, tt.wantSQL)
}
})
}
}
4 changes: 2 additions & 2 deletions models.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (
// His pet also has one Toy (has one - polymorphic)
type User struct {
gorm.Model
Name string
Age uint
Name string `gorm:"comment:double quotation marks \"\" are included in the comment!"`
Age uint `gorm:"comment:single quotation marks '' are included in the comment"`
Birthday *time.Time
Account Account
Pets []*Pet
Expand Down

0 comments on commit a7d7d12

Please sign in to comment.