public static async Task <ArquivoInfo> StartGenerateSQL(SqlGenerator sqlGenerator) { ArquivoInfo _arquivoInfo = new ArquivoInfo(); SqlParcialErros sqlParcialErros = new SqlParcialErros(); _arquivoInfo.erro = false; _arquivoInfo.Mensagem = "SQL Gerado com sucesso!"; columnTable.Clear(); var i = 0; try { if (sqlGenerator.HasHeader) { StringBuilder cabecalho = await Core.ReadFileHead(sqlGenerator.csvFile); _arquivoInfo.cabecalho = cabecalho.ToString().Split(new[] { sqlGenerator.delimiter }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (var item in _arquivoInfo.cabecalho) { Tabela tabela = new Tabela(); var nomeColuna = Core.RemoveAccentsAndEspecialCHars(item); if (columnTable.FindIndex(c => c.NomeCampo == nomeColuna) > 0) { nomeColuna = nomeColuna + "_" + i++; } tabela.NomeCampo = nomeColuna; tabela.TamanhoCampo = 1; columnTable.Add(tabela); } } string res = ConvertCSVtoSqlInsert(sqlGenerator.csvFile, sqlGenerator.delimiter, sqlGenerator.HasHeader, ref sqlParcialErros); gerarSQL(res, sqlGenerator.GenerateCreateTable); if (sqlParcialErros.sqlParcialErros) { _arquivoInfo.caminhoParcialErros = "ParcialErrors.txt"; _arquivoInfo.msgParcialErros = sqlParcialErros.msgParcialErros; using (StreamWriter stw = new StreamWriter("ParcialErrors.txt")) { stw.WriteLine(sqlParcialErros.linhasErros); } } } catch (Exception e) { _arquivoInfo.erro = true; _arquivoInfo.Mensagem = String.Format("Erro ao gerar SQL: {0}", e.Message); } return(_arquivoInfo); }
public static string ConvertCSVtoSqlInsert(IFormFile csvFile, string delimiter, bool hasHeader, ref SqlParcialErros sqlParcialErros) { int FILE_LINE = 0; string ALL_LINES = ""; using (StreamReader reader = new StreamReader(csvFile.OpenReadStream())) { if (hasHeader) { string[] headers = reader.ReadLine().Split(delimiter); } while (!reader.EndOfStream) { FILE_LINE++; string LINHAS_INSERT = "INSERT INTO /*<TABLE_NAME>*/ VALUES ("; try { var linha = reader.ReadLine(); string[] rows = linha.Split(delimiter); if (rows.Length < columnTable.Count) { sqlParcialErros.sqlParcialErros = true; sqlParcialErros.msgParcialErros = "Algumas linhas do arquivo geraram erro. Foi gerado um arquivo com os erros no mesmo diretório do sql"; sqlParcialErros.linhasErros += $"LINHA: {FILE_LINE} - REGISTRO: {linha} \n"; continue; } for (int i = 0; i < columnTable.Count; i++) { if (hasHeader) { if (columnTable[i].TamanhoCampo < rows[i].Length) { columnTable[i].TamanhoCampo = rows[i].Length; } } LINHAS_INSERT += $"'{rows[i].Replace("'", "''")}',"; } // remove ultimo caractere de uma string e fecha parentese LINHAS_INSERT = LINHAS_INSERT.Remove(LINHAS_INSERT.Length - 1, 1); LINHAS_INSERT += " );"; ALL_LINES += LINHAS_INSERT + " \n"; } catch (Exception e) { if (e.Message == "Index was outside the bounds of the array.") { continue; } else { throw new Exception(e.Message); } } } }; return(ALL_LINES); }