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)
48 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
49 fwrite (block, 1, header.block_size, fp);
52 void BTree::AddKey (const Clave &k)
55 Clave *kout = AddKeyR (k.Clone (), 0, left, right);
59 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
60 * que esta usando el hijo izquierdo a un nuevo nodo */
61 std::list<BTreeData *> node_keys;
62 BTreeNodeHeader node_header;
63 uchar *node = ReadBlock (left);
64 ReadNodoHeader (node, &node_header);
65 node_keys = ReadKeys (node, node_header);
66 level = node_header.level + 1;
68 uchar *new_node = NewBlock (left);
69 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
71 WriteKeys (node, node_header, node_keys);
72 WriteNodoHeader (node, &node_header);
73 WriteBlock (node, left);
74 DeleteKeys (node_keys);
77 /* Leo y actualizo la Raiz */
79 ReadNodoHeader (node, &node_header);
80 node_keys = std::list<BTreeData *>();
82 node_keys.push_back (new BTreeChildData (left));
83 node_keys.push_back (new BTreeData (kout, right));
85 node_header.level = level;
86 node_header.item_count = 1;
88 WriteKeys (node, node_header, node_keys);
89 WriteNodoHeader (node, &node_header);
92 DeleteKeys (node_keys);
97 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
99 uchar *node = ReadBlock (node_num);
100 BTreeNodeHeader node_header;
101 ReadNodoHeader (node, &node_header);
104 if (node_header.level == 0)
105 return AddKeyLeafR (k, node_num, left_child, right_child);
107 return AddKeyOtherR (k, node_num, left_child, right_child);
110 Clave* BTree::AddKeyLeafR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
113 std::list<BTreeData *> node_keys;
115 BTreeData *data = new BTreeLeafData (k->Clone ());
117 /* Leo el nodo raiz para empezar a agregar */
118 uchar *node = ReadBlock (node_num);
119 BTreeNodeHeader node_header;
120 ReadNodoHeader (node, &node_header);
122 if (node_header.free_space > data->Size ()) {
124 node_keys = ReadKeys (node, node_header);
125 std::list<BTreeData *>::iterator it = node_keys.begin ();
127 while (it != node_keys.end ()) {
129 if ((*data) < (*datait))
130 /* Me pase, lo agrego aca! */
134 node_keys.insert (it, data);
135 WriteKeys (node, node_header, node_keys);
136 WriteNodoHeader (node, &node_header);
137 WriteBlock (node, node_num);
138 DeleteKeys (node_keys);
141 PrintNode (node_num);
143 /* Split : Creo e inicializo el nuevo nodo */
144 std::list<BTreeData *> new_node_keys;
145 std::list<BTreeData *> old_node_keys;
146 BTreeNodeHeader new_node_header;
148 uchar *new_node = NewBlock (new_node_num);
149 ReadNodoHeader (new_node, &new_node_header);
150 new_node_header.level = node_header.level;
152 node_keys = ReadKeys (node, node_header);
153 new_node_keys = ReadKeys (new_node, new_node_header);
155 /* Agrego la clave en la lista que ya tengo de manera ordenada */
156 std::list<BTreeData *>::iterator it = node_keys.begin ();
157 std::list<BTreeData *>::iterator previt = node_keys.begin ();
159 while (it != node_keys.end ()) {
162 if ((*data) < (*datait))
163 /* Me pase, lo agrego aca! */
168 if (it != node_keys.end ())
169 node_keys.insert (it, data);
171 node_keys.push_back (data);
173 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
174 * y subir la clave del medio */
175 node_header.item_count = 0;
176 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
179 it = node_keys.begin ();
180 while (it != node_keys.end ()) {
183 total_size += datait->Size ();
185 /* Hack : Si me quedo con todas las claves, en el caso de ser
186 * del mismo tama#o se desbalancea. Hay que ver que efecto
187 * puede tener en el caso de claves de long. variable
189 if (it == node_keys.end ())
190 total_size -= datait->Size ();
193 it = node_keys.begin ();
195 while (used < total_size/2) {
196 BTreeData *d = (*it);
197 old_node_keys.push_back (d);
201 kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
203 while (it != node_keys.end ()) {
204 BTreeData *d = (*it);
205 new_node_keys.push_back (d);
210 WriteKeys (node, node_header, old_node_keys);
211 WriteNodoHeader (node, &node_header);
212 WriteBlock (node, node_num);
213 WriteKeys (new_node, new_node_header, new_node_keys);
214 WriteNodoHeader (new_node, &new_node_header);
215 WriteBlock (new_node, new_node_num);
216 DeleteKeys (old_node_keys);
217 DeleteKeys (new_node_keys);
219 PrintNode (node_num);
220 PrintNode (new_node_num);
223 left_child = node_num;
224 right_child = new_node_num;
232 Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
235 std::list<BTreeData *> node_keys;
237 BTreeData *data = new BTreeLeafData (k->Clone ());
239 /* Leo el nodo raiz para empezar a agregar */
240 uchar *node = ReadBlock (node_num);
241 BTreeNodeHeader node_header;
242 ReadNodoHeader (node, &node_header);
244 node_keys = ReadKeys (node, node_header);
246 std::list<BTreeData *>::iterator it = node_keys.begin ();
247 std::list<BTreeData *>::iterator posterior;
248 std::list<BTreeData *>::iterator ultima;
250 /* Se supone que la primera es un hijo :) */
251 BTreeData *lchild = (*it++);
254 while (it != node_keys.end ()) {
255 if ((*data) < (*(*it)))
261 if (it == posterior) {
262 k = AddKeyR (k, lchild->getChild (), left_child, right_child);
264 k = AddKeyR (k, (*ultima)->getChild (), left_child, right_child);
266 DeleteKeys (node_keys);
269 if (data) delete data;
275 data = new BTreeData (k->Clone (), right_child);
277 if (node_header.free_space > data->Size ()) {
279 node_keys = ReadKeys (node, node_header);
280 std::list<BTreeData *>::iterator it = node_keys.begin ();
282 while (it != node_keys.end ()) {
284 if ((*data) < (*datait))
285 /* Me pase, lo agrego aca! */
289 node_keys.insert (it, data);
290 WriteKeys (node, node_header, node_keys);
291 WriteNodoHeader (node, &node_header);
292 WriteBlock (node, node_num);
293 DeleteKeys (node_keys);
296 PrintNode (node_num);
298 /* Split : Creo e inicializo el nuevo nodo */
299 std::list<BTreeData *> new_node_keys;
300 std::list<BTreeData *> old_node_keys;
301 BTreeNodeHeader new_node_header;
303 uchar *new_node = NewBlock (new_node_num);
304 ReadNodoHeader (new_node, &new_node_header);
305 new_node_header.level = node_header.level;
307 node_keys = ReadKeys (node, node_header);
308 new_node_keys = ReadKeys (new_node, new_node_header);
310 /* Agrego la clave en la lista que ya tengo de manera ordenada */
311 std::list<BTreeData *>::iterator it = node_keys.begin ();
312 std::list<BTreeData *>::iterator previt = node_keys.begin ();
316 while (it != node_keys.end ()) {
319 if ((*data) < (*datait))
320 /* Me pase, lo agrego aca! */
325 if (it != node_keys.end ())
326 node_keys.insert (it, data);
328 node_keys.push_back (data);
330 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
331 * y subir la clave del medio */
332 node_header.item_count = 0;
333 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
336 it = node_keys.begin ();
337 while (it != node_keys.end ()) {
340 total_size += datait->Size ();
342 /* Hack : Si me quedo con todas las claves, en el caso de ser
343 * del mismo tama#o se desbalancea. Hay que ver que efecto
344 * puede tener en el caso de claves de long. variable
346 if (it == node_keys.end ())
347 total_size -= datait->Size ();
350 it = node_keys.begin ();
352 while (used < total_size/2) {
353 BTreeData *d = (*it);
354 old_node_keys.push_back (d);
358 kout = (*it)->getClave (); // Esta se retorna al "padre" para que se la agregue
360 new_node_keys.push_back ( new BTreeChildData ((*it)->getChild ()));
362 while (it != node_keys.end ()) {
363 BTreeData *d = (*it);
364 new_node_keys.push_back (d);
369 WriteKeys (node, node_header, old_node_keys);
370 WriteNodoHeader (node, &node_header);
371 WriteBlock (node, node_num);
372 WriteKeys (new_node, new_node_header, new_node_keys);
373 WriteNodoHeader (new_node, &new_node_header);
374 WriteBlock (new_node, new_node_num);
375 DeleteKeys (old_node_keys);
376 DeleteKeys (new_node_keys);
378 PrintNode (node_num);
379 PrintNode (new_node_num);
382 left_child = node_num;
383 right_child = new_node_num;
391 void BTree::DelKey (const Clave &k) {}
393 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
395 memcpy (header, node, sizeof (BTreeNodeHeader));
398 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
400 memcpy (node, header, sizeof (BTreeNodeHeader));
403 uchar *BTree::ReadBlock (uint num)
405 uchar *out = new uchar[header.block_size];
407 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
408 fread (out, 1, header.block_size, fp);
413 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
415 std::list<BTreeData *> keys;
416 node += sizeof (BTreeNodeHeader);
417 uint count = node_header.item_count;
419 if (node_header.item_count == 0) return keys;
421 if (node_header.level != 0) {
422 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
423 BTreeChildData *d = new BTreeChildData (node);
429 for (uint i=0; i<count; i++) {
430 /* TODO : El tipo de clave deberia ser usado
431 * dependiendo de algun dato en el header del
434 /* TODO : Detectar si estoy en una hoja */
436 if (node_header.level == 0) {
437 data = new BTreeLeafData (node, key_type);
439 data = new BTreeData (node, key_type);
441 node += data->Size ();
442 keys.push_back (data);
448 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
450 std::list<BTreeData *>::iterator it = keys.begin ();
452 node += sizeof (BTreeNodeHeader);
454 node_header.item_count = 0;
455 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
457 while (it != keys.end ()) {
458 BTreeData *d = (*it);
459 uchar *n = d->ToArray ();
460 memcpy (node, n, d->Size ());
463 node_header.free_space -= d->Size ();
464 node_header.item_count++;
468 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
471 void BTree::PrintNode (uint num)
473 uchar *node = ReadBlock (num);
474 BTreeNodeHeader node_header;
475 ReadNodoHeader (node, &node_header);
477 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
478 std::list<BTreeData *>::iterator it = node_keys.begin ();
480 std::cout << "Nodo : " << num << std::endl;
481 std::cout << "Level : " << node_header.level << std::endl;
482 std::cout << "Items : " << node_header.item_count << std::endl;
483 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
484 while (it != node_keys.end ()) {
485 std::string s = *(*it);
486 std::cout << s << " ";
489 std::cout << std::endl;
492 DeleteKeys (node_keys);
495 uchar *BTree::NewBlock (uint &num)
501 fseek (fp, 0, SEEK_END);
502 filelen = ftell (fp);
504 num = (filelen - sizeof (BTreeFileHeader))/header.block_size;
506 node = new uchar[header.block_size];
507 ReadNodoHeader (node, &nh);
509 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
511 WriteNodoHeader (node, &nh);
512 WriteBlock (node, num);
517 bool BTree::FindKey (const Clave &k)
519 return FindKeyR (&k, 0);
522 bool BTree::FindKeyR (const Clave *k, uint node_num)
524 std::list<BTreeData *> node_keys;
525 BTreeNodeHeader node_header;
527 /* Leo el nodo raiz para empezar a agregar */
528 uchar *node = ReadBlock (node_num);
529 ReadNodoHeader (node, &node_header);
530 node_keys = ReadKeys (node, node_header);
532 std::list<BTreeData *>::iterator it = node_keys.begin ();
533 std::list<BTreeData *>::iterator posterior;
534 std::list<BTreeData *>::iterator ultima;
536 /* Se supone que la primera es un hijo :) */
538 if (node_header.level != 0) {
544 if (node_header.level == 0)
545 data = new BTreeLeafData ((Clave *)k);
547 data = new BTreeData ((Clave *)k, 0);
549 while (it != node_keys.end ()) {
550 if ((*data) == (*(*it))) {
551 /* La encontre!, retorno */
553 DeleteKeys (node_keys);
557 if ((*data) < (*(*it)))
563 /* TODO: Aca faltaria liberar memoria */
565 return FindKeyR (k, lchild->getChild ());
567 return FindKeyR (k, (*ultima)->getChild ());
570 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
572 std::list<BTreeData *>::iterator it = keys.begin ();
574 while (it != keys.end ()) {
575 BTreeData *d = (*it);