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, 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);
76 /* Leo y actualizo la Raiz */
78 ReadNodoHeader (node, &node_header);
79 node_keys = std::list<BTreeData *>();
81 node_keys.push_back (new BTreeChildData (left));
82 node_keys.push_back (new BTreeData (kout, right));
84 node_header.level = level;
85 node_header.item_count = 1;
87 WriteKeys (node, node_header, node_keys);
88 WriteNodoHeader (node, &node_header);
94 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
96 uchar *node = ReadBlock (node_num);
97 BTreeNodeHeader node_header;
98 ReadNodoHeader (node, &node_header);
101 if (node_header.level == 0)
102 return AddKeyLeafR (k, node_num, left_child, right_child);
104 return AddKeyOtherR (k, node_num, left_child, right_child);
107 Clave* BTree::AddKeyLeafR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
110 std::list<BTreeData *> node_keys;
112 BTreeData *data = new BTreeLeafData (k->Clone ());
114 /* Leo el nodo raiz para empezar a agregar */
115 uchar *node = ReadBlock (node_num);
116 BTreeNodeHeader node_header;
117 ReadNodoHeader (node, &node_header);
119 if (node_header.free_space > data->Size ()) {
121 node_keys = ReadKeys (node, node_header);
122 std::list<BTreeData *>::iterator it = node_keys.begin ();
124 while (it != node_keys.end ()) {
126 if ((*data) < (*datait))
127 /* Me pase, lo agrego aca! */
131 node_keys.insert (it, data);
132 WriteKeys (node, node_header, node_keys);
133 WriteNodoHeader (node, &node_header);
134 WriteBlock (node, node_num);
136 PrintNode (node_num);
138 /* Split : Creo e inicializo el nuevo nodo */
139 std::list<BTreeData *> new_node_keys;
140 std::list<BTreeData *> old_node_keys;
141 BTreeNodeHeader new_node_header;
143 uchar *new_node = NewBlock (new_node_num);
144 ReadNodoHeader (new_node, &new_node_header);
145 new_node_header.level = node_header.level;
147 node_keys = ReadKeys (node, node_header);
148 new_node_keys = ReadKeys (new_node, new_node_header);
150 /* Agrego la clave en la lista que ya tengo de manera ordenada */
151 std::list<BTreeData *>::iterator it = node_keys.begin ();
152 std::list<BTreeData *>::iterator previt = node_keys.begin ();
154 while (it != node_keys.end ()) {
157 if ((*data) < (*datait))
158 /* Me pase, lo agrego aca! */
163 if (it != node_keys.end ())
164 node_keys.insert (it, data);
166 node_keys.push_back (data);
168 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
169 * y subir la clave del medio */
170 node_header.item_count = 0;
171 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
174 it = node_keys.begin ();
175 while (it != node_keys.end ()) {
178 total_size += datait->Size ();
180 /* Hack : Si me quedo con todas las claves, en el caso de ser
181 * del mismo tama#o se desbalancea. Hay que ver que efecto
182 * puede tener en el caso de claves de long. variable
184 if (it == node_keys.end ())
185 total_size -= datait->Size ();
188 it = node_keys.begin ();
190 while (used < total_size/2) {
191 BTreeData *d = (*it);
192 old_node_keys.push_back (d);
196 kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
198 while (it != node_keys.end ()) {
199 BTreeData *d = (*it);
200 new_node_keys.push_back (d);
205 WriteKeys (node, node_header, old_node_keys);
206 WriteNodoHeader (node, &node_header);
207 WriteBlock (node, node_num);
208 WriteKeys (new_node, new_node_header, new_node_keys);
209 WriteNodoHeader (new_node, &new_node_header);
210 WriteBlock (new_node, new_node_num);
212 PrintNode (node_num);
213 PrintNode (new_node_num);
216 left_child = node_num;
217 right_child = new_node_num;
225 Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
228 std::list<BTreeData *> node_keys;
230 BTreeData *data = new BTreeLeafData (k->Clone ());
232 /* Leo el nodo raiz para empezar a agregar */
233 uchar *node = ReadBlock (node_num);
234 BTreeNodeHeader node_header;
235 ReadNodoHeader (node, &node_header);
237 node_keys = ReadKeys (node, node_header);
239 std::list<BTreeData *>::iterator it = node_keys.begin ();
240 std::list<BTreeData *>::iterator posterior;
241 std::list<BTreeData *>::iterator ultima;
243 /* Se supone que la primera es un hijo :) */
244 BTreeData *lchild = (*it++);
247 while (it != node_keys.end ()) {
248 if ((*data) < (*(*it)))
254 if (it == posterior) {
255 k = AddKeyR (k, lchild->getChild (), left_child, right_child);
257 k = AddKeyR (k, (*ultima)->getChild (), left_child, right_child);
263 data = new BTreeData (k->Clone (), right_child);
265 if (node_header.free_space > data->Size ()) {
267 node_keys = ReadKeys (node, node_header);
268 std::list<BTreeData *>::iterator it = node_keys.begin ();
270 while (it != node_keys.end ()) {
272 if ((*data) < (*datait))
273 /* Me pase, lo agrego aca! */
277 node_keys.insert (it, data);
278 WriteKeys (node, node_header, node_keys);
279 WriteNodoHeader (node, &node_header);
280 WriteBlock (node, node_num);
282 PrintNode (node_num);
284 /* Split : Creo e inicializo el nuevo nodo */
285 std::list<BTreeData *> new_node_keys;
286 std::list<BTreeData *> old_node_keys;
287 BTreeNodeHeader new_node_header;
289 uchar *new_node = NewBlock (new_node_num);
290 ReadNodoHeader (new_node, &new_node_header);
291 new_node_header.level = node_header.level;
293 node_keys = ReadKeys (node, node_header);
294 new_node_keys = ReadKeys (new_node, new_node_header);
296 /* Agrego la clave en la lista que ya tengo de manera ordenada */
297 std::list<BTreeData *>::iterator it = node_keys.begin ();
298 std::list<BTreeData *>::iterator previt = node_keys.begin ();
302 while (it != node_keys.end ()) {
305 if ((*data) < (*datait))
306 /* Me pase, lo agrego aca! */
311 if (it != node_keys.end ())
312 node_keys.insert (it, data);
314 node_keys.push_back (data);
316 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
317 * y subir la clave del medio */
318 node_header.item_count = 0;
319 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
322 it = node_keys.begin ();
323 while (it != node_keys.end ()) {
326 total_size += datait->Size ();
328 /* Hack : Si me quedo con todas las claves, en el caso de ser
329 * del mismo tama#o se desbalancea. Hay que ver que efecto
330 * puede tener en el caso de claves de long. variable
332 if (it == node_keys.end ())
333 total_size -= datait->Size ();
336 it = node_keys.begin ();
338 while (used < total_size/2) {
339 BTreeData *d = (*it);
340 old_node_keys.push_back (d);
344 kout = (*it)->getClave (); // Esta se retorna al "padre" para que se la agregue
346 new_node_keys.push_back ( new BTreeChildData ((*it)->getChild ()));
348 while (it != node_keys.end ()) {
349 BTreeData *d = (*it);
350 new_node_keys.push_back (d);
355 WriteKeys (node, node_header, old_node_keys);
356 WriteNodoHeader (node, &node_header);
357 WriteBlock (node, node_num);
358 WriteKeys (new_node, new_node_header, new_node_keys);
359 WriteNodoHeader (new_node, &new_node_header);
360 WriteBlock (new_node, new_node_num);
362 PrintNode (node_num);
363 PrintNode (new_node_num);
366 left_child = node_num;
367 right_child = new_node_num;
375 void BTree::DelKey (const Clave &k) {}
377 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
379 memcpy (header, node, sizeof (BTreeNodeHeader));
382 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
384 memcpy (node, header, sizeof (BTreeNodeHeader));
387 uchar *BTree::ReadBlock (uint num)
389 uchar *out = new uchar[header.block_size];
391 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
392 fread (out, 1, header.block_size, fp);
397 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
399 std::list<BTreeData *> keys;
400 node += sizeof (BTreeNodeHeader);
401 uint count = node_header.item_count;
403 if (node_header.item_count == 0) return keys;
405 if (node_header.level != 0) {
406 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
407 BTreeChildData *d = new BTreeChildData (node);
413 for (uint i=0; i<count; i++) {
414 /* TODO : El tipo de clave deberia ser usado
415 * dependiendo de algun dato en el header del
418 /* TODO : Detectar si estoy en una hoja */
420 if (node_header.level == 0) {
421 data = new BTreeLeafData (node, key_type);
423 data = new BTreeData (node, key_type);
425 node += data->Size ();
426 keys.push_back (data);
432 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
434 std::list<BTreeData *>::iterator it = keys.begin ();
436 node += sizeof (BTreeNodeHeader);
438 node_header.item_count = 0;
439 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
441 while (it != keys.end ()) {
442 BTreeData *d = (*it);
443 memcpy (node, d->ToArray(), d->Size ());
445 node_header.free_space -= d->Size ();
446 node_header.item_count++;
450 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
453 void BTree::PrintNode (uint num)
455 uchar *node = ReadBlock (num);
456 BTreeNodeHeader node_header;
457 ReadNodoHeader (node, &node_header);
459 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
460 std::list<BTreeData *>::iterator it = node_keys.begin ();
462 std::cout << "Nodo : " << num << std::endl;
463 std::cout << "Level : " << node_header.level << std::endl;
464 std::cout << "Items : " << node_header.item_count << std::endl;
465 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
466 while (it != node_keys.end ()) {
467 std::string s = *(*it);
468 std::cout << s << " ";
471 std::cout << std::endl;
476 uchar *BTree::NewBlock (uint &num)
482 fseek (fp, 0, SEEK_END);
483 filelen = ftell (fp);
485 num = (filelen - sizeof (BTreeFileHeader))/header.block_size;
487 node = new uchar[header.block_size];
488 ReadNodoHeader (node, &nh);
490 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
492 WriteNodoHeader (node, &nh);
493 WriteBlock (node, num);