-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComandos.cpp
More file actions
1574 lines (1395 loc) · 52.4 KB
/
Comandos.cpp
File metadata and controls
1574 lines (1395 loc) · 52.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Comandos.h"
#include <vector>
#include <iostream>
#include <cstdlib>
#include "btree.h"
#include "hash.h"
#define MAXVETOR 100
using namespace std;
Comandos::Comandos() {}
string Comandos::horaatual(){
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
mktime (timeinfo);
return string(asctime(timeinfo));
}
string Comandos::convertToString(char* a, int size)
{
int i;
string s = "";
for (i = 0; i < size; i++) {
s = s + a[i];
}
return s;
}
int Comandos::existearquivoindice(string tabela, string tipoindice, string chave){
//VERIFICANDO SE A TABELA TEM INDICE HASH OU ARVORE PARA IGNORAR
//COMENTADO ESSA PARTE POIS FOI IMPLEMENTADO QUE O REGISTRO ESTA INSERINDO MSM COM A HASH
char LOCAL_DIR[FILENAME_MAX];
if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR))) {
string erro = "Erro ao tentar encontrar o local de instalação do programa";
cout << erro;
return 0;
}
DIR *dir;
struct dirent *lsdir;
string diretoriolocal = LOCAL_DIR;
int i = 0, controleqt = 0;
diretoriolocal = diretoriolocal + "/tabelas/";
dir = opendir(diretoriolocal.c_str());
string tabelatemp = tabela + tipoindice + chave; // tabela + 6 de tamanho + chave
while ( ( lsdir = readdir(dir) ) != NULL ) {
i = 0;
controleqt = 0;
//cout << lsdir->d_name << endl;
while(controleqt++ != int(tabelatemp.length()+1)){
if(tabelatemp[i] == lsdir->d_name[i]){
if((i+1) == int(tabelatemp.length())){
return 1;
}
}
else{
break;
}
i++;
}
}
closedir(dir);
return 0;
}
int Comandos::criarArquivoComNomeTabela(string tabela, string* campos) {
// verificar se existe tabela com nome igual
ifstream arquivo_base;
arquivo_base.open("./tabelas/base.txt");
if (arquivo_base.is_open()) {
// verificar se ja existe uma tabela com o mesmo nome
string linha;
while (getline(arquivo_base, linha)) {
if (linha == tabela) {
cout << "Tabela já existe. Terminando execução.\n";
return FINISH_PROGRAM;
}
}
}
ofstream base;
base.open("./tabelas/base.txt", ios_base::app);
if (base.is_open()) {
base << tabela << endl;
base.close();
} else {
cout << "Erro ao criar arquivo base.txt\n";
}
string tab = "tabelas/", meta = "tabelas/";
tab.append(tabela + "_TAB.txt");
meta.append(tabela + "_META.txt");
ofstream(tab.c_str());
ofstream(meta.c_str());
ofstream arquivo_meta;
arquivo_meta.open(meta, ios_base::app);
int j = 1;
cout << "Criando tabela com nome: " << tabela << "\n";
// -1|||||||| é o ponteiro para a primeira ocorrencia de um registro removido (-1 pq nao existe)
arquivo_meta << tabela << ";" << "-1||||||||" << ";" << int(campos[0][0]) << ";";
cout << "Campos:" << " " << int(campos[0][0]) << ";" ;
for(int i = 0; i < int(campos[0][0]); i++){
cout << "TIPO: " << campos[j] << ", NOME: " << campos[j + 1] << endl;
arquivo_meta << campos[j] << ":" << campos[j + 1] << ";";
j += 2;
}
arquivo_meta << Comandos::horaatual();
arquivo_meta.close();
return SUCCESS;
}
int Comandos::apagaArquivoComNomeTabela(string tabela) {
string base = "./tabelas/base.txt";
ifstream arquivo_base;
arquivo_base.open(base);
// tenta abrir arquivo base e temp
if (!arquivo_base.is_open()) {
cout << "Erro ao abrir arquivo base.txt\n";
return FINISH_PROGRAM;
}
// verificar se tabela existe
string linha;
bool existe = false;
while (getline(arquivo_base, linha) && !existe) {
if (linha == tabela)
existe = true;
}
if (!existe) {
cout << "Tabela: " + tabela + " não existe!" << endl
<< "Finalizando execução." << endl;
return FINISH_PROGRAM;
}
// tenta remover arquivo com tabela e metadados
string arquivo_tabela = "./tabelas/" + tabela + "_TAB.txt";
string arquivo_meta = "./tabelas/" + tabela + "_META.txt";
if (remove(arquivo_tabela.c_str()) != 0) {
cout << "Erro ao tentar remover arquivo: " << arquivo_tabela << "\n";
return FINISH_PROGRAM;
}
if (remove(arquivo_meta.c_str()) != 0) {
cout << "Erro ao tentar remover arquivo: " << arquivo_meta << "\n";
return FINISH_PROGRAM;
} else {
ofstream temp;
temp.open("./tabelas/temp.txt");
// copia e remocao de dados da tabela para novo arquivo temp
cout << "Apagando tabela " << tabela << "\n";
string input;
while (getline(arquivo_base, input)) {
if (input != tabela)
temp << input << endl;
}
arquivo_base.close();
temp.close();
if (remove(base.c_str()) != 0) {
cout << "Erro ao tentar remover arquivo.\n";
}
rename("./tabelas/temp.txt", "./tabelas/base.txt");
}
//Retirado de https://pt.stackoverflow.com/questions/47130/como-obter-o-diret%C3%B3rio-que-o-programa-est%C3%A1-sendo-executado
//Recupera onde o programa está sendo executado, parecido com getpwd()
char LOCAL_DIR[FILENAME_MAX];
if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR))) {
string erro = "Erro ao tentar encontrar o local de instalação do programa";
cout << erro;
return 0;
}
//Adaptado junto com o codigo que le os arquivos de dentro da pasta
//https://www.hardware.com.br/comunidade/arquivos-varrer/1103524/
DIR *dir;
struct dirent *lsdir;
string diretoriolocal = LOCAL_DIR, apagando;
int i = 0, controleqt = 0;
//Adapta para o diretorio onde esta as tabelas
diretoriolocal = diretoriolocal + "/tabelas/";
dir = opendir(diretoriolocal.c_str());
/* Imprime e apaga os arquivos referente a tabela do diretorio tabelas */
while ( ( lsdir = readdir(dir) ) != NULL ) {
i = 0;
controleqt = 0;
while(controleqt++ != int(tabela.length()+1)){
if(tabela[i] == lsdir->d_name[i]){
if((i+1) == int(tabela.length())){
apagando = diretoriolocal;
apagando = apagando + lsdir->d_name;
remove(apagando.c_str());
}
}
else{
break;
}
i++;
}
}
closedir(dir);
return SUCCESS;
}
void Comandos::resumoDaTabela(string tabela) {
cout << "Resumo da tabela " << tabela << endl;
string meta = "tabelas/";
meta.append(tabela);
meta.append("_META.txt");
string linha;
ifstream arquivo;
arquivo.open(meta);
if (arquivo.is_open()) {
while (!arquivo.eof() ) {
getline(arquivo,linha);
cout << linha << endl;
}
arquivo.close();
}
else{
cout << "Erro ao tentar ler resumo de tabela" << endl;
}
}
void Comandos::listarTabelas() {
ifstream base;
base.open("./tabelas/base.txt");
if (base.is_open()) {
string linha;
while (getline(base, linha)) {
cout << linha << "\n";
}
}
else{
cout << "Erro ao tentar ler lista de tabelas" << endl;
}
}
// retirado de https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c
bool is_number(const std::string& s) {
return !s.empty() && std::find_if(s.begin(),
s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}
void Comandos::inserirRegistro(string tabela, string registro) {
auto par_meta = getVetorDeMetadados(tabela, true);
vector<string> metadados = par_meta.first;
vector<string> indices_meta = par_meta.second;
size_t quantidade_de_campos = stoi(metadados[2]);
// cout << "Inserir registro " << registro << " na tabela " << tabela << '\n';
// vetor em que cada entrada é um campo da inserção
vector<string> inserir = parseInsercao(registro);
if (quantidade_de_campos != inserir.size())
{
cout << "ERRO IMPOSSÍVEL INSERIR NA TABELA: Quantidade incorreta de campos para inserir\n";
return;
}
//VERIFICANDO SE A TABELA TEM INDICE HASH OU ARVORE PARA IGNORAR
//COMENTADO ESSA PARTE POIS FOI IMPLEMENTADO QUE O REGISTRO ESTA INSERINDO MSM COM A HASH
char LOCAL_DIR[FILENAME_MAX];
if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR))) {
string erro = "Erro ao tentar encontrar o local de instalação do programa";
cout << erro;
return;
}
DIR *dir;
struct dirent *lsdir;
string diretoriolocal = LOCAL_DIR;
int i = 0, controleqt = 0;
diretoriolocal = diretoriolocal + "/tabelas/";
dir = opendir(diretoriolocal.c_str());
string tabelatemp = tabela + "_HASH_"; // tabela + 6 de tamanho
while ( ( lsdir = readdir(dir) ) != NULL ) {
i = 0;
controleqt = 0;
//cout << lsdir->d_name << endl;
while(controleqt++ != int(tabelatemp.length()+1)){
if(tabelatemp[i] == lsdir->d_name[i]){
if((i+1) == int(tabelatemp.length())){
//cout << "tem hash" << endl;
return;
}
}
else{
break;
}
i++;
}
}
closedir(dir);
// vetor com indices (se houver)
vector<string> indices;
// vetor com tipos de indices (se houver)
vector<string> tipos;
// vetor com indice (literalmente) do registro a ser inserido (se houver indice)
vector<int> index;
for (size_t i = 0; i < quantidade_de_campos; i++)
{
string campo = metadados[3+i]; // 3 é a posição do primeiro campo
string tipo = retornaPalavraDeInput(campo, ':');
if (tipo == "INT")
{
if(is_number(inserir[i]) == false) {
cout << "ERRO TIPO INCORRETO: TIPO INCORRETO DE DADOS NO CAMPO " << i << '\n';
return;
}
}
// transforma campo no nome do campo removendo o ':'
campo = campo.erase(0, 1);
// verificar se existe indice para o campo
for (int j = 0; j < indices_meta.size(); j++) {
string indice_campo = indices_meta[j].substr(0, indices_meta[j].find(' '));
string indices_tipos = indices_meta[j].substr(indices_meta[j].find(' ') + 1, indices_meta[j].size());
// adiciona no vetor se indice existir
if (campo == indice_campo) {
indices.push_back(indice_campo);
tipos.push_back(indices_tipos);
index.push_back(i);
}
}
}
// bestFit retorna (0, ponteiro) caso nao exista espacos marcados como invalido
// neste caso, a insercao ocorre no fim do arquivo (onde ponteiro marca),
// ou (1, ponteiro) caso bestFit tenha funcionado e o ponteiro onde foi inserido
auto par = bestFit(tabela, inserir);
int sucesso = par.first;
int ponteiro = par.second;
if (sucesso == 0) {
ofstream file;
file.open("tabelas/" + tabela + "_TAB.txt", ios_base::app);
if (file.fail()) {
// TODO o arquivo não existe (a tabela não foi criada)
std::cout << "ERRO" << '\n';
return;
}
// escrever no arquivo cada entrada do vetor inserir
int tamanho_insercao = 0;
for (auto reg : inserir) {
tamanho_insercao += reg.size();
file << reg << ';';
}
tamanho_insercao = MIN_SIZE - ++tamanho_insercao;
for (int i = 0; i < tamanho_insercao; i++) {
file << '|';
}
file << '\n';
file.close();
}
int trigger = 0;
// inserir nas tabelas de indice
// cout << "INDICES" << endl;
for (int i = 0; i < indices.size(); i++) {
if (tipos[i] == "A" && trigger == 0) {
// inserir em arvore
trigger = 1;
int temp = stoi(inserir[index[i]]);
cout << "Arvore" << endl;
cout << "Inserindo: " << inserir[index[i]] << " na arvore de " << indices[i] << " com ponteiro " << ponteiro << endl;
string TreeFileName;
//nome do arquivo bin
TreeFileName = tabela + "_TREE_" + indices[i] ;
int n = TreeFileName.length();
char char_array[n + 1];
strcpy(char_array, TreeFileName.c_str());
cout << char_array << endl;
Btree t(char_array);
t.insert(char_array, temp, 0);
//btree->print();
/*Btree t(char_array);
if(t.insert(char_array, temp, 0)){
geraNovoIndiceDeTabelaChave(tabela, indices[i]);
}*/
}
}
}
bool linhaInvalida(string linha) {
return linha.find('#') != string::npos;
}
// Função para verificar se um indice em uma dada tabela possui função hash
// retorna true se possui, false caso contrário
bool Comandos::possuiHash(string tabela, string indice) {
vector<string> indices = getVetorDeMetadados(tabela, true).second;
for (auto &ind: indices) {
if (ind.find(indice) != string::npos && ind.find(" H") != string::npos) return true;
}
return false;
}
// Função para verificar se um indice uma dada tabela possui arvore
// retorna true se possui, false caso contrário
bool Comandos::possuiArvore(string tabela, string indice) {
vector<string> indices = getVetorDeMetadados(tabela, true).second;
for (auto &ind: indices) {
if (ind.find(indice) != string::npos && ind.find(" A") != string::npos) return true;
}
return false;
}
void Comandos::buscaEmTabela(string modifier, string tabela, string busca) {
ifstream file; //Leitura do arquivo
struct busca busca_aux;
vector<int> vet_buscas;
file.open("tabelas/" + tabela + "_TAB.txt");
if (file.fail()) {
// TODO o arquivo não existe (a tabela não foi criada)
std::cout << "Não foi possível encontrar a Tabela." << '\n';
return;
}
auto par = getVetorDeMetadados(tabela);
vector<string> linha_meta_dados = par.first;
// Retira o tipo dos campo, mantendo somente o nome do campo
vector<string> nomes_campos;
unsigned int quantidade_de_campos = stoi(linha_meta_dados[2]);
//parse do campo selecionado para busca
size_t pos_dois_pontos = busca.find(":"); //Posição dos ":"
string campo_b = busca.substr(0, pos_dois_pontos); //Separa o início da string até ":"
string elemento_b = busca.substr(pos_dois_pontos + 1); //Separa o ":" até o fim
bool existe_campo = false; // Verificador da existência do campo
unsigned int i = 0;
int indice_campo; // Armazena a posição do campo que foi encontrado na busca
// checa se o campo_b é um inteiro, se for, verifique se existe hash ou árvore.
// Senão, utilize a busca normal.
bool hash = false;
bool arvore = false;
int elemento_int;
if (is_number(elemento_b) == true) {
elemento_int = stoi(elemento_b);
// checa se o indice campo_b possui hash. A verificação da hash acontece primeiro pois
// é mais eficiente, e decidimos por ser preferencial em relação à árvore.
if (possuiHash(tabela, campo_b)) {
cout << "Possui hash do indice: " << campo_b << "." << endl;
hash = true;
}
// checa se o indice campo_b possui arvore
else if (possuiArvore(tabela, campo_b)) {
cout << "possui arvore do indice: " << campo_b << endl;
arvore = true;
}
// caso não tenha hash nem arvore, faz a busca sequencial
}
//Percorre todos os campos presentes no meta, e ao encontrar o campo necessário pra busca, armazena sua posição em indice_campo
while (i < quantidade_de_campos) {
size_t pos_dois_pontos = linha_meta_dados[3 + i].find(":");
string campo = linha_meta_dados[3 + i].substr(pos_dois_pontos + 1);
nomes_campos.push_back(campo); //Insere o nome do campo no vetor
// Se o campo for igual ao campo da busca, armazena a posição
if (campo == campo_b) {
indice_campo = i;
existe_campo = true;
}
i++;
}
if (!existe_campo) {
cout << "Não foi possível encontrar o campo" << endl;
return;
}
// Linha busca = 1;2;3;4;
// Vetor = [1, 2, 3, 4]
string linha_busca;
vector<string> vetor_linha_busca;
int pos_do_char = 0; // posição do ponteiro pro fseek
bool encontrou = false;
bool existe_nas_buscas = false;
if (modifier == "N") {
cout << "Busca em " << tabela << " todos com critério " << busca
<< '\n';
if (hash == false && arvore == false) {
// busca no arquivo
do {
getline(file, linha_busca); //Armazena a linha em linha_busca
int tamanho_da_linha = linha_busca.length();
// Ignora linha inválida
if (linhaInvalida(linha_busca)) {
cout << "ignorado" << '\n';
pos_do_char += tamanho_da_linha + SO;
continue;
}
vetor_linha_busca = parseBuscaMetaDados(linha_busca); //Armazena os campos da linha atual
//Evita segmentation fault quando pega uma linha vazia.
if (linha_busca != "") {
if (vetor_linha_busca[indice_campo] == elemento_b) {
//Compara o conteúdo do campo com o conteúdo da busca
encontrou = true;
busca_aux.linhas.push_back(pos_do_char);
}
}
pos_do_char += tamanho_da_linha + SO;
} while (!file.eof());
}
else if (hash == true) {
// busca na hash
cout << "buscando na hash" << endl;
// vector com ocorrencias onde a busca foi encontrada
vector<int> ponteiro = buscaPonteiroN(tabela, campo_b, elemento_int);
if (ponteiro.size() > 0) { // se encontrou pelo menos um
encontrou = true;
for (int i = 0; i < ponteiro.size(); i++) {
busca_aux.linhas.push_back(ponteiro[i]);
}
}
}
else if (arvore == true) {
// busca na arvore
}
}
else if (modifier == "U") {
cout << "Busca em " << tabela << " primeiro com critério " << busca
<< '\n';
// Busca até encontrar o primeiro campo igual ao conteúdo da busca
if (hash == false && arvore == false) {
// busca no arquivo
do {
getline(file, linha_busca); //Armazena a linha em linha_busca
int tamanho_da_linha = linha_busca.length();
// Ignora linha inválida
if (linhaInvalida(linha_busca)) {
//cout << "ignorado" << '\n';
pos_do_char += tamanho_da_linha + SO;
continue;
}
vetor_linha_busca = parseBuscaMetaDados(linha_busca); //Armazena os campos da linha atual
//Evita segmentation fault quando pega uma linha vazia.
if (linha_busca != "") {
if (vetor_linha_busca[indice_campo] == elemento_b) {
//Compara o conteúdo do campo com o conteúdo da busca
encontrou = true;
busca_aux.linhas.push_back(pos_do_char);
}
}
pos_do_char += tamanho_da_linha + SO;
} while (!file.eof() && !encontrou);
}
else if (hash == true) {
// busca na hash
cout << "buscando na hash" << tabela << campo_b << elemento_int << endl;
int ponteiro = buscaPonteiroU(tabela, campo_b, elemento_int);
if (ponteiro != -1) {
encontrou = true;
busca_aux.linhas.push_back(ponteiro);
}
}
else if (arvore == true) {
// busca na arvore
string TreeFileName;
//nome do arquivo bin
TreeFileName = tabela + "_TREE_" + campo_b ;
/*
int n = TreeFileName.length();
char char_array[n + 1];
strcpy(char_array, TreeFileName.c_str());
cout << char_array << endl;*/
Btree t(TreeFileName);
//Btree * btree = new Btree(char_array);
//btree->ShowSearch(elemento_int);
t.ShowSearch(elemento_int);
//geraNovoIndiceDeTabelaChave(tabela, campo_b);
// busca no arquivo
do {
getline(file, linha_busca); //Armazena a linha em linha_busca
int tamanho_da_linha = linha_busca.length();
// Ignora linha inválida
if (linhaInvalida(linha_busca)) {
cout << "ignorado" << '\n';
pos_do_char += tamanho_da_linha + SO;
continue;
}
vetor_linha_busca = parseBuscaMetaDados(linha_busca); //Armazena os campos da linha atual
//Evita segmentation fault quando pega uma linha vazia.
if (linha_busca != "") {
if (vetor_linha_busca[indice_campo] == elemento_b) {
//Compara o conteúdo do campo com o conteúdo da busca
encontrou = true;
busca_aux.linhas.push_back(pos_do_char);
}
}
pos_do_char += tamanho_da_linha + SO;
} while (!file.eof() && !encontrou);
}
}
else { // Modificador incorreto
cout << "Modificador não reconhecido: " << modifier << ". Utilize N para fazer a busca, na tabela, de todos os registros que satisfaçam o critério de busca e U para fazer a busca, na tabela, do primeiro registro que satisfaça o critério. \n";
return;
}
if (encontrou) {
if(!buscas.size()){
busca_aux.nome_tabela = tabela;
buscas.push_back(busca_aux);
}
else{
i = 0;
while(i < buscas.size() && !existe_nas_buscas){
if(buscas[i].nome_tabela == tabela){
buscas[i].linhas = busca_aux.linhas;
existe_nas_buscas = true;
}
i++;
}
if(!existe_nas_buscas){
busca_aux.nome_tabela = tabela;
buscas.push_back(busca_aux);
}
}
cout << "REGISTRO ENCONTRADO" << endl;
}
else {
cout << "REGISTRO NÃO ENCONTRADO" << endl;
}
}
void Comandos::apresentarRegistrosUltimaBusca(string tabela) {
// ifstream file; //Leitura do arquivo
// file.open("tabelas/" + tabela + "_TAB.txt");
FILE *fp;
fp = fopen(("tabelas/" + tabela + "_TAB.txt").c_str(), "r");
if (fp == NULL) {
// TODO o arquivo não existe (a tabela não foi criada)
std::cout << "Não foi possível encontrar a Tabela." << '\n';
return;
}
//0 = Nome Tabela / 1 = path txt meta / 2 = qtd de campos / 3 até 3+qtd de campos = campos / ultimo = data
auto par = getVetorDeMetadados(tabela);
vector<string> linha_meta_dados = par.first;
// Retira o tipo dos campo, mantendo somente o nome do campo
vector<string> nomes_campos;
unsigned int i = 0;
unsigned int quantidade_de_campos = stoi(linha_meta_dados[2]);
//Percorre todos os campos presentes no meta, e ao encontrar o campo necessário pra busca, armazena sua posição em indice_campo
while (i < quantidade_de_campos){
size_t pos_dois_pontos = linha_meta_dados[3+i].find(":");
string campo = linha_meta_dados[3+i].substr(pos_dois_pontos+1);
nomes_campos.push_back(campo);
i++;
};
bool existe_busca = false;
vector<int> linhas;
cout << "Apresentar registro da última busca em " << tabela << '\n';
if(buscas.size()){
for(i = 0; i < buscas.size(); i++){
if(buscas[i].nome_tabela == tabela){
existe_busca = true;
linhas = buscas[i].linhas;
}
}
}
if(existe_busca){
string resultado;
i = 0;
int linhas_restantes = linhas.size();
while(linhas_restantes--) {
fseek(fp, linhas[i], SEEK_SET);
i++; // próximo elemento do vetor de linhas encontradas;
char tmp[1000000] = {'\n'}; // pode dar problema no tamanho máximo quando tiver o BIN e ele for muito grande.
fscanf(fp, "%[^\n^|]", tmp); // ler a linha atual até | ou \n https://www.quora.com/How-can-I-make-scanf-keep-receiving-characters-until-one-particular-character
resultado = tmp; // convertendo c string para c++ string https://stackoverflow.com/questions/4764897/converting-a-c-style-string-to-a-c-stdstring
for (int k = 0; k < nomes_campos.size(); k++){
cout << nomes_campos[k] << ": " << retornaPalavraDeInput(resultado, ';') << " ";
}
cout << endl;
}
// while(getline(file, resultado) && j < linhas.size()){
// if(i == linhas[j]){
// for (k = 0; k < nomes_campos.size(); k++){
// cout << nomes_campos[k] << ": " << retornaPalavraDeInput(resultado, ';') << " ";
// }
// cout << endl;
// j++;
// }
// i++;
// }
}
else{
cout << "Nenhuma pesquisa referente a essa tabela foi encontrada." << endl;
}
}
void Comandos::removeRegistrosUltimaBusca(string tabela){
auto par_meta = getVetorDeMetadados(tabela, true); //retorna um par com <vetor com os metadados da tabela,indices existentes da tabela c/ o tipo>
vector<string> metadados = par_meta.first;
vector<string> indices_meta = par_meta.second; //vector com cada linha sendo "nomeIndice tipoIndice"
// ponteiro_head: ponteiro para o primeiro registro invalido (salvo nos metadados)
int ponteiro_head = stoi(metadados[1].substr(0, metadados[1].find('|')));
size_t qtd_campo = stoi(metadados[2]);
vector<string> indices; //vector que guarda os indices
vector<string> tipos; //vector que guarda os tipos de cada indice
vector<vector<string>> reg_removido; //guarda os registros que serao removidos dos indices
vector<int> campo_indexado; //indica o(s) campo(s) indexado(s) nessa tabela
vector<int> ponteiro;
char LOCAL_DIR[FILENAME_MAX];
if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR))) {
string erro = "Erro ao tentar encontrar o local de instalação do programa";
cout << erro;
return;
}
//VERIFICANDO SE TEM ARQUIVO HASH PARA IGNORAR A REMOÇÃO
DIR *dir;
struct dirent *lsdir;
string diretoriolocal = LOCAL_DIR;
int i = 0, controleqt = 0;
diretoriolocal = diretoriolocal + "/tabelas/";
dir = opendir(diretoriolocal.c_str());
string tabelatemp = tabela + "_HASH_"; // tabela + 6 de tamanho
while ( ( lsdir = readdir(dir) ) != NULL ) {
i = 0;
controleqt = 0;
//cout << lsdir->d_name << endl;
while(controleqt++ != int(tabelatemp.length()+1)){
if(tabelatemp[i] == lsdir->d_name[i]){
if((i+1) == int(tabelatemp.length())){
return;
}
}
else{
break;
}
i++;
}
}
closedir(dir);
int tab=0;
while(tabela != buscas[tab].nome_tabela || tab == buscas.size())
tab++;
if(tab == buscas.size()){
cout << "erro" << endl;
return;
}
string arquivo_tab = "tabelas/" + tabela + "_TAB.txt";
for (size_t i = 0; i < buscas[tab].linhas.size(); i++) {
ifstream arquivo;
arquivo.open(arquivo_tab);
arquivo.seekg(0, ios::beg);
// anterior: registro que esteja antes do removido
// atual: registro a ser removido
// posterior: registro que esteja apros o removido
int pos = 0;
Comandos::Removido anterior;
anterior.pos = -1;
Comandos::Removido atual;
Comandos::Removido posterior;
posterior.pos = -1;
int global_pos = 0; // ponteiro global e equivalente a linha em que a busca deve aparecer
int qtd_linha = -1;
string linha;
while (getline(arquivo, linha) && posterior.pos == -1) {
qtd_linha++;
global_pos = pos + (SO * qtd_linha);
if (global_pos == buscas[tab].linhas[i]) {
atual.pos = pos + (SO * qtd_linha);
atual.tamanho = linha.size();
atual.conteudo = linha;
reg_removido.push_back(parseInsercao(linha));
ponteiro.push_back(pos + 1);
} else {
if (global_pos < buscas[tab].linhas[i] && linha.find('#') != string::npos) {
anterior.pos = pos + (SO * qtd_linha);
anterior.tamanho = linha.size();
anterior.conteudo = linha;
}
else if (global_pos > buscas[tab].linhas[i] && linha.find('#') != string::npos) {
posterior.pos = pos + (SO * qtd_linha);
posterior.tamanho = linha.size();
posterior.conteudo = linha;
}
}
pos += linha.size();
}
arquivo.close();
// se o registro removido veio antes do ponteiro_head entao atualize o ponteiro_head para o atual
// atualize tmb os metadados assim que terminar o loop
if (atual.pos < ponteiro_head || ponteiro_head == -1)
ponteiro_head = atual.pos;
FILE *fp;
fp = fopen(arquivo_tab.c_str(), "r+");
// se existe um registro anterior (removido), altere o ponteiro do anterior para o atual
// e o ponteiro do atual.prox para aquele que o anterior apontava
// atual.prox -> anterior.prox & anterior.prox -> atual
if (anterior.pos != -1) {
retornaPalavraDeInput(anterior.conteudo, '#');
anterior.conteudo.erase(0, 1);
atual.prox = stoi(anterior.conteudo.substr(0, linha.find('#')));
anterior.prox = atual.pos;
anterior.buffer = to_string(anterior.tamanho) + "#" + to_string(anterior.prox) + '#';
fseek(fp, anterior.pos, SEEK_SET);
fprintf(fp, anterior.buffer.c_str());
}
atual.prox = posterior.pos;
atual.buffer = to_string(atual.tamanho) + '#' + to_string(atual.prox) + '#';
fseek(fp, atual.pos, SEEK_SET);
fprintf(fp, atual.buffer.c_str());
fclose(fp);
}
alterarPonteiroHead(tabela, ponteiro_head);
// checar se exsite indice
for (size_t i = 0; i < qtd_campo; i++){
string campo = metadados[3+i]; // 3 é a posição do primeiro campo
// transforma campo no nome do campo removendo o tipo seguido do ':'
campo = campo.erase(0, 4);
// verificar se existe indice para o campo
for (size_t j = 0; j < indices_meta.size(); j++) {
string indice_campo = indices_meta[j].substr(0, indices_meta[j].find(' '));
string indices_tipos = indices_meta[j].substr(indices_meta[j].find(' ') + 1, indices_meta[j].size());
// adiciona no vetor se indice existir
if (campo == indice_campo) {
indices.push_back(indice_campo);
tipos.push_back(indices_tipos);
campo_indexado.push_back(i);
}
}
}
//Removendo da arvore
string TreeFileName;
//nome do arquivo bin
TreeFileName = tabela + "_TREE_" + indices[i] ;
/*
int n = TreeFileName.length();
char char_array[n + 1];
strcpy(char_array, TreeFileName.c_str());
cout << char_array << endl;
*/
Btree t(TreeFileName);
for(size_t i = 0; i < reg_removido.size(); i++){
for (size_t j = 0; j < indices.size(); j++) {
if (tipos[j] == "A") {
// remove na arvore
cout << "Removendo: " << reg_removido[i][campo_indexado[j]] << " com ponteiro " << ponteiro[i] << " na ARVORE de " << indices[j] << "." << endl;
cout << "Arvore" << endl;
t.DelNode(stoi(reg_removido[i][campo_indexado[j]]));
//geraNovoIndiceDeTabelaChave(tabela, indices[i]);
}
}
}
t.print();
}
int Comandos::criaIndice(string modifier, string tabela, string chave) {
string meta = "./tabelas/" + tabela + "_META.txt";
// verificar se a chave e valida
ifstream arquivo;
arquivo.open(meta);
// qtd de ";" ate os campos (ate o numero que indica a quantidade de campos)
int qtd_ate_campos = 2;
// qtd de campos
int qtd_campos;
string linha;
getline(arquivo, linha);
for (int i = 0; i < qtd_ate_campos; i++) {
retornaPalavraDeInput(linha, ';');
} linha.erase(0, 1);
qtd_campos = stoi(linha.substr(0, linha.find(';')));
// deixa a linha contendo apenas os campos em diante
retornaPalavraDeInput(linha, ';');
linha.erase(0, 1);
// armazena o tipo de cada campo em uma posicao do vector
string campos;
string tipo;
for (int i = 0; i < qtd_campos && campos != chave; i++) {
tipo = retornaPalavraDeInput(linha, ':');
linha.erase(0, 1);
campos = retornaPalavraDeInput(linha, ';');
linha.erase(0, 1);
}
if (campos != chave) {
cout << "Erro: Campo invalido.\nTerminando execução." << endl;
return FINISH_PROGRAM;
}
if (tipo != "INT") {
cout << "Erro: Apenas campos inteiros (INT) podem ser indexados." << endl;
return SUCCESS;
}
// verificar se o indice ja existe
while (getline(arquivo, linha)) {
string campo_encontrado;
string tipo_encontrado;
campo_encontrado = retornaPalavraDeInput(linha, ' ');
linha.erase(0, 1);
tipo_encontrado = linha;
// se o indice ja existe && tipo do indice ja existe
if (campo_encontrado == campos && tipo_encontrado == modifier) {
cout << "Erro: Índice já existe. Comando ignorado." << endl;
return SUCCESS;
}
}
arquivo.close();
// insere indice e tipo no arquivo de metadados
ofstream arquivo_meta;
arquivo_meta.open(meta, ios::app);
arquivo_meta << campos + ' ' + modifier << endl;
arquivo_meta.close();
if (modifier == "A") {
cout << "Cria um índice estruturado para " << tabela
<< " usando a chave " << chave << '\n';
string TreeFileName;
//nome do arquivo bin
TreeFileName = tabela + "_TREE_" + chave;
/*int n = TreeFileName.length();
char char_array[n + 1];
strcpy(char_array, TreeFileName.c_str());
*/
Btree t(TreeFileName);
//INSERIR na arvore
// https://stackoverflow.com/questions/3482064/counting-the-number-of-lines-in-a-text-file
// A Hash recebe como argumento o número de elementos que vão ser adicionados.