bplus_tree.cpp 59.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
/* 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
//
#include "storage/index/bplus_tree.h"
#include "storage/default/disk_buffer_pool.h"
#include "rc.h"
#include "common/log/log.h"
#include "sql/parser/parse_defs.h"
羽飞's avatar
羽飞 已提交
20
#include "common/lang/lower_bound.h"
羽飞's avatar
羽飞 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

#define FIRST_INDEX_PAGE 1

int calc_internal_page_capacity(int attr_length)
{
  int item_size = attr_length + sizeof(RID) + sizeof(PageNum);

  int capacity =
    ((int)BP_PAGE_DATA_SIZE - InternalIndexNode::HEADER_SIZE) / item_size;
  return capacity;
}

int calc_leaf_page_capacity(int attr_length)
{
  int item_size = attr_length + sizeof(RID) + sizeof(RID);
  int capacity =
    ((int)BP_PAGE_DATA_SIZE - LeafIndexNode::HEADER_SIZE) / item_size;
  return capacity;
}

/////////////////////////////////////////////////////////////////////////////////
羽飞's avatar
羽飞 已提交
42 43
IndexNodeHandler::IndexNodeHandler(const IndexFileHeader &header, Frame *frame)
  : header_(header), page_num_(frame->page_num()), node_((IndexNode *)frame->data())
羽飞's avatar
羽飞 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
{}

bool IndexNodeHandler::is_leaf() const
{
  return node_->is_leaf;
}
void IndexNodeHandler::init_empty(bool leaf)
{
  node_->is_leaf = leaf;
  node_->key_num = 0;
  node_->parent = BP_INVALID_PAGE_NUM;
}
PageNum IndexNodeHandler::page_num() const
{
  return page_num_;
}

int IndexNodeHandler::key_size() const
{
  return header_.key_length;
}

int IndexNodeHandler::value_size() const
{
  // return header_.value_size;
  return sizeof(RID);
}

int IndexNodeHandler::item_size() const
{
  return key_size() + value_size();
}

int IndexNodeHandler::size() const
{
  return node_->key_num;
}

void IndexNodeHandler::increase_size(int n)
{
  node_->key_num += n;
}

PageNum IndexNodeHandler::parent_page_num() const
{
  return node_->parent;
}

void IndexNodeHandler::set_parent_page_num(PageNum page_num)
{
  this->node_->parent = page_num;
}
std::string to_string(const IndexNodeHandler &handler)
{
  std::stringstream ss;

  ss << "PageNum:" << handler.page_num()
     << ",is_leaf:" << handler.is_leaf() << ","
     << "key_num:" << handler.size() << ","
     << "parent:" << handler.parent_page_num() << ",";

  return ss.str();
}

bool IndexNodeHandler::validate() const
{
  if (parent_page_num() == BP_INVALID_PAGE_NUM) {
    // this is a root page
    if (size() < 1) {
      LOG_WARN("root page has no item");
      return false;
    }

    if (!is_leaf() && size() < 2) {
      LOG_WARN("root page internal node has less than 2 child. size=%d", size());
      return false;
    }
  }
  return true;
}

/////////////////////////////////////////////////////////////////////////////////
羽飞's avatar
羽飞 已提交
126 127
LeafIndexNodeHandler::LeafIndexNodeHandler(const IndexFileHeader &header, Frame *frame)
  : IndexNodeHandler(header, frame), leaf_node_((LeafIndexNode *)frame->data())
羽飞's avatar
羽飞 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
{}

void LeafIndexNodeHandler::init_empty()
{
  IndexNodeHandler::init_empty(true);
  leaf_node_->prev_brother = BP_INVALID_PAGE_NUM;
  leaf_node_->next_brother = BP_INVALID_PAGE_NUM;
}

void LeafIndexNodeHandler::set_next_page(PageNum page_num)
{
  leaf_node_->next_brother = page_num;
}

void LeafIndexNodeHandler::set_prev_page(PageNum page_num)
{
  leaf_node_->prev_brother = page_num;
}
PageNum LeafIndexNodeHandler::next_page() const
{
  return leaf_node_->next_brother;
}
PageNum LeafIndexNodeHandler::prev_page() const
{
  return leaf_node_->prev_brother;
}

char *LeafIndexNodeHandler::key_at(int index)
{
  assert(index >= 0 && index < size());
  return __key_at(index);
}

char *LeafIndexNodeHandler::value_at(int index)
{
  assert(index >= 0 && index < size());
  return __value_at(index);
}

int LeafIndexNodeHandler::max_size() const
{
  return header_.leaf_max_size;
}

int LeafIndexNodeHandler::min_size() const
{
  return header_.leaf_max_size - header_.leaf_max_size / 2;
}

int LeafIndexNodeHandler::lookup(const KeyComparator &comparator, const char *key, bool *found /* = nullptr */) const
{
  const int size = this->size();
羽飞's avatar
羽飞 已提交
180 181 182 183
  common::BinaryIterator<char> iter_begin(item_size(), __key_at(0));
  common::BinaryIterator<char> iter_end(item_size(), __key_at(size));
  common::BinaryIterator<char> iter = lower_bound(iter_begin, iter_end, key, comparator, found);
  return iter - iter_begin;
羽飞's avatar
羽飞 已提交
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
}

void LeafIndexNodeHandler::insert(int index, const char *key, const char *value)
{
  if (index < size()) {
    memmove(__item_at(index + 1), __item_at(index), (size() - index) * item_size());
  }
  memcpy(__item_at(index), key, key_size());
  memcpy(__item_at(index) + key_size(), value, value_size());
  increase_size(1);
}
void LeafIndexNodeHandler::remove(int index)
{
  assert(index >= 0 && index < size());
  if (index < size() - 1) {
    memmove(__item_at(index), __item_at(index + 1), (size() - index - 1) * item_size());
  }
  increase_size(-1);
}

int LeafIndexNodeHandler::remove(const char *key, const KeyComparator &comparator)
{
  bool found = false;
  int index = lookup(comparator, key, &found);
  if (found) {
    this->remove(index);
    return 1;
  }
  return 0;
}

