From 52f215142261839b465103c9eb2423685a0cdc39 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Sat, 13 Jan 2024 10:20:25 -0600 Subject: [PATCH] Allow NamedArgs to start with underscore fixes #1869 --- named_args.go | 5 ++++- named_args_test.go | 16 ++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/named_args.go b/named_args.go index 1bc32337..8367fc63 100644 --- a/named_args.go +++ b/named_args.go @@ -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. @@ -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]) } diff --git a/named_args_test.go b/named_args_test.go index bd54faa1..49ac817d 100644 --- a/named_args_test.go +++ b/named_args_test.go @@ -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 @", @@ -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{}, }, {