Przeglądaj źródła

report exact literal cast OIDs and float8-backed scalar NUMERIC

- A cast result reports its declared width only when the operand is a constant
  that fits it: SMALLINT/INTEGER use the int64 result range and REAL the
  float32 range, because evalCastExpr carries int64/float64 without range
  checks. A cast over a column, parameter, or nested expression keeps the
  int8/float8 carrier instead.
- A SMALLINT literal cast uses the exact INT2 result spelling (OID 21); a
  SMALLINT column keeps int8 (OID 20) because stored values are not
  range-checked. A UNION widens the exact int2 proof back to int8 because it
  also carries the other branch's values.
- Scalar NUMERIC/DECIMAL casts report float8 (701), matching declared numeric
  columns, while NUMERIC[] keeps exact decimal text and numeric[] (1231).
- Advertise scalar NUMERIC as float8-backed in the capability document
  (types.numeric) and document the result OID contract in the README.

Tests: literal cast OIDs with carrier fallbacks, declared numeric metadata,
NUMERIC[] exactness, pgx float64 scalar scanning, the capability assertion,
binary int2/float4/float8 results, array constructors, and compound widening.
Danilo Fragoso 1 tydzień temu
rodzic
commit
73b2294447

+ 11 - 0
README.md

@@ -507,6 +507,17 @@ curl -X POST "http://localhost:8080/import?format=sqlite" \
 
 **Data Types:** `INTEGER` (INT, BIGINT, BOOLEAN) · `REAL` (FLOAT, DOUBLE, DECIMAL) · `TEXT` (VARCHAR, CHAR) · `BLOB` · `NUMERIC`
 
+**Result type OIDs:** a scalar `NUMERIC`/`DECIMAL` value is carried as float64 and
+reported as `float8` (OID 701), so a client scans it as `float64`. Trailing zeros,
+scale beyond float64 precision, and magnitudes above 2^53 are not preserved for
+scalars; `CAST(x AS NUMERIC)` reports the same `float8` result. `NUMERIC[]` and
+`DECIMAL[]` keep exact decimal text and report `numeric[]` (OID 1231). A literal
+cast reports its declared type when the value fits the engine's carrier
+(`1::SMALLINT` → `int2`, `1::INTEGER` → `int4`, `1.5::REAL` → `float4`,
+`1.5::DOUBLE` → `float8`); a cast over a column or parameter, or a literal that
+does not fit, reports the `int8`/`float8` carrier instead. `INTEGER` and `REAL`
+columns keep their declared OIDs (23 and 700).
+
 **Joins:** INNER · LEFT · RIGHT · FULL OUTER · CROSS
 
 **Aggregates:** COUNT · COUNT(DISTINCT) · SUM · AVG · MIN · MAX

+ 2 - 0
pkg/capabilities/capabilities.go