羽飞's avatar
羽飞 已提交
215
RC LeafIndexNodeHandler::move_half_to(LeafIndexNodeHandler &other, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
216 217 218 219 220 221 222 223 224
{
  const int size = this->size();
  const int move_index = size / 2;

  memcpy(other.__item_at(0), this->__item_at(move_index), item_size() * (size - move_index));
  other.increase_size(size - move_index);
  this->increase_size(- ( size - move_index));
  return RC::SUCCESS;
}
羽飞's avatar
羽飞 已提交
225
RC LeafIndexNodeHandler::move_first_to_end(LeafIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool)
羽飞's avatar
羽飞 已提交
226 227 228 229 230 231 232 233 234 235
{
  other.append(__item_at(0));

  if (size() >= 1) {
    memmove(__item_at(0), __item_at(1), (size() - 1) * item_size() );
  }
  increase_size(-1);
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
236
RC LeafIndexNodeHandler::move_last_to_front(LeafIndexNodeHandler &other, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
237 238 239 240 241 242 243 244 245
{
  other.preappend(__item_at(size() - 1));

  increase_size(-1);
  return RC::SUCCESS;
}
/**
 * move all items to left page
 */
羽飞's avatar
羽飞 已提交
246
RC LeafIndexNodeHandler::move_to(LeafIndexNodeHandler &other, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
247 248 249 250 251 252 253 254 255
{
  memcpy(other.__item_at(other.size()), this->__item_at(0), this->size() * item_size());
  other.increase_size(this->size());
  this->increase_size(- this->size());

  other.set_next_page(this->next_page());

  PageNum next_right_page_num = this->next_page();
  if (next_right_page_num != BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
256 257
    Frame *next_right_frame;
    RC rc = bp->get_this_page(next_right_page_num, &next_right_frame);
羽飞's avatar
羽飞 已提交
258 259 260 261 262
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to fetch next right page. page number:%d. rc=%d:%s", next_right_page_num, rc, strrc(rc));
      return rc;
    }

羽飞's avatar
羽飞 已提交
263
    LeafIndexNodeHandler next_right_node(header_, next_right_frame);
羽飞's avatar
羽飞 已提交
264
    next_right_node.set_prev_page(other.page_num());
羽飞's avatar
羽飞 已提交
265 266
    next_right_frame->mark_dirty();
    bp->unpin_page(next_right_frame);
羽飞's avatar
羽飞 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  }
  return RC::SUCCESS;
}

void LeafIndexNodeHandler::append(const char *item)
{
  memcpy(__item_at(size()), item, item_size());
  increase_size(1);
}

void LeafIndexNodeHandler::preappend(const char *item)
{
  if (size() > 0) {
    memmove(__item_at(1), __item_at(0), size() * item_size());
  }
  memcpy(__item_at(0), item, item_size());
  increase_size(1);
}

char *LeafIndexNodeHandler::__item_at(int index) const
{
  return leaf_node_->array + (index * item_size());
}
char *LeafIndexNodeHandler::__key_at(int index) const
{
  return __item_at(index);
}
char *LeafIndexNodeHandler::__value_at(int index) const
{
  return __item_at(index) + key_size();
}

std::string to_string(const LeafIndexNodeHandler &handler, const KeyPrinter &printer)
{
  std::stringstream ss;
  ss << to_string((const IndexNodeHandler &)handler)
     << ",prev page:" << handler.prev_page()
     << ",next page:" << handler.next_page();
  ss << ",values=[" << printer(handler.__key_at(0)) ;
  for (int i = 1; i < handler.size(); i++) {
    ss << "," << printer(handler.__key_at(i));
  }
  ss << "]";
  return ss.str();
}

羽飞's avatar
羽飞 已提交
313
bool LeafIndexNodeHandler::validate(const KeyComparator &comparator, DiskBufferPool *bp) const
羽飞's avatar
羽飞 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
{
  bool result = IndexNodeHandler::validate();
  if (false == result) {
    return false;
  }

  const int node_size = size();
  for (int i = 1; i < node_size; i++) {
    if (comparator(__key_at(i - 1), __key_at(i)) >= 0) {
      LOG_WARN("page number = %d, invalid key order. id1=%d,id2=%d, this=%s",
	       page_num(), i-1, i, to_string(*this).c_str());
      return false;
    }
  }

  PageNum parent_page_num = this->parent_page_num();
  if (parent_page_num == BP_INVALID_PAGE_NUM) {
    return true;
  }

羽飞's avatar
羽飞 已提交
334 335
  Frame *parent_frame;
  RC rc = bp->get_this_page(parent_page_num, &parent_frame);
羽飞's avatar
羽飞 已提交
336 337 338 339 340 341
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch parent page. page num=%d, rc=%d:%s",
	     parent_page_num, rc, strrc(rc));
    return false;
  }

羽飞's avatar
羽飞 已提交
342
  InternalIndexNodeHandler parent_node(header_, parent_frame);
羽飞's avatar
羽飞 已提交
343 344 345 346
  int index_in_parent = parent_node.value_index(this->page_num());
  if (index_in_parent < 0) {
    LOG_WARN("invalid leaf node. cannot find index in parent. this page num=%d, parent page num=%d",
	     this->page_num(), parent_page_num);
羽飞's avatar
羽飞 已提交
347
    bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
348 349 350 351 352 353 354 355 356
    return false;
  }

  if (0 != index_in_parent) {
    int cmp_result = comparator(__key_at(0), parent_node.key_at(index_in_parent));
    if (cmp_result < 0) {
      LOG_WARN("invalid leaf node. first item should be greate than or equal to parent item. " \
	       "this page num=%d, parent page num=%d, index in parent=%d",
	       this->page_num(), parent_node.page_num(), index_in_parent);
羽飞's avatar
羽飞 已提交
357
      bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
358 359 360 361 362 363 364 365 366 367
      return false;
    }
  }

  if (index_in_parent < parent_node.size() - 1) {
    int cmp_result = comparator(__key_at(size() - 1), parent_node.key_at(index_in_parent + 1));
    if (cmp_result >= 0) {
      LOG_WARN("invalid leaf node. last item should be less than the item at the first after item in parent." \
	       "this page num=%d, parent page num=%d, parent item to compare=%d",
	       this->page_num(), parent_node.page_num(), index_in_parent + 1);
羽飞's avatar
羽飞 已提交
368
      bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
369 370 371
      return false;
    }
  }
羽飞's avatar
羽飞 已提交
372
  bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
373 374 375 376
  return true;
}

/////////////////////////////////////////////////////////////////////////////////
羽飞's avatar
羽飞 已提交
377 378
InternalIndexNodeHandler::InternalIndexNodeHandler(const IndexFileHeader &header, Frame *frame)
  : IndexNodeHandler(header, frame), internal_node_((InternalIndexNode *)frame->data())
羽飞's avatar
羽飞 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
{}

std::string to_string(const InternalIndexNodeHandler &node, const KeyPrinter &printer)
{
  std::stringstream ss;
  ss << to_string((const IndexNodeHandler &)node);
  ss << ",children:["
     << "{key:" << printer(node.__key_at(0)) << ","
     << "value:" << *(PageNum *)node.__value_at(0) << "}";

  for (int i = 1; i < node.size(); i++) {
    ss << ",{key:" << printer(node.__key_at(i))
       << ",value:"<< *(PageNum *)node.__value_at(i) << "}";
  }
  ss << "]";
  return ss.str();
}

void InternalIndexNodeHandler::init_empty()
{
  IndexNodeHandler::init_empty(false);
}
void InternalIndexNodeHandler::create_new_root(PageNum first_page_num, const char *key, PageNum page_num)
{
  memset(__key_at(0), 0, key_size());
  memcpy(__value_at(0), &first_page_num, value_size());
  memcpy(__item_at(1), key, key_size());
  memcpy(__value_at(1), &page_num, value_size());
  increase_size(2);
}

/**
 * insert one entry
 * the entry to be inserted will never at the first slot.
 * the right child page after split will always have bigger keys.
 */
void InternalIndexNodeHandler::insert(const char *key, PageNum page_num, const KeyComparator &comparator)
{
  int insert_position = -1;
  lookup(comparator, key, nullptr, &insert_position);
  if (insert_position < size()) {
    memmove(__item_at(insert_position + 1), __item_at(insert_position), (size() - insert_position) * item_size());
  }
  memcpy(__item_at(insert_position), key, key_size());
  memcpy(__value_at(insert_position), &page_num, value_size());
  increase_size(1);
}

羽飞's avatar
羽飞 已提交
427
RC InternalIndexNodeHandler::move_half_to(InternalIndexNodeHandler &other, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
428 429 430
{
  const int size = this->size();
  const int move_index = size / 2;
羽飞's avatar
羽飞 已提交
431
  RC rc = other.copy_from(this->__item_at(move_index), size - move_index, bp);
羽飞's avatar
羽飞 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to copy item to new node. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

  increase_size(- (size - move_index));
  return rc;
}

int InternalIndexNodeHandler::max_size() const
{
  return header_.internal_max_size;
}

int InternalIndexNodeHandler::min_size() const
{
  return header_.internal_max_size - header_.internal_max_size / 2;
}

/**
 * lookup the first item which key <= item
 * @return unlike the leafNode, the return value is not the insert position,
 * but only the index of child to find. 
 */
int InternalIndexNodeHandler::lookup(const KeyComparator &comparator, const char *key,
				     bool *found /* = nullptr */, int *insert_position /*= nullptr */) const
{
  const int size = this->size();
羽飞's avatar
羽飞 已提交
460 461 462
  if (size == 0) {
    if (insert_position) {
      *insert_position = 1;
羽飞's avatar
羽飞 已提交
463
    }
羽飞's avatar
羽飞 已提交
464 465
    if (found) {
      *found = false;
羽飞's avatar
羽飞 已提交
466
    }
羽飞's avatar
羽飞 已提交
467
    return 0;
羽飞's avatar
羽飞 已提交
468
  }
羽飞's avatar
羽飞 已提交
469 470 471 472 473

  common::BinaryIterator<char> iter_begin(item_size(), __key_at(1));
  common::BinaryIterator<char> iter_end(item_size(), __key_at(size));
  common::BinaryIterator<char> iter = lower_bound(iter_begin, iter_end, key, comparator, found);
  int ret = static_cast<int>(iter - iter_begin) + 1;
羽飞's avatar
羽飞 已提交
474
  if (insert_position) {
羽飞's avatar
羽飞 已提交
475
    *insert_position = ret;
羽飞's avatar
羽飞 已提交
476
  }
羽飞's avatar
羽飞 已提交
477 478 479 480 481

  if (ret >= size || comparator(key, __key_at(ret)) < 0) {
    return ret - 1;
  }
  return ret;
羽飞's avatar
羽飞 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
}

char *InternalIndexNodeHandler::key_at(int index)
{
  assert(index >= 0 && index < size());
  return __key_at(index);
}

void InternalIndexNodeHandler::set_key_at(int index, const char *key)
{
  assert(index >= 0 && index < size());
  memcpy(__key_at(index), key, key_size());
}

PageNum InternalIndexNodeHandler::value_at(int index)
{
  assert(index >= 0 && index < size());
  return *(PageNum *)__value_at(index);
}

int InternalIndexNodeHandler::value_index(PageNum page_num)
{
  for (int i = 0; i < size(); i++) {
    if (page_num == *(PageNum*)__value_at(i)) {
      return i;
    }
  }
  return -1;
}

void InternalIndexNodeHandler::remove(int index)
{
  assert(index >= 0 && index < size());
  if (index < size() - 1) {
    memmove(__item_at(index), __item_at(index + 1), (size() - index - 1) * item_size());
  }
  increase_size(-1);
}

羽飞's avatar
羽飞 已提交
521
RC InternalIndexNodeHandler::move_to(InternalIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool)
羽飞's avatar
羽飞 已提交
522
{
羽飞's avatar
羽飞 已提交
523
  RC rc = other.copy_from(__item_at(0), size(), disk_buffer_pool);
羽飞's avatar
羽飞 已提交
524 525 526 527 528 529 530 531 532
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to copy items to other node. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

  increase_size(- this->size());
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
533
RC InternalIndexNodeHandler::move_first_to_end(InternalIndexNodeHandler &other, DiskBufferPool *disk_buffer_pool)
羽飞's avatar
羽飞 已提交
534
{
羽飞's avatar
羽飞 已提交
535
  RC rc = other.append(__item_at(0), disk_buffer_pool);
羽飞's avatar
羽飞 已提交
536 537 538 539 540 541 542 543 544 545 546 547
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to append item to others.");
    return rc;
  }

  if (size() >= 1) {
    memmove(__item_at(0), __item_at(1), (size() - 1) * item_size() );
  }
  increase_size(-1);
  return rc;
}

羽飞's avatar
羽飞 已提交
548
RC InternalIndexNodeHandler::move_last_to_front(InternalIndexNodeHandler &other, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
549
{
羽飞's avatar
羽飞 已提交
550
  RC rc = other.preappend(__item_at(size() - 1), bp);
羽飞's avatar
羽飞 已提交
551 552 553 554 555 556 557 558 559 560 561
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to preappend to others");
    return rc;
  }

  increase_size(-1);
  return rc;
}
/**
 * copy items from other node to self's right
 */
羽飞's avatar
羽飞 已提交
562
RC InternalIndexNodeHandler::copy_from(const char *items, int num, DiskBufferPool *disk_buffer_pool)
羽飞's avatar
羽飞 已提交
563 564 565 566 567
{
  memcpy(__item_at(this->size()), items, num * item_size());

  RC rc = RC::SUCCESS;
  PageNum this_page_num = this->page_num();
羽飞's avatar
羽飞 已提交
568
  Frame *frame = nullptr;
羽飞's avatar
羽飞 已提交
569 570
  for (int i = 0; i < num; i++) {
    const PageNum page_num = *(const PageNum *)((items + i * item_size()) + key_size());
羽飞's avatar
羽飞 已提交
571
    rc = disk_buffer_pool->get_this_page(page_num, &frame);
羽飞's avatar
羽飞 已提交
572 573 574 575 576
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to set child's page num. child page num:%d, this page num=%d, rc=%d:%s",
	       page_num, this_page_num, rc, strrc(rc));
      return rc;
    }
羽飞's avatar
羽飞 已提交
577
    IndexNodeHandler child_node(header_, frame);
羽飞's avatar
羽飞 已提交
578
    child_node.set_parent_page_num(this_page_num);
羽飞's avatar
羽飞 已提交
579 580
    frame->mark_dirty();
    disk_buffer_pool->unpin_page(frame);
羽飞's avatar
羽飞 已提交
581 582 583 584 585
  }
  increase_size(num);
  return rc;
}

