Repository navigation
Expand file tree
/
Copy pathbTreeInsert.c
More file actions
343 lines (264 loc) · 12.4 KB
/
Copy pathbTreeInsert.c
File metadata and controls
343 lines (264 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#include "bTreeInsert.h"
#include "streamHandler.h"
// *Função para inserir novo nó na bTree
int bTreeInsert(record *newRecord) {
FILE *bFile = fopen(BTREEFILENAME, "r+");
bPageInfo *bInfo = getOrCreateRoot(bFile);
promotedKey *promoted = NULL;
//Coleta a raíz e cria um promotedKey, responsável por cuidar de overflows relacionados
//à atualização de raiz
int error = _bTreeInsert(newRecord, bInfo, &promoted);
//Chama a função recursiva
if(error == -1) { return error; }
//Não foi possível inserir a chave, registro já existe
if(promoted != NULL) { headerUpdate(promoted, bFile); }
//Ao fim do processo, se promoted é não nulo, houve overflow na raíz, necessidade de atualizar
//o cabeçalho do arquivo
insertNodeInBTreeFile(bInfo, bFile, bInfo->RRN);
//Atualiza a raíz. Útil caso tenha ocorrido alguma modificação nesta
fclose(bFile);
free(bInfo);
return 0;
}
// *Função recursiva para inserir nova chave
int _bTreeInsert(record *newRecord, bPageInfo *bInfo, promotedKey **promoted) {
int insertPoint = pageBinarySearch(newRecord->key, bInfo->bPage->records, 0, bInfo->bPage->numRecords);
//Encontra o índice da chave na página
//Verifica se o elemento já existe no nó
if(insertPoint < MAXCHILDS - 1 && bInfo->bPage->records[insertPoint].key == newRecord->key) {
//Chave ja existe, retorna erro
return -1;
}
int status;
if(!bInfo->bPage->isLeaf) { //Caso não seja folha
bPageInfo *searchPage = getPageFromBTreeFile(bInfo->bPage->childs[insertPoint]);
status = _bTreeInsert(newRecord, searchPage, promoted);
//Chama a recursão na subárvore adequada
if(status == -1) { return -1; } //Ao voltar da recursão, checka se o registro existe
if(*promoted == NULL) { return 0; } //Inserção realizada com sucesso e sem overflow
//Promoted diferente de nulo, inserção com overflow, necessidade de inserir promoted
int insertPoint = pageBinarySearch((*promoted)->rec->key, bInfo->bPage->records, 0, bInfo->bPage->numRecords);
bTreeInsertIntoPage((*promoted)->rec, promoted, bInfo, insertPoint);
//Encontra a posição de inserção de promoted e insere na página
return status;
}
//Não é folha e o elemento não existe, realiza a inserção
else {
bTreeInsertIntoPage(newRecord, promoted, bInfo, insertPoint);
}
return 0;
}
// *Função para inserir dados em nova página em caso de overflow
void insertPageData(bTreePage *bPage, bTreePage *createdPage, long *childsArray, long startingPosition) {
//Seta a quantidade de elementos por página de acordo com a posição de inserção
if(startingPosition >= MAXCHILDS / 2 + 1) {
createdPage->numRecords = startingPosition - 1;
bPage->numRecords = MAXCHILDS - startingPosition;
} else {
createdPage->numRecords = startingPosition;
bPage->numRecords = MAXCHILDS - startingPosition - 1;
}
//Copia informações do fim da página com overflow para a página nova
for(long i = 0; i < startingPosition - 1; i++) {
createdPage->records[i].key = bPage->records[i + MAXCHILDS - startingPosition].key;
createdPage->records[i].RRN = bPage->records[i + MAXCHILDS - startingPosition].RRN;
}
//Atualiza os filhos da página, caso necessário
if(childsArray != NULL) {
for(int i = 0; i < MAXCHILDS; i++) {
if(i <= MAXCHILDS - bPage->numRecords - 1) {
createdPage->childs[i] = childsArray[i + MAXCHILDS - bPage->numRecords];
} else {
createdPage->childs[i] = -1;
}
}
}
}
// *Função para remover dados de uma página com overflow
void cleanPageData(bTreePage *bPage, long *childsArray, long startingPosition) {
//Apaga informações inseridas na nova página da página com overflow
for(long i = startingPosition; i < MAXCHILDS - 1; i++) {
bPage->records[i].key = 0;
bPage->records[i].RRN = -1;
}
//Atualiza os filhos da página, caso necessário
if(childsArray != NULL) {
for(int i = 0; i < MAXCHILDS; i++) {
if(i <= bPage->numRecords) {
bPage->childs[i] = childsArray[i];
} else {
bPage->childs[i] = -1;
}
}
}
}
// *Função para promover um record
promotedKey *promoteKey(record *rec, int LeftRRN, int RightRRN) {
promotedKey *promoted = (promotedKey*)malloc(sizeof(promotedKey));
promoted->childs[0] = LeftRRN;
promoted->childs[1] = RightRRN;
promoted->rec = rec;
return promoted;
}
// *Função para criar um vetor de MAXCHILDS + 1 posições, contendo a informação
// *de todos os filhos que precisarão ser alocados depois
long *createChildsArray(bPageInfo *bInfo, promotedKey *promoted) {
static long childsArray[MAXCHILDS + 1];
int found = 0;
for(int i = 0; i < MAXCHILDS + 1; i++) {
childsArray[i + found] = bInfo->bPage->childs[i];
if(bInfo->bPage->childs[i] == promoted->childs[0]) {
found = 1;
childsArray[i+1] = promoted->childs[1];
}
}
return childsArray;
}
// *Função para inserir uma nova chave em um nó
void bTreeInsertIntoPage(record *newRecord, promotedKey **promoted, bPageInfo *bInfo, long insertPosition) {
if(bInfo->bPage->numRecords == MAXCHILDS - 1) {
//Nó está cheio, overflow
bPageInfo *createdPage = (bPageInfo*)malloc(sizeof(bPageInfo));
createdPage->bPage = createPage();
createdPage->bPage->isLeaf = bInfo->bPage->isLeaf;
//TODO remover a abertura de arquivo daqui
FILE *fp = fopen(BTREEFILENAME, "r+");
fseek(fp, 0, SEEK_END);
createdPage->RRN = ftell(fp) / PAGESIZE;
int newRecordInsertPlace = 0;
// 0 - Chave inserida precisa ser promovida
// 1 - Chave inserida na direita
// -1 - Chave inserida na esquerda
int MaxChildsIsOdd = 0;
long promotedIndex;
//Posicionamento da chave inserida e chave promovida
long *childsArray = NULL; //Vetor para armazenar informações de filhos
if(*promoted != NULL) {
//Cria um vetor com filhos de bInfo e promoted que será utilizado no fim
childsArray = createChildsArray(bInfo, *promoted);
}
if(MAXCHILDS % 2 == 0) {
if(insertPosition > MAXCHILDS / 2 - 1) {
//É necessário inserir o elemento na direita
promotedIndex = MAXCHILDS / 2 - 1;
newRecordInsertPlace = 1;
} else {
if(insertPosition == MAXCHILDS / 2 - 1) {
//Novo record corresponde a chave promovida
newRecordInsertPlace = 0;
} else {
//É necessário inserir na esquerda
newRecordInsertPlace = -1;
}
promotedIndex = MAXCHILDS / 2 - 2;
}
}
else {
//Idem ao caso acima, mas para MAXCHILDS ímpar
MaxChildsIsOdd = 1;
if(insertPosition > MAXCHILDS / 2) {
promotedIndex = MAXCHILDS / 2;
newRecordInsertPlace = 1;
} else {
if(insertPosition == MAXCHILDS / 2) {
newRecordInsertPlace = 0;
} else {
newRecordInsertPlace = -1;
}
promotedIndex = MAXCHILDS / 2 - 1;
}
}
//Salva as informações do record a ser promovido em rec
record *rec = (record*)malloc(sizeof(record));
if(newRecordInsertPlace == 0) {
rec->key = newRecord->key;
rec->RRN = newRecord->RRN;
} else {
rec->key = bInfo->bPage->records[promotedIndex].key;
rec->RRN = bInfo->bPage->records[promotedIndex].RRN;
}
//Promove rec
*promoted = promoteKey(rec, bInfo->RRN, createdPage->RRN);
//Atualização das páginas, adicionar elementos na nova página e remover da antiga
if(newRecordInsertPlace == 1)
insertPageData(bInfo->bPage, createdPage->bPage, childsArray, promotedIndex);
else if(newRecordInsertPlace == 0)
insertPageData(bInfo->bPage, createdPage->bPage, childsArray, promotedIndex + 2);
else
insertPageData(bInfo->bPage, createdPage->bPage, childsArray, promotedIndex + 2);
if(newRecordInsertPlace == 1)
cleanPageData(bInfo->bPage, childsArray, promotedIndex);
else if(newRecordInsertPlace == 0)
cleanPageData(bInfo->bPage, childsArray, promotedIndex + 1);
else
cleanPageData(bInfo->bPage, childsArray, promotedIndex);
//Insere o novo registro no nó da direita
if(newRecordInsertPlace == 1) {
insertPosition -= MAXCHILDS / 2;
if(MaxChildsIsOdd) { insertPosition--; }
//Criar função separada para os for
for(int i = (MAXCHILDS-2); i > insertPosition; i--) {
createdPage->bPage->records[i].key = createdPage->bPage->records[i-1].key;
createdPage->bPage->records[i].RRN = createdPage->bPage->records[i-1].RRN;
}
createdPage->bPage->records[insertPosition].key = newRecord->key;
createdPage->bPage->records[insertPosition].RRN = newRecord->RRN;
}
//Insere o novo registro no nó da esquerda
else if(newRecordInsertPlace == -1) {
for(int i = (MAXCHILDS-2); i > insertPosition; i--) {
bInfo->bPage->records[i].key = bInfo->bPage->records[i-1].key;
bInfo->bPage->records[i].RRN = bInfo->bPage->records[i-1].RRN;
}
bInfo->bPage->records[insertPosition].key = newRecord->key;
bInfo->bPage->records[insertPosition].RRN = newRecord->RRN;
}
//Insere a nova página no arquivo da bTree
insertNodeInBTreeFile(createdPage, fp, createdPage->RRN);
}
else {
if(*promoted != NULL) {
//Precisa atualizar os filhos, houve overflow na iteração anterior
for(int i = (MAXCHILDS - 1); i > insertPosition; i--) {
if(i != MAXCHILDS - 1) {
bInfo->bPage->records[i].key = bInfo->bPage->records[i-1].key;
bInfo->bPage->records[i].RRN = bInfo->bPage->records[i-1].RRN;
}
bInfo->bPage->childs[i] = bInfo->bPage->childs[i-1];
}
bInfo->bPage->childs[insertPosition + 1] = (*promoted)->childs[1];
bInfo->bPage->childs[insertPosition] = (*promoted)->childs[0];
}
else {
//Não precisa mexer nos filhos
for(int i = (MAXCHILDS - 2); i > insertPosition; i--) {
bInfo->bPage->records[i].key = bInfo->bPage->records[i-1].key;
bInfo->bPage->records[i].RRN = bInfo->bPage->records[i-1].RRN;
}
}
bInfo->bPage->records[insertPosition].key = newRecord->key;
bInfo->bPage->records[insertPosition].RRN = newRecord->RRN;
bInfo->bPage->numRecords++;
*promoted = NULL;
}
}
// *Função para atualizar a raíz
int headerUpdate(promotedKey *promoted, FILE* bFile) {
bPageInfo *bInfo = (bPageInfo*)malloc(sizeof(bPageInfo));
bInfo->bPage = createPage();
fseek(bFile, 0, SEEK_END);
//Vai para o início do arquivo e cria uma nova página
bInfo->RRN = ftell(bFile) / PAGESIZE;
bInfo->bPage->isLeaf = 0;
//Aloca uma nova página
bTreeInsertIntoPage(promoted->rec, &promoted, bInfo, 0);
//Insere o promoted no nó criado
fseek(bFile, sizeof(int), SEEK_SET);
fwrite(&bInfo->RRN, PAGESIZE - sizeof(int), 1, bFile);
fflush(bFile);
//Atualiza o cabeçalho do arquivo da bTree
insertNodeInBTreeFile(bInfo, bFile, bInfo->RRN);
bInfo = getOrCreateRoot(bFile);
//Insere nova página no arquivo da bTree
return 0;
}