github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/schemaexpr/column_test.go (about)

     1  // Copyright 2020 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package schemaexpr
    12  
    13  import (
    14  	"context"
    15  	"testing"
    16  
    17  	"github.com/cockroachdb/cockroach/pkg/sql/parser"
    18  	"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    19  	"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
    20  	"github.com/cockroachdb/cockroach/pkg/sql/types"
    21  )
    22  
    23  func TestDequalifyColumnRefs(t *testing.T) {
    24  	ctx := context.Background()
    25  
    26  	database := tree.Name("foo")
    27  	table := tree.Name("bar")
    28  	tn := tree.MakeTableName(database, table)
    29  
    30  	cols := []sqlbase.ColumnDescriptor{
    31  		{Name: "a", Type: types.Int},
    32  		{Name: "b", Type: types.String},
    33  	}
    34  
    35  	testData := []struct {
    36  		expr     string
    37  		expected string
    38  	}{
    39  		{"a", "a"},
    40  		{"bar.a", "a"},
    41  		{"foo.bar.a", "a"},
    42  		{"a > 0", "a > 0"},
    43  		{"bar.a > 0", "a > 0"},
    44  		{"foo.bar.a > 0", "a > 0"},
    45  		{"a > 0 AND b = 'baz'", "(a > 0) AND (b = 'baz')"},
    46  		{"bar.a > 0 AND bar.b = 'baz'", "(a > 0) AND (b = 'baz')"},
    47  		{"foo.bar.a > 0 AND foo.bar.b = 'baz'", "(a > 0) AND (b = 'baz')"},
    48  		{"bar.a > 0 AND b = 'baz'", "(a > 0) AND (b = 'baz')"},
    49  		{"foo.bar.a > 0 AND b = 'baz'", "(a > 0) AND (b = 'baz')"},
    50  		{"a > 0 AND bar.b = 'baz'", "(a > 0) AND (b = 'baz')"},
    51  		{"a > 0 AND foo.bar.b = 'baz'", "(a > 0) AND (b = 'baz')"},
    52  	}
    53  
    54  	for _, d := range testData {
    55  		t.Run(d.expr, func(t *testing.T) {
    56  			expr, err := parser.ParseExpr(d.expr)
    57  			if err != nil {
    58  				t.Fatalf("%s: unexpected error: %s", d.expr, err)
    59  			}
    60  
    61  			source := sqlbase.NewSourceInfoForSingleTable(
    62  				tn, sqlbase.ResultColumnsFromColDescs(
    63  					sqlbase.ID(1),
    64  					cols,
    65  				),
    66  			)
    67  
    68  			r, err := DequalifyColumnRefs(ctx, source, expr)
    69  			if err != nil {
    70  				t.Fatalf("%s: expected success, but found error: %s", d.expr, err)
    71  			}
    72  
    73  			s := tree.Serialize(r)
    74  			if s != d.expected {
    75  				t.Errorf("%s: expected %q, got %q", d.expr, d.expected, s)
    76  			}
    77  		})
    78  	}
    79  }