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

     1  // Copyright 2017 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 tree_test
    12  
    13  import (
    14  	"context"
    15  	"testing"
    16  	"time"
    17  
    18  	"github.com/cockroachdb/cockroach/pkg/kv"
    19  	"github.com/cockroachdb/cockroach/pkg/roachpb"
    20  	_ "github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
    21  	"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    22  	"github.com/cockroachdb/cockroach/pkg/testutils"
    23  	"github.com/cockroachdb/cockroach/pkg/util/hlc"
    24  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    25  )
    26  
    27  // Test that EvalContext.GetClusterTimestamp() gets its timestamp from the
    28  // transaction, and also that the conversion to decimal works properly.
    29  func TestClusterTimestampConversion(t *testing.T) {
    30  	defer leaktest.AfterTest(t)()
    31  	testData := []struct {
    32  		walltime int64
    33  		logical  int32
    34  		expected string
    35  	}{
    36  		{42, 0, "42.0000000000"},
    37  		{-42, 0, "-42.0000000000"},
    38  		{42, 69, "42.0000000069"},
    39  		{42, 2147483647, "42.2147483647"},
    40  		{9223372036854775807, 2147483647, "9223372036854775807.2147483647"},
    41  	}
    42  
    43  	clock := hlc.NewClock(hlc.UnixNano, time.Nanosecond)
    44  	senderFactory := kv.MakeMockTxnSenderFactory(
    45  		func(context.Context, *roachpb.Transaction, roachpb.BatchRequest,
    46  		) (*roachpb.BatchResponse, *roachpb.Error) {
    47  			panic("unused")
    48  		})
    49  	db := kv.NewDB(
    50  		testutils.MakeAmbientCtx(),
    51  		senderFactory,
    52  		clock)
    53  
    54  	for _, d := range testData {
    55  		ts := hlc.Timestamp{WallTime: d.walltime, Logical: d.logical}
    56  		txnProto := roachpb.MakeTransaction(
    57  			"test",
    58  			nil, // baseKey
    59  			roachpb.NormalUserPriority,
    60  			ts,
    61  			0, /* maxOffsetNs */
    62  		)
    63  
    64  		ctx := tree.EvalContext{
    65  			Txn: kv.NewTxnFromProto(
    66  				context.Background(),
    67  				db,
    68  				1, /* gatewayNodeID */
    69  				ts,
    70  				kv.RootTxn,
    71  				&txnProto,
    72  			),
    73  		}
    74  
    75  		dec := ctx.GetClusterTimestamp()
    76  		final := dec.Text('f')
    77  		if final != d.expected {
    78  			t.Errorf("expected %s, but found %s", d.expected, final)
    79  		}
    80  	}
    81  }