Skip to content

Commit

Permalink
Forward errors from nested query (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
HenrikPoulsen authored Oct 12, 2023
1 parent 792debd commit 58f8e97
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
19 changes: 19 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,25 @@ func TestJsonPointer(t *testing.T) {

}

func TestErrorSubquery(t *testing.T) {
// One more ? than we are passing args for
subQuery := New("SELECT id FROM table2 WHERE id = ? and value = ?", 1)

// It gives an error when the query is directly turned to sql
_, _, err := subQuery.ToSql()
if err == nil || !strings.Contains(err.Error(), "extra ? in text") {
t.Errorf("expected error for subquery")
}

// But if you pass it into another query instead there is no error and the sql it spits out will be
// "SELECT * FROM table WHERE id IN ()" which is not what I would expect
q := New("SELECT * FROM table WHERE id IN (?)", subQuery)
_, _, err = q.ToSql()
if err == nil || !strings.Contains(err.Error(), "extra ? in text") {
t.Errorf("expected error for subquery")
}
}

func TestOptional(t *testing.T) {
sel := Optional("you should not see this")

Expand Down
8 changes: 6 additions & 2 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,13 @@ func convertArg(text string, arg any) (string, []any, []error) {
newArgs = append(newArgs, nil)
return text, newArgs, errs
}
sql, params, _ := v.toSql()
sql, params, err := v.toSql()
text = strings.Replace(text, "?", sql, 1)
newArgs = append(newArgs, params...)
if err != nil {
errs = append(errs, err)
} else {
newArgs = append(newArgs, params...)
}

case JsonMap, JsonList:
text = strings.Replace(text, "?", paramPh, 1)
Expand Down

0 comments on commit 58f8e97

Please sign in to comment.