4 BTree::BTree (const std::string &name, unsigned int block_size, 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;
22 /* Creo el primer bloque vacio */
23 node = new uchar[block_size];
24 ReadNodoHeader (node, &nh);
26 nh.free_space = block_size - sizeof (BTreeNodeHeader);
28 WriteNodoHeader (node, &nh);
39 void BTree::WriteFileHeader ()
41 fseek (fp, 0L, SEEK_SET);
42 fwrite (&header, 1, sizeof (BTreeFileHeader), fp);
45 void BTree::WriteBlock (uchar *block, uint num)
47 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
48 fwrite (block, 1, header.block_size, fp);
51 void BTree::AddKey (const Clave &k)
54 Clave *kout = AddKeyR (&k, 0, left, right);
58 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
59 * que esta usando el hijo izquierdo a un nuevo nodo */
60 std::list<BTreeData *> node_keys;
61 BTreeNodeHeader node_header;
62 uchar *node = ReadBlock (left);
63 ReadNodoHeader (node, &node_header);
64 node_keys = ReadKeys (node, node_header);
65 level = node_header.level + 1;
67 uchar *new_node = NewBlock (left);
68 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
70 WriteKeys (node, node_header, node_keys);
71 WriteNodoHeader (node, &node_header);
72 WriteBlock (node, left);
75 /* Leo y actualizo la Raiz */
77 ReadNodoHeader (node, &node_header);
78 node_keys = std::list<BTreeData *>();
80 node_keys.push_back (new BTreeChildData (left));
81 node_keys.push_back (new BTreeData (kout, right));
83 node_header.level = level;
84 node_header.item_count = 1;
86 WriteKeys (node, node_header, node_keys);
87 WriteNodoHeader (node, &node_header);
93 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
96 std::list<BTreeData *> node_keys;
98 BTreeData *data = new BTreeLeafData (k->Clone ());
100 /* Leo el nodo raiz para empezar a agregar */
101 uchar *node = ReadBlock (node_num);
102 BTreeNodeHeader node_header;
103 ReadNodoHeader (node, &node_header);
105 if (node_header.level != 0) {
106 std::cout << "Entrando nodo level = " << node_header.level << std::endl;
107 /* No estoy en una hoja, asi que tengo que buscar
108 * para donde moverme para agregar la clave
110 std::cout << "Leo Claves" << std::endl;
111 node_keys = ReadKeys (node, node_header);
113 std::list<BTreeData *>::iterator it = node_keys.begin ();
114 std::list<BTreeData *>::iterator posterior;
115 std::list<BTreeData *>::iterator ultima;
117 /* Se supone que la primera es un hijo :) */
118 BTreeData *lchild = (*it++);
121 while (it != node_keys.end ()) {
122 if ((*data) < (*(*it)))
128 if (it == posterior) {
129 std::cout << "==== Me voy al nodo " << lchild->getChild () << std::endl;
130 k = AddKeyR (k, lchild->getChild (), left_child, right_child);
132 std::cout << "==== Me voy al nodo " << (*ultima)->getChild () << std::endl;
133 k = AddKeyR (k, (*ultima)->getChild (), left_child, right_child);
136 data = new BTreeData (k->Clone (), right_child);
143 /* Estoy en una hoja, veo si lo puedo agregar */
145 if (node_header.free_space > data->Size ()) {
146 /* TODO : Insertar ordenado */
148 node_keys = ReadKeys (node, node_header);
149 std::list<BTreeData *>::iterator it = node_keys.begin ();
151 while (it != node_keys.end ()) {
153 if ((*data) < (*datait))
154 /* Me pase, lo agrego aca! */
158 node_keys.insert (it, data);
159 WriteKeys (node, node_header, node_keys);
160 WriteNodoHeader (node, &node_header);
161 WriteBlock (node, node_num);
163 PrintNode (node_num);
165 std::cout << "=============== SPLIT ================" << std::endl;
166 /* Split : Creo e inicializo el nuevo nodo */
167 std::list<BTreeData *> new_node_keys;
168 std::list<BTreeData *> old_node_keys;
169 BTreeNodeHeader new_node_header;
171 uchar *new_node = NewBlock (new_node_num);
172 ReadNodoHeader (new_node, &new_node_header);
174 node_keys = ReadKeys (node, node_header);
175 new_node_keys = ReadKeys (new_node, new_node_header);
177 /* Agrego la clave en la lista que ya tengo de manera ordenada */
178 std::list<BTreeData *>::iterator it = node_keys.begin ();
180 while (it != node_keys.end ()) {
183 if ((*data) < (*datait))
184 /* Me pase, lo agrego aca! */
188 if (it != node_keys.end ())
189 node_keys.insert (it, data);
191 node_keys.push_back (data);
193 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
194 * y subir la clave del medio */
195 node_header.item_count = 0;
196 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
199 it = node_keys.begin ();
200 while (it != node_keys.end ()) {
203 total_size += datait->Size ();
205 /* Hack : Si me quedo con todas las claves, en el caso de ser
206 * del mismo tama#o se desbalancea. Hay que ver que efecto
207 * puede tener en el caso de claves de long. variable
209 if (it == node_keys.end ())
210 total_size -= datait->Size ();
213 it = node_keys.begin ();
215 while (used < total_size/2) {
216 BTreeData *d = (*it);
217 old_node_keys.push_back (d);
221 kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
222 while (it != node_keys.end ()) {
223 BTreeData *d = (*it);
224 new_node_keys.push_back (d);
229 WriteKeys (node, node_header, old_node_keys);
230 WriteNodoHeader (node, &node_header);
231 WriteBlock (node, node_num);
232 WriteKeys (new_node, new_node_header, new_node_keys);
233 WriteNodoHeader (new_node, &new_node_header);
234 WriteBlock (new_node, new_node_num);
236 PrintNode (node_num);
237 PrintNode (new_node_num);
240 left_child = node_num;
241 right_child = new_node_num;
249 void BTree::DelKey (const Clave &k) {}
251 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
253 memcpy (header, node, sizeof (BTreeNodeHeader));
256 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
258 memcpy (node, header, sizeof (BTreeNodeHeader));
261 uchar *BTree::ReadBlock (uint num)
263 uchar *out = new uchar[header.block_size];
265 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
266 fread (out, 1, header.block_size, fp);
271 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
273 std::list<BTreeData *> keys;
274 node += sizeof (BTreeNodeHeader);
275 uint count = node_header.item_count;
277 if (node_header.item_count == 0) return keys;
279 if (node_header.level != 0) {
280 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
281 BTreeChildData *d = new BTreeChildData (node);
287 for (uint i=0; i<count; i++) {
288 /* TODO : El tipo de clave deberia ser usado
289 * dependiendo de algun dato en el header del
292 /* TODO : Detectar si estoy en una hoja */
294 if (node_header.level == 0) {
295 data = new BTreeLeafData (node);
297 data = new BTreeData (node);
299 node += data->Size ();
300 keys.push_back (data);
306 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
308 std::list<BTreeData *>::iterator it = keys.begin ();
310 node += sizeof (BTreeNodeHeader);
312 node_header.item_count = 0;
313 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
315 while (it != keys.end ()) {
316 BTreeData *d = (*it);
317 memcpy (node, d->ToArray(), d->Size ());
319 node_header.free_space -= d->Size ();
320 node_header.item_count++;
324 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
327 void BTree::PrintNode (uint num)
329 uchar *node = ReadBlock (num);
330 BTreeNodeHeader node_header;
331 ReadNodoHeader (node, &node_header);
333 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
334 std::list<BTreeData *>::iterator it = node_keys.begin ();
336 std::cout << "Nodo : " << num << std::endl;
337 std::cout << "Level : " << node_header.level << std::endl;
338 std::cout << "Items : " << node_header.item_count << std::endl;
339 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
340 while (it != node_keys.end ()) {
341 std::string s = *(*it);
342 std::cout << s << " ";
345 std::cout << std::endl;
350 uchar *BTree::NewBlock (uint &num)
356 fseek (fp, 0, SEEK_END);
357 filelen = ftell (fp);
359 num = (filelen - sizeof (BTreeFileHeader))/header.block_size;
361 node = new uchar[header.block_size];
362 ReadNodoHeader (node, &nh);
364 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
366 WriteNodoHeader (node, &nh);
367 WriteBlock (node, 0);