Skip to content

Commit 89f202d

Browse files
committed
better count params in query
1 parent ab44d14 commit 89f202d

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

main.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import (
99
"io"
1010
"log"
1111
"net/http"
12+
"regexp"
13+
"strconv"
1214
"strings"
1315

1416
_ "github.com/mattn/go-sqlite3"
@@ -189,13 +191,34 @@ func query(w http.ResponseWriter, r *http.Request) {
189191
wFlusher.Flush()
190192
}
191193

194+
func countParams() int {
195+
rows, err := queryStmt.Query()
196+
if err != nil {
197+
regex := regexp.MustCompile(`sql: expected (\d+) arguments, got 0`)
198+
regexSubmatches := regex.FindAllStringSubmatch(err.Error(), 1)
199+
if len(regexSubmatches) != 1 || len(regexSubmatches[0]) != 2 {
200+
// this is weird, return best guess
201+
return strings.Count(queryString, "?")
202+
}
203+
count, err := strconv.Atoi(regexSubmatches[0][1])
204+
if err != nil {
205+
// this is weirder because the regex is \d+
206+
// return best guess
207+
return strings.Count(queryString, "?")
208+
}
209+
return count
210+
}
211+
rows.Close()
212+
return 0
213+
}
214+
192215
func buildHelpMessage() {
193216
helpMessage += fmt.Sprintf(`Query:
194217
%s
195218
196219
`, queryString)
197220

198-
queryParamsCount = strings.Count(queryString, "?")
221+
queryParamsCount = countParams()
199222
helpMessage += fmt.Sprintf(`Params count (question marks in query):
200223
%d
201224

0 commit comments

Comments
 (0)