Example #1
0
        public static void setResultado(TabelaSelect tabela, Dictionary <string, string> retorno)
        {
            gridView.Columns.Clear();

            if (tabela == null)
            {
                addMensagem(String.Format("{0} linhas selecionadas.", 0));
                return;
            }
            if (tabela.Registros.Count < Base.getInstance().qtd_max_registros)
            {
                addMensagem(String.Format("{0} linhas selecionadas.", tabela.Registros.Count));
            }
            else
            {
                addMensagem(String.Format("Retornado primeiras {0} linhas selecionadas.\nFavor refinar a pesquisa!", tabela.Registros.Count));
            }
            int[] indices = new int[retorno.Count];
            for (int i = 0; i < retorno.Count; i++)
            {
                KeyValuePair <string, string> campo = retorno.ElementAt(i);
                //insere a coluna no gridView com o apelido definido
                gridView.Columns.Add(campo.Key, campo.Value);
                //verifica qual eh o índice da tabelaSelect correspondente ao campo para ordenar depois
                if (tabela != null)
                {
                    for (int j = 0; j < tabela.Campos.Length; j++)
                    {
                        if (tabela.Campos[j].Equals(campo.Key))
                        {
                            indices[i] = j;
                            break;
                        }
                    }
                }
            }

            if (tabela == null)
            {
                string[] linha = new string[retorno.Count];
                gridView.Rows.Add(linha);
            }
            else
            {
                foreach (string[] registro in tabela.Registros)
                {
                    string[] linha = new string[registro.Length];
                    for (int i = 0; i < indices.Length; i++)
                    {
                        linha[i] = registro[indices[i]];
                    }

                    gridView.Rows.Add(linha);
                }
            }
        }
Example #2
0
        public static void setResultado(TabelaSelect tabela, Dictionary<string, string> retorno)
        {
            gridView.Columns.Clear();

            if (tabela == null)
            {
                addMensagem(String.Format("{0} linhas selecionadas.", 0));
                return;
            }
            if (tabela.Registros.Count < Base.getInstance().qtd_max_registros)
            {
                addMensagem(String.Format("{0} linhas selecionadas.", tabela.Registros.Count));
            }
            else
            {
                addMensagem(String.Format("Retornado primeiras {0} linhas selecionadas.\nFavor refinar a pesquisa!", tabela.Registros.Count));
            }
            int[] indices = new int[retorno.Count];
            for (int i = 0; i < retorno.Count; i++)
            {
                KeyValuePair<string, string> campo = retorno.ElementAt(i);
                //insere a coluna no gridView com o apelido definido
                gridView.Columns.Add(campo.Key, campo.Value);
                //verifica qual eh o índice da tabelaSelect correspondente ao campo para ordenar depois
                if (tabela != null)
                {
                    for (int j = 0; j < tabela.Campos.Length; j++)
                    {
                        if (tabela.Campos[j].Equals(campo.Key))
                        {
                            indices[i] = j;
                            break;
                        }
                    }
                }
            }

            if (tabela == null)
            {
                string[] linha = new string[retorno.Count];
                gridView.Rows.Add(linha);
            }
            else
                foreach (string[] registro in tabela.Registros)
                {
                    string[] linha = new string[registro.Length];
                    for (int i = 0; i < indices.Length; i++)
                    {
                        linha[i] = registro[indices[i]];
                    }

                    gridView.Rows.Add(linha);
                }
        }
Example #3
0
        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));
        }
Example #4
0
        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;
        }
