This is a single function in C#. It works fine. My concern is that although I've made the code as short and as multi-functional as I can, what it's doing seems very unclear. It looks like the sort of thing I'm going to come back to in six months and hate myself for writing.
Its purpose is to build and execute generic "upsert" sql statements for a variety of scenarios. Each record that it comes across has a name, an address and a flag to say whether the operation on that record is a delete and whether that record represents someone who's gone away. The former tells us whether we're setting a bit value to true or false, while the latter determines the column name.
How can I make this code clearer without turning it into a mess of flow control?
private void Sprail(FileRow fr, string columnName)
{
List<Suppression> addressMatches = GetMatchingRecordsFromDb(SanitiseForMySql(fr.CleanedAddress), SanitiseForMySql(fr.CleanedName));
using (MySqlConnection con = new MySqlConnection(_connectionString))
{
string sqlTargetFlag = columnName;
string sqlTargetValue = "1";
string sql = "";
if (fr.IsDeleted)
{
sqlTargetValue = "0";
}
if (fr.IsGoneaway)
{
sqlTargetFlag = sqlTargetFlag + "Goneaway";
}
if (string.IsNullOrWhiteSpace(fr.CleanedAddress))
{
sql = BuildInsertSql(sqlTargetFlag, fr, sqlTargetValue);
}
foreach (Suppression s in addressMatches)
{
if (fr.CleanedName.ToString().ToLower() == s.NameKey.ToLower())
{
sql = string.Format("UPDATE MyTable set {0} = {1} where SuppressionId = {2}", sqlTargetFlag, sqlTargetValue, s.SuppressionId);
break;
}
}
if(sql != "")
{
con.Open();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.ExecuteNonQuery();
}
}
}
private string BuildInsertSql(string sqlTargetFlag, FileRow fr, string sqlTargetValue)
{
return string.Format(@"INSERT INTO MyTable (`AddressKey`, `NameKey`, `{0}`) VALUES ('{1}', '{2}', '{3}')",
sqlTargetFlag, SanitiseForMySql(fr.CleanedAddress), SanitiseForMySql(fr.CleanedName), sqlTargetValue);
}