// Insere o registro na tabela e nos indices. public void insert(string tabela, RegistroTabela registro) { Binarios binAux = arqBinarios[tabela]; long posicao = binAux.insertTabela(registro); binAux.insertIndices(registro, posicao, tabela); }
// Insere apenas 1 registro na tabela. public long insertTabela(RegistroTabela registro) { try { return(arqTabela.insert(registro)); } catch (Exception e) { throw new SGDBException("Houve erro na inserção do registro! " + e.Message); } }
public TabelaSelect returnTudo() { br.BaseStream.Position = 0; int count; TabelaDado td = new TabelaDado(nome); Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(nome); while (br.BaseStream.Position != br.BaseStream.Length) { RegistroTabela r = new RegistroTabela(br.ReadInt64()); count = br.ReadInt32(); //Form1.addMensagem("Count colunas" + count); // somente para depuração try { for (int i = 0; i < count; i++) { DadoTabela d; if (meta.getDados()[meta.getNomesColunas()[i]].getTipoDado() == TipoDado.Inteiro) { //Form1.addMensagem("Inteiro"); // somente para depuração d = new DadoTabela(meta.getNomesColunas()[i], meta.getDados()[meta.getNomesColunas()[i]].getTipoDado(), br.ReadByte(), br.ReadBoolean(), br.ReadInt32()); } else { //Form1.addMensagem("Char"); // somente para depuração d = new DadoTabela(meta.getNomesColunas()[i], meta.getDados()[meta.getNomesColunas()[i]].getTipoDado(), br.ReadByte(), br.ReadBoolean(), br.ReadString()); } r.dados.Add(d); } } catch (System.Exception e) { Form1.addMensagem(e.Message); } td.registros.Add(r); } return(TabelaSelect.getTabelaSelect(td)); }
// Insere o registro nos indices. public void insertIndices(RegistroTabela registro, long posicao, string tabela) { if (arqsIndices.Count > 0) { // Percorre indices. RegistroIndice registroIndice; Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(tabela); foreach (KeyValuePair <string, string[]> item in meta.getIndexes()) { // Monta indice. registroIndice = new RegistroIndice(); for (int i = 0; i < item.Value.Length; i++) { DadoIndice dadoIndice = new DadoIndice(meta.getDados()[item.Value[i]].getTipoDado(), registro.dados[meta.getNomesColunas().IndexOf(item.Value[i])].valor); registroIndice.dados.Add(dadoIndice); } // Insere no indice. insertIndice(item.Key, registroIndice, posicao); } } }
/* * // Este buffer ficou inutilizado pela linha: * // new System.Text.ASCIIEncoding().GetBytes(d.getValorStr().PadRight(d.tamanho)).CopyTo(valor, 0); * // do método de insert * private void atualizarTamBuffer(RegistroTabela registro) * { * if (buffer == null) * { * long tamBuffer = QTD_BUFFER_REG * registro.getRealTamanhoEmBytes(); * * if (tamBuffer > UM_MEGABYTE) * buffer = new Byte[UM_MEGABYTE]; * else * buffer = new Byte[tamBuffer]; * * ms = new MemoryStream(buffer); * br = new BinaryReader(ms); * //bw = new BinaryWriter(ms); * } * } */ public long insert(RegistroTabela registro) { atualizarPosicaoIni(); //atualizarTamBuffer(registro); // Posição do RegistroTabela bw.Write(posicaoIni); // Quantidade de colunas do RegistroTabela bw.Write(registro.dados.Count); // Dados do RegistroTabela foreach (DadoTabela d in registro.dados) { // tamanho do DadoTabela de acordo com o metadados em bytes bw.Write(d.tamanho); // informa se o DadoTabela é valido bw.Write(d.isValido); // grava o DadoTabela no arquivo if (d.tipo == TipoDado.Inteiro) { bw.Write(d.getValorInt()); } else { // Desta forma o tamanho da string é sempre a mesma, // porém o buffer nao pode ser usado. byte[] valor = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(d.getValorStr().PadRight(d.tamanho)).CopyTo(valor, 0); bw.Write(valor); } } return(posicaoIni); }
private void execucaoComandoReal() { string id; if (operacao != acao.InserirDados && anterior == acao.InserirDados) { //Base.getInstance().naoEhInsert(); memoria.salvarMetadados(); } switch (operacao) { case acao.Nada: //throw new SGDBException("Que ação é essa? Favor incluir um comando válido."); break; case acao.CriarTabela: metadados.criarIndiciePrimary(); memoria.salvarMetadados(metadados); memoria.recuperarMetadados(); break; case acao.InserirDados: id = identificadores[0]; identificadores.RemoveAt(0); RegistroTabela registro = new RegistroTabela(-1); metadados = memoria.recuperarMetadados(id); if (allColunas) { DadoTabela DadoTabela; for (int i = 0; i < identificadores.Count; i++) { if (identificadores[i].Equals("null")) { DadoTabela = new DadoTabela(metadados.getNomesColunas()[i], metadados.getTipoDado(i), (byte)metadados.getDados()[metadados.getNomesColunas()[i]].getTamanho(), false, identificadores[i].Replace("\'", "")); } else { DadoTabela = new DadoTabela(metadados.getNomesColunas()[i], metadados.getTipoDado(i), (byte)metadados.getDados()[metadados.getNomesColunas()[i]].getTamanho(), true, identificadores[i].Replace("\'", "")); } registro.dados.Add(DadoTabela); } } else { DadoTabela dado = null; bool nacho = true; for (int i = 0; i < metadados.getNomesColunas().Count; i++) { nacho = true; for (int j = 0; j < contColunas && nacho; j++) { if (metadados.getNomesColunas()[i].Equals(identificadores[j])) { if (identificadores[j + contColunas].Equals("null")) { dado = new DadoTabela(metadados.getNomesColunas()[i], metadados.getTipoDado(i), (byte)metadados.getDados()[metadados.getNomesColunas()[i]].getTamanho(), false, identificadores[j + contColunas].Replace("\'", "")); } else { dado = new DadoTabela(metadados.getNomesColunas()[i], metadados.getTipoDado(i), (byte)metadados.getDados()[metadados.getNomesColunas()[i]].getTamanho(), true, identificadores[j + contColunas].Replace("\'", "")); } nacho = false; } } if (nacho) { dado = new DadoTabela(metadados.getNomesColunas()[i], metadados.getTipoDado(i), (byte)metadados.getDados()[metadados.getNomesColunas()[i]].getTamanho(), false, "null"); } registro.dados.Add(dado); } } // Console.WriteLine("TO STRING DA TABELA"); /*TabelaDado tabelaDado = new TabelaDado(id, memoria.getPath()); tabelaDado.Registros.Add(RegistroTabela);*/ // Form1.addMensagem(tabelaDado.ToString()); //arquivoBinario = new ArquivoTabela(memoria.getPath()+"\\"+metadados.getNome()+".dat"); //long posi = arquivoBinario.insert(registro); Base.getInstance().insert(metadados.getNome(), registro); metadados.incRegistrosTabela(); //metadados.addIndice(registro, posi, memoria.getPath()); //memoria.salvarMetadados(metadados); memoria.atualizar(); break; case acao.Select: Form1.addMensagem(select.ToString()); Form1.setResultado(select.run(),select.Retorno); select.clear(); break; case acao.CriarIndex: id = identificadores[0]; identificadores.RemoveAt(0); foreach (string item in identificadores) { if (!metadados.getDados().ContainsKey(item)) { new SemanticError("A coluna " + item + "não existe na tabela " + metadados.getNome()); } } metadados.criarIndice(id,identificadores.ToArray()); memoria.salvarMetadados(metadados); memoria.atualizar(); break; case acao.ExcluirIndex: memoria.dropIndex(identificadores[0]); memoria.salvarMetadados(); memoria.atualizar(); break; default: throw new SGDBException("Ação Real" + operacao + " não implementada."); } anterior = operacao; //Console.WriteLine(metadados.StringIndices()); }
public TabelaSelect returnTudo() { br.BaseStream.Position = 0; int count; TabelaDado td = new TabelaDado(nome); Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(nome); while (br.BaseStream.Position != br.BaseStream.Length) { RegistroTabela r = new RegistroTabela(br.ReadInt64()); count = br.ReadInt32(); //Form1.addMensagem("Count colunas" + count); // somente para depuração try { for (int i = 0; i < count; i++) { DadoTabela d; if (meta.getDados()[meta.getNomesColunas()[i]].getTipoDado() == TipoDado.Inteiro) { //Form1.addMensagem("Inteiro"); // somente para depuração d = new DadoTabela(meta.getNomesColunas()[i], meta.getDados()[meta.getNomesColunas()[i]].getTipoDado(), br.ReadByte(), br.ReadBoolean(), br.ReadInt32()); } else { //Form1.addMensagem("Char"); // somente para depuração d = new DadoTabela(meta.getNomesColunas()[i], meta.getDados()[meta.getNomesColunas()[i]].getTipoDado(), br.ReadByte(), br.ReadBoolean(), br.ReadString()); } r.dados.Add(d); } } catch (System.Exception e) { Form1.addMensagem(e.Message); } td.registros.Add(r); } return TabelaSelect.getTabelaSelect(td); }
public TabelaSelect returnFiltrado(Dictionary<string, Filtro> filtrosAND) { br.BaseStream.Position = 0; int count; int tamRegistro = 12; Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(nome); TabelaDado td = new TabelaDado(nome); foreach (DadosTabela dados in meta.getDados().Values) { tamRegistro += dados.getTamanho() + 2; //if (dados.getTipoDado() == TipoDado.String) tamRegistro++; } //lê cada registro while (br.BaseStream.Position != br.BaseStream.Length) { RegistroTabela r = new RegistroTabela(br.BaseStream.Position); count = br.ReadInt32(); bool insere = true; //Lê cada dado dentro do registro for (int i = 0; i < count && insere; i++) { DadoTabela d; //Form1.addMensagem(i.ToString()); // *** erro aqui - inicio *** // select localidade.* from localidade where localidade.cd_localidade = 1; // da erro qdo i = 4 // mas quem deve limitar para nao chegar no 4 ? string nomeColuna = meta.getNomesColunas()[i]; // *** erro aqui - Fim *** TipoDado tipo = meta.getDados()[nomeColuna].getTipoDado(); string campo = meta.getNome() + "." + nomeColuna; Filtro f = filtrosAND.ContainsKey(campo) ? filtrosAND[campo] : null; if (tipo == TipoDado.Inteiro) { d = new DadoTabela(nomeColuna, tipo, br.ReadByte(), br.ReadBoolean(), br.ReadInt32()); if (f != null) { switch (f.Op) { case OperadorRel.Igual: if (f.RValue.ToLower().Equals("null")) { if (d.isValido) insere = false; } else { if (d.getValorInt() != Convert.ToInt32(f.RValue)) insere = false; } break; case OperadorRel.MaiorQue: if (d.getValorInt() <= Convert.ToInt32(f.RValue)) insere = false; break; case OperadorRel.MenorQue: if (d.getValorInt() >= Convert.ToInt32(f.RValue)) insere = false; break; case OperadorRel.MaiorIgualA: if (d.getValorInt() < Convert.ToInt32(f.RValue)) insere = false; break; case OperadorRel.MenorIgualA: if (d.getValorInt() > Convert.ToInt32(f.RValue)) insere = false; break; case OperadorRel.Diferente: if (f.RValue.ToLower().Equals("null")) { if (!d.isValido) insere = false; } else { if (d.getValorInt() == Convert.ToInt32(f.RValue)) insere = false; } break; default: throw new SGDBException("Passou onde nao devia: GambiarraSelect.retornaDados.Inteiro.Default."); } } } else { byte tamanho = br.ReadByte(); bool isValido = br.ReadBoolean(); byte[] valor = br.ReadBytes(tamanho); string texto = new System.Text.ASCIIEncoding().GetString(valor); d = new DadoTabela(nomeColuna, tipo, tamanho, isValido, texto); if (f != null) { switch (f.Op) { case OperadorRel.Igual: if (f.RValue.ToLower().Equals("null")) { if (d.isValido) insere = false; } else { byte[] filtro = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(d.tamanho)).CopyTo(filtro, 0); string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro); if (!texto.Equals(filtro2)) insere = false; } break; case OperadorRel.Diferente: if (f.RValue.ToLower().Equals("null")) { if (!d.isValido) insere = false; } else { byte[] filtro = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(d.tamanho)).CopyTo(filtro, 0); string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro); if (texto.Equals(filtro2)) insere = false; } break; default: throw new SemanticError("Comparação de literais só pode ser igual ou diferente"); } } } r.dados.Add(d); } if (insere) { td.registros.Add(r); } if (br.BaseStream.Position % tamRegistro != 0) br.BaseStream.Position += tamRegistro - (br.BaseStream.Position % tamRegistro); } return TabelaSelect.getTabelaSelect(td); }
/* // Este buffer ficou inutilizado pela linha: // new System.Text.ASCIIEncoding().GetBytes(d.getValorStr().PadRight(d.tamanho)).CopyTo(valor, 0); // do método de insert private void atualizarTamBuffer(RegistroTabela registro) { if (buffer == null) { long tamBuffer = QTD_BUFFER_REG * registro.getRealTamanhoEmBytes(); if (tamBuffer > UM_MEGABYTE) buffer = new Byte[UM_MEGABYTE]; else buffer = new Byte[tamBuffer]; ms = new MemoryStream(buffer); br = new BinaryReader(ms); //bw = new BinaryWriter(ms); } } */ public long insert(RegistroTabela registro) { atualizarPosicaoIni(); //atualizarTamBuffer(registro); // Posição do RegistroTabela bw.Write(posicaoIni); // Quantidade de colunas do RegistroTabela bw.Write(registro.dados.Count); // Dados do RegistroTabela foreach (DadoTabela d in registro.dados) { // tamanho do DadoTabela de acordo com o metadados em bytes bw.Write(d.tamanho); // informa se o DadoTabela é valido bw.Write(d.isValido); // grava o DadoTabela no arquivo if (d.tipo == TipoDado.Inteiro) bw.Write(d.getValorInt()); else { // Desta forma o tamanho da string é sempre a mesma, // porém o buffer nao pode ser usado. byte[] valor = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(d.getValorStr().PadRight(d.tamanho)).CopyTo(valor, 0); bw.Write(valor); } } return posicaoIni; }
public TabelaSelect returnDados(Metadados tabela) { try { Base.getInstance().desalocarBinarios(tabela.getNome()); } catch { } TabelaSelect ts = null; FileStream file = null; BinaryReader br = null; try { string arquivo = mem.getPath() + "\\" + tabela.getNome() + ".dat"; file = new FileStream(arquivo, FileMode.Open); using (br = new BinaryReader(file)) { int count; ts = new TabelaSelect(); Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(tabela.getNome()); int colunas = meta.getNomesColunas().Count; ts.Campos = new string[colunas]; for (int i = 0; i < colunas; i++) { ts.Campos[i] = meta.getNome() + "." + meta.getNomesColunas()[i]; } //lê cada registro while (br.BaseStream.Position != br.BaseStream.Length) { string[] registro = new string[colunas]; RegistroTabela r = new RegistroTabela(br.ReadInt64()); count = br.ReadInt32(); //Lê cada dado dentro do registro for (int i = 0; i < count; i++) { string nomeColuna = meta.getNomesColunas()[i]; TipoDado tipo = meta.getDados()[nomeColuna].getTipoDado(); string valor = ""; if (tipo == TipoDado.Inteiro) { byte tamanho = br.ReadByte(); bool isValido = br.ReadBoolean(); int numero = br.ReadInt32(); valor = isValido ? numero + "" : "NULL"; } else { byte tamanho = br.ReadByte(); bool isValido = br.ReadBoolean(); byte[] literal = br.ReadBytes(tamanho); string texto = new System.Text.ASCIIEncoding().GetString(literal); valor = isValido ? texto : "NULL"; } registro[i] = valor; } ts.Registros.Add(registro); if (ts.Registros.Count >= Base.getInstance().qtd_max_registros) break; } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.ReadLine(); } finally { if (br != null) { br.Close(); } if (file != null) { file.Close(); } } return ts; }
public TabelaSelect returnFiltrado(Dictionary <string, Filtro> filtrosAND) { br.BaseStream.Position = 0; int count; int tamRegistro = 12; Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(nome); TabelaDado td = new TabelaDado(nome); foreach (DadosTabela dados in meta.getDados().Values) { tamRegistro += dados.getTamanho() + 2; //if (dados.getTipoDado() == TipoDado.String) tamRegistro++; } //lê cada registro while (br.BaseStream.Position != br.BaseStream.Length) { RegistroTabela r = new RegistroTabela(br.BaseStream.Position); count = br.ReadInt32(); bool insere = true; //Lê cada dado dentro do registro for (int i = 0; i < count && insere; i++) { DadoTabela d; //Form1.addMensagem(i.ToString()); // *** erro aqui - inicio *** // select localidade.* from localidade where localidade.cd_localidade = 1; // da erro qdo i = 4 // mas quem deve limitar para nao chegar no 4 ? string nomeColuna = meta.getNomesColunas()[i]; // *** erro aqui - Fim *** TipoDado tipo = meta.getDados()[nomeColuna].getTipoDado(); string campo = meta.getNome() + "." + nomeColuna; Filtro f = filtrosAND.ContainsKey(campo) ? filtrosAND[campo] : null; if (tipo == TipoDado.Inteiro) { d = new DadoTabela(nomeColuna, tipo, br.ReadByte(), br.ReadBoolean(), br.ReadInt32()); if (f != null) { switch (f.Op) { case OperadorRel.Igual: if (f.RValue.ToLower().Equals("null")) { if (d.isValido) { insere = false; } } else { if (d.getValorInt() != Convert.ToInt32(f.RValue)) { insere = false; } } break; case OperadorRel.MaiorQue: if (d.getValorInt() <= Convert.ToInt32(f.RValue)) { insere = false; } break; case OperadorRel.MenorQue: if (d.getValorInt() >= Convert.ToInt32(f.RValue)) { insere = false; } break; case OperadorRel.MaiorIgualA: if (d.getValorInt() < Convert.ToInt32(f.RValue)) { insere = false; } break; case OperadorRel.MenorIgualA: if (d.getValorInt() > Convert.ToInt32(f.RValue)) { insere = false; } break; case OperadorRel.Diferente: if (f.RValue.ToLower().Equals("null")) { if (!d.isValido) { insere = false; } } else { if (d.getValorInt() == Convert.ToInt32(f.RValue)) { insere = false; } } break; default: throw new SGDBException("Passou onde nao devia: GambiarraSelect.retornaDados.Inteiro.Default."); } } } else { byte tamanho = br.ReadByte(); bool isValido = br.ReadBoolean(); byte[] valor = br.ReadBytes(tamanho); string texto = new System.Text.ASCIIEncoding().GetString(valor); d = new DadoTabela(nomeColuna, tipo, tamanho, isValido, texto); if (f != null) { switch (f.Op) { case OperadorRel.Igual: if (f.RValue.ToLower().Equals("null")) { if (d.isValido) { insere = false; } } else { byte[] filtro = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(d.tamanho)).CopyTo(filtro, 0); string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro); if (!texto.Equals(filtro2)) { insere = false; } } break; case OperadorRel.Diferente: if (f.RValue.ToLower().Equals("null")) { if (!d.isValido) { insere = false; } } else { byte[] filtro = new byte[d.tamanho]; new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(d.tamanho)).CopyTo(filtro, 0); string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro); if (texto.Equals(filtro2)) { insere = false; } } break; default: throw new SemanticError("Comparação de literais só pode ser igual ou diferente"); } } } r.dados.Add(d); } if (insere) { td.registros.Add(r); } if (br.BaseStream.Position % tamRegistro != 0) { br.BaseStream.Position += tamRegistro - (br.BaseStream.Position % tamRegistro); } } return(TabelaSelect.getTabelaSelect(td)); }
// Insere apenas 1 registro na tabela. public long insertTabela(RegistroTabela registro) { try { return arqTabela.insert(registro); } catch (Exception e) { throw new SGDBException("Houve erro na inserção do registro! " + e.Message); } }
// Insere o registro nos indices. public void insertIndices(RegistroTabela registro, long posicao, string tabela) { if (arqsIndices.Count > 0) { // Percorre indices. RegistroIndice registroIndice; Metadados meta = GerenciadorMemoria.getInstance().recuperarMetadados(tabela); foreach (KeyValuePair<string, string[]> item in meta.getIndexes()) { // Monta indice. registroIndice = new RegistroIndice(); for (int i = 0; i < item.Value.Length; i++) { DadoIndice dadoIndice = new DadoIndice(meta.getDados()[item.Value[i]].getTipoDado(), registro.dados[meta.getNomesColunas().IndexOf(item.Value[i])].valor); registroIndice.dados.Add(dadoIndice); } // Insere no indice. insertIndice(item.Key, registroIndice, posicao); } } }