Skip to content

Commit

Permalink
Added SetSingleQuoteEscaper for #1
Browse files Browse the repository at this point in the history
  • Loading branch information
feiin committed Jul 16, 2022
1 parent 1f3c062 commit 6081e00
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
18 changes: 12 additions & 6 deletions sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import (
)

var (
tmFmtZero = "0000-00-00 00:00:00"
tmFmtWithMS = "2006-01-02 15:04:05.999"
escaper = "'"
nullStr = "NULL"
tmFmtZero = "0000-00-00 00:00:00"
tmFmtWithMS = "2006-01-02 15:04:05.999"
escaper = "'"
nullStr = "NULL"
singleQuoteEscaper = "\\"
)

//Escape escape the val for sql
Expand Down Expand Up @@ -69,7 +70,7 @@ func EscapeInLocation(val interface{}, loc *time.Location) string {
return fmt.Sprintf("%.6f", v)

case string:
return escaper + strings.Replace(v, escaper, "\\"+escaper, -1) + escaper
return escaper + strings.Replace(v, escaper, singleQuoteEscaper+escaper, -1) + escaper
default:
refValue := reflect.ValueOf(v)
if v == nil || !refValue.IsValid() {
Expand All @@ -93,7 +94,7 @@ func EscapeInLocation(val interface{}, loc *time.Location) string {
if err != nil {
return nullStr
}
return escaper + strings.Replace(string(stringifyData), escaper, "\\"+escaper, -1) + escaper
return escaper + strings.Replace(string(stringifyData), escaper, singleQuoteEscaper+escaper, -1) + escaper

}
}
Expand Down Expand Up @@ -141,3 +142,8 @@ func FormatInLocation(query string, loc *time.Location, args ...interface{}) str
}
return sql.String()
}

//SetSingleQuoteEscaper set the singleQuoteEscaper
func SetSingleQuoteEscaper(escaper string) {
singleQuoteEscaper = escaper
}
18 changes: 18 additions & 0 deletions sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ func TestStringEscape(t *testing.T) {
}
}

func TestStringCustomEscape(t *testing.T) {
s := "hello world"
SetSingleQuoteEscaper("'")
result := Escape(s)
if result != "'hello world'" {
t.Fatalf("escape string error")

}

s = "hello ' world"
result = Escape(s)
t.Logf("TestStringCustomEscape result: %s", result)
if result != "'hello '' world'" {
t.Fatalf("escape string error")

}
}

func TestBytesEscape(t *testing.T) {
s := []byte{0, 1, 254, 255}
result := Escape(s)
Expand Down

0 comments on commit 6081e00

Please sign in to comment.