/
dtids.go
58 lines (51 loc) · 1.87 KB
/
dtids.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2016, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package dtids contains dtid convenience functions.
package dtids
import (
"fmt"
"strconv"
"strings"
"github.com/youtube/vitess/go/vt/vterrors"
querypb "github.com/youtube/vitess/go/vt/proto/query"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
vtgatepb "github.com/youtube/vitess/go/vt/proto/vtgate"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
// New generates a dtid based on Session_ShardSession.
func New(mmShard *vtgatepb.Session_ShardSession) string {
return fmt.Sprintf("%s:%s:%d", mmShard.Target.Keyspace, mmShard.Target.Shard, mmShard.TransactionId)
}
// ShardSession builds a Session_ShardSession from a dtid.
func ShardSession(dtid string) (*vtgatepb.Session_ShardSession, error) {
splits := strings.Split(dtid, ":")
if len(splits) != 3 {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid parts in dtid: %s", dtid)
}
target := &querypb.Target{
Keyspace: splits[0],
Shard: splits[1],
TabletType: topodatapb.TabletType_MASTER,
}
txid, err := strconv.ParseInt(splits[2], 10, 0)
if err != nil {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid transaction id in dtid: %s", dtid)
}
return &vtgatepb.Session_ShardSession{
Target: target,
TransactionId: txid,
}, nil
}
// TransactionID extracts the original transaction ID from the dtid.
func TransactionID(dtid string) (int64, error) {
splits := strings.Split(dtid, ":")
if len(splits) != 3 {
return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid parts in dtid: %s", dtid)
}
txid, err := strconv.ParseInt(splits[2], 10, 0)
if err != nil {
return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid transaction id in dtid: %s", dtid)
}
return txid, nil
}