bplus_tree.h 14.7 KB
Newer Older
羽飞's avatar
羽飞 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
//
// Created by Xie Meiyi
// Rewritten by Longda & Wangyunlai
//
//
#ifndef __OBSERVER_STORAGE_COMMON_INDEX_MANAGER_H_
#define __OBSERVER_STORAGE_COMMON_INDEX_MANAGER_H_

#include <string.h>
#include <sstream>
羽飞's avatar
羽飞 已提交
22
#include <functional>
羽飞's avatar
羽飞 已提交
23

羽飞's avatar
羽飞 已提交
24
#include "storage/record/record_manager.h"
羽飞's avatar
羽飞 已提交
25 26
#include "storage/default/disk_buffer_pool.h"
#include "sql/parser/parse_defs.h"
27
#include "util/comparator.h"
羽飞's avatar
羽飞 已提交
28 29 30 31

#define EMPTY_RID_PAGE_NUM -1
#define EMPTY_RID_SLOT_NUM -1

L
Longda Feng 已提交
32
class AttrComparator {
羽飞's avatar
羽飞 已提交
33 34 35 36 37 38 39
public:
  void init(AttrType type, int length)
  {
    attr_type_ = type;
    attr_length_ = length;
  }

L
Longda Feng 已提交
40 41
  int attr_length() const
  {
羽飞's avatar
羽飞 已提交
42 43 44
    return attr_length_;
  }

L
Longda Feng 已提交
45 46
  int operator()(const char *v1, const char *v2) const
  {
羽飞's avatar
羽飞 已提交
47
    switch (attr_type_) {
L
Longda Feng 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60
      case INTS: {
        return compare_int((void *)v1, (void *)v2);
      } break;
      case FLOATS: {
        return compare_float((void *)v1, (void *)v2);
      }
      case CHARS: {
        return compare_string((void *)v1, attr_length_, (void *)v2, attr_length_);
      }
      default: {
        LOG_ERROR("unknown attr type. %d", attr_type_);
        abort();
      }
羽飞's avatar
羽飞 已提交
61 62
    }
  }
L
Longda Feng 已提交
63

羽飞's avatar
羽飞 已提交
64 65 66 67 68
private:
  AttrType attr_type_;
  int attr_length_;
};

L
Longda Feng 已提交
69
class KeyComparator {
羽飞's avatar
羽飞 已提交
70 71 72 73 74 75
public:
  void init(AttrType type, int length)
  {
    attr_comparator_.init(type, length);
  }

L
Longda Feng 已提交
76 77
  const AttrComparator &attr_comparator() const
  {
羽飞's avatar
羽飞 已提交
78 79 80
    return attr_comparator_;
  }

L
Longda Feng 已提交
81 82
  int operator()(const char *v1, const char *v2) const
  {
羽飞's avatar
羽飞 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
    int result = attr_comparator_(v1, v2);
    if (result != 0) {
      return result;
    }

    const RID *rid1 = (const RID *)(v1 + attr_comparator_.attr_length());
    const RID *rid2 = (const RID *)(v2 + attr_comparator_.attr_length());
    return RID::compare(rid1, rid2);
  }

private:
  AttrComparator attr_comparator_;
};

L
Longda Feng 已提交
97
class AttrPrinter {
羽飞's avatar
羽飞 已提交
98 99 100 101 102 103 104
public:
  void init(AttrType type, int length)
  {
    attr_type_ = type;
    attr_length_ = length;
  }

L
Longda Feng 已提交
105 106
  int attr_length() const
  {
羽飞's avatar
羽飞 已提交
107 108 109
    return attr_length_;
  }

L
Longda Feng 已提交
110 111
  std::string operator()(const char *v) const
  {
羽飞's avatar
羽飞 已提交
112
    switch (attr_type_) {
L
Longda Feng 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
      case INTS: {
        return std::to_string(*(int *)v);
      } break;
      case FLOATS: {
        return std::to_string(*(float *)v);
      }
      case CHARS: {
        std::string str;
        for (int i = 0; i < attr_length_; i++) {
          if (v[i] == 0) {
            break;
          }
          str.push_back(v[i]);
        }
        return str;
      }
      default: {
        LOG_ERROR("unknown attr type. %d", attr_type_);
        abort();
羽飞's avatar
羽飞 已提交
132
      }
羽飞's avatar
羽飞 已提交
133 134
    }
  }
L
Longda Feng 已提交
135

羽飞's avatar
羽飞 已提交
136 137 138 139 140
private:
  AttrType attr_type_;
  int attr_length_;
};