羽飞's avatar
羽飞 已提交
586
RC InternalIndexNodeHandler::append(const char *item, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
587
{
羽飞's avatar
羽飞 已提交
588
  return this->copy_from(item, 1, bp);
羽飞's avatar
羽飞 已提交
589 590
}

羽飞's avatar
羽飞 已提交
591
RC InternalIndexNodeHandler::preappend(const char *item, DiskBufferPool *bp)
羽飞's avatar
羽飞 已提交
592 593
{
  PageNum child_page_num = *(PageNum *)(item + key_size());
羽飞's avatar
羽飞 已提交
594 595
  Frame *frame = nullptr;
  RC rc = bp->get_this_page(child_page_num, &frame);
羽飞's avatar
羽飞 已提交
596 597 598 599 600
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch child page. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
601
  IndexNodeHandler child_node(header_, frame);
羽飞's avatar
羽飞 已提交
602 603
  child_node.set_parent_page_num(this->page_num());

羽飞's avatar
羽飞 已提交
604 605
  frame->mark_dirty();
  bp->unpin_page(frame);
羽飞's avatar
羽飞 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

  if (this->size() > 0) {
    memmove(__item_at(1), __item_at(0), this->size() * item_size());
  }

  memcpy(__item_at(0), item, item_size());
  increase_size(1);
  return RC::SUCCESS;
}

char *InternalIndexNodeHandler::__item_at(int index) const
{
  return internal_node_->array + (index * item_size());
}

char *InternalIndexNodeHandler::__key_at(int index) const
{
  return __item_at(index);
}

char *InternalIndexNodeHandler::__value_at(int index) const
{
  return __item_at(index) + key_size();
}

int InternalIndexNodeHandler::value_size() const
{
  return sizeof(PageNum);
}

int InternalIndexNodeHandler::item_size() const
{
  return key_size() + this->value_size();
}

羽飞's avatar
羽飞 已提交
641
bool InternalIndexNodeHandler::validate(const KeyComparator &comparator, DiskBufferPool *bp) const
羽飞's avatar
羽飞 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
{
  bool result = IndexNodeHandler::validate();
  if (false == result) {
    return false;
  }

  const int node_size = size();
  for (int i = 2; i < node_size; i++) {
    if (comparator(__key_at(i - 1), __key_at(i)) >= 0) {
      LOG_WARN("page number = %d, invalid key order. id1=%d,id2=%d, this=%s",
	       page_num(), i-1, i, to_string(*this).c_str());
      return false;
    }
  }

  for (int i = 0; result && i < node_size; i++) {
    PageNum page_num = *(PageNum *)__value_at(i);
    if (page_num < 0) {
      LOG_WARN("this page num=%d, got invalid child page. page num=%d", this->page_num(), page_num);
    } else {
羽飞's avatar
羽飞 已提交
662 663
      Frame *child_frame;
      RC rc = bp->get_this_page(page_num, &child_frame);
羽飞's avatar
羽飞 已提交
664 665 666 667
      if (rc != RC::SUCCESS) {
	LOG_WARN("failed to fetch child page while validate internal page. page num=%d, rc=%d:%s",
		 page_num, rc, strrc(rc));
      } else {
羽飞's avatar
羽飞 已提交
668
	IndexNodeHandler child_node(header_, child_frame);
羽飞's avatar
羽飞 已提交
669 670 671 672 673
	if (child_node.parent_page_num() != this->page_num()) {
	  LOG_WARN("child's parent page num is invalid. child page num=%d, parent page num=%d, this page num=%d",
		   child_node.page_num(), child_node.parent_page_num(), this->page_num());
	  result = false;
	}
羽飞's avatar
羽飞 已提交
674
	bp->unpin_page(child_frame);
羽飞's avatar
羽飞 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687
      }
    }
  }

  if (!result) {
    return result;
  }

  const PageNum parent_page_num = this->parent_page_num();
  if (parent_page_num == BP_INVALID_PAGE_NUM) {
    return result;
  }

羽飞's avatar
羽飞 已提交
688 689
  Frame *parent_frame;
  RC rc = bp->get_this_page(parent_page_num, &parent_frame);
羽飞's avatar
羽飞 已提交
690 691 692 693 694
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch parent page. page num=%d, rc=%d:%s", parent_page_num, rc, strrc(rc));
    return false;
  }

羽飞's avatar
羽飞 已提交
695
  InternalIndexNodeHandler parent_node(header_, parent_frame);
羽飞's avatar
羽飞 已提交
696 697 698 699
  int index_in_parent = parent_node.value_index(this->page_num());
  if (index_in_parent < 0) {
    LOG_WARN("invalid internal node. cannot find index in parent. this page num=%d, parent page num=%d",
	     this->page_num(), parent_page_num);
羽飞's avatar
羽飞 已提交
700
    bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
701 702 703 704 705 706 707 708 709
    return false;
  }

  if (0 != index_in_parent) {
    int cmp_result = comparator(__key_at(1), parent_node.key_at(index_in_parent));
    if (cmp_result < 0) {
      LOG_WARN("invalid internal node. the second item should be greate than or equal to parent item. " \
	       "this page num=%d, parent page num=%d, index in parent=%d",
	       this->page_num(), parent_node.page_num(), index_in_parent);
羽飞's avatar
羽飞 已提交
710
      bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
711 712 713 714 715 716 717 718 719 720
      return false;
    }
  }

  if (index_in_parent < parent_node.size() - 1) {
    int cmp_result = comparator(__key_at(size() - 1), parent_node.key_at(index_in_parent + 1));
    if (cmp_result >= 0) {
      LOG_WARN("invalid internal node. last item should be less than the item at the first after item in parent." \
	       "this page num=%d, parent page num=%d, parent item to compare=%d",
	       this->page_num(), parent_node.page_num(), index_in_parent + 1);
羽飞's avatar
羽飞 已提交
721
      bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
722 723 724
      return false;
    }
  }
羽飞's avatar
羽飞 已提交
725
  bp->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
726 727 728 729 730 731 732 733

  return result;
}

/////////////////////////////////////////////////////////////////////////////////

RC BplusTreeHandler::sync()
{
羽飞's avatar
羽飞 已提交
734
  return disk_buffer_pool_->flush_all_pages();
羽飞's avatar
羽飞 已提交
735 736 737 738 739
}

RC BplusTreeHandler::create(const char *file_name, AttrType attr_type, int attr_length,
			    int internal_max_size /* = -1*/, int leaf_max_size /* = -1 */)
{
羽飞's avatar
羽飞 已提交
740 741
  BufferPoolManager &bpm = BufferPoolManager::instance();
  RC rc = bpm.create_file(file_name);
羽飞's avatar
羽飞 已提交
742 743 744 745 746 747
  if (rc != RC::SUCCESS) {
    LOG_WARN("Failed to create file. file name=%s, rc=%d:%s", file_name, rc, strrc(rc));
    return rc;
  }
  LOG_INFO("Successfully create index file:%s", file_name);

羽飞's avatar
羽飞 已提交
748 749
  DiskBufferPool *bp = nullptr;
  rc = bpm.open_file(file_name, bp);
羽飞's avatar
羽飞 已提交
750 751 752 753 754 755
  if (rc != RC::SUCCESS) {
    LOG_WARN("Failed to open file. file name=%s, rc=%d:%s", file_name, rc, strrc(rc));
    return rc;
  }
  LOG_INFO("Successfully open index file %s.", file_name);

羽飞's avatar
羽飞 已提交
756 757
  Frame *header_frame;
  rc = bp->allocate_page(&header_frame);
羽飞's avatar
羽飞 已提交
758 759
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to allocate header page for bplus tree. rc=%d:%s", rc, strrc(rc));
羽飞's avatar
羽飞 已提交
760
    bpm.close_file(file_name);
羽飞's avatar
羽飞 已提交
761 762 763
    return rc;
  }

羽飞's avatar
羽飞 已提交
764
  if (header_frame->page_num() != FIRST_INDEX_PAGE) {
羽飞's avatar
羽飞 已提交
765
    LOG_WARN("header page num should be %d but got %d. is it a new file : %s",
羽飞's avatar
羽飞 已提交
766 767
	     FIRST_INDEX_PAGE, header_frame->page_num(), file_name);
    bpm.close_file(file_name);
羽飞's avatar
羽飞 已提交
768 769 770 771 772 773 774 775 776
    return RC::INTERNAL;
  }

  if (internal_max_size < 0) {
    internal_max_size = calc_internal_page_capacity(attr_length);
  }
  if (leaf_max_size < 0) {
    leaf_max_size = calc_leaf_page_capacity(attr_length);
  }
羽飞's avatar
羽飞 已提交
777 778

  char *pdata = header_frame->data();
羽飞's avatar
羽飞 已提交
779 780 781 782 783 784 785 786
  IndexFileHeader *file_header = (IndexFileHeader *)pdata;
  file_header->attr_length = attr_length;
  file_header->key_length = attr_length + sizeof(RID);
  file_header->attr_type = attr_type;
  file_header->internal_max_size = internal_max_size;
  file_header->leaf_max_size = leaf_max_size;
  file_header->root_page = BP_INVALID_PAGE_NUM;

羽飞's avatar
羽飞 已提交
787
  header_frame->mark_dirty();
羽飞's avatar
羽飞 已提交
788

羽飞's avatar
羽飞 已提交
789
  disk_buffer_pool_ = bp;
羽飞's avatar
羽飞 已提交
790 791 792

  memcpy(&file_header_, pdata, sizeof(file_header_));
  header_dirty_ = false;
羽飞's avatar
羽飞 已提交
793
  bp->unpin_page(header_frame);
羽飞's avatar
羽飞 已提交
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

  mem_pool_item_ = new common::MemPoolItem(file_name);
  if (mem_pool_item_->init(file_header->key_length) < 0) {
    LOG_WARN("Failed to init memory pool for index %s", file_name);
    close();
    return RC::NOMEM;
  }

  key_comparator_.init(file_header->attr_type, file_header->attr_length);
  key_printer_.init(file_header->attr_type, file_header->attr_length);
  LOG_INFO("Successfully create index %s", file_name);
  return RC::SUCCESS;
}