@@ -105,6 +105,7 @@ type Types struct {
 	Integer  bool    `json:"integer"`
 	Bigint   bool    `json:"bigint"`
 	Real     bool    `json:"real"`
+	Numeric  Feature `json:"numeric"`
 	Text     bool    `json:"text"`
 	Blob     bool    `json:"blob"`
 	Boolean  bool    `json:"boolean"`
@@ -225,6 +226,7 @@ func Current() *Document {
 			Integer:  true,
 			Bigint:   true,
 			Real:     true,
+			Numeric:  Feature{Supported: true, Status: "float8_backed", Notes: "a scalar NUMERIC or DECIMAL value is carried as float64 and reported as float8 (OID 701), so a client scans it as float64: trailing zeros, scale beyond float64 precision, and magnitudes above 2^53 are not preserved; CAST(x AS NUMERIC/DECIMAL) reports the same float8 result; NUMERIC[] and DECIMAL[] keep their exact decimal text and report numeric[] (OID 1231), validated and canonicalized per element; NUMERIC-typed comparisons, including CAST(... AS NUMERIC), stay exact"},
 			Text:     true,
 			Blob:     true,
 			Boolean:  true,

+ 26 - 0
pkg/capabilities/capabilities_test.go

@@ -421,3 +421,29 @@ func TestCatalogIntrospectionIsAdvertised(t *testing.T) {
 		t.Fatalf("document does not advertise the catalog as read-only: %s", body)
 	}
 }
+
+// The scalar NUMERIC contract is advertised: float8-backed scalars with a
+// float64 client type, while NUMERIC[] keeps exact text.
+func TestScalarNumericIsAdvertisedAsFloat8Backed(t *testing.T) {
+	doc := Current()
+	numeric := doc.Types.Numeric
+	if !numeric.Supported {
+		t.Fatalf("types.numeric = %+v, want supported", numeric)
+	}
+	if numeric.Status != "float8_backed" {
+		t.Fatalf("types.numeric status = %q, want float8_backed", numeric.Status)
+	}
+	for _, want := range []string{"OID 701", "float8", "float64", "NUMERIC[]", "OID 1231", "exact"} {
+		if !strings.Contains(numeric.Notes, want) {
+			t.Fatalf("types.numeric notes = %q, want it to mention %q", numeric.Notes, want)
+		}
+	}
+
+	body, err := json.Marshal(doc)
+	if err != nil {
+		t.Fatalf("marshal: %v", err)
+	}
+	if !strings.Contains(string(body), `"numeric":{"supported":true`) {
+		t.Fatalf("document does not advertise types.numeric as supported: %s", body)
+	}
+}

+ 1 - 1
pkg/executor/arrays.go

@@ -586,7 +586,7 @@ func (e *Executor) parsedArray(expr parser.Expr, value interface{}) ([]*string,
 
 // isNumericExprType reports whether an expression's declared type is NUMERIC or
 // DECIMAL, which compares exactly instead of through float64. CAST(... AS
-// NUMERIC) is included even though its result metadata stays unchanged: the
+// NUMERIC) is included even though its result metadata advertises float8: the
 // cast leaves the value's carrier alone, but comparisons still mean decimal.
 func (e *Executor) isNumericExprType(expr parser.Expr) bool {
 	switch x := expr.(type) {

+ 6 - 1
pkg/executor/executor.go

@@ -1598,8 +1598,13 @@ func (e *Executor) executeCompound(c *parser.CompoundSelect) (*Result, error) {
 		result.AddColumn(col)
 	}
 	// A compound SELECT reports the left branch's projection metadata, as
-	// PostgreSQL does: the set operation does not retype its columns.
+	// PostgreSQL does: the set operation does not retype its columns. A union
+	// also carries the right branch's values, so an exact-width type the left
+	// branch proved widens back to its carrier.
 	result.ColumnTypes = append([]string(nil), left.ColumnTypes...)
+	if c.Op == parser.SetOpUnion || c.Op == parser.SetOpUnionAll {
+		result.ColumnTypes = carrierColumnTypes(result.ColumnTypes)
+	}
 
 	switch c.Op {
 	case parser.SetOpUnion:

+ 99 - 10
pkg/executor/result_types.go

@@ -1,6 +1,7 @@
 package executor
 
 import (
+	"math"
 	"strconv"
 	"strings"
 
@@ -319,7 +320,7 @@ func inferExprType(expr parser.Expr, resolve columnTypeResolver) string {
 	case *parser.LiteralExpr:
 		return literalType(e)
 	case *parser.CastExpr:
-		if typeName, ok := castResultType(e.Type.SQLTypeName()); ok {
+		if typeName, ok := castResultType(e.Type.SQLTypeName(), e.Expr); ok {
 			return typeName
 		}
 		return "TEXT"
@@ -370,22 +371,52 @@ func literalType(lit *parser.LiteralExpr) string {
 	}
 }
 
+// exactInt2TypeName is the result type name for a SMALLINT cast whose constant
+// operand fits int2. A SMALLINT column keeps reporting the int8 carrier because
+// stored values are not range-checked, so the exact width needs its own spelling
+// for the wire layer to map to OID 21 (int2).
+const exactInt2TypeName = "INT2"
+
 // castResultType reports the result type of CAST(x AS name). Only targets the
 // executor actually converts are reported; every other target leaves the value
 // untouched, so the value keeps its original encoding and stays TEXT metadata.
 //
-// Casts report the carrier type of the converted value, not the target width:
-// evalCastExpr always produces int64 for integer targets and float64 for
-// real targets, and it does not range-check them. A narrower advertised type
-// (int2/int4/float4) could otherwise fail to decode a value the engine accepted.
-func castResultType(name string) (string, bool) {
+// evalCastExpr always produces int64 for integer targets and float64 for real
+// targets and does not range-check them, so a narrower advertised type could
+// fail to decode a value the engine accepted. A cast therefore reports its
+// declared width only when the operand is a constant that fits that width:
+// SMALLINT and INTEGER use the int64 result range, and REAL the float32 range.
+// A cast over a column, parameter, or other expression reports the carrier type
+// instead (int8 or float8).
+func castResultType(name string, operand parser.Expr) (string, bool) {
 	if element, isArray := arrayElementType(name); isArray {
 		return arrayResultTypeName(element), true
 	}
 	switch strings.ToUpper(strings.TrimSpace(name)) {
-	case "INTEGER", "INT", "SMALLINT", "TINYINT", "MEDIUMINT", "BIGINT":
+	case "SMALLINT":
+		if value, ok := constantNumericValue(operand); ok && value >= math.MinInt16 && value <= math.MaxInt16 {
+			return exactInt2TypeName, true
+		}
+		return "BIGINT", true
+	case "INTEGER", "INT":
+		if value, ok := constantNumericValue(operand); ok && value >= math.MinInt32 && value <= math.MaxInt32 {
+			return "INTEGER", true
+		}
 		return "BIGINT", true
-	case "REAL", "FLOAT", "DOUBLE":
+	case "TINYINT", "MEDIUMINT", "BIGINT":
+		return "BIGINT", true
+	case "REAL", "FLOAT":
+		// float4 cannot represent a magnitude above MaxFloat32; the binary
+		// encoder rejects such a value rather than sending an infinity.
+		if value, ok := constantNumericValue(operand); ok && math.Abs(value) <= math.MaxFloat32 {
+			return "REAL", true
+		}
+		return "DOUBLE", true
+	case "DOUBLE":
+		return "DOUBLE", true
+	case "NUMERIC", "DECIMAL":
+		// A scalar NUMERIC is float64-backed: the engine keeps no exact decimal
+		// carrier and the wire reports float8 (701). NUMERIC[] keeps exact text.
 		return "DOUBLE", true
 	case "TEXT", "VARCHAR", "CHAR", "CHARACTER", "CLOB", "NCHAR", "NVARCHAR":
 		return "TEXT", true
@@ -406,6 +437,48 @@ func castResultType(name string) (string, bool) {
 	}
 }
 
+// constantNumericValue reports the numeric value of a cast operand that is
+// statically known: a numeric or string literal, optionally parenthesized or
+// signed. It reports false for every other expression, including a NULL literal,
+// so the caller keeps the carrier type when the value is not proven to fit.
+func constantNumericValue(expr parser.Expr) (float64, bool) {
+	switch e := expr.(type) {
+	case *parser.ParenExpr:
+		return constantNumericValue(e.Expr)
+	case *parser.UnaryExpr:
+		if e.Op != lexer.TokenMinus && e.Op != lexer.TokenPlus {
+			return 0, false
+		}
+		value, ok := constantNumericValue(e.Operand)
+		if !ok {
+			return 0, false
+		}
+		if e.Op == lexer.TokenMinus {
+			return -value, true
+		}
+		return value, true
+	case *parser.LiteralExpr:
+		switch e.Type {
+		case lexer.TokenNumber, lexer.TokenString:
+			// evalCastExpr converts through toFloat, which parses the same
+			// decimal text; a value that does not parse is not proven either.
+			value, err := strconv.ParseFloat(e.Value, 64)
+			if err != nil {
+				return 0, false
+			}
+			return value, true
+		case lexer.TokenTRUE:
+			return 1, true
+		case lexer.TokenFALSE:
+			return 0, true
+		default:
+			return 0, false
+		}
+	default:
+		return 0, false
+	}
+}
+
 // arrayConstructorType reports the array type of an ARRAY[...] constructor. The
 // element type follows the first non-NULL element; a constructor mixing element
 // types falls back to TEXT[].
@@ -449,7 +522,7 @@ func arrayResultTypeName(elementType string) string {
 	switch strings.ToUpper(strings.TrimSpace(elementType)) {
 	case "INTEGER", "INT", "INT4":
 		return "INTEGER[]"
-	case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
+	case "BIGINT", "INT8", "SMALLINT", exactInt2TypeName, "TINYINT", "MEDIUMINT":
 		return "BIGINT[]"
 	case "REAL", "FLOAT", "FLOAT4":
 		return "REAL[]"
@@ -622,13 +695,29 @@ func caseResultType(e *parser.CaseExpr, resolve columnTypeResolver) string {
 // isIntegerTypeName reports whether a type name is an integer type.
 func isIntegerTypeName(name string) bool {
 	switch strings.ToUpper(strings.TrimSpace(name)) {
-	case "INTEGER", "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT":
+	case "INTEGER", "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT", exactInt2TypeName:
 		return true
 	default:
 		return false
 	}
 }
 
+// carrierColumnTypes widens exact-width result types to their carrier. A compound
+// SELECT reports the left branch's metadata but also contains the right branch's
+// values, which were never checked against the narrower type the left branch
+// proved.
+func carrierColumnTypes(types []string) []string {
+	wides := make([]string, len(types))
+	for i, typeName := range types {
+		if strings.EqualFold(typeName, exactInt2TypeName) {
+			wides[i] = "BIGINT"
+			continue
+		}
+		wides[i] = typeName
+	}
+	return wides
+}
+
 // isFloatCarrierTypeName reports whether a type name is carried as float64.
 // NUMERIC and DECIMAL have no exact decimal carrier in the engine: their values
 // round-trip through JSON as float64, so they behave like floating-point types.

+ 54 - 3
pkg/executor/result_types_test.go

@@ -209,7 +209,8 @@ func TestInferExprType(t *testing.T) {
 		{"-1.5", "DOUBLE"},
 		{"(id)", "INTEGER"},
 
-		// Casts report the target type the executor converts to.
+		// Casts over a column report the carrier type the executor produces, not
+		// the target width: the value is not proven to fit a narrower type.
 		{"CAST(id AS BIGINT)", "BIGINT"},
 		{"CAST(id AS SMALLINT)", "BIGINT"},
 		{"CAST(id AS TEXT)", "TEXT"},
@@ -219,7 +220,29 @@ func TestInferExprType(t *testing.T) {
 		{"CAST(id AS INTEGER)", "BIGINT"},
 		{"CAST(id AS TINYINT)", "BIGINT"},
 		{"CAST(id AS DATE)", "TEXT"},
-		{"CAST(id AS NUMERIC)", "TEXT"},
+		// Scalar NUMERIC is float64-backed, so its result metadata is float8.
+		{"CAST(id AS NUMERIC)", "DOUBLE"},
+		{"CAST(id AS DECIMAL)", "DOUBLE"},
+
+		// A literal cast reports its declared width when the constant fits the
+		// carrier; INT2 is the exact-width spelling a SMALLINT column cannot use.
+		{"CAST(1 AS SMALLINT)", "INT2"},
+		{"1::SMALLINT", "INT2"},
+		{"'5'::SMALLINT", "INT2"},
+		{"32767::SMALLINT", "INT2"},
+		{"32768::SMALLINT", "BIGINT"},
+		{"'abc'::SMALLINT", "BIGINT"},
+		{"CAST(NULL AS SMALLINT)", "BIGINT"},
+		{"CAST(1 AS INTEGER)", "INTEGER"},
+		{"2147483647::INTEGER", "INTEGER"},
+		{"2147483648::INTEGER", "BIGINT"},
+		{"1::BIGINT", "BIGINT"},
+		{"1.5::REAL", "REAL"},
+		{"CAST(1 AS REAL)", "REAL"},
+		{"3.5e38::REAL", "DOUBLE"},
+		{"1.5::DOUBLE", "DOUBLE"},
+		{"1::NUMERIC", "DOUBLE"},
+		{"1.5::DECIMAL", "DOUBLE"},
 
 		// NUMERIC/DECIMAL have no exact decimal carrier: their values are
 		// float64, so expressions over them report DOUBLE.
@@ -266,6 +289,12 @@ func TestSelectColumnTypesExpressions(t *testing.T) {
 		{"SELECT 42 FROM t", []string{"INTEGER"}},
 		{"SELECT 1.5 FROM t", []string{"DOUBLE"}},
 		{"SELECT CAST(id AS BIGINT) FROM t", []string{"BIGINT"}},
+		{"SELECT 1::SMALLINT FROM t", []string{"INT2"}},
+		{"SELECT 40000::SMALLINT FROM t", []string{"BIGINT"}},
+		{"SELECT 1.5::REAL FROM t", []string{"REAL"}},
+		{"SELECT 1.5::DOUBLE FROM t", []string{"DOUBLE"}},
+		{"SELECT 1::NUMERIC FROM t", []string{"DOUBLE"}},
+		{"SELECT CAST(id AS SMALLINT) FROM t", []string{"BIGINT"}},
 		{"SELECT created_at FROM t GROUP BY created_at", []string{"TIMESTAMP"}},
 		{"SELECT id FROM t UNION SELECT id FROM t", []string{"INTEGER"}},
 		// The empty result still reports projection metadata.
@@ -295,7 +324,7 @@ func TestSelectColumnTypesWithoutFrom(t *testing.T) {
 	e := newExec(schema, table)
 
 	res := execMust(t, e, "SELECT 1, 1.5, 'x', 1 = 1, CAST(1 AS SMALLINT)")
-	want := []string{"INTEGER", "DOUBLE", "TEXT", "BOOLEAN", "BIGINT"}
+	want := []string{"INTEGER", "DOUBLE", "TEXT", "BOOLEAN", "INT2"}
 	if len(res.ColumnTypes) != len(want) {
 		t.Fatalf("column types = %v, want %v", res.ColumnTypes, want)
 	}
@@ -305,3 +334,25 @@ func TestSelectColumnTypesWithoutFrom(t *testing.T) {
 		}
 	}
 }
+
+// TestCompoundWidensExactInt2 covers the one composition where an exact literal
+// cast type stops being safe: a union also carries the right branch's values, so
+// the left branch's int2 proof widens back to the int8 carrier. INTERSECT and
+// EXCEPT keep only the left branch's rows and keep the exact type.
+func TestCompoundWidensExactInt2(t *testing.T) {
+	_, schema, table := newTestDB(t)
+	e := newExec(schema, table)
+
+	res := execMust(t, e, `SELECT 1::SMALLINT AS v UNION ALL SELECT 40000`)
+	if len(res.ColumnTypes) != 1 || res.ColumnTypes[0] != "BIGINT" {
+		t.Fatalf("union column types = %v, want [BIGINT]", res.ColumnTypes)
+	}
+	if len(res.Rows) != 2 || res.Rows[1][0] != int64(40000) {
+		t.Fatalf("union rows = %v", res.Rows)
+	}
+
+	res = execMust(t, e, `SELECT 1::SMALLINT AS v INTERSECT SELECT 1`)
+	if len(res.ColumnTypes) != 1 || res.ColumnTypes[0] != "INT2" {
+		t.Fatalf("intersect column types = %v, want [INT2]", res.ColumnTypes)
+	}
+}

+ 201 - 0
pkg/pgserver/cast_result_oids_test.go

@@ -0,0 +1,201 @@
+package pgserver
+
+import "testing"
+
+// TestLiteralCastResultOIDs pins the reported type of a cast whose operand is a
+// constant. evalCastExpr carries int64/float64 and does not range-check, so a
+// declared width narrower than the carrier is advertised only when the constant
+// fits it; otherwise the carrier type (int8/float8) is reported.
+func TestLiteralCastResultOIDs(t *testing.T) {
+	c, client := newDataConnection(t)
+
+	cases := []struct {
+		sql   string
+		want  int32
+		value string
+	}{
+		{"SELECT 1::SMALLINT", 21, "1"},         // int2
+		{"SELECT CAST(1 AS SMALLINT)", 21, "1"}, // int2
+		{"SELECT 32767::SMALLINT", 21, "32767"}, // int2
+		{"SELECT -1::SMALLINT", 21, "-1"},       // int2
+		{"SELECT 32768::SMALLINT", 20, "32768"}, // int8 carrier
+		{"SELECT 1::INTEGER", 23, "1"},          // int4
+		{"SELECT 1::INT", 23, "1"},              // int4
+		{"SELECT 2147483647::INTEGER", 23, "2147483647"},
+		{"SELECT 2147483648::INTEGER", 20, "2147483648"}, // int8 carrier
+		{"SELECT 1::BIGINT", 20, "1"},                    // int8
+		{"SELECT 1.5::REAL", 700, "1.5"},                 // float4
+		{"SELECT CAST(1 AS REAL)", 700, "1"},             // float4
+		{"SELECT 3.5e38::REAL", 701, "3.5e+38"},          // float8 carrier
+		{"SELECT 1.5::DOUBLE", 701, "1.5"},               // float8
+		{"SELECT 1.5::DOUBLE PRECISION", 701, "1.5"},     // float8
+		{"SELECT 1::NUMERIC", 701, "1"},                  // float8 carrier
+		{"SELECT 1.5::DECIMAL", 701, "1.5"},              // float8 carrier
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.sql, func(t *testing.T) {
+			msgs := resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(tc.sql), 0)}))
+			if errMsg := findError(msgs); errMsg != nil {
+				t.Fatalf("%s failed: %s", tc.sql, errorCode(errMsg))
+			}
+			oids := rowDescriptionOIDs(t, findRowDescription(t, msgs).Data)
+			if len(oids) != 1 || oids[0] != tc.want {
+				t.Fatalf("%s: OIDs = %v, want [%d]", tc.sql, oids, tc.want)
+			}
+			if row := firstDataRow(t, msgs); len(row) != 1 || row[0] != tc.value {
+				t.Fatalf("%s: row = %v, want [%s]", tc.sql, row, tc.value)
+			}
+		})
+	}
+}
+
+// TestNumericResultMetadataIsFloat8 pins the scalar NUMERIC contract from both
+// directions: a declared NUMERIC/DECIMAL column and a NUMERIC cast report
+// float8 (701) because scalars are float64-backed, while NUMERIC[] keeps exact
+// element text and reports numeric[] (1231).
+func TestNumericResultMetadataIsFloat8(t *testing.T) {
+	c, client := newDataConnection(t)
+	for _, sql := range []string{
+		`CREATE TABLE amounts (id INTEGER PRIMARY KEY, price NUMERIC, discount DECIMAL, history NUMERIC[])`,
+		`INSERT INTO amounts VALUES (1, '12345678901234567890.50', '1.10', '{12345678901234567890.50,1.10}')`,
+	} {
+		if msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(sql), 0)}); findError(msgs) != nil {
+			t.Fatalf("%s: %s", sql, errorCode(findError(msgs)))
+		}
+	}
+
+	cases := []struct {
+		sql   string
+		want  int32
+		value string
+	}{
+		{"SELECT price FROM amounts", 701, "12345678901234567890.50"},
+		{"SELECT discount FROM amounts", 701, "1.10"},
+		{"SELECT history FROM amounts", 1231, "{12345678901234567890.50,1.10}"},
+		{"SELECT price::NUMERIC FROM amounts", 701, "12345678901234567890.50"},
+		{"SELECT CAST(discount AS DECIMAL) FROM amounts", 701, "1.10"},
+		{"SELECT price + 0 FROM amounts", 701, "1.2345678901234567e+19"},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.sql, func(t *testing.T) {
+			msgs := resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(tc.sql), 0)}))
+			if errMsg := findError(msgs); errMsg != nil {
+				t.Fatalf("%s failed: %s", tc.sql, errorCode(errMsg))
+			}
+			oids := rowDescriptionOIDs(t, findRowDescription(t, msgs).Data)
+			if len(oids) != 1 || oids[0] != tc.want {
+				t.Fatalf("%s: OIDs = %v, want [%d]", tc.sql, oids, tc.want)
+			}
+			if row := firstDataRow(t, msgs); len(row) != 1 || row[0] != tc.value {
+				t.Fatalf("%s: row = %v, want [%s]", tc.sql, row, tc.value)
+			}
+		})
+	}
+}
+
+// TestCastOverColumnKeepsCarrierOID guards the other half of the literal-cast
+// rule: the value of a column is not proven to fit, so it keeps the carrier
+// type even when the column's declared type is narrower.
+func TestCastOverColumnKeepsCarrierOID(t *testing.T) {
+	c, client := newDataConnection(t)
+	for _, sql := range []string{
+		`CREATE TABLE wide (id INTEGER PRIMARY KEY, big BIGINT, score DOUBLE)`,
+		`INSERT INTO wide VALUES (1, 40000, 3.5e38)`,
+	} {
+		if msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(sql), 0)}); findError(msgs) != nil {
+			t.Fatalf("%s: %s", sql, errorCode(findError(msgs)))
+		}
+	}
+
+	for _, tc := range []struct {
+		sql  string
+		want int32
+	}{
+		{`SELECT big::SMALLINT FROM wide`, 20},
+		{`SELECT big::INTEGER FROM wide`, 20},
+		{`SELECT score::REAL FROM wide`, 701},
+	} {
+		t.Run(tc.sql, func(t *testing.T) {
+			msgs := resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(tc.sql), 0)}))
+			if errMsg := findError(msgs); errMsg != nil {
+				t.Fatalf("%s failed: %s", tc.sql, errorCode(errMsg))
+			}
+			oids := rowDescriptionOIDs(t, findRowDescription(t, msgs).Data)
+			if len(oids) != 1 || oids[0] != tc.want {
+				t.Fatalf("%s: OIDs = %v, want [%d]", tc.sql, oids, tc.want)
+			}
+		})
+	}
+}
+
+// TestExactCastOIDsSurviveBinaryResults checks that a binary result requests the
+// exact width the RowDescription advertises: int2 is two bytes, float4 is four,
+// and a scalar NUMERIC cast is a float8.
+func TestExactCastOIDsSurviveBinaryResults(t *testing.T) {
+	cases := []struct {
+		sql  string
+		want int32
+		data []byte
+	}{
+		{"SELECT 1::SMALLINT", 21, []byte{0, 1}},
+		{"SELECT 1.5::REAL", 700, []byte{0x3f, 0xc0, 0, 0}},
+		{"SELECT 1::NUMERIC", 701, []byte{0x3f, 0xf0, 0, 0, 0, 0, 0, 0}},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.sql, func(t *testing.T) {
+			c, conn := extendedResultConnection(t)
+			sendExtended(t, c,
+				parseMessage("s", tc.sql),
+				bindResultMessage("p", "s", nil, []int16{1}),
+				executeMessage("p"),
+				&Message{Type: MsgSync},
+			)
+			msgs := readAllMessages(t, conn.bytes())
+			if errMsg := findError(msgs); errMsg != nil {
+				t.Fatalf("%s failed: %s", tc.sql, errorCode(errMsg))
+			}
+			oids := rowDescriptionOIDs(t, findRowDescription(t, msgs).Data)
+			if len(oids) != 1 || oids[0] != tc.want {
+				t.Fatalf("%s: OIDs = %v, want [%d]", tc.sql, oids, tc.want)
+			}
+			rows := dataRowsRaw(t, msgs)
+			if len(rows) != 1 || len(rows[0]) != 1 {
+				t.Fatalf("%s: rows = %v", tc.sql, rows)
+			}
+			assertBytes(t, tc.sql, rows[0][0], tc.data)
+		})
+	}
+}
+
+// TestArrayConstructorOfExactCast keeps the array path consistent: an exact cast
+// used as an ARRAY[...] element maps back to its carrier array OID instead of
+// falling through to text[].
+func TestArrayConstructorOfExactCast(t *testing.T) {
+	c, client := newDataConnection(t)
+	cases := []struct {
+		sql   string
+		want  int32
+		value string
+	}{
+		{"SELECT ARRAY[1::SMALLINT]", 1016, "{1}"},
+		{"SELECT ARRAY[1.5::REAL]", 1021, "{1.5}"},
+	}
+	for _, tc := range cases {
+		t.Run(tc.sql, func(t *testing.T) {
+			msgs := resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(tc.sql), 0)}))
+			if errMsg := findError(msgs); errMsg != nil {
+				t.Fatalf("%s failed: %s", tc.sql, errorCode(errMsg))
+			}
+			oids := rowDescriptionOIDs(t, findRowDescription(t, msgs).Data)
+			if len(oids) != 1 || oids[0] != tc.want {
+				t.Fatalf("%s: OIDs = %v, want [%d]", tc.sql, oids, tc.want)
+			}
+			if row := firstDataRow(t, msgs); len(row) != 1 || row[0] != tc.value {
+				t.Fatalf("%s: row = %v, want [%s]", tc.sql, row, tc.value)
+			}
+		})
+	}
+}

