4 BTree::BTree (const std::string &name, unsigned int block_size, int tt, int kt, bool create_new_file)
9 fp = fopen (name.c_str(), "wb+");
11 /* TODO : mandar una exception ? */
15 /* Nombre de archivo */
18 /* Inicializo el header */
19 header.block_size = block_size;
20 header.tree_type = tt;
24 /* Creo el primer bloque vacio */
25 node = new uchar[block_size];
26 ReadNodoHeader (node, &nh);
28 nh.free_space = block_size - sizeof (BTreeNodeHeader);
30 WriteNodoHeader (node, &nh);
36 BTree::BTree (const std::string &name)
38 /* Leo los bloques recuperables */
39 std::string del = filename + ".del";
41 fp = fopen (del.c_str (), "wb");
45 while (fread (&i, 1, sizeof (uint), fp)) {
46 deleted_nodes.push_back (i);
52 fp = fopen (name.c_str(), "rb+");
54 /* TODO : mandar una exception ? */
64 std::string del = filename + ".del";
66 fp = fopen (del.c_str (), "wb");
67 std::list<uint>::iterator it = deleted_nodes.begin ();
69 while (it != deleted_nodes.end ()) {
71 fwrite (&i, 1, sizeof (uint), fp);
78 void BTree::ReadFileHeader ()
80 fseek (fp, 0L, SEEK_SET);
81 fread (&header, 1, sizeof (BTreeFileHeader), fp);
84 void BTree::WriteFileHeader ()
86 fseek (fp, 0L, SEEK_SET);
87 fwrite (&header, 1, sizeof (BTreeFileHeader), fp);
90 void BTree::WriteBlock (uchar *block, uint num)
93 fseek (fp, num*header.block_size, SEEK_SET);
94 fwrite (block, 1, header.block_size, fp);
97 void BTree::AddKey (const Clave &k)
103 /* TODO : Hacer un contador con recuperacion */
104 in->SetBlockData (0);
107 kout = AddKeyR (in->Clone (), 0, left, right);
108 } catch (Exception *e) {
115 unsigned short level;
116 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
117 * que esta usando el hijo izquierdo a un nuevo nodo */
118 std::list<BTreeData *> node_keys;
119 BTreeNodeHeader node_header;
120 uchar *node = ReadBlock (left);
121 ReadNodoHeader (node, &node_header);
122 node_keys = ReadKeys (node, node_header);
123 level = node_header.level + 1;
125 uchar *new_node = NewBlock (left);
126 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
128 WriteKeys (node, node_header, node_keys);
129 WriteNodoHeader (node, &node_header);
130 WriteBlock (node, left);
131 DeleteKeys (node_keys);
134 /* Leo y actualizo la Raiz */
135 node = ReadBlock (0);
136 ReadNodoHeader (node, &node_header);
137 node_keys = std::list<BTreeData *>();
139 node_keys.push_back (new BTreeChildData (left));
140 node_keys.push_back (new BTreeData (kout, right));
142 node_header.level = level;
143 node_header.item_count = 1;
145 WriteKeys (node, node_header, node_keys);
146 WriteNodoHeader (node, &node_header);
147 WriteBlock (node, 0);
149 DeleteKeys (node_keys);
154 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
156 uchar *node = ReadBlock (node_num);
157 BTreeNodeHeader node_header;
158 ReadNodoHeader (node, &node_header);
161 if (node_header.level == 0) {
163 return AddKeyLeafR (k, node_num, left_child, right_child);
164 } catch (Exception *e) {
170 return AddKeyOtherR (k, node_num, left_child, right_child);
171 } catch (Exception *e) {
176 Clave* BTree::AddKeyLeafR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
179 std::list<BTreeData *> node_keys;
181 BTreeData *data = new BTreeLeafData (k->Clone ());
183 /* Leo el nodo raiz para empezar a agregar */
184 uchar *node = ReadBlock (node_num);
185 BTreeNodeHeader node_header;
186 ReadNodoHeader (node, &node_header);
188 if (node_header.free_space > data->Size ()) {
190 node_keys = ReadKeys (node, node_header);
191 std::list<BTreeData *>::iterator it = node_keys.begin ();
193 while (it != node_keys.end ()) {
195 if (header.tree_type == TYPE_IDENTIFICACION) {
196 /* Verifico que la clave no existea ya en el arbol */
197 if ((*data) == (*datait)) {
198 throw new AddException ();
203 if ((*data) < (*datait))
204 /* Me pase, lo agrego aca! */
208 node_keys.insert (it, data);
209 WriteKeys (node, node_header, node_keys);
210 WriteNodoHeader (node, &node_header);
211 WriteBlock (node, node_num);
212 DeleteKeys (node_keys);
215 PrintNode (node_num);
217 /* Split : Creo e inicializo el nuevo nodo */
218 std::list<BTreeData *> new_node_keys;
219 std::list<BTreeData *> old_node_keys;
220 BTreeNodeHeader new_node_header;
222 uchar *new_node = NewBlock (new_node_num);
223 ReadNodoHeader (new_node, &new_node_header);
224 new_node_header.level = node_header.level;
226 node_keys = ReadKeys (node, node_header);
227 new_node_keys = ReadKeys (new_node, new_node_header);
229 /* Agrego la clave en la lista que ya tengo de manera ordenada */
230 std::list<BTreeData *>::iterator it = node_keys.begin ();
231 std::list<BTreeData *>::iterator previt = node_keys.begin ();
233 while (it != node_keys.end ()) {
236 if (header.tree_type == TYPE_IDENTIFICACION) {
237 /* Verifico que la clave no existea ya en el arbol */
238 if ((*data) == (*datait)) {
239 throw new AddException ();
243 if ((*data) < (*datait))
244 /* Me pase, lo agrego aca! */
249 if (it != node_keys.end ())
250 node_keys.insert (it, data);
252 node_keys.push_back (data);
254 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
255 * y subir la clave del medio */
256 node_header.item_count = 0;
257 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
260 it = node_keys.begin ();
261 while (it != node_keys.end ()) {
264 total_size += datait->Size ();
266 /* Hack : Si me quedo con todas las claves, en el caso de ser
267 * del mismo tama#o se desbalancea. Hay que ver que efecto
268 * puede tener en el caso de claves de long. variable
270 if (it == node_keys.end ())
271 total_size -= datait->Size ();
274 it = node_keys.begin ();
276 while (used < total_size/2) {
277 BTreeData *d = (*it);
278 old_node_keys.push_back (d);
282 kout = (*it++)->GetKey (); // Esta se retorna al "padre" para que se la agregue
284 while (it != node_keys.end ()) {
285 BTreeData *d = (*it);
286 new_node_keys.push_back (d);
291 WriteKeys (node, node_header, old_node_keys);
292 WriteNodoHeader (node, &node_header);
293 WriteBlock (node, node_num);
294 WriteKeys (new_node, new_node_header, new_node_keys);
295 WriteNodoHeader (new_node, &new_node_header);
296 WriteBlock (new_node, new_node_num);
297 DeleteKeys (old_node_keys);
298 DeleteKeys (new_node_keys);
300 PrintNode (node_num);
301 PrintNode (new_node_num);
304 left_child = node_num;
305 right_child = new_node_num;
313 Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
316 std::list<BTreeData *> node_keys;
318 BTreeData *data = new BTreeLeafData (k->Clone ());
320 /* Leo el nodo raiz para empezar a agregar */
321 uchar *node = ReadBlock (node_num);
322 BTreeNodeHeader node_header;
323 ReadNodoHeader (node, &node_header);
325 node_keys = ReadKeys (node, node_header);
327 std::list<BTreeData *>::iterator it = node_keys.begin ();
328 std::list<BTreeData *>::iterator posterior;
329 std::list<BTreeData *>::iterator ultima;
331 /* Se supone que la primera es un hijo :) */
332 BTreeData *lchild = (*it++);
335 while (it != node_keys.end ()) {
336 if (header.tree_type == TYPE_IDENTIFICACION) {
337 /* Verifico que la clave no existea ya en el arbol */
338 if ((*data) == (*(*it))) {
339 throw new AddException ();
343 if ((*data) < (*(*it)))
349 if (it == posterior) {
350 k = AddKeyR (k, lchild->GetChild (), left_child, right_child);
352 k = AddKeyR (k, (*ultima)->GetChild (), left_child, right_child);
354 DeleteKeys (node_keys);
357 if (data) delete data;
363 data = new BTreeData (k->Clone (), right_child);
365 if (node_header.free_space > data->Size ()) {
367 node_keys = ReadKeys (node, node_header);
368 std::list<BTreeData *>::iterator it = node_keys.begin ();
370 while (it != node_keys.end ()) {
372 if (header.tree_type == TYPE_IDENTIFICACION) {
373 /* Verifico que la clave no existea ya en el arbol */
374 if ((*data) == (*datait)) {
375 throw new AddException ();
379 if ((*data) < (*datait))
380 /* Me pase, lo agrego aca! */
384 node_keys.insert (it, data);
385 WriteKeys (node, node_header, node_keys);
386 WriteNodoHeader (node, &node_header);
387 WriteBlock (node, node_num);
388 DeleteKeys (node_keys);
391 PrintNode (node_num);
393 /* Split : Creo e inicializo el nuevo nodo */
394 std::list<BTreeData *> new_node_keys;
395 std::list<BTreeData *> old_node_keys;
396 BTreeNodeHeader new_node_header;
398 uchar *new_node = NewBlock (new_node_num);
399 ReadNodoHeader (new_node, &new_node_header);
400 new_node_header.level = node_header.level;
402 node_keys = ReadKeys (node, node_header);
403 new_node_keys = ReadKeys (new_node, new_node_header);
405 /* Agrego la clave en la lista que ya tengo de manera ordenada */
406 std::list<BTreeData *>::iterator it = node_keys.begin ();
407 std::list<BTreeData *>::iterator previt = node_keys.begin ();
411 while (it != node_keys.end ()) {
414 if (header.tree_type == TYPE_IDENTIFICACION) {
415 /* Verifico que la clave no existea ya en el arbol */
416 if ((*data) == (*datait)) {
417 throw new AddException ();
421 if ((*data) < (*datait))
422 /* Me pase, lo agrego aca! */
427 if (it != node_keys.end ())
428 node_keys.insert (it, data);
430 node_keys.push_back (data);
432 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
433 * y subir la clave del medio */
434 node_header.item_count = 0;
435 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
438 it = node_keys.begin ();
439 while (it != node_keys.end ()) {
442 total_size += datait->Size ();
444 /* Hack : Si me quedo con todas las claves, en el caso de ser
445 * del mismo tama#o se desbalancea. Hay que ver que efecto
446 * puede tener en el caso de claves de long. variable
448 if (it == node_keys.end ())
449 total_size -= datait->Size ();
452 it = node_keys.begin ();
454 while (used < total_size/2) {
455 BTreeData *d = (*it);
456 old_node_keys.push_back (d);
460 kout = (*it)->GetKey (); // Esta se retorna al "padre" para que se la agregue
462 new_node_keys.push_back ( new BTreeChildData ((*it)->GetChild ()));
464 while (it != node_keys.end ()) {
465 BTreeData *d = (*it);
466 new_node_keys.push_back (d);
471 WriteKeys (node, node_header, old_node_keys);
472 WriteNodoHeader (node, &node_header);
473 WriteBlock (node, node_num);
474 WriteKeys (new_node, new_node_header, new_node_keys);
475 WriteNodoHeader (new_node, &new_node_header);
476 WriteBlock (new_node, new_node_num);
477 DeleteKeys (old_node_keys);
478 DeleteKeys (new_node_keys);
480 PrintNode (node_num);
481 PrintNode (new_node_num);
484 left_child = node_num;
485 right_child = new_node_num;
493 void BTree::DelKey (const Clave &k)
496 std::cout << "========= Borrando " << s << " =================\n";
497 BTreeData *b = new BTreeLeafData (k.Clone ());
502 void BTree::DelKeyR (BTreeData *k, uint node_num, uint padre)
504 std::list<BTreeData *> node_keys;
505 BTreeNodeHeader node_header;
508 node = ReadBlock (node_num);
509 ReadNodoHeader (node, &node_header);
510 node_keys = ReadKeys (node, node_header);
512 std::list<BTreeData *>::iterator it = node_keys.begin ();
513 std::list<BTreeData *>::iterator ultima;
514 std::list<BTreeData *>::iterator posterior;
517 if (node_header.level != 0) {
522 while (it != node_keys.end ()) {
523 if ((*k) == (*(*it))) {
524 /* La encontre!, retorno */
525 if (node_header.level == 0) {
526 DelKeyFromLeaf (k->GetKey (), node_num, padre);
529 if (it == posterior) {
530 left = lchild->GetChild ();
531 right = (*it)->GetChild ();
533 left = (*ultima)->GetChild ();
534 right = (*it)->GetChild ();
536 std::cout << "Eliminar de Nodo con hijos : " << left << " y " << right << std::endl;
537 DelKeyFromNode (k->GetKey (), node_num, padre, left, right);
539 DeleteKeys (node_keys);
550 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
551 * decir que no lo encontre
553 if (node_header.level == 0) {
554 std::cout << "*** Clave no encontrada ***\n";
558 /* TODO: Aca faltaria liberar memoria */
559 if (it == posterior) {
560 DelKeyR (k, lchild->GetChild (), node_num);
562 DelKeyR (k, (*ultima)->GetChild (), node_num);
566 void BTree::DelKeyFromLeaf (Clave *k, uint node_num, uint padre)
570 BTreeNodeHeader node_header;
571 std::list<BTreeData *> node_keys;
573 node = ReadBlock (node_num);
574 ReadNodoHeader (node, &node_header);
575 node_keys = ReadKeys (node, node_header);
577 data = new BTreeLeafData (k->Clone ());
579 std::list<BTreeData *>::iterator it;
580 it = node_keys.begin ();
581 while (it != node_keys.end ()) {
582 if ((*data) == (*(*it))) {
583 BTreeData *aborrar = (*it);
584 node_keys.erase (it);
593 WriteKeys (node, node_header, node_keys);
594 WriteNodoHeader (node, &node_header);
595 WriteBlock (node, node_num);
597 /* Veo si se cumple la condición de minimalidad */
598 uint min_free = (header.block_size-sizeof(BTreeNodeHeader))/2;
599 if ((node_header.free_space > min_free) && (node_num != 0)) {
600 /* Oops! Debo pedir prestada clave */
604 FindBrothers (node_num, padre, hi, hd);
606 if ((pedida = GetKey (hi, 1)) != NULL) {
607 std::string s = *pedida;
608 std::cout << "Clave Pedida : " << s << std::endl;
610 pedida = ReplaceKeyInFather (node_num, padre, pedida);
612 node_keys.insert (node_keys.begin (), new BTreeLeafData (pedida));
613 } else if ((pedida = GetKey (hd, 0)) != NULL) {
614 std::string s = *pedida;
615 std::cout << "Clave Pedida : " << s << std::endl;
617 pedida = ReplaceKeyInFather (node_num, padre, pedida);
619 node_keys.push_back (new BTreeLeafData (pedida));
621 std::cout << "NADIE ME PUEDE PRESTAR, FUNDIR NODOS\n";
625 std::cout << "Join con Hermano Izquierdo\n";
630 std::cout << "Join con Hermano Derecho\n";
636 JoinNodes (join1, join2, padre, tipoh);
638 DeleteKeys (node_keys);
643 WriteKeys (node, node_header, node_keys);
644 WriteNodoHeader (node, &node_header);
645 WriteBlock (node, node_num);
648 DeleteKeys (node_keys);
650 std::cout << "Borrado de una hoja listo\n";
653 void BTree::JoinNodes (uint node1, uint node2, uint padre, int tipohermano)
655 uchar *n1, *n2, *npadre;
656 BTreeNodeHeader nh1, nh2, nhp;
657 std::list<BTreeData *> nk1, nk2, nkpadre;
659 if (node1 == node2) {
660 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
663 if (node1 == padre) {
664 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
667 if (node2 == padre) {
668 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
677 n1 = ReadBlock (node1);
678 n2 = ReadBlock (node2);
679 npadre = ReadBlock (padre);
681 ReadNodoHeader (n1, &nh1);
682 ReadNodoHeader (n2, &nh2);
683 ReadNodoHeader (npadre, &nhp);
686 uint tmp = header.block_size - sizeof (BTreeNodeHeader);
687 uint l = tmp - nh1.free_space;
688 l += tmp - nh1.free_space;
691 std::cout << "Espacio ocupado despues de unir : " << l << " de " << tmp << std::endl;
693 nk1 = ReadKeys (n1, nh1);
694 nk2 = ReadKeys (n2, nh2);
695 nkpadre = ReadKeys (npadre, nhp);
697 /* Busco la clave del padre a juntar con los nodos */
698 std::list<BTreeData *>::iterator it = nkpadre.begin ();
699 std::list<BTreeData *>::iterator borrar_padre;
700 std::list<BTreeData *>::iterator sig;
701 std::list<BTreeData *>::iterator anterior = it;
704 BTreeData *lchild = (*it++);
706 if (lchild->GetChild () == node1) {
707 cpadre = (*it)->GetKey ();
710 while (it != nkpadre.end ()) {
711 if (tipohermano == 0) {
712 if ((*it)->GetChild () == node2)
715 if ((*it)->GetChild () == node1)
721 cpadre = (*it)->GetKey ();
724 if (it == nkpadre.end ()) {
725 std::cout << "PANIC : Me pase sin encontrar la clave!!\n";
731 std::list<BTreeData *> newkeys;
732 std::list<BTreeData *>::iterator i;
735 while (i != nk1.end ()) {
736 newkeys.push_back ( new BTreeLeafData ((*i)->GetKey ()->Clone ()));
739 //if (tipohermano == 0)
740 newkeys.push_back ( new BTreeLeafData (cpadre->Clone ()));
742 while (i != nk2.end ()) {
743 newkeys.push_back ( new BTreeLeafData ((*i)->GetKey ()->Clone ()));
747 std::cout << "Espacio ocupado por las nuevas claves : " << (newkeys.size()*4) << std::endl;
748 if ((newkeys.size()*4) > tmp) {
749 std::cout << "PANIC : El nodo fundido no entra !!!\n";
753 /* Para el padre, tener 2 items significa tener solo 1 clave, ya que
754 * el otro item es el LeftChild!
756 if ((padre == 0) && (nhp.item_count == 2)) {
757 /* Si junte 2 nodos, cuyo padre era la raiz, y esta tenia
758 * solo una clave, quiere decir que lo que me queda
759 * es de nuevo solo una raiz con todas las claves
762 WriteKeys (npadre, nhp, newkeys);
763 WriteNodoHeader (npadre, &nhp);
764 WriteBlock (npadre, padre);
766 deleted_nodes.push_back (node1);
767 deleted_nodes.push_back (node2);
769 WriteKeys (n1, nh1, newkeys);
770 WriteNodoHeader (n1, &nh1);
771 WriteBlock (n1, node1);
773 deleted_nodes.push_back (node2);
775 /* Actualizo punero al padre */
776 (*anterior)->SetChild (node1);
778 nkpadre.erase (borrar_padre);
779 WriteKeys (npadre, nhp, nkpadre);
780 WriteNodoHeader (npadre, &nhp);
781 WriteBlock (npadre, padre);
784 std::cout << " ----- Luego de Fundir -----\n";
787 std::cout << " ---------------------------\n";
791 DeleteKeys (nkpadre);
792 DeleteKeys (newkeys);
799 Clave *BTree::GetKey (uint node_num, char maxmin)
802 std::cout << "Nodo no me puede prestar ... es NULL\n";
807 BTreeNodeHeader node_header;
808 std::list<BTreeData *> node_keys;
810 node = ReadBlock (node_num);
811 ReadNodoHeader (node, &node_header);
812 node_keys = ReadKeys (node, node_header);
814 std::list<BTreeData *>::iterator it = node_keys.begin ();
816 if (node_header.level != 0) it++;
819 uint free = node_header.free_space; // + (*it)->Size ();
820 uint min_free = (header.block_size - sizeof (BTreeNodeHeader))/2;
821 if (free > min_free) {
822 std::cout << "No puedo prestar : Free = " << free << " Minimo = " << min_free << std::endl;
823 PrintNode (node_num);
824 WriteKeys (node, node_header, node_keys);
825 WriteNodoHeader (node, &node_header);
826 WriteBlock (node, node_num);
827 DeleteKeys (node_keys);
835 k = (*it)->GetKey ()->Clone ();
836 node_keys.erase (it);
838 it = node_keys.end ();
840 k = (*it)->GetKey ()->Clone ();
841 node_keys.erase (it);
844 WriteKeys (node, node_header, node_keys);
845 WriteNodoHeader (node, &node_header);
846 WriteBlock (node, node_num);
847 DeleteKeys (node_keys);
854 void BTree::FindBrothers (uint node_num, uint padre, uint &left, uint &right)
857 BTreeNodeHeader node_header;
858 std::list<BTreeData *> node_keys;
860 node = ReadBlock (padre);
861 ReadNodoHeader (node, &node_header);
862 node_keys = ReadKeys (node, node_header);
864 std::list<BTreeData *>::iterator it = node_keys.begin ();
865 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
866 std::list<BTreeData *>::iterator siguiente;
868 BTreeData *lchild = (*it++);
870 if (lchild->GetChild () == node_num) {
871 /* Solo tengo hermano derecho */
872 std::cout << "Hermano Izquierdo : NO TENGO" << std::endl;
874 std::cout << "Hermano Derecho : " << (*it)->GetChild () << std::endl;
875 right = (*it)->GetChild ();
879 while (it != node_keys.end ()) {
880 if ((*it)->GetChild () == node_num)
887 std::cout << "Hermano Izquierdo : " << (*anterior)->GetChild () << std::endl;
888 left = (*anterior)->GetChild ();
889 if (siguiente != node_keys.end ()) {
890 right = (*siguiente)->GetChild ();
891 std::cout << "Hermano Derecho : " << (*siguiente)->GetChild () << std::endl;
894 std::cout << "Hermano Derecho : NO TENGO" << std::endl;
898 Clave *BTree::ReplaceKeyInFather (uint node_num, uint padre, Clave *k)
901 BTreeNodeHeader node_header;
902 std::list<BTreeData *> node_keys;
904 node = ReadBlock (padre);
905 ReadNodoHeader (node, &node_header);
906 node_keys = ReadKeys (node, node_header);
908 std::list<BTreeData *>::iterator it = node_keys.begin ();
909 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
910 std::list<BTreeData *>::iterator siguiente;
912 BTreeData *lchild = (*it++);
914 if (lchild->GetChild () == node_num) {
915 Clave *ret = (*it)->GetKey ();
918 WriteKeys (node, node_header, node_keys);
919 WriteNodoHeader (node, &node_header);
920 WriteBlock (node, padre);
921 DeleteKeys (node_keys);
927 while (it != node_keys.end ()) {
928 if ((*it)->GetChild () == node_num)
934 Clave *ret = (*it)->GetKey ();
937 WriteKeys (node, node_header, node_keys);
938 WriteNodoHeader (node, &node_header);
939 WriteBlock (node, padre);
940 DeleteKeys (node_keys);
946 void BTree::DelKeyFromNode (Clave *k, uint node_num, uint padre, uint left, uint right)
950 BTreeNodeHeader node_header;
951 std::list<BTreeData *> node_keys;
953 node = ReadBlock (node_num);
954 ReadNodoHeader (node, &node_header);
955 node_keys = ReadKeys (node, node_header);
958 std::cout << "Busco para la derecha y luego todo a la izquierda\n";
960 BTreeNodeHeader node_hr;
961 std::list<BTreeData *> node_keyr;
963 /* Busco la clave inmediatamente superior en el arbol */
964 padre_hijo = node_num;
966 node_r = ReadBlock (right);
967 ReadNodoHeader (node_r, &node_hr);
968 if (node_hr.level != 0) {
970 node_keyr = ReadKeys (node_r, node_hr);
971 data_r = *(node_keyr.begin ());
973 right = data_r->GetChild ();
975 DeleteKeys (node_keyr);
978 } while (node_hr.level != 0);
980 std::cout << "Voy a reemplazar en el nodo " << right << std::endl;
982 /* Reemplazo la clave a borrar por la de la hoja */
983 node_keyr = ReadKeys (node_r, node_hr);
984 BTreeData *reemplazar = *(node_keyr.begin ());
986 std::string ss = *reemplazar;
987 std::cout << "Voy a reemplazar por : " << ss << std::endl;
989 BTreeData *data = new BTreeLeafData (k->Clone());
991 std::list<BTreeData *>::iterator it = node_keys.begin ();
992 while (it != node_keys.end ()) {
993 std::string ss1, ss2;
996 std::cout << ss1 << " == " << ss2 << std::endl;
997 if ((*data) == (*(*it))) {
1002 if (it == node_keys.end ()) {
1003 std::cout << "PANIC : No encontre la clave en el nodo!!!!\n";
1004 std::string s = *data;
1005 std::cout << s << std::endl;
1006 PrintNode (node_num);
1009 (*it)->SetKey (reemplazar->GetKey ());
1010 reemplazar->SetKey (k->Clone ());
1012 std::cout << "Tengo todo reemplazado ...\n";
1014 /* Grabo los nodos */
1015 WriteKeys (node, node_header, node_keys);
1016 WriteNodoHeader (node, &node_header);
1017 WriteBlock (node, node_num);
1018 DeleteKeys (node_keys);
1021 WriteKeys (node_r, node_hr, node_keyr);
1022 WriteNodoHeader (node_r, &node_hr);
1023 WriteBlock (node_r, right);
1024 DeleteKeys (node_keyr);
1027 std::cout << "Grabe todo en disco ...\n";
1028 PrintNode (node_num);
1030 /* Ahora debo eliminar la clave que puse en el nodo hoja */
1031 std::cout << "Borro la clave desde la hoja!\n";
1033 DelKeyFromLeaf (k, right, padre_hijo);
1035 std::cout << "Listo, Listo!\n";
1036 } else if (left != 0) {
1037 std::cout << "PANIC : Deberia poder reemplazar en la derecha!!!!!\n";
1040 std::cout << "PANIC : No tengo hijos para reemplazar!!!!\n";
1045 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
1047 memcpy (header, node, sizeof (BTreeNodeHeader));
1050 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
1052 memcpy (node, header, sizeof (BTreeNodeHeader));
1055 uchar *BTree::ReadBlock (uint num)
1057 /* Como el bloque 0 se usa para el header, el Nodo "num"
1058 * está en el bloque "num+1"
1062 uchar *out = new uchar[header.block_size];
1064 fseek (fp, num*header.block_size, SEEK_SET);
1065 fread (out, 1, header.block_size, fp);
1070 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
1072 std::list<BTreeData *> keys;
1073 node += sizeof (BTreeNodeHeader);
1074 uint count = node_header.item_count;
1076 if (node_header.item_count == 0) return keys;
1078 if (node_header.level != 0) {
1079 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
1080 BTreeChildData *d = new BTreeChildData (node);
1086 for (uint i=0; i<count; i++) {
1088 if (node_header.level == 0) {
1089 data = new BTreeLeafData (node, header.key_type);
1091 data = new BTreeData (node, header.key_type);
1093 node += data->Size ();
1094 keys.push_back (data);
1101 void BTree::AbrevKey (std::list<BTreeData *> &lst)
1103 /* Claves Fijas No se abrevian */
1104 if (header.key_type == KEY_FIXED) return;
1106 BTreeData *primera = NULL;
1107 std::list<BTreeData *>::iterator it = lst.begin ();
1109 while (it != lst.end ()) {
1110 if ((*it)->Abrev (primera) == false)
1116 void BTree::DeAbrevKey (std::list<BTreeData *> &lst)
1118 /* Claves Fijas No se abrevian */
1119 if (header.key_type == KEY_FIXED) return;
1121 BTreeData *primera = NULL;
1122 std::list<BTreeData *>::iterator it = lst.begin ();
1124 while (it != lst.end ()) {
1125 if ((*it)->DesAbrev (primera) == false)
1131 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
1135 std::list<BTreeData *>::iterator it = keys.begin ();
1137 node += sizeof (BTreeNodeHeader);
1139 node_header.item_count = 0;
1140 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
1143 while (it != keys.end ()) {
1144 BTreeData *d = (*it);
1145 uchar *n = d->ToArray ();
1146 acumulado += d->Size ();
1147 //std::cout << "WriteKeys :: Acumulado = " << acumulado << std::endl;
1148 memcpy (node, n, d->Size ());
1151 node_header.free_space -= d->Size ();
1152 node_header.item_count++;
1159 void BTree::PrintNode (uint num)
1161 uchar *node = ReadBlock (num);
1162 BTreeNodeHeader node_header;
1163 ReadNodoHeader (node, &node_header);
1165 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
1166 std::list<BTreeData *>::iterator it = node_keys.begin ();
1168 std::cout << "Nodo : " << num << std::endl;
1169 std::cout << "Level : " << node_header.level << std::endl;
1170 std::cout << "Items : " << node_header.item_count << std::endl;
1171 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
1172 while (it != node_keys.end ()) {
1173 std::string s = *(*it);
1174 std::cout << s << " ";
1177 std::cout << std::endl;
1180 DeleteKeys (node_keys);
1183 uchar *BTree::NewBlock (uint &num)
1189 std::list<uint>::iterator it;
1191 if (deleted_nodes.size ()) {
1192 it = deleted_nodes.begin ();
1194 deleted_nodes.erase (it);
1196 fseek (fp, 0, SEEK_END);
1197 filelen = ftell (fp);
1199 num = filelen/header.block_size - 1;
1201 node = new uchar[header.block_size];
1202 ReadNodoHeader (node, &nh);
1204 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
1206 WriteNodoHeader (node, &nh);
1207 WriteBlock (node, num);
1212 BTreeFindResult *BTree::FindKey (const Clave &k)
1214 return FindKeyR (&k, 0);
1217 BTreeFindResult *BTree::FindKeyR (const Clave *k, uint node_num)
1219 std::list<BTreeData *> node_keys;
1220 BTreeNodeHeader node_header;
1222 /* Leo el nodo raiz para empezar a agregar */
1223 uchar *node = ReadBlock (node_num);
1224 ReadNodoHeader (node, &node_header);
1225 node_keys = ReadKeys (node, node_header);
1227 std::list<BTreeData *>::iterator it = node_keys.begin ();
1228 std::list<BTreeData *>::iterator posterior;
1229 std::list<BTreeData *>::iterator ultima;
1231 /* Se supone que la primera es un hijo :) */
1233 if (node_header.level != 0) {
1239 if (node_header.level == 0)
1240 data = new BTreeLeafData (k->Clone ());
1242 data = new BTreeData (k->Clone (), 0);
1244 while (it != node_keys.end ()) {
1245 if ((*data) == (*(*it))) {
1246 /* La encontre!, retorno */
1249 DeleteKeys (node_keys);
1250 BTreeFindResult *result = new BTreeFindResult ();
1251 result->node = node_num;
1252 result->header = node_header;
1257 if ((*data) < (*(*it)))
1265 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
1266 * decir que no lo encontré
1268 if (node_header.level == 0) {
1269 DeleteKeys (node_keys);
1274 /* TODO: Aca faltaria liberar memoria */
1275 BTreeFindResult *ret;
1276 if (it == posterior)
1277 ret = FindKeyR (k, lchild->GetChild ());
1279 ret = FindKeyR (k, (*ultima)->GetChild ());
1281 DeleteKeys (node_keys);
1286 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
1288 std::list<BTreeData *>::iterator it = keys.begin ();
1290 while (it != keys.end ()) {
1291 BTreeData *d = (*it);
1297 int BTree::type () const
1299 return header.key_type;