Example #5
0
        public TabelaSelect returnDados(List<Filtro> filtrosAND, Dictionary<string, List<string>> filtrosJoin, 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];
                    }

                    //calcula o tamanho de cada registro
                    int tamRegistro = 12;
                    int posPrimary = 0;//posicao do primary key no registro
                    foreach (DadosTabela dados in meta.getDados().Values)
                    {
                        if (dados.isPrimary()) posPrimary = tamRegistro + 2;
                        tamRegistro += dados.getTamanho() + 2;
                    }

                    long posMax = br.BaseStream.Length; //posicao máxima para leitura do arquivo
                    //organiza os filtros por coluna
                    List<Filtro>[] filtrosCampo = new List<Filtro>[colunas];
                    for (int i = 0; i < colunas; i++)
                    {
                        ts.Campos[i] = meta.getNome() + "." + meta.getNomesColunas()[i];
                        filtrosCampo[i] = new List<Filtro>();
                        foreach (Filtro f in filtrosAND)
                        {
                            if (f.LValue.Equals(ts.Campos[i])) filtrosCampo[i].Add(f);
                        }
                        if (filtrosJoin.ContainsKey(ts.Campos[i]))
                        {
                            posMax = posicionaPonteiroArquivo(filtrosJoin[ts.Campos[i]], br, tamRegistro, posPrimary);
                        }
                        //se o campo for PrimaryKey organiza o filtro
                        else if (filtrosCampo[i].Count > 0 && meta.getDados()[meta.getNomesColunas()[i]].isPrimary())
                        {
                            ordenaFiltros(filtrosCampo[i]);
                            //define o intervalo de consulta do arquivo caso exista filtro de chave primaria
                            posMax = posicionaPonteiroArquivo(filtrosCampo[i], br, tamRegistro, posPrimary);
                        }
                    }

                    //lê cada registro
                    while (br.BaseStream.Position < posMax)
                    {
                        string[] registro = new string[colunas];
                        long posicao = br.ReadInt64();
                        count = br.ReadInt32();
                        bool insere = true;
                        //Lê cada dado dentro do registro
                        for (int i = 0; i < count && insere; i++)
                        {
                            string nomeColuna = meta.getNomesColunas()[i];
                            TipoDado tipo = meta.getDados()[nomeColuna].getTipoDado();
                            bool isPrimary = meta.getDados()[nomeColuna].isPrimary();
                            string valor = "";
                            string campo = meta.getNome() + "." + nomeColuna;

                            if (tipo == TipoDado.Inteiro)
                            {
                                byte tamanho = br.ReadByte();
                                bool isValido = br.ReadBoolean();
                                int numero = br.ReadInt32();
                                valor = isValido ? numero + "" : "NULL";
                                foreach (Filtro f in filtrosCampo[i])
                                {
                                    switch (f.Op)
                                    {
                                        case OperadorRel.Igual:
                                            if (f.RValue.ToLower().Equals("null"))
                                            {
                                                if (isValido) insere = false;
                                            }
                                            else
                                            {
                                                if (numero != Convert.ToInt32(f.RValue)) insere = false;
                                            }
                                            break;
                                        case OperadorRel.MaiorQue:
                                            if (numero <= Convert.ToInt32(f.RValue)) insere = false;
                                            break;
                                        case OperadorRel.MenorQue:
                                            if (numero >= Convert.ToInt32(f.RValue)) insere = false;
                                            break;
                                        case OperadorRel.MaiorIgualA:
                                            if (numero < Convert.ToInt32(f.RValue)) insere = false;
                                            break;
                                        case OperadorRel.MenorIgualA:
                                            if (numero > Convert.ToInt32(f.RValue)) insere = false;
                                            break;
                                        case OperadorRel.Diferente:
                                            if (f.RValue.ToLower().Equals("null"))
                                            {
                                                if (!isValido) insere = false;
                                            }
                                            else
                                            {
                                                if (numero == Convert.ToInt32(f.RValue)) insere = false;
                                            }
                                            break;
                                        default:
                                            throw new SGDBException("Passou onde nao devia: GambiarraSelect.retornaDados.Inteiro.Default.");
                                    }
                                }
                                if(insere && filtrosJoin.ContainsKey(campo))
                                {
                                    insere = filtrosJoin[campo].Exists(s => s.Equals(valor));
                                }
                            }
                            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.TrimEnd() : "NULL";
                                foreach (Filtro f in filtrosCampo[i])
                                {
                                    switch (f.Op)
                                    {
                                        case OperadorRel.Igual:
                                            if (f.RValue.ToLower().Equals("null"))
                                            {
                                                if (isValido) insere = false;
                                            }
                                            else
                                            {
                                                byte[] filtro = new byte[tamanho];
                                                new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(tamanho)).CopyTo(filtro, 0);
                                                string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro).TrimEnd();
                                                if (!valor.Equals(filtro2)) insere = false;
                                            }
                                            break;
                                        case OperadorRel.Diferente:
                                            if (f.RValue.ToLower().Equals("null"))
                                            {
                                                if (isValido) insere = false;
                                            }
                                            else
                                            {
                                                byte[] filtro = new byte[tamanho];
                                                new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(tamanho)).CopyTo(filtro, 0);
                                                string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro).TrimEnd();
                                                if (valor.Equals(filtro2)) insere = false;
                                            }
                                            break;
                                        default:
                                            throw new SemanticError("Comparação de literais só pode ser igual ou diferente");
                                    }
                                }
                                if (insere && filtrosJoin.ContainsKey(campo))
                                {
                                    insere = filtrosJoin[campo].Exists(s => s.Equals(valor));
                                }

                            }

                            registro[i] = valor;
                        }

                        if (insere)
                        {
                            ts.Registros.Add(registro);
                            if (ts.Registros.Count >= Base.getInstance().qtd_max_registros) break;
                        }

                        if (br.BaseStream.Position % tamRegistro != 0)
                            br.BaseStream.Position += tamRegistro - (br.BaseStream.Position % tamRegistro);
                    }
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
            finally
            {
                if (br != null)
                {
                    br.Close();
                }
                if (file != null)
                {
                    file.Close();
                }
            }
            return ts;
        }