L
Longda Feng 已提交
141
class KeyPrinter {
羽飞's avatar
羽飞 已提交
142 143 144 145 146 147
public:
  void init(AttrType type, int length)
  {
    attr_printer_.init(type, length);
  }

L
Longda Feng 已提交
148 149
  const AttrPrinter &attr_printer() const
  {
羽飞's avatar
羽飞 已提交
150 151 152
    return attr_printer_;
  }

L
Longda Feng 已提交
153 154
  std::string operator()(const char *v) const
  {
羽飞's avatar
羽飞 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    std::stringstream ss;
    ss << "{key:" << attr_printer_(v) << ",";

    const RID *rid = (const RID *)(v + attr_printer_.attr_length());
    ss << "rid:{" << rid->to_string() << "}}";
    return ss.str();
  }

private:
  AttrPrinter attr_printer_;
};

/**
 * the meta information of bplus tree
 * this is the first page of bplus tree.
 * only one field can be supported, can you extend it to multi-fields?
 */
struct IndexFileHeader {
  IndexFileHeader()
  {
    memset(this, 0, sizeof(IndexFileHeader));
    root_page = BP_INVALID_PAGE_NUM;
  }
L
Longda Feng 已提交
178 179 180 181 182
  PageNum root_page;
  int32_t internal_max_size;
  int32_t leaf_max_size;
  int32_t attr_length;
  int32_t key_length;  // attr length + sizeof(RID)
羽飞's avatar
羽飞 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  AttrType attr_type;

  const std::string to_string()
  {
    std::stringstream ss;

    ss << "attr_length:" << attr_length << ","
       << "key_length:" << key_length << ","
       << "attr_type:" << attr_type << ","
       << "root_page:" << root_page << ","
       << "internal_max_size:" << internal_max_size << ","
       << "leaf_max_size:" << leaf_max_size << ";";

    return ss.str();
  }
};

#define RECORD_RESERVER_PAIR_NUM 2
/**
 * the common part of page describtion of bplus tree
 * storage format:
 * | page type | item number | parent page id |
 */
struct IndexNode {
  static constexpr int HEADER_SIZE = 12;

  bool is_leaf;
  int key_num;
  PageNum parent;
};

/**
 * leaf page of bplus tree
 * storage format:
 * | common header | prev page id | next page id |
 * | key0, rid0 | key1, rid1 | ... | keyn, ridn |
 *
 * the key is in format: the key value of record and rid.
 * so the key in leaf page must be unique.
 * the value is rid.
 * can you implenment a cluster index ?
 */
struct LeafIndexNode : public IndexNode {
  static constexpr int HEADER_SIZE = IndexNode::HEADER_SIZE + 8;
L
Longda Feng 已提交
227

羽飞's avatar
羽飞 已提交
228 229 230 231 232 233 234 235 236 237 238
  PageNum prev_brother;
  PageNum next_brother;
  /**
   * leaf can store order keys and rids at most
   */
  char array[0];
};

/**
 * internal page of bplus tree
 * storage format:
L
Longda Feng 已提交
239
 * | common header |
羽飞's avatar
羽飞 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
 * | key(0),page_id(0) | key(1), page_id(1) | ... | key(n), page_id(n) |
 *
 * the first key is ignored(key0).
 * so it will waste space, can you fix this?
 */
struct InternalIndexNode : public IndexNode {
  static constexpr int HEADER_SIZE = IndexNode::HEADER_SIZE;

  /**
   * internal node just store order -1 keys and order rids, the last rid is last rght child.
   */
  char array[0];
};

class IndexNodeHandler {
public:
羽飞's avatar
羽飞 已提交
256
  IndexNodeHandler(const IndexFileHeader &header, Frame *frame);
羽飞's avatar
羽飞 已提交
257 258 259 260

  void init_empty(bool leaf);

  bool is_leaf() const;
L
Longda Feng 已提交
261 262 263
  int key_size() const;
  int value_size() const;
  int item_size() const;
羽飞's avatar
羽飞 已提交
264 265

  void increase_size(int n);
L
Longda Feng 已提交
266
  int size() const;
羽飞's avatar
羽飞 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  void set_parent_page_num(PageNum page_num);
  PageNum parent_page_num() const;

