Skip to content

Commit

Permalink
auto convert strings in ids
Browse files Browse the repository at this point in the history
  • Loading branch information
NoBypass committed Mar 25, 2024
1 parent 689614e commit a92b9cd
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 10 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,5 @@ Just make a pull request, and it will be reviewed as soon as possible.
## To-Do

- [ ] Optimize parameter parsing
- [x] Automatically use string syntax for string IDs
- [ ] Document IDs and Ranged IDs
4 changes: 3 additions & 1 deletion actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ func (db *DB) Scan(scan any, query string, args ...any) error {
last := res[len(res)-1]
if last.Error != nil {
return last.Error
} else if last.Data == nil || len(last.Data.([]any)) == 0 {
return nil
}

return scanData(scan, last)
Expand Down Expand Up @@ -85,6 +87,6 @@ func (db *DB) MustExec(query string, args ...any) {
}
}

type ID [2]any
type ID []any

type Range [2]ID
10 changes: 10 additions & 0 deletions intergration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ SELECT * FROM test;
err := db.Scan(&obj, "SELECT * FROM other:$", Range{ID{123}, ID{457}})
assert.NoError(t, err)
})
t.Run("With string id", func(t *testing.T) {
var obj string
err := db.Scan(&obj, "SELECT * FROM other:$", ID{"123"})
assert.NoError(t, err)
})
t.Run("With ranged string id", func(t *testing.T) {
var obj []string
err := db.Scan(&obj, "SELECT * FROM other:$", Range{ID{"123"}, ID{"457"}})
assert.NoError(t, err)
})
t.Run("Scan only", func(t *testing.T) {
only := testObject{}
err := db.Scan(&only, "SELECT * FROM ONLY test WHERE time_since = $time_since", testObject{TimeSince: ts})
Expand Down
27 changes: 18 additions & 9 deletions internals.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,27 @@ func setVal(dest, src reflect.Value) {
}

func (id ID) string() string {
s := make([]string, 0, 2)
for _, v := range id {
if v == nil {
continue
if len(id) == 1 {
switch id[0].(type) {
case string:
return fmt.Sprintf("`%s`", strings.Replace(id[0].(string), "`", "", -1))
default:
return fmt.Sprintf("%v", id[0])
}
s = append(s, fmt.Sprintf("%v", v))
}
str := strings.Join(s, ", ")
if len(s) == 1 {
return str

str := "["
for _, v := range id {
switch v.(type) {
case string:
v = fmt.Sprintf("'%s'", strings.Replace(v.(string), "'", "", -1))
default:
v = fmt.Sprintf("%v", v)
}

str += fmt.Sprintf("%v, ", v)
}
return fmt.Sprintf("[%s]", str)
return str[:len(str)-1] + "]"
}

func (r Range) string() string {
Expand Down

0 comments on commit a92b9cd

Please sign in to comment.