int interface() { pthread_t pth; pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL); pthread_join(pth, NULL); connect("uffsdb"); // conecta automaticamente no banco padrão while(1){ if (!connected.conn_active) { printf(">"); } else { printf("%s=# ", connected.db_name); } pthread_create(&pth, NULL, (void*)yyparse, &GLOBAL_PARSER); pthread_join(pth, NULL); if (GLOBAL_PARSER.noerror) { if (GLOBAL_PARSER.mode != 0) { if (!connected.conn_active) { notConnected(); } else { switch(GLOBAL_PARSER.mode) { case OP_INSERT: if (GLOBAL_DATA.N > 0) { insert(&GLOBAL_DATA); } else printf("WARNING: Nothing to be inserted. Command ignored.\n"); break; case OP_SELECT_ALL: pulpfic(select_attributes, GLOBAL_DATA.objName, token_list); /*w_token *jujuba; for(jujuba=token_list;jujuba;jujuba=jujuba->next){ printf("jujuba = %s\n",(char*)jujuba->valor); }*/ break; case OP_CREATE_TABLE: createTable(&GLOBAL_DATA); break; case OP_CREATE_DATABASE: createDB(GLOBAL_DATA.objName); break; case OP_DROP_TABLE: excluirTabela(GLOBAL_DATA.objName); break; case OP_DROP_DATABASE: dropDatabase(GLOBAL_DATA.objName); break; default: break; } } } } else { GLOBAL_PARSER.consoleFlag = 1; switch(GLOBAL_PARSER.mode) { case OP_CREATE_DATABASE: case OP_DROP_DATABASE: case OP_CREATE_TABLE: case OP_DROP_TABLE: case OP_SELECT_ALL: case OP_INSERT: if (GLOBAL_PARSER.step == 1) { GLOBAL_PARSER.consoleFlag = 0; printf("Expected object name.\n"); } break; default: break; } if (GLOBAL_PARSER.mode == OP_CREATE_TABLE) { if (GLOBAL_PARSER.step == 2) { printf("Column not specified correctly.\n"); GLOBAL_PARSER.consoleFlag = 0; } } else if (GLOBAL_PARSER.mode == OP_INSERT) { if (GLOBAL_PARSER.step == 2) { printf("Expected token \"VALUES\" after object name.\n"); GLOBAL_PARSER.consoleFlag = 0; } } printf("ERROR: syntax error.\n"); GLOBAL_PARSER.noerror = 1; } if (GLOBAL_PARSER.mode != 0) { pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL); pthread_join(pth, NULL); } } return 0; }
int interface() { pthread_t pth; pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL); pthread_join(pth, NULL); connect("ibetres"); // conecta automaticamente no banco padrão while(1){ if (!connected.conn_active) { printf(">"); } else { printf("%s=# ", connected.db_name); } pthread_create(&pth, NULL, (void*)yyparse, &GLOBAL_PARSER); pthread_join(pth, NULL); if (GLOBAL_PARSER.noerror) { if (GLOBAL_PARSER.mode != 0) { if (!connected.conn_active) { notConnected(); } else { switch(GLOBAL_PARSER.mode) { case OP_INSERT: if (GLOBAL_DATA.N > 0) { insert(&GLOBAL_DATA); } else printf("WARNING: Nothing to be inserted. Command ignored.\n"); break; case OP_SELECT_ALL: if (GLOBAL_DATA.imprimeTudo == 1 && GLOBAL_WHERE.where == 1) { whereSemProj(&GLOBAL_DATA, &GLOBAL_WHERE, GLOBAL_DATA.objName); GLOBAL_WHERE.where = 0; GLOBAL_DATA.imprimeTudo = 0; } else if (GLOBAL_DATA.imprimeTudo == 1 && GLOBAL_WHERE.where == 0) { imprimeAll(GLOBAL_DATA.objName); GLOBAL_DATA.imprimeTudo = 0; } else if (GLOBAL_DATA.imprimeTudo == 0 && GLOBAL_WHERE.where == 1) { whereComProj(&GLOBAL_DATA, &GLOBAL_WHERE, GLOBAL_DATA.objName, GLOBAL_PARSER.col_count); GLOBAL_DATA.imprimeTudo = 0; GLOBAL_WHERE.where = 0; } else { selecionar(&GLOBAL_DATA, GLOBAL_PARSER.col_count); } break; case OP_CREATE_TABLE: createTable(&GLOBAL_DATA); break; case OP_CREATE_DATABASE: createDB(GLOBAL_DATA.objName); break; case OP_DROP_TABLE: excluirTabela(GLOBAL_DATA.objName); break; case OP_DROP_DATABASE: dropDatabase(GLOBAL_DATA.objName); break; default: break; } } } } else { GLOBAL_PARSER.consoleFlag = 1; switch(GLOBAL_PARSER.mode) { case OP_CREATE_DATABASE: case OP_DROP_DATABASE: case OP_CREATE_TABLE: case OP_DROP_TABLE: case OP_SELECT_ALL: case OP_INSERT: if (GLOBAL_PARSER.step == 1) { GLOBAL_PARSER.consoleFlag = 0; printf("Expected object name.\n"); } break; default: break; } if (GLOBAL_PARSER.mode == OP_CREATE_TABLE) { if (GLOBAL_PARSER.step == 2) { printf("Column not specified correctly.\n"); GLOBAL_PARSER.consoleFlag = 0; } } else if (GLOBAL_PARSER.mode == OP_INSERT) { if (GLOBAL_PARSER.step == 2) { printf("Expected token \"VALUES\" after object name.\n"); GLOBAL_PARSER.consoleFlag = 0; } } printf("ERROR: syntax error.\n"); GLOBAL_PARSER.noerror = 1; } if (GLOBAL_PARSER.mode != 0) { pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL); pthread_join(pth, NULL); } } return 0; }
void shell() { current_database = -1; char entrada[1000], nomeBD[TAM_NOME_BANCO]; int resultado = 0, codDB = -1; nomeBD[0]='\0'; char *current_db_name = strdup(">");//inicializa com nenhum banco conectado char *start; start = strdup("dbms-start");//este comando posteriormente como start do banco, no momento ele é automatico printf("\nWelcome to the DBMS Interface.\nType 'help' '\\h' for help.\n\n"); /** * **************************** * * Comandos do shell * * **************************** */ using_history ();//função para usar o histórico read_history (".history_file"); while(1) { int nTokens; strcpy(entrada, readline(current_db_name)); /** * Adiciona ao histórico */ if (entrada[0]) { char *expansion; int result; result = history_expand (entrada, &expansion); if (result) fprintf (stderr, "%s", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (entrada, expansion, sizeof (entrada) - 1); free (expansion); write_history (".history_file");//adiciona no histórico } char **tokens = tokenize( trim_white_space(remove_newline(entrada)),' ',&nTokens); /** * Opção para criar tabela e banco de dados */ if (strcmp(strtolower(tokens[0]),"create")==0) { if(strcmp(strtolower(tokens[1]),"table")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } createTable(entrada,current_database); } else if(strcmp(strtolower(tokens[1]),"database")==0) { if (nTokens >= 5) { printf("Invalid command. Type help to show de interface usage.\n"); continue; } if (strlen(tokens[2]) > TAM_NOME_BANCO ) { printf("Database name too big.\n"); continue; } resultado = checkCreateDB( remove_semicolon(tokens[2]) );//verifica a existência do nome e grava-o no arquivo if(resultado==-1) { printf("Error creating database file.\n"); } if(resultado==-3) { printf("Database exists.\n"); } else { printf("Database created successfully.\n"); } } else { printf("Invalid command. Type help to show de interface usage.\n"); continue; } } /** * Conecta ao banco de dados passado como parâmetro */ else if(strcmp(strtolower(tokens[0]),"\\c") == 0){ if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } char *name_db = remove_semicolon(tokens[1]); codDB = busca(name_db,1); //função chamada para conecção no banco, retorna o codigo do banco ao conectar if (codDB >= 0) { strcpy(nomeBD, name_db); //passa o nome do bd, para a variavel mostrar ao usuario qual o banco conectado free(current_db_name); current_db_name = (char*) malloc (sizeof(char)*(strlen(name_db)+3)); if (current_db_name == NULL) { printf("Out of memory.\nAborting...\n"); } strcpy(current_db_name,name_db); current_database = codDB; strcat(current_db_name,"=#"); current_db_name[strlen(current_db_name)] = '\0'; } else { printf("No such database '%s'.\n", name_db); continue; } } /** * Insere tuplas em uma tabela */ else if(strcmp(strtolower(tokens[0]),"insert")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } insert(entrada,current_database); } /** * Imprime as tabelas do banco de dados atual * ou o esquema de uma tabela */ else if(strcmp(strtolower(tokens[0]),"\\d")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (nTokens >= 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if (nTokens == 1) { //imprime tabelas do banco de dados listaTabelas(current_database); } else { //imprime o esquema de uma tabela char *t = table_name_real(remove_semicolon(tokens[1]),current_database); if(!verificaNomeTabela(t)){ printf("Invalid table name.\n"); free(t); continue; } struct fs_objects objeto = leObjeto(t);//para verificar se a tabela esta no banco show_schema(objeto,tokens[1]); free(t); } } /** * Comando temporário para imprimir tabela */ else if (strcmp(strtolower(tokens[0]),"select")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } selectTable(entrada,current_database); } /** * Imprime os registros da tabela passada */ else if (strcmp(strtolower(tokens[0]),"show")==0) { if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[1]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[1])); continue; } char *t = table_name_real(remove_semicolon(tokens[1]),current_database); char *file = table_name_real(remove_semicolon(tokens[1]),current_database); strcat(file,".dat"); if (existeArquivo(file) == 0) { printf("Table is empty.\n" ); continue; } imprime(t); free(file); free(t); } /** * Lista os bancos existentes */ else if(strcmp(strtolower(tokens[0]),"\\l")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } //LISTA os bancos existentes listaBancos(); } /** * Opção para deletar o banco de dados e tabelas */ else if(strcmp(strtolower(tokens[0]),"drop")==0) { if (nTokens != 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if(strcmp(strtolower(tokens[1]),"table") == 0){ if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[2]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[2])); continue; } char *t = table_name_real(remove_semicolon(tokens[2]),current_database); char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); int ok = excluirTabela(t); if (ok == SUCCESS) { printf("Table deleted successfully.\n"); } free(exist); free(t); } else if(strcmp(strtolower(tokens[1]),"database") == 0){ char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); strcat(exist,".dat"); if (existeArquivo(exist) != 0) { printf("The database is not empty for drop, there are existing tables.\n" ); continue; } exist = remove_semicolon(tokens[2]); codDB = busca(exist,1); if(codDB == current_database) { printf("Cannot drop the currently open database.\n"); continue; } int drop = dropDatabase(remove_semicolon(tokens[2])); if(drop == 1)printf("Database deleted successfully.\n"); free(exist); } } /** * Ajuda ao usuário com exemplos da sintaxe dos comandos */ else if (strcmp(strtolower(tokens[0]),"help")==0 || strcmp(strtolower(tokens[0]),"\\h")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); } help(); } /** * Imprime mensagem de copyright */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\copyright")==0) { printf("\nDatabase Management System\n"); printf("\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose, without fee, and without a written agreement\nis hereby granted, provided that the above copyright notice and this\nparagraph and the following two paragraphs appear in all copies.\n"); printf("\nTHIS SOFTWARE IS BEING DEVELOPED BY STUDENTS OF DATABASE II CLASS AT UNIVERSIDADE FEDERAL DA FRONTEIRA SUL.\n\n"); } /** * Comando de saída */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"exit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"quit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"bye")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\q")==0) { break; } else { printf("Invalid command. Type help to show the interface usage.\n"); continue; } } free(start); free(current_db_name); }