Skip to content

Commit

Permalink
Add quoting from
Browse files Browse the repository at this point in the history
  • Loading branch information
qbart committed Dec 7, 2021
1 parent efabcd5 commit b00fb55
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
25 changes: 24 additions & 1 deletion krabdb/quote.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package krabdb

import (
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"

"github.com/jackc/pgx/v4"
)
Expand Down Expand Up @@ -37,5 +41,24 @@ func QuoteIdentStrings(in []string) []string {

// Quote escapes values in PG.
func Quote(o interface{}) string {
panic("Quote not implemented")
switch o := o.(type) {
case nil:
return "null"
case int64:
return strconv.FormatInt(o, 10)
case uint64:
return strconv.FormatUint(o, 10)
case float64:
return strconv.FormatFloat(o, 'f', -1, 64)
case bool:
return strconv.FormatBool(o)
case []byte:
return `'\x` + hex.EncodeToString(o) + "'"
case string:
return "'" + strings.ReplaceAll(o, "'", "''") + "'"
case time.Time:
return o.Truncate(time.Microsecond).Format("'2006-01-02 15:04:05.999999999Z07:00:00'")
default:
panic(fmt.Sprintf("Quote not implemented for type %T", o))
}
}
36 changes: 36 additions & 0 deletions krabdb/quote_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package krabdb

import (
"testing"
"time"
)

func TestQuote(t *testing.T) {
testCases := []struct {
given interface{}
expected string
}{
{nil, "null"},
{int64(420), "420"},
{uint64(420), "420"},
{float64(42.1), "42.1"},
{true, "true"},
{false, "false"},
{[]byte{255, 128, 0}, `'\xff8000'`},
{`krab`, `'krab'`},
{`oh'krab`, `'oh''krab'`},
{`oh\'krab`, `'oh\''krab'`},
{
time.Date(2020, time.March, 1, 23, 59, 59, 999999999, time.UTC),
`'2020-03-01 23:59:59.999999Z'`,
},
}

for i, tc := range testCases {
actual := Quote(tc.given)

if tc.expected != actual {
t.Errorf("[%d] expected %s, but got %s", i, tc.expected, actual)
}
}
}

0 comments on commit b00fb55

Please sign in to comment.