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 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
396 memcpy (header, node, sizeof (BTreeNodeHeader));
399 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
401 memcpy (node, header, sizeof (BTreeNodeHeader));
404 uchar *BTree::ReadBlock (uint num)
406 /* Como el bloque 0 se usa para el header, el Nodo "num"
407 * está en el bloque "num+1"
411 uchar *out = new uchar[header.block_size];
413 fseek (fp, num*header.block_size, SEEK_SET);
414 fread (out, 1, header.block_size, fp);
419 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
421 std::list<BTreeData *> keys;
422 node += sizeof (BTreeNodeHeader);
423 uint count = node_header.item_count;
425 if (node_header.item_count == 0) return keys;
427 if (node_header.level != 0) {
428 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
429 BTreeChildData *d = new BTreeChildData (node);
435 for (uint i=0; i<count; i++) {
436 /* TODO : El tipo de clave deberia ser usado
437 * dependiendo de algun dato en el header del
440 /* TODO : Detectar si estoy en una hoja */
442 if (node_header.level == 0) {
443 data = new BTreeLeafData (node, key_type);
445 data = new BTreeData (node, key_type);
447 node += data->Size ();
448 keys.push_back (data);
454 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
456 std::list<BTreeData *>::iterator it = keys.begin ();
458 node += sizeof (BTreeNodeHeader);
460 node_header.item_count = 0;
461 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
463 while (it != keys.end ()) {
464 BTreeData *d = (*it);
465 uchar *n = d->ToArray ();
466 memcpy (node, n, d->Size ());
469 node_header.free_space -= d->Size ();
470 node_header.item_count++;
474 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
477 void BTree::PrintNode (uint num)
479 uchar *node = ReadBlock (num);
480 BTreeNodeHeader node_header;
481 ReadNodoHeader (node, &node_header);
483 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
484 std::list<BTreeData *>::iterator it = node_keys.begin ();
486 std::cout << "Nodo : " << num << std::endl;
487 std::cout << "Level : " << node_header.level << std::endl;
488 std::cout << "Items : " << node_header.item_count << std::endl;
489 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
490 while (it != node_keys.end ()) {
491 std::string s = *(*it);
492 std::cout << s << " ";
495 std::cout << std::endl;
498 DeleteKeys (node_keys);
501 uchar *BTree::NewBlock (uint &num)
507 fseek (fp, 0, SEEK_END);
508 filelen = ftell (fp);
510 num = filelen/header.block_size - 1;
512 node = new uchar[header.block_size];
513 ReadNodoHeader (node, &nh);
515 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
517 WriteNodoHeader (node, &nh);
518 WriteBlock (node, num);
523 bool BTree::FindKey (const Clave &k)
525 return FindKeyR (&k, 0);
528 bool BTree::FindKeyR (const Clave *k, uint node_num)
530 std::list<BTreeData *> node_keys;
531 BTreeNodeHeader node_header;
533 /* Leo el nodo raiz para empezar a agregar */
534 uchar *node = ReadBlock (node_num);
535 ReadNodoHeader (node, &node_header);
536 node_keys = ReadKeys (node, node_header);
538 std::list<BTreeData *>::iterator it = node_keys.begin ();
539 std::list<BTreeData *>::iterator posterior;
540 std::list<BTreeData *>::iterator ultima;
542 /* Se supone que la primera es un hijo :) */
544 if (node_header.level != 0) {
550 if (node_header.level == 0)
551 data = new BTreeLeafData ((Clave *)k);
553 data = new BTreeData ((Clave *)k, 0);
555 while (it != node_keys.end ()) {
556 if ((*data) == (*(*it))) {
557 /* La encontre!, retorno */
559 DeleteKeys (node_keys);
563 if ((*data) < (*(*it)))
569 /* TODO: Aca faltaria liberar memoria */
571 return FindKeyR (k, lchild->getChild ());
573 return FindKeyR (k, (*ultima)->getChild ());
576 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
578 std::list<BTreeData *>::iterator it = keys.begin ();
580 while (it != keys.end ()) {
581 BTreeData *d = (*it);