Browse Source

mark bound parameters so cast metadata stays on the carrier

Bound parameters are inlined as literals before parsing, so a cast over a
parameter was narrowed like a user-written constant and reported a
value-dependent OID. Wrap substituted parameters in an internal
pizzasql_param() marker: it returns its argument unchanged, keeps the
carrier type in inference, and is transparent to the analyzer.
Danilo Fragoso 1 week ago
parent
commit
b1c65de222

+ 1 - 1
pkg/analyzer/analyzer.go

@@ -1346,7 +1346,7 @@ func (a *Analyzer) analyzeFunctionCall(e *parser.FunctionCall) (*ExprInfo, error
 // first argument rather than a fixed signature type.
 func isPolymorphicFunction(name string) bool {
 	switch strings.ToUpper(name) {
-	case "MIN", "MAX", "COALESCE", "IFNULL", "NVL", "NULLIF", "IIF":
+	case "MIN", "MAX", "COALESCE", "IFNULL", "NVL", "NULLIF", "IIF", "PIZZASQL_PARAM":
 		return true
 	}
 	return false

+ 1 - 0
pkg/analyzer/types.go

@@ -272,6 +272,7 @@ var builtinFunctions = map[string]FunctionSignature{
 	// SQLite specific
 	"SQLITE_VERSION":   {Name: "SQLITE_VERSION", MinArgs: 0, MaxArgs: 0, ArgTypes: []Type{}, ReturnType: TypeText, IsAggregate: false},
 	"PIZZASQL_VERSION": {Name: "PIZZASQL_VERSION", MinArgs: 0, MaxArgs: 0, ArgTypes: []Type{}, ReturnType: TypeText, IsAggregate: false},
+	"PIZZASQL_PARAM":   {Name: "PIZZASQL_PARAM", MinArgs: 1, MaxArgs: 1, ArgTypes: []Type{TypeAny}, ReturnType: TypeAny, IsAggregate: false},
 	"PG_BACKEND_PID":   {Name: "PG_BACKEND_PID", MinArgs: 0, MaxArgs: 0, ArgTypes: []Type{}, ReturnType: TypeInteger, IsAggregate: false},
 	"VERSION":          {Name: "VERSION", MinArgs: 0, MaxArgs: 0, ArgTypes: []Type{}, ReturnType: TypeText, IsAggregate: false},
 

+ 9 - 0
pkg/executor/executor.go

@@ -6174,6 +6174,15 @@ func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (i
 		args[i] = val
 	}
 
+	if name == "PIZZASQL_PARAM" {
+		// Internal marker for a bound parameter: it returns its argument
+		// unchanged so casts over parameters stay on the carrier type.
+		if len(args) != 1 {
+			return nil, fmt.Errorf("pizzasql_param expects exactly one argument")
+		}
+		return args[0], nil
+	}
+
 	// Native jsonb functions and JSON1 scalar functions are dispatched
 	// separately to keep this switch tidy.
 	if val, handled, err := e.evalJSONBFunction(name, fn, args); handled {

+ 5 - 0
pkg/executor/result_types.go

@@ -568,6 +568,11 @@ func functionResultType(fn *parser.FunctionCall, resolve columnTypeResolver) str
 		return "REGCLASS"
 	case "TO_REGTYPE":
 		return "REGTYPE"
+	case "PIZZASQL_PARAM":
+		// Internal marker for a bound parameter. It returns its argument
+		// unchanged, and reporting the carrier type keeps cast metadata
+		// independent of the bound value.
+		return firstArgType(fn, resolve)
 	default:
 		return "TEXT"
 	}

+ 5 - 0
pkg/pgserver/connection.go

@@ -1077,7 +1077,12 @@ func bindQuery(query string, params []boundParameter) (string, error) {
 		if err != nil {
 			return "", fmt.Errorf("parameter $%d: %w", reference.number, err)
 		}
+		// Mark substituted parameters so result-type inference does not treat
+		// them as user-written constants. A cast over a parameter must keep the
+		// carrier type instead of narrowing to the literal's width.
+		result.WriteString("pizzasql_param(")
 		result.WriteString(literal)
+		result.WriteString(")")
 		last = reference.end
 	}
 	result.WriteString(query[last:])

+ 1 - 1
pkg/pgserver/connection_test.go

@@ -27,7 +27,7 @@ func TestBindQuery(t *testing.T) {
 	if err != nil {
 		t.Fatal(err)
 	}
-	want := "SELECT 'O''Reilly', 42, NULL, TRUE, '$5'"
+	want := "SELECT pizzasql_param('O''Reilly'), pizzasql_param(42), pizzasql_param(NULL), pizzasql_param(TRUE), '$5'"
 	if query != want {
 		t.Fatalf("bound query = %q, want %q", query, want)
 	}

+ 46 - 0
pkg/pgserver/param_cast_oid_test.go

@@ -0,0 +1,46 @@
+package pgserver
+
+import (
+	"context"
+	"testing"
+)
+
+// A bound parameter is inlined as a literal, but that literal is not a
+// user-written constant: casts over parameters must keep the carrier OID so
+// result metadata does not depend on the bound value.
+func TestParameterCastKeepsCarrierOID(t *testing.T) {
+	conn := connectPGX(t)
+	defer conn.Close(context.Background())
+
+	cases := []struct {
+		query string
+		arg   any
+		want  uint32
+	}{
+		{"SELECT $1::SMALLINT", int16(1), 20},
+		{"SELECT $1::SMALLINT", int64(40000), 20},
+		{"SELECT $1::INTEGER", int32(1), 20},
+		{"SELECT $1::REAL", float32(1.5), 701},
+	}
+	for _, tc := range cases {
+		rows, err := conn.Query(context.Background(), tc.query, tc.arg)
+		if err != nil {
+			t.Fatalf("%s: %v", tc.query, err)
+		}
+		fields := rows.FieldDescriptions()
+		if len(fields) != 1 || fields[0].DataTypeOID != tc.want {
+			t.Fatalf("%s: got %v, want OID %d", tc.query, fields, tc.want)
+		}
+		rows.Close()
+	}
+
+	// User-written literals still report their exact width.
+	rows, err := conn.Query(context.Background(), "SELECT 1::SMALLINT")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if got := rows.FieldDescriptions()[0].DataTypeOID; got != 21 {
+		t.Fatalf("literal SMALLINT cast OID = %d, want 21", got)
+	}
+	rows.Close()
+}

+ 5 - 5
pkg/pgserver/sql_matching_test.go

@@ -7,12 +7,12 @@ import (
 
 func TestBindQuerySkipsCommentsAndQuotedRegions(t *testing.T) {
 	for _, tc := range []struct{ query, want string }{
-		{"SELECT $1 /* ' $99 */ + $2", "SELECT 1 /* ' $99 */ + 2"},
-		{"SELECT $1 -- '$99\n + $2", "SELECT 1 -- '$99\n + 2"},
-		{"SELECT $1 -- $99", "SELECT 1 -- $99"},
+		{"SELECT $1 /* ' $99 */ + $2", "SELECT pizzasql_param(1) /* ' $99 */ + pizzasql_param(2)"},
+		{"SELECT $1 -- '$99\n + $2", "SELECT pizzasql_param(1) -- '$99\n + pizzasql_param(2)"},
+		{"SELECT $1 -- $99", "SELECT pizzasql_param(1) -- $99"},
 		// Brackets are not a quoted region: a subscript such as tags[$1] binds.
-		{"SELECT '$99''$88', \"$77\", `$66`, tags[$1]", "SELECT '$99''$88', \"$77\", `$66`, tags[1]"},
-		{"SELECT '$1 /* no comment */', $2", "SELECT '$1 /* no comment */', 2"},
+		{"SELECT '$99''$88', \"$77\", `$66`, tags[$1]", "SELECT '$99''$88', \"$77\", `$66`, tags[pizzasql_param(1)]"},
+		{"SELECT '$1 /* no comment */', $2", "SELECT '$1 /* no comment */', pizzasql_param(2)"},
 	} {
 		got, err := bindQuery(tc.query, []boundParameter{{value: []byte("1")}, {value: []byte("2")}})
 		if err != nil || got != tc.want {