RC BplusTreeHandler::open(const char *file_name)
{
羽飞's avatar
羽飞 已提交
810
  if (disk_buffer_pool_ != nullptr) {
羽飞's avatar
羽飞 已提交
811 812 813 814
    LOG_WARN("%s has been opened before index.open.", file_name);
    return RC::RECORD_OPENNED;
  }

羽飞's avatar
羽飞 已提交
815 816 817
  BufferPoolManager &bpm = BufferPoolManager::instance();
  DiskBufferPool *disk_buffer_pool;
  RC rc = bpm.open_file(file_name, disk_buffer_pool);
羽飞's avatar
羽飞 已提交
818 819 820 821 822
  if (rc != RC::SUCCESS) {
    LOG_WARN("Failed to open file name=%s, rc=%d:%s", file_name, rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
823 824
  Frame *frame;
  rc = disk_buffer_pool->get_this_page(FIRST_INDEX_PAGE, &frame);
羽飞's avatar
羽飞 已提交
825 826
  if (rc != RC::SUCCESS) {
    LOG_WARN("Failed to get first page file name=%s, rc=%d:%s", file_name, rc, strrc(rc));
羽飞's avatar
羽飞 已提交
827
    bpm.close_file(file_name);
羽飞's avatar
羽飞 已提交
828 829 830
    return rc;
  }

羽飞's avatar
羽飞 已提交
831
  char *pdata = frame->data();
羽飞's avatar
羽飞 已提交
832 833 834 835 836 837 838 839 840 841 842 843
  memcpy(&file_header_, pdata, sizeof(IndexFileHeader));
  header_dirty_ = false;
  disk_buffer_pool_ = disk_buffer_pool;

  mem_pool_item_ = new common::MemPoolItem(file_name);
  if (mem_pool_item_->init(file_header_.key_length) < 0) {
    LOG_WARN("Failed to init memory pool for index %s", file_name);
    close();
    return RC::NOMEM;
  }

  // close old page_handle
羽飞's avatar
羽飞 已提交
844
  disk_buffer_pool->unpin_page(frame);
羽飞's avatar
羽飞 已提交
845 846

  key_comparator_.init(file_header_.attr_type, file_header_.attr_length);
羽飞's avatar
羽飞 已提交
847
  key_printer_.init(file_header_.attr_type, file_header_.attr_length);
羽飞's avatar
羽飞 已提交
848 849 850 851 852 853
  LOG_INFO("Successfully open index %s", file_name);
  return RC::SUCCESS;
}

RC BplusTreeHandler::close()
{
羽飞's avatar
羽飞 已提交
854
  if (disk_buffer_pool_ != nullptr) {
羽飞's avatar
羽飞 已提交
855

羽飞's avatar
羽飞 已提交
856
    disk_buffer_pool_->close_file(); // TODO
羽飞's avatar
羽飞 已提交
857 858 859 860 861 862 863 864 865

    delete mem_pool_item_;
    mem_pool_item_ = nullptr;
  }

  disk_buffer_pool_ = nullptr;
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
866
RC BplusTreeHandler::print_leaf(Frame *frame)
羽飞's avatar
羽飞 已提交
867
{
羽飞's avatar
羽飞 已提交
868
  LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
869
  LOG_INFO("leaf node: %s", to_string(leaf_node, key_printer_).c_str());
羽飞's avatar
羽飞 已提交
870
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
871 872 873
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
874
RC BplusTreeHandler::print_internal_node_recursive(Frame *frame)
羽飞's avatar
羽飞 已提交
875 876 877
{
  RC rc = RC::SUCCESS;
  LOG_INFO("bplus tree. file header: %s", file_header_.to_string().c_str());
羽飞's avatar
羽飞 已提交
878
  InternalIndexNodeHandler internal_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
879 880 881 882 883
  LOG_INFO("internal node: %s", to_string(internal_node, key_printer_).c_str());

  int node_size = internal_node.size();
  for (int i = 0; i < node_size; i++) {
    PageNum page_num = internal_node.value_at(i);
羽飞's avatar
羽飞 已提交
884 885
    Frame *child_frame;
    rc = disk_buffer_pool_->get_this_page(page_num, &child_frame);
羽飞's avatar
羽飞 已提交
886 887
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to fetch child page. page id=%d, rc=%d:%s", page_num, rc, strrc(rc));
羽飞's avatar
羽飞 已提交
888
      disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
889 890 891
      return rc;
    }

羽飞's avatar
羽飞 已提交
892
    IndexNodeHandler node(file_header_, child_frame);
羽飞's avatar
羽飞 已提交
893
    if (node.is_leaf()) {
羽飞's avatar
羽飞 已提交
894
      rc = print_leaf(child_frame);
羽飞's avatar
羽飞 已提交
895
    } else {
羽飞's avatar
羽飞 已提交
896
      rc = print_internal_node_recursive(child_frame);
羽飞's avatar
羽飞 已提交
897 898
    }
    if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
899 900
      LOG_WARN("failed to print node. page id=%d, rc=%d:%s", child_frame->page_num(), rc, strrc(rc));
      disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
901 902 903 904
      return rc;
    }
  }

羽飞's avatar
羽飞 已提交
905
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
906 907 908 909 910
  return RC::SUCCESS;
}

RC BplusTreeHandler::print_tree()
{
羽飞's avatar
羽飞 已提交
911
  if (disk_buffer_pool_ == nullptr) {
羽飞's avatar
羽飞 已提交
912 913 914 915 916 917 918 919
    LOG_WARN("Index hasn't been created or opened, fail to print");
    return RC::SUCCESS;
  }
  if (is_empty()) {
    LOG_INFO("tree is empty");
    return RC::SUCCESS;
  }

羽飞's avatar
羽飞 已提交
920
  Frame *frame;
羽飞's avatar
羽飞 已提交
921
  PageNum page_num = file_header_.root_page;
羽飞's avatar
羽飞 已提交
922
  RC rc = disk_buffer_pool_->get_this_page(page_num, &frame);
羽飞's avatar
羽飞 已提交
923 924 925 926 927
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch page. page id=%d, rc=%d:%s", page_num, rc, strrc(rc));
    return rc;
  }
  
羽飞's avatar
羽飞 已提交
928
  IndexNodeHandler node(file_header_, frame);
羽飞's avatar
羽飞 已提交
929
  if (node.is_leaf()) {
羽飞's avatar
羽飞 已提交
930
    rc = print_leaf(frame);
羽飞's avatar
羽飞 已提交
931
  } else {
羽飞's avatar
羽飞 已提交
932
    rc = print_internal_node_recursive(frame);
羽飞's avatar
羽飞 已提交
933 934 935 936 937 938 939 940 941 942 943
  }
  return rc;
}

RC BplusTreeHandler::print_leafs()
{
  if (is_empty()) {
    LOG_INFO("empty tree");
    return RC::SUCCESS;
  }

羽飞's avatar
羽飞 已提交
944
  Frame *frame;
羽飞's avatar
羽飞 已提交
945
  
羽飞's avatar
羽飞 已提交
946
  RC rc = left_most_page(frame);
羽飞's avatar
羽飞 已提交
947 948 949 950 951
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to get left most page. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
952 953
  while (frame->page_num() != BP_INVALID_PAGE_NUM) {
    LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
954 955 956
    LOG_INFO("leaf info: %s", to_string(leaf_node, key_printer_).c_str());

    PageNum next_page_num = leaf_node.next_page();
羽飞's avatar
羽飞 已提交
957
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
958 959 960 961 962

    if (next_page_num == BP_INVALID_PAGE_NUM) {
      break;
    }

羽飞's avatar
羽飞 已提交
963
    rc = disk_buffer_pool_->get_this_page(next_page_num, &frame);
羽飞's avatar
羽飞 已提交
964 965 966 967 968 969 970 971
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to get next page. page id=%d, rc=%d:%s", next_page_num, rc, strrc(rc));
      return rc;
    }
  }
  return rc;
}

羽飞's avatar
羽飞 已提交
972
bool BplusTreeHandler::validate_node_recursive(Frame *frame)
羽飞's avatar
羽飞 已提交
973 974
{
  bool result = true;
羽飞's avatar
羽飞 已提交
975
  IndexNodeHandler node(file_header_, frame);
羽飞's avatar
羽飞 已提交
976
  if (node.is_leaf()) {
羽飞's avatar
羽飞 已提交
977 978
    LeafIndexNodeHandler leaf_node(file_header_, frame);
    result = leaf_node.validate(key_comparator_, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
979
  } else {
羽飞's avatar
羽飞 已提交
980 981
    InternalIndexNodeHandler internal_node(file_header_, frame);
    result = internal_node.validate(key_comparator_, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
982 983
    for (int i = 0; result && i < internal_node.size(); i++) {
      PageNum page_num = internal_node.value_at(i);
羽飞's avatar
羽飞 已提交
984 985
      Frame *child_frame;
      RC rc = disk_buffer_pool_->get_this_page(page_num, &child_frame);
羽飞's avatar
羽飞 已提交
986 987 988 989 990 991
      if (rc != RC::SUCCESS) {
        LOG_WARN("failed to fetch child page.page id=%d, rc=%d:%s", page_num, rc, strrc(rc));
        result = false;
        break;
      }

羽飞's avatar
羽飞 已提交
992
      result = validate_node_recursive(child_frame);
羽飞's avatar
羽飞 已提交
993 994 995
    }
  }

羽飞's avatar
羽飞 已提交
996
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
997 998 999 1000 1001 1002 1003 1004 1005
  return result;
}

bool BplusTreeHandler::validate_leaf_link()
{
  if (is_empty()) {
    return true;
  }

羽飞's avatar
羽飞 已提交
1006 1007
  Frame *frame;
  RC rc = left_most_page(frame);
羽飞's avatar
羽飞 已提交
1008 1009 1010 1011 1012 1013 1014
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch left most page. rc=%d:%s", rc, strrc(rc));
    return false;
  }

  PageNum prev_page_num = BP_INVALID_PAGE_NUM;

羽飞's avatar
羽飞 已提交
1015
  LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1016 1017
  if (leaf_node.prev_page() != prev_page_num) {
    LOG_WARN("invalid page. current_page_num=%d, prev page num should be %d but got %d",
羽飞's avatar
羽飞 已提交
1018
  	       frame->page_num(), prev_page_num, leaf_node.prev_page());
羽飞's avatar
羽飞 已提交
1019 1020 1021 1022
    return false;
  }
  PageNum next_page_num = leaf_node.next_page();

羽飞's avatar
羽飞 已提交
1023
  prev_page_num = frame->page_num();
羽飞's avatar
羽飞 已提交
1024 1025
  char *prev_key = (char *)mem_pool_item_->alloc();
  memcpy(prev_key, leaf_node.key_at(leaf_node.size() - 1), file_header_.key_length);
羽飞's avatar
羽飞 已提交
1026
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1027 1028 1029

  bool result = true;
  while (result && next_page_num != BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
1030
    rc = disk_buffer_pool_->get_this_page(next_page_num, &frame);
羽飞's avatar
羽飞 已提交
1031
    if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1032
      free_key(prev_key);
羽飞's avatar
羽飞 已提交
1033 1034 1035 1036
      LOG_WARN("failed to fetch next page. page num=%d, rc=%d:%s", next_page_num, rc, strrc(rc));
      return false;
    }

羽飞's avatar
羽飞 已提交
1037
    LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1038 1039
    if (leaf_node.prev_page() != prev_page_num) {
      LOG_WARN("invalid page. current_page_num=%d, prev page num should be %d but got %d",
羽飞's avatar
羽飞 已提交
1040
	       frame->page_num(), prev_page_num, leaf_node.prev_page());
羽飞's avatar
羽飞 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049
      result = false;
    }
    if (key_comparator_(prev_key, leaf_node.key_at(0)) >= 0) {
      LOG_WARN("invalid page. current first key is not bigger than last");
      result = false;
    }

    next_page_num = leaf_node.next_page();
    memcpy(prev_key, leaf_node.key_at(leaf_node.size() - 1), file_header_.key_length);
羽飞's avatar
羽飞 已提交
1050 1051
    prev_page_num = frame->page_num();
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  }

  free_key(prev_key);
  // can do more things
  return result;
}

bool BplusTreeHandler::validate_tree()
{
  if (is_empty()) {
    return true;
  }

羽飞's avatar
羽飞 已提交
1065 1066
  Frame *frame;
  RC rc = disk_buffer_pool_->get_this_page(file_header_.root_page, &frame);
羽飞's avatar
羽飞 已提交
1067 1068 1069 1070 1071
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch root page. page id=%d, rc=%d:%s", file_header_.root_page, rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
1072
  if (!validate_node_recursive(frame) || !validate_leaf_link()) {
羽飞's avatar
羽飞 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    LOG_WARN("Current B+ Tree is invalid");
    print_tree();
    return false;
  }

  LOG_INFO("great! current tree is valid");
  return true;
}

bool BplusTreeHandler::is_empty() const
{
  return file_header_.root_page == BP_INVALID_PAGE_NUM;
}

羽飞's avatar
羽飞 已提交
1087
RC BplusTreeHandler::find_leaf(const char *key, Frame *&frame)
羽飞's avatar
羽飞 已提交
1088 1089 1090 1091 1092
{
  return find_leaf_internal(
			    [&](InternalIndexNodeHandler &internal_node) {
			      return internal_node.value_at(internal_node.lookup(key_comparator_, key));
			    },
羽飞's avatar
羽飞 已提交
1093
			    frame);
羽飞's avatar
羽飞 已提交
1094 1095
}

羽飞's avatar
羽飞 已提交
1096
RC BplusTreeHandler::left_most_page(Frame *&frame)
羽飞's avatar
羽飞 已提交
1097 1098 1099 1100 1101
{
  return find_leaf_internal(
			    [&](InternalIndexNodeHandler &internal_node) {
			      return internal_node.value_at(0);
			    },
羽飞's avatar
羽飞 已提交
1102
			    frame
羽飞's avatar
羽飞 已提交
1103 1104
			    );
}
羽飞's avatar
羽飞 已提交
1105
RC BplusTreeHandler::right_most_page(Frame *&frame)
羽飞's avatar
羽飞 已提交
1106 1107 1108 1109 1110
{
  return find_leaf_internal(
			    [&](InternalIndexNodeHandler &internal_node) {
			      return internal_node.value_at(internal_node.size() - 1);
			    },
羽飞's avatar
羽飞 已提交
1111
			    frame
羽飞's avatar
羽飞 已提交
1112 1113 1114 1115
			    );
}

RC BplusTreeHandler::find_leaf_internal(const std::function<PageNum(InternalIndexNodeHandler &)> &child_page_getter,
羽飞's avatar
羽飞 已提交
1116
					Frame *&frame)
