optimizing

This commit is contained in:
Kacper Donat 2018-12-14 22:32:02 +01:00
parent 22548bbeeb
commit bafb629b6a
3 changed files with 48 additions and 0 deletions

38
index.c
View File

@ -672,3 +672,41 @@ void btree_flush(btree_t* tree)
file_flush(tree->file);
file_flush(tree->main->file);
}
void _btree_optimize_page(btree_t* tree, tape_t* tmp, page_t page)
{
if (!page) return;
btree_node_t node;
btree_entry_t *entry;
record_t record;
_btree_load_node(&node, tree, page);
for (int i = 0; i < node.header.entries; i++) {
entry = btree_get_entry(&node, i);
_btree_optimize_page(tree, tmp, entry->left);
tape_read(tree->main, entry->location, &record, sizeof(record_t));
entry->location = tape_append(tmp, &record, sizeof(record_t));
}
_btree_write_node(&node, tree, node.page);
_btree_optimize_page(tree, tmp, entry->right);
}
void btree_optimize(btree_t *tree)
{
char tmp[PATH_MAX + 4], old[PATH_MAX];
strcpy(old, tree->main->file->filename);
sprintf(tmp, "%s.tmp", old);
tape_t *temp = tape_open(tmp, "wb+");
_btree_optimize_page(tree, temp, tree->header.root);
tape_close(temp);
tape_close(tree->main);
remove(old);
rename(tmp, old);
tree->main = tape_open(old, "rb+");
}

View File

@ -70,6 +70,8 @@ typedef struct {
int btree_init(btree_t *tree, char* filename, size_t d);
int btree_open(btree_t *tree, char* filename);
void btree_optimize(btree_t *tree);
page_t btree_insert(btree_t *tree, record_t record);
page_t btree_remove(btree_t *tree, record_key_t key);
bool btree_update(btree_t *tree, record_key_t key, record_t record);

View File

@ -68,6 +68,7 @@ result_t update_command(const char* command, char* args);
result_t verbosity_command(const char* command, char* args);
result_t iostat_command(const char* command, char* args);
result_t flush_command(const char* command, char* args);
result_t optimize_command(const char* command, char* args);
static command_t commands[] = {
{ "help", "Prints out help", help_command },
@ -83,6 +84,7 @@ static command_t commands[] = {
{ "iostat", "Prints IO counts", iostat_command },
{ "flush", "Fluhshes index into disk", flush_command },
{ "verbosity", "Changes the verbosity", verbosity_command },
{ "optimize", "Optimizes the index", optimize_command },
};
result_t exit_command(const char* command, char* args)
@ -102,6 +104,12 @@ result_t flush_command(const char* command, char* args)
return RESULT_OK;
}
result_t optimize_command(const char* command, char* args)
{
btree_optimize(&tree);
return RESULT_OK;
}
result_t verbosity_command(const char* command, char* args)
{
verbosity_t v;