vitess.io/vitess@v0.16.2/go/vt/dtids/dtids.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 dtids contains dtid convenience functions. 18 package dtids 19 20 import ( 21 "fmt" 22 "strconv" 23 "strings" 24 25 "vitess.io/vitess/go/vt/vterrors" 26 27 querypb "vitess.io/vitess/go/vt/proto/query" 28 topodatapb "vitess.io/vitess/go/vt/proto/topodata" 29 vtgatepb "vitess.io/vitess/go/vt/proto/vtgate" 30 vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc" 31 ) 32 33 // New generates a dtid based on Session_ShardSession. 34 func New(mmShard *vtgatepb.Session_ShardSession) string { 35 return fmt.Sprintf("%s:%s:%d", mmShard.Target.Keyspace, mmShard.Target.Shard, mmShard.TransactionId) 36 } 37 38 // ShardSession builds a Session_ShardSession from a dtid. 39 func ShardSession(dtid string) (*vtgatepb.Session_ShardSession, error) { 40 splits := strings.Split(dtid, ":") 41 if len(splits) != 3 { 42 return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid parts in dtid: %s", dtid) 43 } 44 target := &querypb.Target{ 45 Keyspace: splits[0], 46 Shard: splits[1], 47 TabletType: topodatapb.TabletType_PRIMARY, 48 } 49 txid, err := strconv.ParseInt(splits[2], 10, 0) 50 if err != nil { 51 return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid transaction id in dtid: %s", dtid) 52 } 53 return &vtgatepb.Session_ShardSession{ 54 Target: target, 55 TransactionId: txid, 56 }, nil 57 } 58 59 // TransactionID extracts the original transaction ID from the dtid. 60 func TransactionID(dtid string) (int64, error) { 61 splits := strings.Split(dtid, ":") 62 if len(splits) != 3 { 63 return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid parts in dtid: %s", dtid) 64 } 65 txid, err := strconv.ParseInt(splits[2], 10, 0) 66 if err != nil { 67 return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid transaction id in dtid: %s", dtid) 68 } 69 return txid, nil 70 }