羽飞's avatar
羽飞 已提交
1117 1118 1119 1120 1121
{
  if (is_empty()) {
    return RC::EMPTY;
  }

羽飞's avatar
羽飞 已提交
1122
  RC rc = disk_buffer_pool_->get_this_page(file_header_.root_page, &frame);
羽飞's avatar
羽飞 已提交
1123 1124 1125 1126 1127
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch root page. page id=%d, rc=%d:%s", file_header_.root_page, rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
1128
  IndexNode *node = (IndexNode *)frame->data();
羽飞's avatar
羽飞 已提交
1129
  while (false == node->is_leaf) {
羽飞's avatar
羽飞 已提交
1130
    InternalIndexNodeHandler internal_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1131 1132
    PageNum page_num = child_page_getter(internal_node);

羽飞's avatar
羽飞 已提交
1133
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1134

羽飞's avatar
羽飞 已提交
1135
    rc = disk_buffer_pool_->get_this_page(page_num, &frame);
羽飞's avatar
羽飞 已提交
1136
    if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1137
      LOG_WARN("Failed to load page page_num:%d", page_num);
羽飞's avatar
羽飞 已提交
1138 1139
      return rc;
    }
羽飞's avatar
羽飞 已提交
1140
    node = (IndexNode *)frame->data();
羽飞's avatar
羽飞 已提交
1141 1142 1143 1144 1145
  }

  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
1146
RC BplusTreeHandler::insert_entry_into_leaf_node(Frame *frame, const char *key, const RID *rid)
羽飞's avatar
羽飞 已提交
1147
{
羽飞's avatar
羽飞 已提交
1148
  LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157
  bool exists = false;
  int insert_position = leaf_node.lookup(key_comparator_, key, &exists);
  if (exists) {
    LOG_TRACE("entry exists");
    return RC::RECORD_DUPLICATE_KEY;
  }

  if (leaf_node.size() < leaf_node.max_size()) {
    leaf_node.insert(insert_position, key, (const char *)rid);
羽飞's avatar
羽飞 已提交
1158 1159
    frame->mark_dirty();
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1160 1161 1162
    return RC::SUCCESS;
  }

羽飞's avatar
羽飞 已提交
1163 1164
  Frame * new_frame = nullptr;
  RC rc = split<LeafIndexNodeHandler>(frame, new_frame);
羽飞's avatar
羽飞 已提交
1165 1166 1167 1168 1169
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to split leaf node. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
1170 1171
  LeafIndexNodeHandler new_index_node(file_header_, new_frame);
  new_index_node.set_prev_page(frame->page_num());
羽飞's avatar
羽飞 已提交
1172 1173
  new_index_node.set_next_page(leaf_node.next_page());
  new_index_node.set_parent_page_num(leaf_node.parent_page_num());
羽飞's avatar
羽飞 已提交
1174
  leaf_node.set_next_page(new_frame->page_num());
羽飞's avatar
羽飞 已提交
1175 1176 1177

  PageNum next_page_num = new_index_node.next_page();
  if (next_page_num != BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
1178 1179
    Frame * next_frame;
    rc = disk_buffer_pool_->get_this_page(next_page_num, &next_frame);
羽飞's avatar
羽飞 已提交
1180 1181 1182 1183 1184
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to fetch next page. page num=%d, rc=%d:%s", next_page_num, rc, strrc(rc));
      return rc;
    }

羽飞's avatar
羽飞 已提交
1185 1186 1187
    LeafIndexNodeHandler next_node(file_header_, next_frame);
    next_node.set_prev_page(new_frame->page_num());
    disk_buffer_pool_->unpin_page(next_frame);
羽飞's avatar
羽飞 已提交
1188 1189 1190 1191 1192 1193 1194 1195
  }

  if (insert_position < leaf_node.size()) {
    leaf_node.insert(insert_position, key, (const char *)rid);
  } else {
    new_index_node.insert(insert_position - leaf_node.size(), key, (const char *)rid);
  }

羽飞's avatar
羽飞 已提交
1196
  return insert_entry_into_parent(frame, new_frame, new_index_node.key_at(0));
羽飞's avatar
羽飞 已提交
1197 1198
}

羽飞's avatar
羽飞 已提交
1199
RC BplusTreeHandler::insert_entry_into_parent(Frame *frame, Frame *new_frame, const char *key)
羽飞's avatar
羽飞 已提交
1200 1201 1202
{
  RC rc = RC::SUCCESS;

羽飞's avatar
羽飞 已提交
1203 1204
  IndexNodeHandler node_handler(file_header_, frame);
  IndexNodeHandler new_node_handler(file_header_, new_frame);
羽飞's avatar
羽飞 已提交
1205 1206 1207 1208 1209
  PageNum parent_page_num = node_handler.parent_page_num();

  if (parent_page_num == BP_INVALID_PAGE_NUM) {

    // create new root page
羽飞's avatar
羽飞 已提交
1210 1211
    Frame *root_frame;
    rc = disk_buffer_pool_->allocate_page(&root_frame);
羽飞's avatar
羽飞 已提交
1212 1213 1214 1215 1216
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to allocate new root page. rc=%d:%s", rc, strrc(rc));
      return rc;
    }

羽飞's avatar
羽飞 已提交
1217
    InternalIndexNodeHandler root_node(file_header_, root_frame);
羽飞's avatar
羽飞 已提交
1218
    root_node.init_empty();
羽飞's avatar
羽飞 已提交
1219 1220 1221
    root_node.create_new_root(frame->page_num(), key, new_frame->page_num());
    node_handler.set_parent_page_num(root_frame->page_num());
    new_node_handler.set_parent_page_num(root_frame->page_num());
羽飞's avatar
羽飞 已提交
1222

羽飞's avatar
羽飞 已提交
1223 1224 1225 1226
    frame->mark_dirty();
    new_frame->mark_dirty();
    disk_buffer_pool_->unpin_page(frame);
    disk_buffer_pool_->unpin_page(new_frame);
羽飞's avatar
羽飞 已提交
1227

羽飞's avatar
羽飞 已提交
1228
    file_header_.root_page = root_frame->page_num();
羽飞's avatar
羽飞 已提交
1229
    update_root_page_num(); // TODO
羽飞's avatar
羽飞 已提交
1230 1231
    root_frame->mark_dirty();
    disk_buffer_pool_->unpin_page(root_frame);
羽飞's avatar
羽飞 已提交
1232 1233 1234 1235 1236

    return RC::SUCCESS;

  } else {

羽飞's avatar
羽飞 已提交
1237 1238
    Frame *parent_frame;
    rc = disk_buffer_pool_->get_this_page(parent_page_num, &parent_frame);
羽飞's avatar
羽飞 已提交
1239 1240 1241 1242 1243 1244
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to insert entry into leaf. rc=%d:%s", rc, strrc(rc));
      // should do more things to recover
      return rc;
    }

羽飞's avatar
羽飞 已提交
1245
    InternalIndexNodeHandler node(file_header_, parent_frame);
羽飞's avatar
羽飞 已提交
1246 1247 1248

    /// current node is not in full mode, insert the entry and return
    if (node.size() < node.max_size()) {
羽飞's avatar
羽飞 已提交
1249
      node.insert(key, new_frame->page_num(), key_comparator_);
羽飞's avatar
羽飞 已提交
1250 1251
      new_node_handler.set_parent_page_num(parent_page_num);

羽飞's avatar
羽飞 已提交
1252 1253 1254 1255 1256 1257
      frame->mark_dirty();
      new_frame->mark_dirty();
      parent_frame->mark_dirty();
      disk_buffer_pool_->unpin_page(frame);
      disk_buffer_pool_->unpin_page(new_frame);
      disk_buffer_pool_->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
1258 1259 1260 1261

    } else {

      // we should split the node and insert the entry and then insert new entry to current node's parent
羽飞's avatar
羽飞 已提交
1262 1263
      Frame * new_parent_frame;
      rc = split<InternalIndexNodeHandler>(parent_frame, new_parent_frame);
羽飞's avatar
羽飞 已提交
1264 1265
      if (rc != RC::SUCCESS) {
	LOG_WARN("failed to split internal node. rc=%d:%s", rc, strrc(rc));
羽飞's avatar
羽飞 已提交
1266 1267 1268
	disk_buffer_pool_->unpin_page(frame);
	disk_buffer_pool_->unpin_page(new_frame);
	disk_buffer_pool_->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
1269 1270
      } else {
	// insert into left or right ? decide by key compare result
羽飞's avatar
羽飞 已提交
1271
	InternalIndexNodeHandler new_node(file_header_, new_parent_frame);
羽飞's avatar
羽飞 已提交
1272
	if (key_comparator_(key, new_node.key_at(0)) > 0) {
羽飞's avatar
羽飞 已提交
1273
	  new_node.insert(key, new_frame->page_num(), key_comparator_);
羽飞's avatar
羽飞 已提交
1274 1275
          new_node_handler.set_parent_page_num(new_node.page_num());
	} else {
羽飞's avatar
羽飞 已提交
1276
	  node.insert(key, new_frame->page_num(), key_comparator_);
羽飞's avatar
羽飞 已提交
1277 1278 1279
          new_node_handler.set_parent_page_num(node.page_num());
	}

羽飞's avatar
羽飞 已提交
1280 1281
	disk_buffer_pool_->unpin_page(frame);
	disk_buffer_pool_->unpin_page(new_frame);
羽飞's avatar
羽飞 已提交
1282
	
羽飞's avatar
羽飞 已提交
1283
	rc = insert_entry_into_parent(parent_frame, new_parent_frame, new_node.key_at(0));
羽飞's avatar
羽飞 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
      }
    }
  }
  return rc;
}

/**
 * split one full node into two
 * @param page_handle[inout] the node to split
 * @param new_page_handle[out] the new node after split
 * @param intert_position the intert position of new key
 */
template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
1297
RC BplusTreeHandler::split(Frame *frame, Frame *&new_frame)
羽飞's avatar
羽飞 已提交
1298
{
羽飞's avatar
羽飞 已提交
1299
  IndexNodeHandlerType old_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1300 1301

  // add a new node
羽飞's avatar
羽飞 已提交
1302
  RC rc = disk_buffer_pool_->allocate_page(&new_frame);
羽飞's avatar
羽飞 已提交
1303
  if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1304
    LOG_WARN("Failed to split index page due to failed to allocate page, rc=%d:%s", rc, strrc(rc));
羽飞's avatar
羽飞 已提交
1305 1306 1307
    return rc;
  }

羽飞's avatar
羽飞 已提交
1308
  IndexNodeHandlerType new_node(file_header_, new_frame);
羽飞's avatar
羽飞 已提交
1309 1310 1311
  new_node.init_empty();
  new_node.set_parent_page_num(old_node.parent_page_num());

羽飞's avatar
羽飞 已提交
1312
  old_node.move_half_to(new_node, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
1313

羽飞's avatar
羽飞 已提交
1314 1315
  frame->mark_dirty();
  new_frame->mark_dirty();
羽飞's avatar
羽飞 已提交
1316 1317 1318 1319 1320
  return RC::SUCCESS;
}

RC BplusTreeHandler::update_root_page_num()
{
羽飞's avatar
羽飞 已提交
1321 1322
  Frame * header_frame;
  RC rc = disk_buffer_pool_->get_this_page(FIRST_INDEX_PAGE, &header_frame);
羽飞's avatar
羽飞 已提交
1323 1324 1325 1326 1327
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch header page. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
1328
  IndexFileHeader *header = (IndexFileHeader *)header_frame->data();
羽飞's avatar
羽飞 已提交
1329
  header->root_page = file_header_.root_page;
羽飞's avatar
羽飞 已提交
1330 1331
  header_frame->mark_dirty();
  disk_buffer_pool_->unpin_page(header_frame);
羽飞's avatar
羽飞 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
  return rc;
}


