4 BTree::BTree (const std::string &name, unsigned int block_size, int kt, bool create_new_file)
10 fp = fopen (name.c_str(), "wb+");
12 /* TODO : mandar una exception ? */
16 /* Nombre de archivo */
19 /* Inicializo el header */
20 header.block_size = block_size;
23 /* Creo el primer bloque vacio */
24 node = new uchar[block_size];
25 ReadNodoHeader (node, &nh);
27 nh.free_space = block_size - sizeof (BTreeNodeHeader);
29 WriteNodoHeader (node, &nh);
40 void BTree::WriteFileHeader ()
42 fseek (fp, 0L, SEEK_SET);
43 fwrite (&header, 1, sizeof (BTreeFileHeader), fp);
46 void BTree::WriteBlock (uchar *block, uint num)
49 fseek (fp, num*header.block_size, SEEK_SET);
50 fwrite (block, 1, header.block_size, fp);
53 void BTree::AddKey (const Clave &k)
56 Clave *kout = AddKeyR (k.Clone (), 0, left, right);
60 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
61 * que esta usando el hijo izquierdo a un nuevo nodo */
62 std::list<BTreeData *> node_keys;
63 BTreeNodeHeader node_header;
64 uchar *node = ReadBlock (left);
65 ReadNodoHeader (node, &node_header);
66 node_keys = ReadKeys (node, node_header);
67 level = node_header.level + 1;
69 uchar *new_node = NewBlock (left);
70 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
72 WriteKeys (node, node_header, node_keys);
73 WriteNodoHeader (node, &node_header);
74 WriteBlock (node, left);
75 DeleteKeys (node_keys);
78 /* Leo y actualizo la Raiz */
80 ReadNodoHeader (node, &node_header);
81 node_keys = std::list<BTreeData *>();
83 node_keys.push_back (new BTreeChildData (left));
84 node_keys.push_back (new BTreeData (kout, right));
86 node_header.level = level;
87 node_header.item_count = 1;
89 WriteKeys (node, node_header, node_keys);
90 WriteNodoHeader (node, &node_header);
93 DeleteKeys (node_keys);
98 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
100 uchar *node = ReadBlock (node_num);
101 BTreeNodeHeader node_header;
102 ReadNodoHeader (node, &node_header);
105 if (node_header.level == 0)
106 return AddKeyLeafR (k, node_num, left_child, right_child);
108 return AddKeyOtherR (k, node_num, left_child, right_child);
111 Clave* BTree::AddKeyLeafR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
114 std::list<BTreeData *> node_keys;
116 BTreeData *data = new BTreeLeafData (k->Clone ());
118 /* Leo el nodo raiz para empezar a agregar */
119 uchar *node = ReadBlock (node_num);
120 BTreeNodeHeader node_header;
121 ReadNodoHeader (node, &node_header);
123 if (node_header.free_space > data->Size ()) {
125 node_keys = ReadKeys (node, node_header);
126 std::list<BTreeData *>::iterator it = node_keys.begin ();
128 while (it != node_keys.end ()) {
130 if ((*data) < (*datait))
131 /* Me pase, lo agrego aca! */
135 node_keys.insert (it, data);
136 WriteKeys (node, node_header, node_keys);
137 WriteNodoHeader (node, &node_header);
138 WriteBlock (node, node_num);
139 DeleteKeys (node_keys);
142 PrintNode (node_num);
144 /* Split : Creo e inicializo el nuevo nodo */
145 std::list<BTreeData *> new_node_keys;
146 std::list<BTreeData *> old_node_keys;
147 BTreeNodeHeader new_node_header;
149 uchar *new_node = NewBlock (new_node_num);
150 ReadNodoHeader (new_node, &new_node_header);
151 new_node_header.level = node_header.level;
153 node_keys = ReadKeys (node, node_header);
154 new_node_keys = ReadKeys (new_node, new_node_header);
156 /* Agrego la clave en la lista que ya tengo de manera ordenada */
157 std::list<BTreeData *>::iterator it = node_keys.begin ();
158 std::list<BTreeData *>::iterator previt = node_keys.begin ();
160 while (it != node_keys.end ()) {
163 if ((*data) < (*datait))
164 /* Me pase, lo agrego aca! */
169 if (it != node_keys.end ())
170 node_keys.insert (it, data);
172 node_keys.push_back (data);
174 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
175 * y subir la clave del medio */
176 node_header.item_count = 0;
177 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
180 it = node_keys.begin ();
181 while (it != node_keys.end ()) {
184 total_size += datait->Size ();
186 /* Hack : Si me quedo con todas las claves, en el caso de ser
187 * del mismo tama#o se desbalancea. Hay que ver que efecto
188 * puede tener en el caso de claves de long. variable
190 if (it == node_keys.end ())
191 total_size -= datait->Size ();
194 it = node_keys.begin ();
196 while (used < total_size/2) {
197 BTreeData *d = (*it);
198 old_node_keys.push_back (d);
202 kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
204 while (it != node_keys.end ()) {
205 BTreeData *d = (*it);
206 new_node_keys.push_back (d);
211 WriteKeys (node, node_header, old_node_keys);
212 WriteNodoHeader (node, &node_header);
213 WriteBlock (node, node_num);
214 WriteKeys (new_node, new_node_header, new_node_keys);
215 WriteNodoHeader (new_node, &new_node_header);
216 WriteBlock (new_node, new_node_num);
217 DeleteKeys (old_node_keys);
218 DeleteKeys (new_node_keys);
220 PrintNode (node_num);
221 PrintNode (new_node_num);
224 left_child = node_num;
225 right_child = new_node_num;
233 Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
236 std::list<BTreeData *> node_keys;
238 BTreeData *data = new BTreeLeafData (k->Clone ());
240 /* Leo el nodo raiz para empezar a agregar */
241 uchar *node = ReadBlock (node_num);
242 BTreeNodeHeader node_header;
243 ReadNodoHeader (node, &node_header);
245 node_keys = ReadKeys (node, node_header);
247 std::list<BTreeData *>::iterator it = node_keys.begin ();
248 std::list<BTreeData *>::iterator posterior;
249 std::list<BTreeData *>::iterator ultima;
251 /* Se supone que la primera es un hijo :) */
252 BTreeData *lchild = (*it++);
255 while (it != node_keys.end ()) {
256 if ((*data) < (*(*it)))
262 if (it == posterior) {
263 k = AddKeyR (k, lchild->getChild (), left_child, right_child);
265 k = AddKeyR (k, (*ultima)->getChild (), left_child, right_child);
267 DeleteKeys (node_keys);
270 if (data) delete data;
276 data = new BTreeData (k->Clone (), right_child);
278 if (node_header.free_space > data->Size ()) {
280 node_keys = ReadKeys (node, node_header);
281 std::list<BTreeData *>::iterator it = node_keys.begin ();
283 while (it != node_keys.end ()) {
285 if ((*data) < (*datait))
286 /* Me pase, lo agrego aca! */
290 node_keys.insert (it, data);
291 WriteKeys (node, node_header, node_keys);
292 WriteNodoHeader (node, &node_header);
293 WriteBlock (node, node_num);
294 DeleteKeys (node_keys);
297 PrintNode (node_num);
299 /* Split : Creo e inicializo el nuevo nodo */
300 std::list<BTreeData *> new_node_keys;
301 std::list<BTreeData *> old_node_keys;
302 BTreeNodeHeader new_node_header;
304 uchar *new_node = NewBlock (new_node_num);
305 ReadNodoHeader (new_node, &new_node_header);
306 new_node_header.level = node_header.level;
308 node_keys = ReadKeys (node, node_header);
309 new_node_keys = ReadKeys (new_node, new_node_header);
311 /* Agrego la clave en la lista que ya tengo de manera ordenada */
312 std::list<BTreeData *>::iterator it = node_keys.begin ();
313 std::list<BTreeData *>::iterator previt = node_keys.begin ();
317 while (it != node_keys.end ()) {
320 if ((*data) < (*datait))
321 /* Me pase, lo agrego aca! */
326 if (it != node_keys.end ())
327 node_keys.insert (it, data);
329 node_keys.push_back (data);
331 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
332 * y subir la clave del medio */
333 node_header.item_count = 0;
334 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
337 it = node_keys.begin ();
338 while (it != node_keys.end ()) {
341 total_size += datait->Size ();
343 /* Hack : Si me quedo con todas las claves, en el caso de ser
344 * del mismo tama#o se desbalancea. Hay que ver que efecto
345 * puede tener en el caso de claves de long. variable
347 if (it == node_keys.end ())
348 total_size -= datait->Size ();
351 it = node_keys.begin ();
353 while (used < total_size/2) {
354 BTreeData *d = (*it);
355 old_node_keys.push_back (d);
359 kout = (*it)->getClave (); // Esta se retorna al "padre" para que se la agregue
361 new_node_keys.push_back ( new BTreeChildData ((*it)->getChild ()));
363 while (it != node_keys.end ()) {
364 BTreeData *d = (*it);
365 new_node_keys.push_back (d);
370 WriteKeys (node, node_header, old_node_keys);
371 WriteNodoHeader (node, &node_header);
372 WriteBlock (node, node_num);
373 WriteKeys (new_node, new_node_header, new_node_keys);
374 WriteNodoHeader (new_node, &new_node_header);
375 WriteBlock (new_node, new_node_num);
376 DeleteKeys (old_node_keys);
377 DeleteKeys (new_node_keys);
379 PrintNode (node_num);
380 PrintNode (new_node_num);
383 left_child = node_num;
384 right_child = new_node_num;
392 void BTree::DelKey (const Clave &k)
394 DelKeyR (new BTreeLeafData (k.Clone ()), 0, 0);
397 void BTree::DelKeyR (BTreeData *k, uint node_num, uint padre)
399 std::list<BTreeData *> node_keys;
400 BTreeNodeHeader node_header;
403 node = ReadBlock (node_num);
404 ReadNodoHeader (node, &node_header);
405 node_keys = ReadKeys (node, node_header);
407 std::list<BTreeData *>::iterator it = node_keys.begin ();
408 std::list<BTreeData *>::iterator ultima;
409 std::list<BTreeData *>::iterator posterior;
412 if (node_header.level != 0) {
417 while (it != node_keys.end ()) {
418 if ((*k) == (*(*it))) {
419 /* La encontre!, retorno */
420 if (node_header.level == 0) {
421 DelKeyFromLeaf (k->getClave (), node_num, padre);
432 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
433 * decir que no lo encontre
435 if (node_header.level == 0) {
436 std::cout << "Clave no encontrada\n";
440 /* TODO: Aca faltaria liberar memoria */
441 if (it == posterior) {
442 DelKeyR (k, lchild->getChild (), node_num);
444 DelKeyR (k, (*ultima)->getChild (), node_num);
448 void BTree::DelKeyFromLeaf (Clave *k, uint node_num, uint padre)
452 BTreeNodeHeader node_header;
453 std::list<BTreeData *> node_keys;
455 node = ReadBlock (node_num);
456 ReadNodoHeader (node, &node_header);
457 node_keys = ReadKeys (node, node_header);
459 data = new BTreeLeafData (k);
461 std::list<BTreeData *>::iterator it;
462 it = node_keys.begin ();
463 while (it != node_keys.end ()) {
464 if ((*data) == (*(*it))) {
465 node_keys.erase (it);
473 /* TODO : que pasa cuando el nodo se queda vacio o con
476 WriteKeys (node, node_header, node_keys);
477 WriteNodoHeader (node, &node_header);
478 WriteBlock (node, node_num);
480 /* Veo si se cumple la condición de minimalidad */
481 if ((node_header.free_space <= (header.block_size/2)) && (node_num != 0)) {
482 /* Oops! Debo pedir prestada clave */
486 FindB (node_num, padre, hi, hd);
488 if ((pedida = GetKey (hi, 1)) != NULL) {
489 std::string s = *pedida;
490 std::cout << "Clave Pedida : " << s << std::endl;
492 node_keys.insert (node_keys.begin (), new BTreeLeafData (pedida));
493 } else if ((pedida = GetKey (hd, 0)) != NULL) {
494 std::string s = *pedida;
495 std::cout << "Clave Pedida : " << s << std::endl;
497 node_keys.push_back (new BTreeLeafData (pedida));
499 std::cout << "NADIE ME PUEDE PRESTAR, FUNDIR NODOS\n";
503 WriteKeys (node, node_header, node_keys);
504 WriteNodoHeader (node, &node_header);
505 WriteBlock (node, node_num);
508 DeleteKeys (node_keys);
510 std::cout << "Borrado de una hoja listo\n";
513 Clave *BTree::GetKey (uint node_num, char maxmin)
515 if (node_num == 0) return NULL;
518 BTreeNodeHeader node_header;
519 std::list<BTreeData *> node_keys;
521 node = ReadBlock (node_num);
522 ReadNodoHeader (node, &node_header);
523 node_keys = ReadKeys (node, node_header);
525 std::list<BTreeData *>::iterator it = node_keys.begin ();
527 if (node_header.level != 0) it++;
531 k = (*it)->getClave ()->Clone ();
532 node_keys.erase (it);
534 it = node_keys.end ();
536 k = (*it)->getClave ()->Clone ();
537 node_keys.erase (it);
540 WriteKeys (node, node_header, node_keys);
541 WriteNodoHeader (node, &node_header);
542 WriteBlock (node, node_num);
543 DeleteKeys (node_keys);
548 void BTree::FindB (uint node_num, uint padre, uint &left, uint &right)
551 BTreeNodeHeader node_header;
552 std::list<BTreeData *> node_keys;
554 node = ReadBlock (padre);
555 ReadNodoHeader (node, &node_header);
556 node_keys = ReadKeys (node, node_header);
558 std::list<BTreeData *>::iterator it = node_keys.begin ();
559 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
560 std::list<BTreeData *>::iterator siguiente;
562 BTreeData *lchild = (*it++);
564 if (lchild->getChild () == node_num) {
565 /* Solo tengo hermano derecho */
566 std::cout << "Hermano Izquierdo : NO TENGO" << std::endl;
568 std::cout << "Hermano Derecho : " << (*it)->getChild () << std::endl;
569 right = (*it)->getChild ();
573 while (it != node_keys.end ()) {
574 if ((*it)->getChild () == node_num)
581 std::cout << "Hermano Izquierdo : " << (*anterior)->getChild () << std::endl;
582 left = (*anterior)->getChild ();
583 if (siguiente != node_keys.end ()) {
584 right = (*siguiente)->getChild ();
585 std::cout << "Hermano Derecho : " << (*siguiente)->getChild () << std::endl;
588 std::cout << "Hermano Derecho : NO TENGO" << std::endl;
592 void BTree::DelKeyFromOther (const Clave &k, BTreeFindResult *r)
596 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
598 memcpy (header, node, sizeof (BTreeNodeHeader));
601 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
603 memcpy (node, header, sizeof (BTreeNodeHeader));
606 uchar *BTree::ReadBlock (uint num)
608 /* Como el bloque 0 se usa para el header, el Nodo "num"
609 * está en el bloque "num+1"
613 uchar *out = new uchar[header.block_size];
615 fseek (fp, num*header.block_size, SEEK_SET);
616 fread (out, 1, header.block_size, fp);
621 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
623 std::list<BTreeData *> keys;
624 node += sizeof (BTreeNodeHeader);
625 uint count = node_header.item_count;
627 if (node_header.item_count == 0) return keys;
629 if (node_header.level != 0) {
630 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
631 BTreeChildData *d = new BTreeChildData (node);
637 for (uint i=0; i<count; i++) {
638 /* TODO : El tipo de clave deberia ser usado
639 * dependiendo de algun dato en el header del
642 /* TODO : Detectar si estoy en una hoja */
644 if (node_header.level == 0) {
645 data = new BTreeLeafData (node, key_type);
647 data = new BTreeData (node, key_type);
649 node += data->Size ();
650 keys.push_back (data);
656 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
658 std::list<BTreeData *>::iterator it = keys.begin ();
660 node += sizeof (BTreeNodeHeader);
662 node_header.item_count = 0;
663 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
665 while (it != keys.end ()) {
666 BTreeData *d = (*it);
667 uchar *n = d->ToArray ();
668 memcpy (node, n, d->Size ());
671 node_header.free_space -= d->Size ();
672 node_header.item_count++;
676 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
679 void BTree::PrintNode (uint num)
681 uchar *node = ReadBlock (num);
682 BTreeNodeHeader node_header;
683 ReadNodoHeader (node, &node_header);
685 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
686 std::list<BTreeData *>::iterator it = node_keys.begin ();
688 std::cout << "Nodo : " << num << std::endl;
689 std::cout << "Level : " << node_header.level << std::endl;
690 std::cout << "Items : " << node_header.item_count << std::endl;
691 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
692 while (it != node_keys.end ()) {
693 std::string s = *(*it);
694 std::cout << s << " ";
697 std::cout << std::endl;
700 DeleteKeys (node_keys);
703 uchar *BTree::NewBlock (uint &num)
709 fseek (fp, 0, SEEK_END);
710 filelen = ftell (fp);
712 num = filelen/header.block_size - 1;
714 node = new uchar[header.block_size];
715 ReadNodoHeader (node, &nh);
717 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
719 WriteNodoHeader (node, &nh);
720 WriteBlock (node, num);
725 BTreeFindResult *BTree::FindKey (const Clave &k)
727 return FindKeyR (&k, 0);
730 BTreeFindResult *BTree::FindKeyR (const Clave *k, uint node_num)
732 std::list<BTreeData *> node_keys;
733 BTreeNodeHeader node_header;
735 /* Leo el nodo raiz para empezar a agregar */
736 uchar *node = ReadBlock (node_num);
737 ReadNodoHeader (node, &node_header);
738 node_keys = ReadKeys (node, node_header);
740 std::list<BTreeData *>::iterator it = node_keys.begin ();
741 std::list<BTreeData *>::iterator posterior;
742 std::list<BTreeData *>::iterator ultima;
744 /* Se supone que la primera es un hijo :) */
746 if (node_header.level != 0) {
752 if (node_header.level == 0)
753 data = new BTreeLeafData ((Clave *)k);
755 data = new BTreeData ((Clave *)k, 0);
757 while (it != node_keys.end ()) {
758 if ((*data) == (*(*it))) {
759 /* La encontre!, retorno */
761 DeleteKeys (node_keys);
762 BTreeFindResult *result = new BTreeFindResult ();
763 result->node = node_num;
764 result->header = node_header;
768 if ((*data) < (*(*it)))
774 /* TODO: Aca faltaria liberar memoria */
776 return FindKeyR (k, lchild->getChild ());
778 return FindKeyR (k, (*ultima)->getChild ());
781 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
783 std::list<BTreeData *>::iterator it = keys.begin ();
785 while (it != keys.end ()) {
786 BTreeData *d = (*it);