forked from laisborin/bufferpoll_BDII
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
510 lines (395 loc) · 13.2 KB
/
main.c
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "buffend.c"
int menu();
void insereChaves(){
int erro;
column *c = NULL;
c = insereValor(c, "TabelaOrigem", "Cargo");
c = insereValor(c, "ID", "4");
c = insereValor(c, "Tipo", "P");
c = insereValor(c, "TabelaDestino", "");
c = insereValor(c, "CampoOrigem", "CodCarg");
c = insereValor(c, "CampoDestino", "");
c = insereValor(c, "TabelaOrigem", "Funcionario");
c = insereValor(c, "ID", "2");
c = insereValor(c, "Tipo", "P");
c = insereValor(c, "TabelaDestino", "");
c = insereValor(c, "CampoOrigem", "CodFunc");
c = insereValor(c, "CampoDestino", "");
c = insereValor(c, "TabelaOrigem", "Funcionario");
c = insereValor(c, "ID", "5");
c = insereValor(c, "Tipo", "F");
c = insereValor(c, "TabelaDestino", "Cargo");
c = insereValor(c, "CampoOrigem", "CodCarg");
c = insereValor(c, "CampoDestino", "CodCarg");
erro = finalizaInsert("BD_Chaves", c);
if(erro == ERRO_VIOLACAO_PK){
printf("\nErro %d: A tabela ja possui chave primaria(PK) !\n",erro);
}else if(erro != SUCCESS){
printf("Erro %d: na função finalizaInsert()\n", erro);
return;
}
}
int buscar_tabela(char tabela[], char busca[]){
int erro;
struct fs_objects objeto = leObjeto(tabela);
tp_table *esquema = leSchema(objeto);
if(esquema == ERRO_ABRIR_ESQUEMA){
printf("Erro ao criar o esquema.\n");
return 0;
}
tp_buffer *bufferpoll = initbuffer();
if(bufferpoll == ERRO_DE_ALOCACAO){
printf("Erro ao alocar memória para o buffer.\n");
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 0, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 1, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 2, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
column *pagina = getPage(bufferpoll, esquema, objeto, 0);
if(pagina == ERRO_PARAMETRO){
printf("Erro, na função getPage(), problemas no parametro.\n");
return 0;
}
// Impressão dos dados da tupla buscada
int j=0,y=0,aux=0;
for(j=0; j < objeto.qtdCampos*bufferpoll[0].nrec; j++){
//Caso for string, compara com o campo buscado
if(pagina[j].tipoCampo == 'S'){
if (strcmp (pagina[j].valorCampo, busca) == 0){
aux = 1;
printf("Tupla encontrada! Os dados serão mostrados abaixo:\n\n");
for(y=j;y<j+objeto.qtdCampos;y++){
if(pagina[y].tipoCampo == 'S')
printf("%s: %s ", pagina[y].nomeCampo,pagina[y].valorCampo);
else if(pagina[y].tipoCampo == 'I'){
int *n = (int *)&pagina[y].valorCampo[0];
printf("%s: %d ",pagina[y].nomeCampo, *n);
}
else if(pagina[y].tipoCampo == 'C'){
printf("%s: %c ",pagina[y].nomeCampo, pagina[y].valorCampo[0]);
}
else if(pagina[y].tipoCampo == 'D'){
double *n = (double *)&pagina[y].valorCampo[0];
printf("%s: %.2f ",pagina[y].nomeCampo, *n);
}
printf("\n");
}
printf("\n");
}
}
}
//Verifica se encontrou nome buscado
if(aux==0)
printf("'%s' não foi encontrado na tabela %s!\n",busca,tabela);
//~ erro = printbufferpoll(bufferpoll, esquema, objeto, 0);
//~ if(erro != SUCCESS){
//~ printf("Erro %d: na função printbufferpoll().\n", erro);
//~ return 0;
//~ }
return 1;
}
int consultar(){
char *tabela=(char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
char busca[20];
char arquivo_dados[20];
printf("\(Tabelas Padroes: Funcionario, Produto, Cargo, BD_Chaves(pk/fks)");
printf("\nDeseja consultar os dados de qual tabela?\n");
scanf("%s",tabela);
//Verifica se tabela existe no dicionário
if(!verificaNomeTabela(tabela)){
printf("\nErro: A Tabela informada nao existe!\n");
return 0;
}
strcpy(arquivo_dados,tabela);
strcat(arquivo_dados,".dat");
if(!existe_arquivo(arquivo_dados)){
printf("\nErro: Nao existem tuplas cadastradas nesta tabela! (Tabela Vazia)\n");
return 0;
}
if(strcmp(tabela, "BD_Chaves") == 0)
printf("\nVoce selecionou Consultar as Chaves(PK/FK)!\nDigite a tabela que deseja consultar as chaves:\n");
else
printf("\nVoce selecionou Consultar!\n(Consulte a documentacao parte 2 para ver possiveis buscas)\nDigite o nome/descricao que deseja consultar:\n");
scanf(" %s",busca);
printf("\nVoce esta buscando por %s em %s\n",busca,tabela);
buscar_tabela(tabela,busca);
return 1;
}
//tipo_tabela utilizado apenas enquanto dados forem criados de forma estatica
int criar_tabela(char nomeTabela[], int tipo_tabela){
int erro;
table *t = NULL;
column *c = NULL;
t = iniciaTabela(nomeTabela);
if(t == ERRO_NOME_TABELA_INVALIDO){
printf("Erro: na função iniciaTabela(). A tabela %s já existe.\n",nomeTabela);
return 0;
}
switch(tipo_tabela){
case 1://Funcionarios
t = adicionaCampo(t, "Nome", 'S', 20);
t = adicionaCampo(t, "CodFunc", 'I', (sizeof(int)));
t = adicionaCampo(t, "Sexo", 'C', (sizeof(char)));
t = adicionaCampo(t, "Obs", 'S', 40);
t = adicionaCampo(t, "CodCarg", 'I', (sizeof(double)));
break;
case 2://Produtos
t = adicionaCampo(t, "Produto", 'S', 20);
t = adicionaCampo(t, "CodProd", 'I', (sizeof(int)));
t = adicionaCampo(t, "Novo", 'C', (sizeof(char)));
t = adicionaCampo(t, "Descricao", 'S', 40);
t = adicionaCampo(t, "Preco", 'D', (sizeof(double)));
break;
case 3://Cargos
t = adicionaCampo(t, "Cargo", 'S', 20);
t = adicionaCampo(t, "CodCarg", 'I', (sizeof(int)));
t = adicionaCampo(t, "Tipo de Contrato", 'C', (sizeof(char)));
t = adicionaCampo(t, "Obs", 'S', 40);
t = adicionaCampo(t, "Salario", 'D', (sizeof(double)));
break;
}
erro = finalizaTabela(t);
if(erro != SUCCESS){
printf("Erro %d: na função finalizaTabela().\n", erro);
return 0;
}
switch(tipo_tabela){
case 1://Funcionarios
c = insereValor(c, "Nome", "Func1");
c = insereValor(c, "CodFunc", "40");
c = insereValor(c, "Sexo", "F");
c = insereValor(c, "Obs", "Obs. Um");
c = insereValor(c, "CodCarg", "2");
c = insereValor(c, "Nome", "Func2");
c = insereValor(c, "CodFunc", "20");
c = insereValor(c, "Sexo", "M");
c = insereValor(c, "Obs", "Obs. Dois");
c = insereValor(c, "CodCarg", "1");
c = insereValor(c, "Nome", "Func3");
c = insereValor(c, "CodFunc", "30");
c = insereValor(c, "Sexo", "F");
c = insereValor(c, "Obs", "Obs. Tres");
c = insereValor(c, "CodCarg", "1");
break;
case 2://Produtos
c = insereValor(c, "Produto", "Produto1");
c = insereValor(c, "CodProd", "14");
c = insereValor(c, "Novo", "N");
c = insereValor(c, "Descricao", "Descr Um");
c = insereValor(c, "Preco", "50.00");
c = insereValor(c, "Produto", "Produto2");
c = insereValor(c, "CodProd", "15");
c = insereValor(c, "Novo", "S");
c = insereValor(c, "Descricao", "Descr Dois");
c = insereValor(c, "Preco", "16.00");
c = insereValor(c, "Produto", "Produto3");
c = insereValor(c, "CodProd", "17");
c = insereValor(c, "Novo", "S");
c = insereValor(c, "Descricao", "Descr Tres");
c = insereValor(c, "Preco", "14.60");
break;
case 3://Cargos
c = insereValor(c, "Cargo", "Cargo1");
c = insereValor(c, "CodCarg", "1");
c = insereValor(c, "Tipo de Contrato", "F");
c = insereValor(c, "Obs", "Obs. Um");
c = insereValor(c, "Salario", "2500.00");
c = insereValor(c, "Cargo", "Cargo2");
c = insereValor(c, "CodCarg", "2");
c = insereValor(c, "Tipo de Contrato", "M");
c = insereValor(c, "Obs", "Obs. Dois");
c = insereValor(c, "Salario", "1500.00");
c = insereValor(c, "Cargo", "Cargo3");
c = insereValor(c, "CodCarg", "3");
c = insereValor(c, "Tipo de Contrato", "F");
c = insereValor(c, "Obs", "Obs. Tres");
c = insereValor(c, "Salario", "1000.00");
break;
}
erro = finalizaInsert(nomeTabela, c);
if(erro != SUCCESS){
printf("Erro %d: na função finalizaInsert()\n", erro);
return 0;
}
struct fs_objects objeto = leObjeto(nomeTabela);
tp_table *esquema = leSchema(objeto);
if(esquema == ERRO_ABRIR_ESQUEMA){
printf("Erro ao criar o esquema.\n");
return 0;
}
tp_buffer *bufferpoll = initbuffer();
if(bufferpoll == ERRO_DE_ALOCACAO){
printf("Erro ao alocar memória para o buffer.\n");
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 0, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 1, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
erro = colocaTuplaBuffer(bufferpoll, 2, esquema, objeto);
if(erro != SUCCESS){
printf("Erro %d: na função colocaTuplaBuffer().\n", erro);
return 0;
}
column *tuplaE = excluirTuplaBuffer(bufferpoll, esquema, objeto, 0, 2); //pg, tupla
column *pagina = getPage(bufferpoll, esquema, objeto, 0);
if(tuplaE == ERRO_PARAMETRO){
printf("Erro, na função excluirTuplaBuffer(), problemas no parametro.\n");
return 0;
}
if(pagina == ERRO_PARAMETRO){
printf("Erro, na função getPage(), problemas no parametro.\n");
return 0;
}
printf("\nTabela %s criada com sucesso!",nomeTabela);
return 1;
}
//Cria tabelas pre-estabelecidas
void criar_tabelas_padrao(){
criar_tabela("Funcionario",1);
criar_tabela("Produto",2);
criar_tabela("Cargo",3);
insereChaves();
}
int excluir_arquivo(char* nomeTabela){
char *nomeArquivo=(char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
struct fs_objects objeto;
//Concatela nome da tabela com .dat para verificar arquivo
strcpy(nomeArquivo,nomeTabela);
strcat(nomeArquivo,".dat");
//Verifica se arquivo existe
if(existe_arquivo(nomeArquivo)){
if(remove(nomeArquivo)){
printf("Erro ao remover arquivo das tuplas!\n");
return 0;
}
}
//Verifica se tabela existe no dicionário
if(!verificaNomeTabela(nomeTabela)){
printf("Tabela nao existente!\n");
return 0;
}
// Começa verificação no dicionário de dados para atualizá-lo sem a tabela que está sendo removida
FILE *dicionario;
char *tupla = (char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
if((dicionario = fopen("fs_object.dat","a+b")) == NULL)
return ERRO_ABRIR_ARQUIVO;
// Inicia novo dicionário que substituirá o antigo
FILE *dicionario_novo;
if((dicionario_novo = fopen("fs_object2.dat","wb")) == NULL)
return ERRO_ABRIR_ARQUIVO;
while(fgetc (dicionario) != EOF){
fseek(dicionario, -1, 1);
fread(tupla, sizeof(char), TAMANHO_NOME_TABELA, dicionario); //Lê somente o nome da tabela
// Caso não seja a tabela a ser removida, escreve as informações no novo dicionário
if(strcmp(tupla, nomeTabela) != 0){
objeto = leObjeto(tupla);
// Salva dados sobre a tabela no novo dicionario.
fwrite(&objeto.nome,sizeof(objeto.nome),1,dicionario_novo);
fwrite(&objeto.cod,sizeof(objeto.cod),1,dicionario_novo);
fwrite(&objeto.nArquivo,sizeof(objeto.nArquivo),1,dicionario_novo);
fwrite(&objeto.qtdCampos,sizeof(objeto.qtdCampos),1,dicionario_novo);
}
fseek(dicionario, 28, 1);
}
fclose(dicionario);
fclose(dicionario_novo);
//Sobrescreve o dicionário antigo pelo novo dicionário
system("mv fs_object2.dat fs_object.dat");
return 1;
}
void remover_tabela(){
char *nomeTabela=(char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
printf("Digite o nome da tabela que deseja remover!\n");
scanf("%s",nomeTabela);
printf("\nRemovendo tabela %s...\n", nomeTabela);
//Código para remoção
if(excluir_arquivo(nomeTabela))
printf("Tabela %s removida com sucesso!\n",nomeTabela);
else
printf("Ocorreu um problema ao remover a tabela %s!\n",nomeTabela);
}
int menu(){
int opcao;
//Menu
printf("\nO que deseja fazer?\n");
printf("1 - Consultar tabelas\n2 - Criar tabelas\n3 - Remover Tabela\n0 - Sair\n");
scanf("%d",&opcao);
switch(opcao){
case 1: // Consultas dados existentes nas tabelas criadas
consultar();
break;
case 2: // Criar tabelas padrões (Produto, Funcionario, Cargo)
//Descomentar quando criação dinamica de tabelas for implementado
//~ printf("1-Criar uma tabela especifica\n2-Criar tabelas pre-estabelecidas\n");
//~ scanf("%d",&tipo_tabela);
//~ tipo_tabela == 1 ? criar_tabela() : criar_tabelas_padrao();
criar_tabelas_padrao();
printf("\n");
break;
case 3: // Remover tabelas
remover_tabela();
break;
case 0:
return 0;
break;
default:
printf("Opcao invalida, verifique o menu e tente novamente!\n");
break;
}
menu();
return 0;
}
//Criar tabela para pk e fks
int criar_tabela_chaves(){
int erro;
table *t = NULL;
t = iniciaTabela("BD_Chaves");
if(t == ERRO_NOME_TABELA_INVALIDO){
printf("Erro: na função iniciaTabela(). Nome da tabela já existente.\n");
return 0;
}
t = adicionaCampo(t, "TabelaOrigem", 'S', 20);
t = adicionaCampo(t, "ID", 'I', (sizeof(int)));
t = adicionaCampo(t, "Tipo", 'C', (sizeof(char)));
t = adicionaCampo(t, "TabelaDestino", 'S', 20);
t = adicionaCampo(t, "CampoOrigem", 'S', 10);
t = adicionaCampo(t, "CampoDestino", 'S', 10);
erro = finalizaTabela(t);
if(erro != SUCCESS){
printf("Erro %d: na função finalizaTabela().\n", erro);
return 0;
}
return 1;
}
void inicializacao(){
//Cria tabela de chaves(pk,fk) caso não exista no dicionário
if(!verificaNomeTabela("BD_Chaves"))
criar_tabela_chaves();
}
int main(){
inicializacao();
menu();
return 0;
}