RC BplusTreeHandler::create_new_tree(const char *key, const RID *rid)
{
  RC rc = RC::SUCCESS;
  if (file_header_.root_page != BP_INVALID_PAGE_NUM) {
    rc = RC::INTERNAL;
    LOG_WARN("cannot create new tree while root page is valid. root page id=%d", file_header_.root_page);
    return rc;
  }

羽飞's avatar
羽飞 已提交
1345 1346
  Frame *frame;
  rc = disk_buffer_pool_->allocate_page(&frame);
羽飞's avatar
羽飞 已提交
1347 1348 1349 1350 1351
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to allocate root page. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

羽飞's avatar
羽飞 已提交
1352
  LeafIndexNodeHandler leaf_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1353 1354
  leaf_node.init_empty();
  leaf_node.insert(0, key, (const char *)rid);
羽飞's avatar
羽飞 已提交
1355 1356 1357
  file_header_.root_page = frame->page_num();
  frame->mark_dirty();
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367

  rc = update_root_page_num();
  // disk_buffer_pool_->check_all_pages_unpinned(file_id_);
  return rc;
}

char *BplusTreeHandler::make_key(const char *user_key, const RID &rid)
{
  char *key = (char *)mem_pool_item_->alloc();
  if (key == nullptr) {
羽飞's avatar
羽飞 已提交
1368
    LOG_WARN("Failed to alloc memory for key.");
羽飞's avatar
羽飞 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    return nullptr;
  }
  memcpy(key, user_key, file_header_.attr_length);
  memcpy(key + file_header_.attr_length, &rid, sizeof(rid));
  return key;
}

void BplusTreeHandler::free_key(char *key)
{
  mem_pool_item_->free(key);
}

RC BplusTreeHandler::insert_entry(const char *user_key, const RID *rid)
{
  if (user_key == nullptr || rid == nullptr) {
    LOG_WARN("Invalid arguments, key is empty or rid is empty");
    return RC::INVALID_ARGUMENT;
  }

  char *key = make_key(user_key, *rid);
  if (key == nullptr) {
羽飞's avatar
羽飞 已提交
1390
    LOG_WARN("Failed to alloc memory for key.");
羽飞's avatar
羽飞 已提交
1391 1392 1393 1394
    return RC::NOMEM;
  }

  if (is_empty()) {
羽飞's avatar
羽飞 已提交
1395 1396 1397
    RC rc = create_new_tree(key, rid);
    mem_pool_item_->free(key);
    return rc;
羽飞's avatar
羽飞 已提交
1398 1399
  }

羽飞's avatar
羽飞 已提交
1400 1401
  Frame *frame;
  RC rc = find_leaf(key, frame);
羽飞's avatar
羽飞 已提交
1402
  if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1403
    LOG_WARN("Failed to find leaf %s. rc=%d:%s", rid->to_string().c_str(), rc, strrc(rc));
羽飞's avatar
羽飞 已提交
1404 1405 1406 1407
    mem_pool_item_->free(key);
    return rc;
  }

羽飞's avatar
羽飞 已提交
1408
  rc = insert_entry_into_leaf_node(frame, key, rid);
羽飞's avatar
羽飞 已提交
1409
  if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1410 1411
    LOG_TRACE("Failed to insert into leaf of index, rid:%s", rid->to_string().c_str());
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    mem_pool_item_->free(key);
    // disk_buffer_pool_->check_all_pages_unpinned(file_id_);
    return rc;
  }

  mem_pool_item_->free(key);
  LOG_TRACE("insert entry success");
  // disk_buffer_pool_->check_all_pages_unpinned(file_id_);
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
1423
RC BplusTreeHandler::get_entry(const char *user_key, int key_len, std::list<RID> &rids)
羽飞's avatar
羽飞 已提交
1424 1425
{
  BplusTreeScanner scanner(*this);
羽飞's avatar
羽飞 已提交
1426
  RC rc = scanner.open(user_key, key_len, true/*left_inclusive*/, user_key, key_len, true/*right_inclusive*/);
羽飞's avatar
羽飞 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to open scanner. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

  RID rid;
  while ((rc = scanner.next_entry(&rid)) == RC::SUCCESS) {
    rids.push_back(rid);
  }

  scanner.close();
  if (rc != RC::RECORD_EOF) {
    LOG_WARN("scanner return error. rc=%d:%s", rc, strrc(rc));
  } else {
    rc = RC::SUCCESS;
  }
  return rc;
}

羽飞's avatar
羽飞 已提交
1446
RC BplusTreeHandler::adjust_root(Frame *root_frame)
羽飞's avatar
羽飞 已提交
1447
{
羽飞's avatar
羽飞 已提交
1448
  IndexNodeHandler root_node(file_header_, root_frame);
羽飞's avatar
羽飞 已提交
1449
  if (root_node.is_leaf() && root_node.size() > 0) {
羽飞's avatar
羽飞 已提交
1450 1451
    root_frame->mark_dirty();
    disk_buffer_pool_->unpin_page(root_frame);
羽飞's avatar
羽飞 已提交
1452 1453 1454 1455 1456 1457 1458 1459
    return RC::SUCCESS;
  }

  if (root_node.is_leaf()) {
    // this is a leaf and an empty node
    file_header_.root_page = BP_INVALID_PAGE_NUM;
  } else {
    // this is an internal node and has only one child node
羽飞's avatar
羽飞 已提交
1460
    InternalIndexNodeHandler internal_node(file_header_, root_frame);
羽飞's avatar
羽飞 已提交
1461 1462

    const PageNum child_page_num = internal_node.value_at(0);
羽飞's avatar
羽飞 已提交
1463 1464
    Frame * child_frame;
    RC rc = disk_buffer_pool_->get_this_page(child_page_num, &child_frame);
羽飞's avatar
羽飞 已提交
1465 1466 1467 1468 1469
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to fetch child page. page num=%d, rc=%d:%s", child_page_num, rc, strrc(rc));
      return rc;
    }

羽飞's avatar
羽飞 已提交
1470
    IndexNodeHandler child_node(file_header_, child_frame);
羽飞's avatar
羽飞 已提交
1471
    child_node.set_parent_page_num(BP_INVALID_PAGE_NUM);
羽飞's avatar
羽飞 已提交
1472
    disk_buffer_pool_->unpin_page(child_frame);
羽飞's avatar
羽飞 已提交
1473 1474 1475 1476 1477 1478
    
    file_header_.root_page = child_page_num;
  }

  update_root_page_num();

羽飞's avatar
羽飞 已提交
1479 1480 1481
  PageNum old_root_page_num = root_frame->page_num();
  disk_buffer_pool_->unpin_page(root_frame);
  disk_buffer_pool_->dispose_page(old_root_page_num);
羽飞's avatar
羽飞 已提交
1482 1483 1484
  return RC::SUCCESS;
}
template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
1485
RC BplusTreeHandler::coalesce_or_redistribute(Frame *frame)
羽飞's avatar
羽飞 已提交
1486
{
羽飞's avatar
羽飞 已提交
1487
  IndexNodeHandlerType index_node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1488
  if (index_node.size() >= index_node.min_size()) {
羽飞's avatar
羽飞 已提交
1489
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1490 1491 1492 1493 1494 1495 1496
    return RC::SUCCESS;
  }

  const PageNum parent_page_num = index_node.parent_page_num();
  if (BP_INVALID_PAGE_NUM == parent_page_num) {
    // this is the root page
    if (index_node.size() > 1) {
羽飞's avatar
羽飞 已提交
1497
      disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1498 1499
    } else {
      // adjust the root node
羽飞's avatar
羽飞 已提交
1500
      adjust_root(frame);
羽飞's avatar
羽飞 已提交
1501 1502 1503 1504
    }
    return RC::SUCCESS;
  }

羽飞's avatar
羽飞 已提交
1505 1506
  Frame * parent_frame;
  RC rc = disk_buffer_pool_->get_this_page(parent_page_num, &parent_frame);
羽飞's avatar
羽飞 已提交
1507 1508
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch parent page. page id=%d, rc=%d:%s", parent_page_num, rc, strrc(rc));
羽飞's avatar
羽飞 已提交
1509
    disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1510 1511 1512
    return rc;
  }

羽飞's avatar
羽飞 已提交
1513
  InternalIndexNodeHandler parent_index_node(file_header_, parent_frame);
羽飞's avatar
羽飞 已提交
1514
  int index = parent_index_node.lookup(key_comparator_, index_node.key_at(index_node.size() - 1));
羽飞's avatar
羽飞 已提交
1515
  if (parent_index_node.value_at(index) != frame->page_num()) {
羽飞's avatar
羽飞 已提交
1516
    LOG_ERROR("lookup return an invalid value. index=%d, this page num=%d, but got %d",
羽飞's avatar
羽飞 已提交
1517
	      index, frame->page_num(), parent_index_node.value_at(index));
羽飞's avatar
羽飞 已提交
1518 1519 1520 1521 1522 1523 1524 1525
  }
  PageNum neighbor_page_num;
  if (index == 0) {
    neighbor_page_num = parent_index_node.value_at(1);
  } else {
    neighbor_page_num = parent_index_node.value_at(index - 1);
  }

羽飞's avatar
羽飞 已提交
1526 1527
  Frame * neighbor_frame;
  rc = disk_buffer_pool_->get_this_page(neighbor_page_num, &neighbor_frame);
羽飞's avatar
羽飞 已提交
1528 1529 1530
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to fetch neighbor page. page id=%d, rc=%d:%s", neighbor_page_num, rc, strrc(rc));
    // TODO do more thing to release resource
羽飞's avatar
羽飞 已提交
1531 1532
    disk_buffer_pool_->unpin_page(frame);
    disk_buffer_pool_->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
1533 1534 1535
    return rc;
  }

羽飞's avatar
羽飞 已提交
1536
  IndexNodeHandlerType neighbor_node(file_header_, neighbor_frame);
羽飞's avatar
羽飞 已提交
1537
  if (index_node.size() + neighbor_node.size() > index_node.max_size()) {
羽飞's avatar
羽飞 已提交
1538
    rc = redistribute<IndexNodeHandlerType>(neighbor_frame, frame, parent_frame, index);
羽飞's avatar
羽飞 已提交
1539
  } else {
羽飞's avatar
羽飞 已提交
1540
    rc = coalesce<IndexNodeHandlerType>(neighbor_frame, frame, parent_frame, index);
羽飞's avatar
羽飞 已提交
1541 1542 1543 1544 1545
  }
  return rc;
}

