int RM_FileHandle::DeleteRec(RID &rid) { //检测错误 int index; Bytes head = (Bytes)bpm->getPage(fileid, rid.GetPageid(), index); Bits* slots = new Bits(head, pernum); if (!slots->bit_get(rid.GetSlotid())) { //cout << "[RM_FileHandle-Del]Warning: RID doesn't exist" << endl; return 1; } //删除对应记录以及更新空项记录和未满数据页页码记录 int first_index; BufType first_head = bpm->getPage(fileid, 0, first_index); //打开第一页 int empty_page = *(int*)(first_head + EMPTY_PAGE_OFFSET_4BYTE); //获取未满的最前面数据页页码 int empty_rid_offset = EMPTY_RID_OFFSET_BYTE; //获取下一可插入项的偏移 RID* current_empty_rid = (RID*)(head + empty_rid_offset); //获取下一可插入项 int next_page_offset = NEXT_EMPTY_PAGE_BYTE; //获取下一个含空项页页码的偏移 int next_page = *(int*)(head + next_page_offset); //获取下一个含空项页页码 slots->bit_setzero(rid.GetSlotid()); //删除该记录 bpm->markDirty(index); //将该页标记为脏页 if (current_empty_rid->GetSlotid() == -1) { //若之前为满页 current_empty_rid->slotid = rid.GetSlotid(); //将下一可插入记录项置成当前删除记录 *(int*)(first_head + EMPTY_PAGE_OFFSET_4BYTE) = rid.GetPageid();//则将第一页的值的页码更改为本页码 *(int*)(head + next_page_offset) = empty_page; //本页码的下一空项页改为第一页原来存的页码值 bpm->markDirty(first_index); } else { if (current_empty_rid->slotid > rid.GetSlotid()) { //更新下一可插入项的偏移槽的值 current_empty_rid->slotid = rid.GetSlotid(); } } return 0; }
int RM_FileHandle::GetRec(RID &rid, RM_Record &rec) { int index; Bytes head = (Bytes)bpm->getPage(fileid, rid.GetPageid(), index); Bits* slots = new Bits(head, pernum); //获取slot数组,先判断获取的记录是否为空 if (!slots->bit_get(rid.GetSlotid())) { // cout << "[RM_FileHandle]Invalid Record:Empty" << endl; return 1; } int offset = PAGE_HEAD_BYTE; offset = offset + rid.GetSlotid() * recordsize; char* get_data = new char[recordsize]; memcpy(get_data,head + offset,recordsize); RM_Record *newR = new RM_Record(get_data, recordsize); rec = *newR; return 0; }
int RM_FileHandle::UpdateRec(RID &rid, RM_Record &rec) { int index; Bytes head = (Bytes)bpm->getPage(fileid, rid.GetPageid(), index); Bits* slots = new Bits(head, pernum); if (!slots->bit_get(rid.GetSlotid())) { //cout << "[RM_FileHandle-Update]Warning: RID doesn't exist,Maybe need Insert" << endl; return 1; } int offset = PAGE_HEAD_BYTE; offset = offset + recordsize * rid.GetSlotid(); Bytes rlocation = (Bytes)head; rlocation = rlocation + offset; memcpy(rlocation, rec.GetRdata(), rec.GetSize()); slots->bit_setone(rid.GetSlotid()); bpm->markDirty(index); return 0; }