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);
144 /* Estoy en una hoja, veo si lo puedo agregar */
146 if (node_header.free_space > data->Size ()) {
147 /* TODO : Insertar ordenado */
149 node_keys = ReadKeys (node, node_header);
150 std::list<BTreeData *>::iterator it = node_keys.begin ();
152 while (it != node_keys.end ()) {
154 if ((*data) < (*datait))
155 /* Me pase, lo agrego aca! */
159 node_keys.insert (it, data);
160 WriteKeys (node, node_header, node_keys);
161 WriteNodoHeader (node, &node_header);
162 WriteBlock (node, node_num);
164 PrintNode (node_num);
166 std::cout << "=============== SPLIT ================" << std::endl;
167 /* Split : Creo e inicializo el nuevo nodo */
168 std::list<BTreeData *> new_node_keys;
169 std::list<BTreeData *> old_node_keys;
170 BTreeNodeHeader new_node_header;
172 uchar *new_node = NewBlock (new_node_num);
173 ReadNodoHeader (new_node, &new_node_header);
174 new_node_header.level = node_header.level;
176 node_keys = ReadKeys (node, node_header);
177 new_node_keys = ReadKeys (new_node, new_node_header);
179 /* Agrego la clave en la lista que ya tengo de manera ordenada */
180 std::list<BTreeData *>::iterator it = node_keys.begin ();
181 std::list<BTreeData *>::iterator previt = node_keys.begin ();
183 if (node_header.level != 0) {
184 /* La primera es ChildData */
189 while (it != node_keys.end ()) {
192 if ((*data) < (*datait))
193 /* Me pase, lo agrego aca! */
198 if (it != node_keys.end ())
199 node_keys.insert (it, data);
201 node_keys.push_back (data);
203 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
204 * y subir la clave del medio */
205 node_header.item_count = 0;
206 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
209 it = node_keys.begin ();
210 while (it != node_keys.end ()) {
213 total_size += datait->Size ();
215 /* Hack : Si me quedo con todas las claves, en el caso de ser
216 * del mismo tama#o se desbalancea. Hay que ver que efecto
217 * puede tener en el caso de claves de long. variable
219 if (it == node_keys.end ())
220 total_size -= datait->Size ();
223 it = node_keys.begin ();
225 while (used < total_size/2) {
226 BTreeData *d = (*it);
227 old_node_keys.push_back (d);
231 kout = (*it)->getClave (); // Esta se retorna al "padre" para que se la agregue
232 if (node_header.level != 0) {
233 new_node_keys.push_back ( new BTreeChildData ((*it)->getChild ()));
237 std::string s = *kout;
238 std::cout << "SPLIT Retorna : " << s << std::endl;
239 while (it != node_keys.end ()) {
240 BTreeData *d = (*it);
241 new_node_keys.push_back (d);
246 WriteKeys (node, node_header, old_node_keys);
247 WriteNodoHeader (node, &node_header);
248 WriteBlock (node, node_num);
249 WriteKeys (new_node, new_node_header, new_node_keys);
250 WriteNodoHeader (new_node, &new_node_header);
251 WriteBlock (new_node, new_node_num);
253 PrintNode (node_num);
254 PrintNode (new_node_num);
257 left_child = node_num;
258 right_child = new_node_num;
266 void BTree::DelKey (const Clave &k) {}
268 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
270 memcpy (header, node, sizeof (BTreeNodeHeader));
273 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
275 memcpy (node, header, sizeof (BTreeNodeHeader));
278 uchar *BTree::ReadBlock (uint num)
280 uchar *out = new uchar[header.block_size];
282 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
283 fread (out, 1, header.block_size, fp);
288 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
290 std::list<BTreeData *> keys;
291 node += sizeof (BTreeNodeHeader);
292 uint count = node_header.item_count;
294 if (node_header.item_count == 0) return keys;
296 if (node_header.level != 0) {
297 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
298 BTreeChildData *d = new BTreeChildData (node);
304 for (uint i=0; i<count; i++) {
305 /* TODO : El tipo de clave deberia ser usado
306 * dependiendo de algun dato en el header del
309 /* TODO : Detectar si estoy en una hoja */
311 if (node_header.level == 0) {
312 data = new BTreeLeafData (node);
314 data = new BTreeData (node);
316 node += data->Size ();
317 keys.push_back (data);
323 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
325 std::list<BTreeData *>::iterator it = keys.begin ();
327 node += sizeof (BTreeNodeHeader);
329 node_header.item_count = 0;
330 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
332 while (it != keys.end ()) {
333 BTreeData *d = (*it);
334 memcpy (node, d->ToArray(), d->Size ());
336 node_header.free_space -= d->Size ();
337 node_header.item_count++;
341 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
344 void BTree::PrintNode (uint num)
346 uchar *node = ReadBlock (num);
347 BTreeNodeHeader node_header;
348 ReadNodoHeader (node, &node_header);
350 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
351 std::list<BTreeData *>::iterator it = node_keys.begin ();
353 std::cout << "Nodo : " << num << std::endl;
354 std::cout << "Level : " << node_header.level << std::endl;
355 std::cout << "Items : " << node_header.item_count << std::endl;
356 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
357 while (it != node_keys.end ()) {
358 std::string s = *(*it);
359 std::cout << s << " ";
362 std::cout << std::endl;
367 uchar *BTree::NewBlock (uint &num)
373 fseek (fp, 0, SEEK_END);
374 filelen = ftell (fp);
376 num = (filelen - sizeof (BTreeFileHeader))/header.block_size;
378 node = new uchar[header.block_size];
379 ReadNodoHeader (node, &nh);
381 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
383 WriteNodoHeader (node, &nh);
384 WriteBlock (node, num);