template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
1546
RC BplusTreeHandler::coalesce(Frame *neighbor_frame, Frame *frame, Frame *parent_frame, int index)
羽飞's avatar
羽飞 已提交
1547
{
羽飞's avatar
羽飞 已提交
1548 1549
  IndexNodeHandlerType neighbor_node(file_header_, neighbor_frame);
  IndexNodeHandlerType node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1550

羽飞's avatar
羽飞 已提交
1551
  InternalIndexNodeHandler parent_node(file_header_, parent_frame);
羽飞's avatar
羽飞 已提交
1552

羽飞's avatar
羽飞 已提交
1553 1554
  Frame *left_frame = nullptr;
  Frame *right_frame = nullptr;
羽飞's avatar
羽飞 已提交
1555 1556
  if (index == 0) {
    // neighbor node is at right
羽飞's avatar
羽飞 已提交
1557 1558
    left_frame  = frame;
    right_frame = neighbor_frame;
羽飞's avatar
羽飞 已提交
1559 1560
    index++;
  } else {
羽飞's avatar
羽飞 已提交
1561 1562
    left_frame  = neighbor_frame;
    right_frame = frame;
羽飞's avatar
羽飞 已提交
1563 1564 1565
    // neighbor is at left
  }

羽飞's avatar
羽飞 已提交
1566 1567
  IndexNodeHandlerType left_node(file_header_, left_frame);
  IndexNodeHandlerType right_node(file_header_, right_frame);
羽飞's avatar
羽飞 已提交
1568 1569 1570

  parent_node.remove(index);
  // parent_node.validate(key_comparator_, disk_buffer_pool_, file_id_);
羽飞's avatar
羽飞 已提交
1571
  RC rc = right_node.move_to(left_node, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
1572 1573 1574 1575 1576 1577 1578
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to move right node to left. rc=%d:%s", rc, strrc(rc));
    return rc;
  }
  // left_node.validate(key_comparator_);

  if (left_node.is_leaf()) {
羽飞's avatar
羽飞 已提交
1579 1580
    LeafIndexNodeHandler left_leaf_node(file_header_, left_frame);
    LeafIndexNodeHandler right_leaf_node(file_header_, right_frame);
羽飞's avatar
羽飞 已提交
1581 1582 1583 1584
    left_leaf_node.set_next_page(right_leaf_node.next_page());

    PageNum next_right_page_num = right_leaf_node.next_page();
    if (next_right_page_num != BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
1585 1586
      Frame *next_right_frame;
      rc = disk_buffer_pool_->get_this_page(next_right_page_num, &next_right_frame);
羽飞's avatar
羽飞 已提交
1587 1588
      if (rc != RC::SUCCESS) {
        LOG_WARN("failed to fetch next right page. page number:%d. rc=%d:%s", next_right_page_num, rc, strrc(rc));
羽飞's avatar
羽飞 已提交
1589 1590 1591
	disk_buffer_pool_->unpin_page(frame);
	disk_buffer_pool_->unpin_page(neighbor_frame);
	disk_buffer_pool_->unpin_page(parent_frame);
羽飞's avatar
羽飞 已提交
1592 1593 1594
        return rc;
      }

羽飞's avatar
羽飞 已提交
1595
      LeafIndexNodeHandler next_right_node(file_header_, next_right_frame);
羽飞's avatar
羽飞 已提交
1596
      next_right_node.set_prev_page(left_node.page_num());
羽飞's avatar
羽飞 已提交
1597
      disk_buffer_pool_->unpin_page(next_right_frame);
羽飞's avatar
羽飞 已提交
1598 1599 1600 1601
    }
    
  }

羽飞's avatar
羽飞 已提交
1602 1603 1604 1605 1606
  PageNum right_page_num = right_frame->page_num();
  disk_buffer_pool_->unpin_page(left_frame);
  disk_buffer_pool_->unpin_page(right_frame);
  disk_buffer_pool_->dispose_page(right_page_num);
  return coalesce_or_redistribute<InternalIndexNodeHandler>(parent_frame);
羽飞's avatar
羽飞 已提交
1607 1608 1609
}

template <typename IndexNodeHandlerType>
羽飞's avatar
羽飞 已提交
1610
RC BplusTreeHandler::redistribute(Frame *neighbor_frame, Frame *frame, Frame *parent_frame, int index)
羽飞's avatar
羽飞 已提交
1611
{
羽飞's avatar
羽飞 已提交
1612 1613 1614
  InternalIndexNodeHandler parent_node(file_header_, parent_frame);
  IndexNodeHandlerType neighbor_node(file_header_, neighbor_frame);
  IndexNodeHandlerType node(file_header_, frame);
羽飞's avatar
羽飞 已提交
1615 1616 1617 1618 1619 1620
  if (neighbor_node.size() < node.size()) {
    LOG_ERROR("got invalid nodes. neighbor node size %d, this node size %d",
	      neighbor_node.size(), node.size());
  }
  if (index == 0) {
    // the neighbor is at right
羽飞's avatar
羽飞 已提交
1621
    neighbor_node.move_first_to_end(node, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
1622 1623 1624 1625 1626 1627
    // neighbor_node.validate(key_comparator_, disk_buffer_pool_, file_id_);
    // node.validate(key_comparator_, disk_buffer_pool_, file_id_);
    parent_node.set_key_at(index + 1, neighbor_node.key_at(0));
    // parent_node.validate(key_comparator_, disk_buffer_pool_, file_id_);
  } else {
    // the neighbor is at left
羽飞's avatar
羽飞 已提交
1628
    neighbor_node.move_last_to_front(node, disk_buffer_pool_);
羽飞's avatar
羽飞 已提交
1629 1630 1631 1632 1633 1634
    // neighbor_node.validate(key_comparator_, disk_buffer_pool_, file_id_);
    // node.validate(key_comparator_, disk_buffer_pool_, file_id_);
    parent_node.set_key_at(index, node.key_at(0));
    // parent_node.validate(key_comparator_, disk_buffer_pool_, file_id_);
  }

羽飞's avatar
羽飞 已提交
1635 1636 1637 1638 1639 1640
  neighbor_frame->mark_dirty();
  frame->mark_dirty();
  parent_frame->mark_dirty();
  disk_buffer_pool_->unpin_page(parent_frame);
  disk_buffer_pool_->unpin_page(neighbor_frame);
  disk_buffer_pool_->unpin_page(frame);
羽飞's avatar
羽飞 已提交
1641 1642 1643
  return RC::SUCCESS;
}

羽飞's avatar
羽飞 已提交
1644
RC BplusTreeHandler::delete_entry_internal(Frame *leaf_frame, const char *key)
羽飞's avatar
羽飞 已提交
1645
{
羽飞's avatar
羽飞 已提交
1646
  LeafIndexNodeHandler leaf_index_node(file_header_, leaf_frame);
羽飞's avatar
羽飞 已提交
1647 1648 1649 1650

  const int remove_count = leaf_index_node.remove(key, key_comparator_);
  if (remove_count == 0) {
    LOG_TRACE("no data to remove");
羽飞's avatar
羽飞 已提交
1651
    disk_buffer_pool_->unpin_page(leaf_frame);
羽飞's avatar
羽飞 已提交
1652 1653 1654 1655
    return RC::RECORD_RECORD_NOT_EXIST;
  }
  // leaf_index_node.validate(key_comparator_, disk_buffer_pool_, file_id_);

羽飞's avatar
羽飞 已提交
1656
  leaf_frame->mark_dirty();
羽飞's avatar
羽飞 已提交
1657 1658

  if (leaf_index_node.size() >= leaf_index_node.min_size()) {
羽飞's avatar
羽飞 已提交
1659
    disk_buffer_pool_->unpin_page(leaf_frame);
羽飞's avatar
羽飞 已提交
1660 1661 1662
    return RC::SUCCESS;
  }

羽飞's avatar
羽飞 已提交
1663
  return coalesce_or_redistribute<LeafIndexNodeHandler>(leaf_frame);
羽飞's avatar
羽飞 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
}

RC BplusTreeHandler::delete_entry(const char *user_key, const RID *rid)
{
  char *key = (char *)mem_pool_item_->alloc();
  if (nullptr == key) {
    LOG_WARN("Failed to alloc memory for key. size=%d", file_header_.key_length);
    return RC::NOMEM;
  }
  memcpy(key, user_key, file_header_.attr_length);
  memcpy(key + file_header_.attr_length, rid, sizeof(*rid));

羽飞's avatar
羽飞 已提交
1676 1677
  Frame *leaf_frame;
  RC rc = find_leaf(key, leaf_frame);
羽飞's avatar
羽飞 已提交
1678 1679 1680 1681 1682
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to find leaf page. rc =%d:%s", rc, strrc(rc));
    mem_pool_item_->free(key);
    return rc;
  }
羽飞's avatar
羽飞 已提交
1683
  rc = delete_entry_internal(leaf_frame, key);
羽飞's avatar
羽飞 已提交
1684
  if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1685
    LOG_WARN("Failed to delete index");
羽飞's avatar
羽飞 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    mem_pool_item_->free(key);
    return rc;
  }
  mem_pool_item_->free(key);
  return RC::SUCCESS;
}

BplusTreeScanner::BplusTreeScanner(BplusTreeHandler &tree_handler) : tree_handler_(tree_handler)
{}

BplusTreeScanner::~BplusTreeScanner()
{
  close();
}

羽飞's avatar
羽飞 已提交
1701 1702
RC BplusTreeScanner::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
羽飞 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
{
  RC rc = RC::SUCCESS;
  if (inited_) {
    LOG_WARN("tree scanner has been inited");
    return RC::INTERNAL;
  }

  inited_ = true;
  
  // 校验输入的键值是否是合法范围
  if (left_user_key && right_user_key) {
    const auto &attr_comparator = tree_handler_.key_comparator_.attr_comparator();
    const int result = attr_comparator(left_user_key, right_user_key);
    if (result > 0 || // left < right
         // left == right but is (left,right)/[left,right) or (left,right]
	(result == 0 && (left_inclusive == false || right_inclusive == false))) { 
      return RC::INVALID_ARGUMENT;
    }
  }

  if (nullptr == left_user_key) {
羽飞's avatar
羽飞 已提交
1724
    rc = tree_handler_.left_most_page(left_frame_);
羽飞's avatar
羽飞 已提交
1725 1726 1727 1728 1729 1730 1731 1732
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to find left most page. rc=%d:%s", rc, strrc(rc));
      return rc;
    }

    iter_index_ = 0;
  } else {
    char *left_key = nullptr;
羽飞's avatar
羽飞 已提交
1733 1734 1735 1736 1737 1738

    char *fixed_left_key = const_cast<char *>(left_user_key);
    if (tree_handler_.file_header_.attr_type == CHARS) {
      bool should_inclusive_after_fix = false;
      rc = fix_user_key(left_user_key, left_len, true/*greater*/, &fixed_left_key, &should_inclusive_after_fix);
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1739 1740
        LOG_WARN("failed to fix left user key. rc=%s", strrc(rc));
        return rc;
羽飞's avatar
羽飞 已提交
1741 1742 1743
      }

      if (should_inclusive_after_fix) {
羽飞's avatar
羽飞 已提交
1744
	      left_inclusive = true;
羽飞's avatar
羽飞 已提交
1745 1746 1747 1748 1749
      }
    }

    if (left_inclusive) {
      left_key = tree_handler_.make_key(fixed_left_key, *RID::min());
羽飞's avatar
羽飞 已提交
1750
    } else {
羽飞's avatar
羽飞 已提交
1751 1752 1753 1754 1755 1756
      left_key = tree_handler_.make_key(fixed_left_key, *RID::max());
    }

    if (fixed_left_key != left_user_key) {
      delete[] fixed_left_key;
      fixed_left_key = nullptr;
羽飞's avatar
羽飞 已提交
1757
    }
羽飞's avatar
羽飞 已提交
1758
    rc = tree_handler_.find_leaf(left_key, left_frame_);
羽飞's avatar
羽飞 已提交
1759 1760 1761 1762 1763 1764

    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to find left page. rc=%d:%s", rc, strrc(rc));
      tree_handler_.free_key(left_key);
      return rc;
    }
羽飞's avatar
羽飞 已提交
1765
    LeafIndexNodeHandler left_node(tree_handler_.file_header_, left_frame_);