Example #6
0
        /// <summary>
        /// método responsável por retornar o resultado do SELECT
        /// </summary>
        /// <returns>TabelaSelect formatada para apresentar no Form1</returns>
        public TabelaSelect run()
        {
            TabelaSelect tabelaSelect = null;

            //caso e select seja select tabela.* from tabela não será necessário
            //aplicar join pois tratará de apenas uma tabela
            //tratamento apenas para where
            if (asterisco)
            {
                string arqTabela = mem.getPath() + "\\" + tabelas[0].getNome() + ".dat";
                if (where != null)
                {
                    if (where.ListaFiltro == null || where.ListaFiltro.Count == 0)
                    {
                        //se não tiver filtro retorna tudo
                        //tabelaSelect = new Binarios(arqTabela).returnDados(tabelas[0]);
                        tabelaSelect = returnDados(tabelas[0]);
                    }
                    //traz os resultados filtrados por grupos de AND e depois junta com os OR's
                    foreach (List <Filtro> filtrosAND in where.ListaFiltro)
                    {
                        TabelaSelect tabelaFiltro = null;
                        tabelaFiltro = returnDados(filtrosAND, new Dictionary <string, List <string> >(), tabelas[0]);
                        if (tabelaSelect == null)
                        {
                            tabelaSelect = tabelaFiltro;
                        }
                        else
                        {
                            tabelaSelect.uniaoDistinct(tabelaFiltro);
                        }
                    }
                }
                else
                {
                    //se nao tiver filtro retorna tudo

                    tabelaSelect = returnDados(tabelas[0]);
                }
                //envia comando para a TabelaSelect ordenar os registros
                if (ordem.Count > 0)
                {
                    tabelaSelect.ordenaRegistros(ordem, ordemAscendente);
                }
                return(tabelaSelect);
            }

            //Se não tem asterisco o negócio complica

            //ordena as tabelas por qtdade registros
            tabelas.Sort(delegate(Metadados m1, Metadados m2)
            {
                return(m1.getNumeroRegistrosTabela() > m2.getNumeroRegistrosTabela() ? -1 : 1);
            });


            Dictionary <Metadados, Where> filtros = new Dictionary <Metadados, Where>();

            //separa os filtros referentes a cada tabela e, se tiver filtro, joga a tabela no inicio da ordenação
            for (int i = 0; i < tabelas.Count; i++)
            {
                Metadados m       = tabelas[i];
                Where     filtroE = new Where();
                //separa os filtros
                foreach (List <Filtro> filtrosAND in where.ListaFiltro)
                {
                    List <Filtro> maisFiltro = (filtrosAND.Where(f => f.LValue.StartsWith(m.getNome())).ToList());
                    filtroE.ListaFiltro.Add(maisFiltro);
                }
                //ordena pro inicio
                if (filtroE.ListaFiltro.Count > 0)
                {
                    m = tabelas[i];
                    tabelas.Remove(m);
                    tabelas.Insert(0, m);
                }
                filtros.Add(m, filtroE);
            }
            //seleciona cada tabela separadamente
            while (tabelas.Count > 0)
            {
                Metadados    m            = tabelas.First();
                TabelaSelect tabelaFiltro = null;
                //traz os resultados filtrados por grupos de AND e depois junta com os OR's
                if (filtros[m].ListaFiltro.Count > 0)
                {
                    foreach (List <Filtro> filtrosAND in where.ListaFiltro)
                    {
                        TabelaSelect tabelaFiltroOR = null;
                        //informa apenas os filtros relacionados com a tabela em questão
                        tabelaFiltroOR = returnDados(filtrosAND, filtros[m].FiltroJoin, m);
                        if (tabelaFiltro == null)
                        {
                            tabelaFiltro = tabelaFiltroOR;
                        }
                        else
                        {
                            tabelaFiltro.uniaoDistinct(tabelaFiltroOR);
                        }
                    }
                }
                else
                {
                    tabelaFiltro = returnDados(m);
                }

                tabelas.Remove(m);
                filtros.Remove(m);
                //Adicionando campos de join como filtro.

                foreach (Filtro f in where.ListaJoin)
                {
                    if (f.LValue.StartsWith(m.getNome()))
                    {
                        Metadados outroM = null;
                        foreach (Metadados meta in filtros.Keys)
                        {
                            if (f.RValue.StartsWith(meta.getNome()))
                            {
                                outroM = meta;
                                break;
                            }
                        }
                        //insere os registros de join como filtro para as proximas tabelas
                        if (outroM != null)
                        {
                            List <string> maisFiltro = new List <string>();
                            int           colEsq     = 0;
                            for (int i = 0; i < tabelaFiltro.Campos.Length; i++)
                            {
                                if (tabelaFiltro.Campos[i].Equals(f.LValue))
                                {
                                    colEsq = i;
                                    break;
                                }
                            }
                            foreach (string[] reg in tabelaFiltro.Registros)
                            {
                                maisFiltro.Add(reg[colEsq]);
                            }
                            maisFiltro.Sort();
                            filtros[outroM].FiltroJoin.Add(f.LValue, maisFiltro);

                            //joga o outroM para ser o proximo a pesquisar
                            tabelas.Remove(outroM);
                            tabelas.Insert(0, outroM);
                        }
                    }
                    if (f.RValue.StartsWith(m.getNome()))
                    {
                        Metadados outroM = null;
                        foreach (Metadados meta in filtros.Keys)
                        {
                            if (f.LValue.StartsWith(meta.getNome()))
                            {
                                outroM = meta;
                                break;
                            }
                        }
                        //insere os registros de join como filtro para as proximas tabelas
                        if (outroM != null)
                        {
                            List <string> maisFiltro = new List <string>();
                            int           colDir     = 0;
                            for (int i = 0; i < tabelaFiltro.Campos.Length; i++)
                            {
                                if (tabelaFiltro.Campos[i].Equals(f.LValue))
                                {
                                    colDir = i;
                                    break;
                                }
                            }
                            foreach (string[] reg in tabelaFiltro.Registros)
                            {
                                maisFiltro.Add(reg[colDir]);
                            }
                            maisFiltro.Sort();
                            filtros[outroM].FiltroJoin.Add(f.RValue, maisFiltro);

                            //joga o outroM para ser o proximo a pesquisar
                            tabelas.Remove(outroM);
                            tabelas.Insert(0, outroM);
                        }
                    }
                }/**/
                //se tem mais tabelas faz o join
                if (tabelaSelect == null)
                {
                    tabelaSelect = tabelaFiltro;
                }
                else
                {
                    tabelaSelect = tabelaSelect.join(tabelaFiltro, Where.ListaJoin);
                }
            }
            //envia comando para a TabelaSelect ordenar os registros
            if (ordem.Count > 0)
            {
                tabelaSelect.ordenaRegistros(ordem, ordemAscendente);
            }
            return(tabelaSelect);
        }