  PageNum page_num() const;

  bool validate() const;

  friend std::string to_string(const IndexNodeHandler &handler);

protected:
  const IndexFileHeader &header_;
  PageNum page_num_;
  IndexNode *node_;
};

class LeafIndexNodeHandler : public IndexNodeHandler {
L
Longda Feng 已提交
283
public:
羽飞's avatar
羽飞 已提交
284
  LeafIndexNodeHandler(const IndexFileHeader &header, Frame *frame);
羽飞's avatar
羽飞 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

  void init_empty();
  void set_next_page(PageNum page_num);
  void set_prev_page(PageNum page_num);
  PageNum next_page() const;
  PageNum prev_page() const;

  char *key_at(int index);
  char *value_at(int index);

  /**
   * 查找指定key的插入位置(注意不是key本身)
   * 如果key已经存在,会设置found的值
   * NOTE: 当前lookup的实现效率非常低,你是否可以优化它?
   */
  int lookup(const KeyComparator &comparator, const char *key, bool *found = nullptr) const;

  void insert(int index, const char *key, const char *value);
  void remove(int index);
L
Longda Feng 已提交
304 305 306 307
  int remove(const char *key, const KeyComparator &comparator);
  RC move_half_to(LeafIndexNodeHandler &other, DiskBufferPool *bp);
  RC move_first_to_end(LeafIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool);
  RC move_last_to_front(LeafIndexNodeHandler &other, DiskBufferPool *bp);
羽飞's avatar
羽飞 已提交
308 309 310
  /**
   * move all items to left page
   */
羽飞's avatar
羽飞 已提交
311
  RC move_to(LeafIndexNodeHandler &other, DiskBufferPool *bp);
羽飞's avatar
羽飞 已提交
312 313 314 315

  int max_size() const;
  int min_size() const;

羽飞's avatar
羽飞 已提交
316
  bool validate(const KeyComparator &comparator, DiskBufferPool *bp) const;
羽飞's avatar
羽飞 已提交
317 318

  friend std::string to_string(const LeafIndexNodeHandler &handler, const KeyPrinter &printer);
L
Longda Feng 已提交
319

羽飞's avatar
羽飞 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333
private:
  char *__item_at(int index) const;
  char *__key_at(int index) const;
  char *__value_at(int index) const;

  void append(const char *item);
  void preappend(const char *item);

private:
  LeafIndexNode *leaf_node_;
};

class InternalIndexNodeHandler : public IndexNodeHandler {
public:
羽飞's avatar
羽飞 已提交
334
  InternalIndexNodeHandler(const IndexFileHeader &header, Frame *frame);
羽飞's avatar
羽飞 已提交
335 336 337 338 339

  void init_empty();
  void create_new_root(PageNum first_page_num, const char *key, PageNum page_num);

  void insert(const char *key, PageNum page_num, const KeyComparator &comparator);
L
Longda Feng 已提交
340
  RC move_half_to(LeafIndexNodeHandler &other, DiskBufferPool *bp);
羽飞's avatar
羽飞 已提交
341 342 343 344 345 346
  char *key_at(int index);
  PageNum value_at(int index);

  /**
   * 返回指定子节点在当前节点中的索引
   */
L
Longda Feng 已提交
347
  int value_index(PageNum page_num);
羽飞's avatar
羽飞 已提交
348 349 350 351 352 353 354 355
  void set_key_at(int index, const char *key);
  void remove(int index);

  /**
   * 与Leaf节点不同,lookup返回指定key应该属于哪个子节点,返回这个子节点在当前节点中的索引
   * 如果想要返回插入位置,就提供 `insert_position` 参数
   * NOTE: 查找效率不高,你可以优化它吗?
   */
L
Longda Feng 已提交
356 357 358
  int lookup(
      const KeyComparator &comparator, const char *key, bool *found = nullptr, int *insert_position = nullptr) const;

羽飞's avatar
羽飞 已提交
359 360 361
  int max_size() const;
  int min_size() const;

羽飞's avatar
羽飞 已提交
362 363 364 365
  RC move_to(InternalIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool);
  RC move_first_to_end(InternalIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool);
  RC move_last_to_front(InternalIndexNodeHandler &other, DiskBufferPool *bp);
  RC move_half_to(InternalIndexNodeHandler &other, DiskBufferPool *bp);
羽飞's avatar
羽飞 已提交
366

羽飞's avatar
羽飞 已提交
367
  bool validate(const KeyComparator &comparator, DiskBufferPool *bp) const;
羽飞's avatar
羽飞 已提交
368 369