+ 9 - 2
pkg/pgserver/connection.go

@@ -1600,7 +1600,12 @@ func (c *Connection) getOIDForType(typeName string) int32 {
 		return arrayOIDForElement(element)
 	}
 	switch strings.ToUpper(typeName) {
-	case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
+	case "INT2":
+		// The executor's exact-width spelling for a SMALLINT cast whose
+		// constant value fits int2. A SMALLINT column is grouped below because
+		// its stored values are not range-checked.
+		return 21 // INT2OID
+	case "SMALLINT", "TINYINT", "MEDIUMINT":
 		// Carried as int64 and not range-checked, so int8 is the honest type.
 		return 20 // INT8OID
 	case "INTEGER", "INT", "INT4":
@@ -1653,7 +1658,9 @@ func (c *Connection) getTypeSizeForType(typeName string) int16 {
 		return -1 // arrays are variable length
 	}
 	switch strings.ToUpper(typeName) {
-	case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
+	case "INT2":
+		return 2 // Exact int2 cast result; see getOIDForType.
+	case "SMALLINT", "TINYINT", "MEDIUMINT":
 		return 8 // Reported as int8; see getOIDForType.
 	case "INTEGER", "INT", "INT4":
 		return 4

+ 4 - 2
pkg/pgserver/oid_test.go

@@ -18,9 +18,10 @@ func TestGetOIDForTypeDatetime(t *testing.T) {
 		"TIMESTAMP": 1184,
 		"DATE":      1082,
 		// Integer types narrower than the int64 carrier report int8 because the
-		// engine does not range-check stored values.
+		// engine does not range-check stored values. INT2 is the executor's
+		// exact-width spelling for a constant SMALLINT cast that fits int2.
 		"SMALLINT":  20,
-		"INT2":      20,
+		"INT2":      21,
 		"TINYINT":   20,
 		"MEDIUMINT": 20,
 		"INTEGER":   23,
@@ -137,6 +138,7 @@ func TestGetTypeSizeForType(t *testing.T) {
 		"MEDIUMINT": 8,
 		"INTEGER":   4,
 		"BIGINT":    8,
+		"INT2":      2,
 		"REAL":      4,
 		"DOUBLE":    8,
 		"NUMERIC":   8,

+ 106 - 0
pkg/pgserver/pgx_numeric_test.go

@@ -0,0 +1,106 @@
+package pgserver
+
+import (
+	"context"
+	"strconv"
+	"testing"
+)
+
+// TestPGXNumericScalarIsFloat8 pins the chosen scalar NUMERIC contract: a
+// NUMERIC column and a NUMERIC cast are reported as float8 (701), so pgx scans
+// them as float64 and loses digits beyond float64 precision. NUMERIC[] keeps
+// exact element text and reports numeric[] (1231).
+func TestPGXNumericScalarIsFloat8(t *testing.T) {
+	conn := connectPGX(t)
+	ctx := context.Background()
+	for _, sql := range []string{
+		`CREATE TABLE amounts (id INTEGER PRIMARY KEY, amount NUMERIC, history NUMERIC[])`,
+		`INSERT INTO amounts VALUES (1, '12345678901234567890.50', '{12345678901234567890.50,1.10}')`,
+	} {
+		if _, err := conn.Exec(ctx, sql); err != nil {
+			t.Fatalf("%s: %v", sql, err)
+		}
+	}
+
+	rows, err := conn.Query(ctx, `SELECT amount FROM amounts WHERE id = 1`)
+	if err != nil {
+		t.Fatalf("query: %v", err)
+	}
+	if oid := rows.FieldDescriptions()[0].DataTypeOID; oid != 701 {
+		t.Fatalf("numeric column OID = %d, want 701 (float8)", oid)
+	}
+	if !rows.Next() {
+		t.Fatal("no row returned")
+	}
+	var amount float64
+	if err := rows.Scan(&amount); err != nil {
+		t.Fatalf("scan numeric as float64: %v", err)
+	}
+	want, err := strconv.ParseFloat("12345678901234567890.50", 64)
+	if err != nil {
+		t.Fatalf("parse expected value: %v", err)
+	}
+	if amount != want {
+		t.Fatalf("numeric value = %v, want the float64 rounding %v", amount, want)
+	}
+	if err := rows.Err(); err != nil {
+		t.Fatalf("rows: %v", err)
+	}
+	rows.Close()
+
+	rows, err = conn.Query(ctx, `SELECT 1::NUMERIC`)
+	if err != nil {
+		t.Fatalf("query cast: %v", err)
+	}
+	defer rows.Close()
+	if oid := rows.FieldDescriptions()[0].DataTypeOID; oid != 701 {
+		t.Fatalf("numeric cast OID = %d, want 701 (float8)", oid)
+	}
+	var cast float64
+	if !rows.Next() {
+		t.Fatal("no row returned for the cast")
+	}
+	if err := rows.Scan(&cast); err != nil || cast != 1 {
+		t.Fatalf("numeric cast scan = %v, %v; want 1", cast, err)
+	}
+}
+
+// TestPGXNumericArrayKeepsExactText is the other half of the contract: an array
+// of NUMERIC stays exact, so pgx reads back every digit and trailing zero.
+func TestPGXNumericArrayKeepsExactText(t *testing.T) {
+	conn := connectPGX(t)
+	ctx := context.Background()
+	for _, sql := range []string{
+		`CREATE TABLE amounts (id INTEGER PRIMARY KEY, history NUMERIC[])`,
+		`INSERT INTO amounts VALUES (1, '{12345678901234567890.50,1.10}')`,
+	} {
+		if _, err := conn.Exec(ctx, sql); err != nil {
+			t.Fatalf("%s: %v", sql, err)
+		}
+	}
+
+	rows, err := conn.Query(ctx, `SELECT history FROM amounts WHERE id = 1`)
+	if err != nil {
+		t.Fatalf("query: %v", err)
+	}
+	defer rows.Close()
+	if oid := rows.FieldDescriptions()[0].DataTypeOID; oid != 1231 {
+		t.Fatalf("numeric[] OID = %d, want 1231", oid)
+	}
+	if !rows.Next() {
+		t.Fatal("no row returned")
+	}
+	var history []string
+	if err := rows.Scan(&history); err != nil {
+		t.Fatalf("scan numeric[]: %v", err)
+	}
+	want := []string{"12345678901234567890.50", "1.10"}
+	if len(history) != len(want) {
+		t.Fatalf("numeric[] = %v, want %v", history, want)
+	}
+	for i := range want {
+		if history[i] != want[i] {
+			t.Fatalf("numeric[] = %v, want %v", history, want)
+		}
+	}
+}