羽飞's avatar
羽飞 已提交
1766 1767 1768 1769 1770 1771
    int left_index = left_node.lookup(tree_handler_.key_comparator_, left_key);
    tree_handler_.free_key(left_key);
    // lookup 返回的是适合插入的位置,还需要判断一下是否在合适的边界范围内
    if (left_index >= left_node.size()) { // 超出了当前页,就需要向后移动一个位置
      const PageNum next_page_num = left_node.next_page();
      if (next_page_num == BP_INVALID_PAGE_NUM) { // 这里已经是最后一页,说明当前扫描,没有数据
羽飞's avatar
羽飞 已提交
1772
	      return RC::SUCCESS;
羽飞's avatar
羽飞 已提交
1773 1774
      }

羽飞's avatar
羽飞 已提交
1775 1776
      tree_handler_.disk_buffer_pool_->unpin_page(left_frame_);
      rc = tree_handler_.disk_buffer_pool_->get_this_page(next_page_num, &left_frame_);
羽飞's avatar
羽飞 已提交
1777
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1778 1779
        LOG_WARN("failed to fetch next page. page num=%d, rc=%d:%s", next_page_num, rc, strrc(rc));
        return rc;
羽飞's avatar
羽飞 已提交
1780 1781 1782 1783 1784 1785 1786 1787 1788
      }

      left_index = 0;
    }
    iter_index_ = left_index;
  }

  // 没有指定右边界范围,那么就返回右边界最大值
  if (nullptr == right_user_key) {
羽飞's avatar
羽飞 已提交
1789
    rc = tree_handler_.right_most_page(right_frame_);
羽飞's avatar
羽飞 已提交
1790 1791 1792 1793 1794
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to fetch right most page. rc=%d:%s", rc, strrc(rc));
      return rc;
    }

羽飞's avatar
羽飞 已提交
1795
    LeafIndexNodeHandler node(tree_handler_.file_header_, right_frame_);
羽飞's avatar
羽飞 已提交
1796 1797 1798 1799
    end_index_ = node.size() - 1;
  } else {

    char *right_key = nullptr;
羽飞's avatar
羽飞 已提交
1800 1801 1802 1803 1804
    char *fixed_right_key = const_cast<char *>(right_user_key);
    bool should_include_after_fix = false;
    if (tree_handler_.file_header_.attr_type == CHARS) {
      rc = fix_user_key(right_user_key, right_len, false/*want_greater*/, &fixed_right_key, &should_include_after_fix);
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1805 1806
        LOG_WARN("failed to fix right user key. rc=%s", strrc(rc));
        return rc;
羽飞's avatar
羽飞 已提交
1807 1808 1809
      }

      if (should_include_after_fix) {
羽飞's avatar
羽飞 已提交
1810
	      right_inclusive = true;
羽飞's avatar
羽飞 已提交
1811 1812
      }
    }
羽飞's avatar
羽飞 已提交
1813
    if (right_inclusive) {
羽飞's avatar
羽飞 已提交
1814
      right_key = tree_handler_.make_key(fixed_right_key, *RID::max());
羽飞's avatar
羽飞 已提交
1815
    } else {
羽飞's avatar
羽飞 已提交
1816 1817 1818 1819 1820 1821
      right_key = tree_handler_.make_key(fixed_right_key, *RID::min());
    }

    if (fixed_right_key != right_user_key) {
      delete[] fixed_right_key;
      fixed_right_key = nullptr;
羽飞's avatar
羽飞 已提交
1822 1823
    }

羽飞's avatar
羽飞 已提交
1824
    rc = tree_handler_.find_leaf(right_key, right_frame_);
羽飞's avatar
羽飞 已提交
1825 1826 1827 1828 1829 1830
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to find left page. rc=%d:%s", rc, strrc(rc));
      tree_handler_.free_key(right_key);
      return rc;
    }

羽飞's avatar
羽飞 已提交
1831
    LeafIndexNodeHandler right_node(tree_handler_.file_header_, right_frame_);
羽飞's avatar
羽飞 已提交
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
    int right_index = right_node.lookup(tree_handler_.key_comparator_, right_key);
    tree_handler_.free_key(right_key);
    // lookup 返回的是适合插入的位置,需要根据实际情况做调整
    // 通常情况下需要找到上一个位置
    if (right_index > 0) {
      right_index--;
    } else {
      // 实际上,只有最左边的叶子节点查找时,lookup 才可能返回0
      // 其它的叶子节点都不可能返回0,所以这段逻辑其实是可以简化的
      const PageNum prev_page_num = right_node.prev_page();
      if (prev_page_num == BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
1843 1844
        end_index_ = -1;
        return RC::SUCCESS;
羽飞's avatar
羽飞 已提交
1845 1846
      }

羽飞's avatar
羽飞 已提交
1847 1848
      tree_handler_.disk_buffer_pool_->unpin_page(right_frame_);
      rc = tree_handler_.disk_buffer_pool_->get_this_page(prev_page_num, &right_frame_);
羽飞's avatar
羽飞 已提交
1849
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1850 1851
        LOG_WARN("failed to fetch prev page num. page num=%d, rc=%d:%s", prev_page_num, rc, strrc(rc));
        return rc;
羽飞's avatar
羽飞 已提交
1852 1853
      }

羽飞's avatar
羽飞 已提交
1854
      LeafIndexNodeHandler tmp_node(tree_handler_.file_header_, right_frame_);
羽飞's avatar
羽飞 已提交
1855 1856 1857 1858 1859 1860 1861 1862
      right_index = tmp_node.size() - 1;
    }
    end_index_ = right_index;
  }

  // 判断是否左边界比右边界要靠后
  // 两个边界最多会多一页
  // 查找不存在的元素,或者不存在的范围数据时,可能会存在这个问题
羽飞's avatar
羽飞 已提交
1863
  if (left_frame_->page_num() == right_frame_->page_num() &&
羽飞's avatar
羽飞 已提交
1864 1865 1866
      iter_index_ > end_index_) {
    end_index_ = -1;
  } else {
羽飞's avatar
羽飞 已提交
1867 1868
    LeafIndexNodeHandler left_node(tree_handler_.file_header_, left_frame_);
    LeafIndexNodeHandler right_node(tree_handler_.file_header_, right_frame_);
羽飞's avatar
羽飞 已提交
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    if (left_node.prev_page() == right_node.page_num()) {
      end_index_ = -1;
    }
  }
  return RC::SUCCESS;
}

RC BplusTreeScanner::next_entry(RID *rid)
{
  if (-1 == end_index_) {
    return RC::RECORD_EOF;
  }

羽飞's avatar
羽飞 已提交
1882
  LeafIndexNodeHandler node(tree_handler_.file_header_, left_frame_);
羽飞's avatar
羽飞 已提交
1883 1884
  memcpy(rid, node.value_at(iter_index_), sizeof(*rid));

羽飞's avatar
羽飞 已提交
1885
  if (left_frame_->page_num() == right_frame_->page_num() &&
羽飞's avatar
羽飞 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
      iter_index_ == end_index_) {
    end_index_ = -1;
    return RC::SUCCESS;
  }

  if (iter_index_ < node.size() - 1) {
    ++iter_index_;
    return RC::SUCCESS;
  }

  RC rc = RC::SUCCESS;
羽飞's avatar
羽飞 已提交
1897
  if (left_frame_->page_num() != right_frame_->page_num()) {
羽飞's avatar
羽飞 已提交
1898
    PageNum page_num = node.next_page();
羽飞's avatar
羽飞 已提交
1899
    tree_handler_.disk_buffer_pool_->unpin_page(left_frame_);
羽飞's avatar
羽飞 已提交
1900
    if (page_num == BP_INVALID_PAGE_NUM) {
羽飞's avatar
羽飞 已提交
1901
      left_frame_ = nullptr;
羽飞's avatar
羽飞 已提交
1902 1903 1904
      LOG_WARN("got invalid next page. page num=%d", page_num);
      rc = RC::INTERNAL;
    } else {
羽飞's avatar
羽飞 已提交
1905
      rc = tree_handler_.disk_buffer_pool_->get_this_page(page_num, &left_frame_);
羽飞's avatar
羽飞 已提交
1906
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
1907
	      left_frame_ = nullptr;
羽飞's avatar
羽飞 已提交
1908 1909 1910 1911 1912 1913 1914 1915
        LOG_WARN("failed to fetch next page. page num=%d, rc=%d:%s", page_num, rc, strrc(rc));
        return rc;
      }

      iter_index_ = 0;
    }
  } else if (end_index_ != -1) {
    LOG_WARN("should have more pages but not. left page=%d, right page=%d",
羽飞's avatar
羽飞 已提交
1916
	     left_frame_->page_num(), right_frame_->page_num());
羽飞's avatar
羽飞 已提交
1917 1918 1919 1920 1921 1922 1923
    rc = RC::INTERNAL;
  }
  return rc;
}

RC BplusTreeScanner::close()
{
羽飞's avatar
羽飞 已提交
1924 1925
  if (left_frame_ != nullptr) {
    tree_handler_.disk_buffer_pool_->unpin_page(left_frame_);
羽飞's avatar
羽飞 已提交
1926
    left_frame_ = nullptr;
羽飞's avatar
羽飞 已提交
1927
  }
羽飞's avatar
羽飞 已提交
1928 1929
  if (right_frame_ != nullptr) {
    tree_handler_.disk_buffer_pool_->unpin_page(right_frame_);
羽飞's avatar
羽飞 已提交
1930
    right_frame_ = nullptr;
羽飞's avatar
羽飞 已提交
1931 1932 1933 1934 1935 1936
  }
  end_index_ = -1;
  inited_ = false;
  LOG_INFO("bplus tree scanner closed");
  return RC::SUCCESS;
}
羽飞's avatar
羽飞 已提交
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

RC BplusTreeScanner::fix_user_key(const char *user_key, int key_len, bool want_greater,
			      char **fixed_key, bool *should_inclusive)
{
  if (nullptr == fixed_key || nullptr == should_inclusive) {
    return RC::INVALID_ARGUMENT;
  }

  // 这里很粗暴,变长字段才需要做调整,其它默认都不需要做调整
  assert(tree_handler_.file_header_.attr_type == CHARS);
  assert(strlen(user_key) >= static_cast<size_t>(key_len));
  
  *should_inclusive = false;
  
  int32_t attr_length = tree_handler_.file_header_.attr_length;
  char *key_buf = new (std::nothrow)char [attr_length];
  if (nullptr == key_buf) {
    return RC::NOMEM;
  }

  if (key_len <= attr_length) {
    memcpy(key_buf, user_key, key_len);
    memset(key_buf + key_len, 0, attr_length - key_len);

    *fixed_key = key_buf;
    return RC::SUCCESS;
  }

  // key_len > attr_length
  memcpy(key_buf, user_key, attr_length);

  char c = user_key[attr_length];
  if (c == 0) {
    *fixed_key = key_buf;
    return RC::SUCCESS;
  }

  // 扫描 >=/> user_key 的数据
  // 示例:>=/> ABCD1 的数据,attr_length=4,
  //      等价于扫描 >= ABCE 的数据
  // 如果是扫描 <=/< user_key的数据
  // 示例:<=/< ABCD1  <==> <= ABCD  (attr_length=4)
  *should_inclusive = true;
  if (want_greater) {
    key_buf[attr_length - 1]++;
  }
  
  *fixed_key = key_buf;
  return RC::SUCCESS;
}