sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Inline comment with a question mark ? results in a "number of bindVars exceeds arguments" error within sqlx.In

Open shakram02 opened this issue 1 year ago • 1 comments

Consider this panicing main.go file

package main

import (
	"fmt"

	"github.com/jmoiron/sqlx"
)

func main() {
	query, args, err := sqlx.In(`
		SELECT
			*	-- Should we use field names ?
		FROM students
		WHERE id IN (?)
	`,
		[]int{1, 2, 3},
	)

	if err != nil {
		panic(fmt.Sprintf("Failed to generate query: %v", err.Error()))
	}

	fmt.Printf("Query: %s Args: %s", query, args)
}

If we remove the ? the program will work normally.

My educated guess is that the reason is that the following lines check for the position of the ? regardless of the existence of an inline comment, i.e. the query isn't being cleaned before bindVars getting evaluated. in bind.go line 201

for i := strings.IndexByte(query[offset:], '?'); i != -1; i = strings.IndexByte(query[offset:], '?') {
		if arg >= len(meta) {
			// if an argument wasn't passed, lets return an error;  this is
			// not actually how database/sql Exec/Query works, but since we are
			// creating an argument list programmatically, we want to be able
			// to catch these programmer errors earlier.
			return "", nil, errors.New("number of bindVars exceeds arguments")
		}
// ....
}

shakram02 avatar Jan 28 '25 16:01 shakram02