vitess.io/vitess@v0.16.2/go/vt/binlog/eventtoken/compare.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package eventtoken includes utility methods for event token
    18  // handling.
    19  package eventtoken
    20  
    21  import (
    22  	"vitess.io/vitess/go/mysql"
    23  	querypb "vitess.io/vitess/go/vt/proto/query"
    24  )
    25  
    26  // Fresher compares two event tokens.  It returns a negative number if
    27  // ev1<ev2, zero if they're equal, and a positive number if
    28  // ev1>ev2. In case of doubt (we don't have enough information to know
    29  // for sure), it returns a negative number.
    30  func Fresher(ev1, ev2 *querypb.EventToken) int {
    31  	if ev1 == nil || ev2 == nil {
    32  		// Either one is nil, we don't know.
    33  		return -1
    34  	}
    35  
    36  	if ev1.Timestamp != ev2.Timestamp {
    37  		// The timestamp is enough to set them apart.
    38  		return int(ev1.Timestamp - ev2.Timestamp)
    39  	}
    40  
    41  	if ev1.Shard != "" && ev1.Shard == ev2.Shard {
    42  		// They come from the same shard. See if we have positions.
    43  		if ev1.Position == "" || ev2.Position == "" {
    44  			return -1
    45  		}
    46  
    47  		// We can parse them.
    48  		pos1, err := mysql.DecodePosition(ev1.Position)
    49  		if err != nil {
    50  			return -1
    51  		}
    52  		pos2, err := mysql.DecodePosition(ev2.Position)
    53  		if err != nil {
    54  			return -1
    55  		}
    56  
    57  		// Then compare.
    58  		if pos1.Equal(pos2) {
    59  			return 0
    60  		}
    61  		if pos1.AtLeast(pos2) {
    62  			return 1
    63  		}
    64  		return -1
    65  	}
    66  
    67  	// We do not know.
    68  	return -1
    69  }