mirror of https://github.com/jackc/pgx.git
parent
1752f7b4c1
commit
58d4c0c94f
|
@ -4,6 +4,7 @@ import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
@ -78,7 +79,7 @@ func (q *Query) Sanitize(args ...any) (string, error) {
|
||||||
case bool:
|
case bool:
|
||||||
p = strconv.AppendBool(buf.AvailableBuffer(), arg)
|
p = strconv.AppendBool(buf.AvailableBuffer(), arg)
|
||||||
case []byte:
|
case []byte:
|
||||||
p = []byte(QuoteBytes(arg))
|
p = quoteBytes(buf.AvailableBuffer(), arg)
|
||||||
case string:
|
case string:
|
||||||
p = []byte(QuoteString(arg))
|
p = []byte(QuoteString(arg))
|
||||||
case time.Time:
|
case time.Time:
|
||||||
|
@ -127,7 +128,19 @@ func QuoteString(str string) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func QuoteBytes(buf []byte) string {
|
func QuoteBytes(buf []byte) string {
|
||||||
return `'\x` + hex.EncodeToString(buf) + "'"
|
return string(quoteBytes(nil, buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
func quoteBytes(dst, buf []byte) []byte {
|
||||||
|
dst = append(dst, `'\x`...)
|
||||||
|
|
||||||
|
n := hex.EncodedLen(len(buf))
|
||||||
|
p := slices.Grow(dst[len(dst):], n)[:n]
|
||||||
|
hex.Encode(p, buf)
|
||||||
|
dst = append(dst, p...)
|
||||||
|
|
||||||
|
dst = append(dst, `'`...)
|
||||||
|
return dst
|
||||||
}
|
}
|
||||||
|
|
||||||
type sqlLexer struct {
|
type sqlLexer struct {
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package sanitize_test
|
package sanitize_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/hex"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -227,3 +228,27 @@ func TestQuerySanitize(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestQuoteBytes(t *testing.T) {
|
||||||
|
tc := func(name string, input []byte) {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
got := sanitize.QuoteBytes(input)
|
||||||
|
want := oldQuoteBytes(input)
|
||||||
|
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("got: %s", got)
|
||||||
|
t.Fatalf("want: %s", want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
tc("nil", nil)
|
||||||
|
tc("empty", []byte{})
|
||||||
|
tc("text", []byte("abcd"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func oldQuoteBytes(buf []byte) string {
|
||||||
|
return `'\x` + hex.EncodeToString(buf) + "'"
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue