|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Use of this software is governed by the CockroachDB Software License |
| 4 | +// included in the /LICENSE file. |
| 5 | + |
| 6 | +package eval_test |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/cockroachdb/cockroach/pkg/settings/cluster" |
| 13 | + "github.com/cockroachdb/cockroach/pkg/sql/randgen" |
| 14 | + "github.com/cockroachdb/cockroach/pkg/sql/sem/eval" |
| 15 | + "github.com/cockroachdb/cockroach/pkg/sql/types" |
| 16 | + "github.com/cockroachdb/cockroach/pkg/util/leaktest" |
| 17 | + "github.com/cockroachdb/cockroach/pkg/util/log" |
| 18 | + "github.com/cockroachdb/cockroach/pkg/util/randutil" |
| 19 | + "github.com/stretchr/testify/require" |
| 20 | +) |
| 21 | + |
| 22 | +func TestCastIdentityRandom(t *testing.T) { |
| 23 | + defer leaktest.AfterTest(t)() |
| 24 | + defer log.Scope(t).Close(t) |
| 25 | + |
| 26 | + var usesFamily func(typ *types.T, family types.Family) bool |
| 27 | + usesFamily = func(typ *types.T, family types.Family) bool { |
| 28 | + switch typ.Family() { |
| 29 | + case family: |
| 30 | + return true |
| 31 | + case types.ArrayFamily: |
| 32 | + return usesFamily(typ.ArrayContents(), family) |
| 33 | + case types.TupleFamily: |
| 34 | + for _, tupleType := range typ.TupleContents() { |
| 35 | + if usesFamily(tupleType, family) { |
| 36 | + return true |
| 37 | + } |
| 38 | + } |
| 39 | + return false |
| 40 | + default: |
| 41 | + return false |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + ctx := context.Background() |
| 46 | + castCtx := eval.MakeTestingEvalContext(cluster.MakeTestingClusterSettings()) |
| 47 | + rng, _ := randutil.NewTestRand() |
| 48 | + for trial := 0; trial < 100; trial++ { |
| 49 | + typ := randgen.RandType(rng) |
| 50 | + |
| 51 | + // Test eval context does not support the OidFamily |
| 52 | + if usesFamily(typ, types.OidFamily) { |
| 53 | + continue |
| 54 | + } |
| 55 | + |
| 56 | + value := randgen.RandDatum(rng, typ, true /* nullOk */) |
| 57 | + |
| 58 | + // A value should cast to its own type and be equal to itself after the |
| 59 | + // cast. |
| 60 | + identityCastValue, err := eval.PerformCast(ctx, &castCtx, value, typ) |
| 61 | + require.NoError(t, err) |
| 62 | + |
| 63 | + cmp, err := value.Compare(ctx, &castCtx, identityCastValue) |
| 64 | + require.NoError(t, err) |
| 65 | + require.Zero(t, cmp) |
| 66 | + |
| 67 | + // A value should cast to its canonical type and be equal to itself after |
| 68 | + // the cast. |
| 69 | + canonicalCastValue, err := eval.PerformCast(ctx, &castCtx, value, typ.Canonical()) |
| 70 | + require.NoError(t, err) |
| 71 | + |
| 72 | + cmp, err = value.Compare(ctx, &castCtx, canonicalCastValue) |
| 73 | + require.NoError(t, err) |
| 74 | + require.Zero(t, cmp) |
| 75 | + } |
| 76 | +} |
0 commit comments