Skip to content

fix: avoid placeholder detection in SQL comments #1573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ func bind(tz *time.Location, query string, args ...any) (string, error) {
return bindNamed(tz, query, args...)
}

haveNumeric = bindNumericRe.MatchString(query)
havePositional = bindPositionalRe.MatchString(query)
cleanQuery := stripLineComments(query)
haveNumeric = bindNumericRe.MatchString(cleanQuery)
havePositional = bindPositionalRe.MatchString(cleanQuery)
if haveNumeric && havePositional {
return "", ErrBindMixedParamsFormats
}
Expand All @@ -93,6 +94,18 @@ func bind(tz *time.Location, query string, args ...any) (string, error) {
return bindPositional(tz, query, args...)
}

// stripLineComments removes `--` style line comments from SQL queries.
// This avoids false-positive placeholder matches (e.g. `?` or `$1`) inside comments during bind() processing.
func stripLineComments(query string) string {
lines := strings.Split(query, "\n")
for i, line := range lines {
if idx := strings.Index(line, "--"); idx != -1 {
lines[i] = line[:idx]
}
}
return strings.Join(lines, "\n")
}

func checkAllNamedArguments(args ...any) (bool, error) {
var (
haveNamed bool
Expand Down
26 changes: 26 additions & 0 deletions tests/issues/1537_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package issues

import (
"context"
"testing"

"github.com/ClickHouse/clickhouse-go/v2/tests"
"github.com/stretchr/testify/require"
)

func TestIssue1537_MixedPlaceholdersAndComment(t *testing.T) {
ctx := context.Background()

conn, err := tests.GetConnection("issues", nil, nil, nil)
require.NoError(t, err)
defer conn.Close()

// PostgreSQL-style placeholder in query; `?` is in comment and should be ignored
row := conn.QueryRow(ctx, "SELECT $1 -- some comment with ?", "clickhouse")

var s string
err = row.Scan(&s)
require.NoError(t, err)
require.Equal(t, "clickhouse", s)
}

Loading