  friend std::string to_string(const InternalIndexNodeHandler &handler, const KeyPrinter &printer);
L
Longda Feng 已提交
370

羽飞's avatar
羽飞 已提交
371
private:
羽飞's avatar
羽飞 已提交
372 373 374
  RC copy_from(const char *items, int num, DiskBufferPool *disk_buffer_pool);
  RC append(const char *item, DiskBufferPool *bp);
  RC preappend(const char *item, DiskBufferPool *bp);
羽飞's avatar
羽飞 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

private:
  char *__item_at(int index) const;
  char *__key_at(int index) const;
  char *__value_at(int index) const;

  int value_size() const;
  int item_size() const;

private:
  InternalIndexNode *internal_node_;
};

class BplusTreeHandler {
public:
  /**
   * 此函数创建一个名为fileName的索引。
   * attrType描述被索引属性的类型,attrLength描述被索引属性的长度
   */
L
Longda Feng 已提交
394 395
  RC create(
      const char *file_name, AttrType attr_type, int attr_length, int internal_max_size = -1, int leaf_max_size = -1);
羽飞's avatar
羽飞 已提交
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

  /**
   * 打开名为fileName的索引文件。
   * 如果方法调用成功,则indexHandle为指向被打开的索引句柄的指针。
   * 索引句柄用于在索引中插入或删除索引项,也可用于索引的扫描
   */
  RC open(const char *file_name);

  /**
   * 关闭句柄indexHandle对应的索引文件
   */
  RC close();

  /**
   * 此函数向IndexHandle对应的索引中插入一个索引项。
   * 参数user_key指向要插入的属性值,参数rid标识该索引项对应的元组,
   * 即向索引中插入一个值为(user_key,rid)的键值对
羽飞's avatar
羽飞 已提交
413
   * @note 这里假设user_key的内存大小与attr_length 一致
羽飞's avatar
羽飞 已提交
414 415 416 417 418 419
   */
  RC insert_entry(const char *user_key, const RID *rid);

  /**
   * 从IndexHandle句柄对应的索引中删除一个值为(*pData,rid)的索引项
   * @return RECORD_INVALID_KEY 指定值不存在
羽飞's avatar
羽飞 已提交
420
   * @note 这里假设user_key的内存大小与attr_length 一致
羽飞's avatar
羽飞 已提交
421 422 423 424 425 426 427
   */
  RC delete_entry(const char *user_key, const RID *rid);

  bool is_empty() const;

  /**
   * 获取指定值的record
羽飞's avatar
羽飞 已提交
428
   * @param key_len user_key的长度
羽飞's avatar
羽飞 已提交
429 430
   * @param rid  返回值,记录记录所在的页面号和slot
   */
羽飞's avatar
羽飞 已提交
431
  RC get_entry(const char *user_key, int key_len, std::list<RID> &rids);
羽飞's avatar
羽飞 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

  RC sync();

  /**
   * Check whether current B+ tree is invalid or not.
   * return true means current tree is valid, return false means current tree is invalid.
   * @return
   */
  bool validate_tree();

public:
  RC print_tree();
  RC print_leafs();

private:
羽飞's avatar
羽飞 已提交
447 448
  RC print_leaf(Frame *frame);
  RC print_internal_node_recursive(Frame *frame);
羽飞's avatar
羽飞 已提交
449 450 451

  bool validate_node(IndexNode *node);
  bool validate_leaf_link();
羽飞's avatar
羽飞 已提交
452
  bool validate_node_recursive(Frame *frame);
羽飞's avatar
羽飞 已提交
453 454

protected:
羽飞's avatar
羽飞 已提交
455 456 457
  RC find_leaf(const char *key, Frame *&frame);
  RC left_most_page(Frame *&frame);
  RC right_most_page(Frame *&frame);
L
Longda Feng 已提交
458
  RC find_leaf_internal(const std::function<PageNum(InternalIndexNodeHandler &)> &child_page_getter, Frame *&frame);
羽飞's avatar
羽飞 已提交
459

L
Longda Feng 已提交
460
  RC insert_into_parent(PageNum parent_page, Frame *left_frame, const char *pkey, Frame &right_frame);
羽飞's avatar
羽飞 已提交
461

羽飞's avatar
羽飞 已提交
462
  RC delete_entry_internal(Frame *leaf_frame, const char *key);
羽飞's avatar
羽飞 已提交
463

羽飞's avatar
羽飞 已提交
464
  RC insert_into_new_root(Frame *left_frame, const char *pkey, Frame &right_frame);
羽飞's avatar
羽飞 已提交
465 466

