cockroach底层存储RocksDB自定义Key比较器(libroach)

排序规则:
首先按照roachpb.Key的字节序顺序比较
其次,在有一个时间戳值为空时,按照hlc时间戳正序比较,否则,按照hlc时间戳逆序比较
如下排序结果: 
key, hlc

123, 0
123, 0
123, 54
123, 24
123, 24
234, 0
234, 34
234, 24
234, 14

源码分析:
pkg/storage/engine/mvcc.go

type MVCCKey struct {
    Key       roachpb.Key
    Timestamp hlc.Timestamp
}

c-deps/libroach/comparator.h


class DBComparator : public rocksdb::Comparator {

    ...
    virtual int Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const override;
    ...
}

c-deps/libroach/comparator.cc

int DBComparator::Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const {
  rocksdb::Slice key_a, key_b;
  rocksdb::Slice ts_a, ts_b;
  if (!SplitKey(a, &key_a, &ts_a) || !SplitKey(b, &key_b, &ts_b)) {
    // This should never happen unless there is some sort of corruption of
    // the keys.
    return a.compare(b);
  }

  const int c = key_a.compare(key_b);
  if (c != 0) {
    return c;
  }
  if (ts_a.empty()) {
    if (ts_b.empty()) {
      return 0;
    }
    return -1;
  } else if (ts_b.empty()) {
    return +1;
  }
  return ts_b.compare(ts_a);
}

cockroach底层存储RocksDB自定义Key比较器(libroach)

上一篇:golang Gorm执行原生SQL


下一篇:.NET Core 下使用 Log4Net 记录日志