Skip to content

Commit

Permalink
Allow NamedArgs to start with underscore
Browse files Browse the repository at this point in the history
fixes #1869
  • Loading branch information
jackc committed Jan 13, 2024
1 parent dfb6489 commit 52f2151
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
5 changes: 4 additions & 1 deletion named_args.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (
//
// conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2})
// conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2)
//
// Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be
// letters, numbers, or underscores.
type NamedArgs map[string]any

// RewriteQuery implements the QueryRewriter interface.
Expand Down Expand Up @@ -80,7 +83,7 @@ func rawState(l *sqlLexer) stateFn {
return doubleQuoteState
case '@':
nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
if isLetter(nextRune) {
if isLetter(nextRune) || nextRune == '_' {
if l.pos-l.start > 0 {
l.parts = append(l.parts, l.src[l.start:l.pos-width])
}
Expand Down
16 changes: 8 additions & 8 deletions named_args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ func TestNamedArgsRewriteQuery(t *testing.T) {
expectedArgs: []any{int32(42), "foo"},
},
{
sql: "select @Abc::int, @b_4::text",
namedArgs: pgx.NamedArgs{"Abc": int32(42), "b_4": "foo"},
expectedSQL: "select $1::int, $2::text",
expectedArgs: []any{int32(42), "foo"},
sql: "select @Abc::int, @b_4::text, @_c::int",
namedArgs: pgx.NamedArgs{"Abc": int32(42), "b_4": "foo", "_c": int32(1)},
expectedSQL: "select $1::int, $2::text, $3::int",
expectedArgs: []any{int32(42), "foo", int32(1)},
},
{
sql: "at end @",
Expand All @@ -50,15 +50,15 @@ func TestNamedArgsRewriteQuery(t *testing.T) {
expectedArgs: []any{},
},
{
sql: "ignores without letter after @ foo bar",
sql: "ignores without valid character after @ foo bar",
namedArgs: pgx.NamedArgs{"a": int32(42), "b": "foo"},
expectedSQL: "ignores without letter after @ foo bar",
expectedSQL: "ignores without valid character after @ foo bar",
expectedArgs: []any{},
},
{
sql: "name must start with letter @1 foo bar",
sql: "name cannot start with number @1 foo bar",
namedArgs: pgx.NamedArgs{"a": int32(42), "b": "foo"},
expectedSQL: "name must start with letter @1 foo bar",
expectedSQL: "name cannot start with number @1 foo bar",
expectedArgs: []any{},
},
{
Expand Down

0 comments on commit 52f2151

Please sign in to comment.