  template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
467
  RC split(Frame *frame, Frame *&new_frame);
羽飞's avatar
羽飞 已提交
468
  template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
469
  RC coalesce_or_redistribute(Frame *frame);
羽飞's avatar
羽飞 已提交
470
  template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
471
  RC coalesce(Frame *neighbor_frame, Frame *frame, Frame *parent_frame, int index);
羽飞's avatar
羽飞 已提交
472
  template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
473
  RC redistribute(Frame *neighbor_frame, Frame *frame, Frame *parent_frame, int index);
羽飞's avatar
羽飞 已提交
474

羽飞's avatar
羽飞 已提交
475 476
  RC insert_entry_into_parent(Frame *frame, Frame *new_frame, const char *key);
  RC insert_entry_into_leaf_node(Frame *frame, const char *pkey, const RID *rid);
羽飞's avatar
羽飞 已提交
477 478 479
  RC update_root_page_num();
  RC create_new_tree(const char *key, const RID *rid);

羽飞's avatar
羽飞 已提交
480
  RC adjust_root(Frame *root_frame);
羽飞's avatar
羽飞 已提交
481 482 483

private:
  char *make_key(const char *user_key, const RID &rid);
L
Longda Feng 已提交
484 485
  void free_key(char *key);

羽飞's avatar
羽飞 已提交
486 487 488 489 490 491
protected:
  DiskBufferPool *disk_buffer_pool_ = nullptr;
  bool header_dirty_ = false;
  IndexFileHeader file_header_;

  KeyComparator key_comparator_;
L
Longda Feng 已提交
492
  KeyPrinter key_printer_;
羽飞's avatar
羽飞 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

  common::MemPoolItem *mem_pool_item_ = nullptr;

private:
  friend class BplusTreeScanner;
  friend class BplusTreeTester;
};

class BplusTreeScanner {
public:
  BplusTreeScanner(BplusTreeHandler &tree_handler);
  ~BplusTreeScanner();

  /**
   * 扫描指定范围的数据
羽飞's avatar
羽飞 已提交
508 509
   * @param left_user_key 扫描范围的左边界,如果是null,则没有左边界
   * @param left_len left_user_key 的内存大小(只有在变长字段中才会关注)
羽飞's avatar
羽飞 已提交
510
   * @param left_inclusive 左边界的值是否包含在内
羽飞's avatar
羽飞 已提交
511 512
   * @param right_user_key 扫描范围的右边界。如果是null,则没有右边界
   * @param right_len right_user_key 的内存大小(只有在变长字段中才会关注)
羽飞's avatar
羽飞 已提交
513 514
   * @param right_inclusive 右边界的值是否包含在内
   */
L
Longda Feng 已提交
515 516
  RC open(const char *left_user_key, int left_len, bool left_inclusive, const char *right_user_key, int right_len,
      bool right_inclusive);
羽飞's avatar
羽飞 已提交
517 518 519 520 521

  RC next_entry(RID *rid);

  RC close();

羽飞's avatar
羽飞 已提交
522 523 524 525
private:
  /**
   * 如果key的类型是CHARS, 扩展或缩减user_key的大小刚好是schema中定义的大小
   */
L
Longda Feng 已提交
526 527
  RC fix_user_key(const char *user_key, int key_len, bool want_greater, char **fixed_key, bool *should_inclusive);

羽飞's avatar
羽飞 已提交
528 529 530 531 532 533
private:
  bool inited_ = false;
  BplusTreeHandler &tree_handler_;

  /// 使用左右叶子节点和位置来表示扫描的起始位置和终止位置
  /// 起始位置和终止位置都是有效的数据
L
Longda Feng 已提交
534 535 536 537
  Frame *left_frame_ = nullptr;
  Frame *right_frame_ = nullptr;
  int iter_index_ = -1;
  int end_index_ = -1;  // use -1 for end of scan
羽飞's avatar
羽飞 已提交
538 539 540
};

#endif  //__OBSERVER_STORAGE_COMMON_INDEX_MANAGER_H_