Example #7
0
        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));
        }
Example #8
0
        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);
        }
Example #9
0
        public TabelaSelect returnDados(List <Filtro> filtrosAND, Dictionary <string, List <string> > filtrosJoin, 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];
                    }

                    //calcula o tamanho de cada registro
                    int tamRegistro = 12;
                    int posPrimary  = 0;//posicao do primary key no registro
                    foreach (DadosTabela dados in meta.getDados().Values)
                    {
                        if (dados.isPrimary())
                        {
                            posPrimary = tamRegistro + 2;
                        }
                        tamRegistro += dados.getTamanho() + 2;
                    }

                    long posMax = br.BaseStream.Length; //posicao máxima para leitura do arquivo
                    //organiza os filtros por coluna
                    List <Filtro>[] filtrosCampo = new List <Filtro> [colunas];
                    for (int i = 0; i < colunas; i++)
                    {
                        ts.Campos[i]    = meta.getNome() + "." + meta.getNomesColunas()[i];
                        filtrosCampo[i] = new List <Filtro>();
                        foreach (Filtro f in filtrosAND)
                        {
                            if (f.LValue.Equals(ts.Campos[i]))
                            {
                                filtrosCampo[i].Add(f);
                            }
                        }
                        if (filtrosJoin.ContainsKey(ts.Campos[i]))
                        {
                            posMax = posicionaPonteiroArquivo(filtrosJoin[ts.Campos[i]], br, tamRegistro, posPrimary);
                        }
                        //se o campo for PrimaryKey organiza o filtro
                        else if (filtrosCampo[i].Count > 0 && meta.getDados()[meta.getNomesColunas()[i]].isPrimary())
                        {
                            ordenaFiltros(filtrosCampo[i]);
                            //define o intervalo de consulta do arquivo caso exista filtro de chave primaria
                            posMax = posicionaPonteiroArquivo(filtrosCampo[i], br, tamRegistro, posPrimary);
                        }
                    }

                    //lê cada registro
                    while (br.BaseStream.Position < posMax)
                    {
                        string[] registro = new string[colunas];
                        long     posicao  = br.ReadInt64();
                        count = br.ReadInt32();
                        bool insere = true;
                        //Lê cada dado dentro do registro
                        for (int i = 0; i < count && insere; i++)
                        {
                            string   nomeColuna = meta.getNomesColunas()[i];
                            TipoDado tipo       = meta.getDados()[nomeColuna].getTipoDado();
                            bool     isPrimary  = meta.getDados()[nomeColuna].isPrimary();
                            string   valor      = "";
                            string   campo      = meta.getNome() + "." + nomeColuna;

                            if (tipo == TipoDado.Inteiro)
                            {
                                byte tamanho  = br.ReadByte();
                                bool isValido = br.ReadBoolean();
                                int  numero   = br.ReadInt32();
                                valor = isValido ? numero + "" : "NULL";
                                foreach (Filtro f in filtrosCampo[i])
                                {
                                    switch (f.Op)
                                    {
                                    case OperadorRel.Igual:
                                        if (f.RValue.ToLower().Equals("null"))
                                        {
                                            if (isValido)
                                            {
                                                insere = false;
                                            }
                                        }
                                        else
                                        {
                                            if (numero != Convert.ToInt32(f.RValue))
                                            {
                                                insere = false;
                                            }
                                        }
                                        break;

                                    case OperadorRel.MaiorQue:
                                        if (numero <= Convert.ToInt32(f.RValue))
                                        {
                                            insere = false;
                                        }
                                        break;

                                    case OperadorRel.MenorQue:
                                        if (numero >= Convert.ToInt32(f.RValue))
                                        {
                                            insere = false;
                                        }
                                        break;

                                    case OperadorRel.MaiorIgualA:
                                        if (numero < Convert.ToInt32(f.RValue))
                                        {
                                            insere = false;
                                        }
                                        break;

                                    case OperadorRel.MenorIgualA:
                                        if (numero > Convert.ToInt32(f.RValue))
                                        {
                                            insere = false;
                                        }
                                        break;

                                    case OperadorRel.Diferente:
                                        if (f.RValue.ToLower().Equals("null"))
                                        {
                                            if (!isValido)
                                            {
                                                insere = false;
                                            }
                                        }
                                        else
                                        {
                                            if (numero == Convert.ToInt32(f.RValue))
                                            {
                                                insere = false;
                                            }
                                        }
                                        break;

                                    default:
                                        throw new SGDBException("Passou onde nao devia: GambiarraSelect.retornaDados.Inteiro.Default.");
                                    }
                                }
                                if (insere && filtrosJoin.ContainsKey(campo))
                                {
                                    insere = filtrosJoin[campo].Exists(s => s.Equals(valor));
                                }
                            }
                            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.TrimEnd() : "NULL";
                                foreach (Filtro f in filtrosCampo[i])
                                {
                                    switch (f.Op)
                                    {
                                    case OperadorRel.Igual:
                                        if (f.RValue.ToLower().Equals("null"))
                                        {
                                            if (isValido)
                                            {
                                                insere = false;
                                            }
                                        }
                                        else
                                        {
                                            byte[] filtro = new byte[tamanho];
                                            new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(tamanho)).CopyTo(filtro, 0);
                                            string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro).TrimEnd();
                                            if (!valor.Equals(filtro2))
                                            {
                                                insere = false;
                                            }
                                        }
                                        break;

                                    case OperadorRel.Diferente:
                                        if (f.RValue.ToLower().Equals("null"))
                                        {
                                            if (isValido)
                                            {
                                                insere = false;
                                            }
                                        }
                                        else
                                        {
                                            byte[] filtro = new byte[tamanho];
                                            new System.Text.ASCIIEncoding().GetBytes(f.RValue.PadRight(tamanho)).CopyTo(filtro, 0);
                                            string filtro2 = new System.Text.ASCIIEncoding().GetString(filtro).TrimEnd();
                                            if (valor.Equals(filtro2))
                                            {
                                                insere = false;
                                            }
                                        }
                                        break;

                                    default:
                                        throw new SemanticError("Comparação de literais só pode ser igual ou diferente");
                                    }
                                }
                                if (insere && filtrosJoin.ContainsKey(campo))
                                {
                                    insere = filtrosJoin[campo].Exists(s => s.Equals(valor));
                                }
                            }

                            registro[i] = valor;
                        }

                        if (insere)
                        {
                            ts.Registros.Add(registro);
                            if (ts.Registros.Count >= Base.getInstance().qtd_max_registros)
                            {
                                break;
                            }
                        }

                        if (br.BaseStream.Position % tamRegistro != 0)
                        {
                            br.BaseStream.Position += tamRegistro - (br.BaseStream.Position % tamRegistro);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
            finally
            {
                if (br != null)
                {
                    br.Close();
                }
                if (file != null)
                {
                    file.Close();
                }
            }
            return(ts);
        }