Skip to content

Commit

Permalink
#103 quote slices
Browse files Browse the repository at this point in the history
  • Loading branch information
kshvakov committed May 7, 2018
1 parent 4dcd9b8 commit 5e58803
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"database/sql/driver"
"fmt"
"reflect"
"regexp"
"strings"
"time"
Expand Down Expand Up @@ -116,6 +117,14 @@ func isInsert(query string) bool {
}

func quote(v driver.Value) string {
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.Slice:
values := make([]string, 0, v.Len())
for i := 0; i < v.Len(); i++ {
values = append(values, quote(v.Index(i).Interface()))
}
return strings.Join(values, ", ")
}
switch v := v.(type) {
case string:
return "'" + strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace(v) + "'"
Expand Down
11 changes: 11 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,14 @@ func Benchmark_NumInput(b *testing.B) {
numInput("SELECT * FROM example WHERE os_id in (@os_id,@browser_id) browser_id = @browser_id")
}
}

func Test_Quote(t *testing.T) {
for expected, value := range map[string]interface{}{
"'a'": "a",
"1": 1,
"'a', 'b', 'c'": []string{"a", "b", "c"},
"1, 2, 3, 4, 5": []int{1, 2, 3, 4, 5},
} {
assert.Equal(t, expected, quote(value))
}
}

0 comments on commit 5e58803

Please sign in to comment.