danikf/tik4net

[Suggestion] ExecuteScalarOrDefault

Deantwo opened this issue · 4 comments

Same as with #58, cmd.ExecuteScalar() throws an exception when no result is found. It might be acceptable that it throws an exception when there are multiple results, rather than randomly return the first value in the sentence.

But a cmd.ExecuteScalarOrDefault() would be nice to have.

A extension method version of this:

internal static string ExecuteScalarOrDefault(this ITikCommand cmd)
{
    IEnumerable<ITikSentence> sentences = cmd.ExecuteList();
    ITikSentence sentence = sentences.SingleOrDefault();
    if (sentence == null || sentence.Words == null)
        return null;
    KeyValuePair<string, string> word = sentence.Words.SingleOrDefault();
    if (word.Equals(default(KeyValuePair<string, string>)))
        return null;
    return word.Value;
}

Could actually upgrade cmd.ExecuteScalar() to take an optional string argument, so it can automatically add a command parameter with $"=.proplist={target}".

Extension method example:

internal static string ExecuteScalar(this ITikCommand cmd, string target)
{
    cmd.AddProplistParameter(target);
    return cmd.ExecuteScalar();
}

internal static string ExecuteScalarOrDefault(this ITikCommand cmd, string target)
{
    cmd.AddProplistParameter(target);
    return cmd.ExecuteScalarOrDefault();
}

See #56, for my notes on .proplist and the cmd.AddProplistParameter(params string[] proplist) extension method.

Another fun idea, do a scalar list.
Extension method example:

internal static List<string> ExecuteScalarList(this ITikCommand cmd)
{
    //throw new NotImplementedException();
    IEnumerable<ITikReSentence> listRe = cmd.ExecuteList();
    List<string> listScalar = new List<string>();
    foreach (ITikReSentence re in listRe)
    {
        string scalar = re.Words.Single().Value;
        listScalar.Add(scalar);
    }
    return listScalar;
}

internal static List<string> ExecuteScalarList(this ITikCommand cmd, string target)
{
    cmd.AddProplistParameter(target);
    IEnumerable<ITikReSentence> listRe = cmd.ExecuteList();
    return cmd.ExecuteScalarList();
}

This might be a little too situational, but useful nonetheless.
Maybe I should just add some of all these extension methods to the wiki or something?

ExecuteScalarOrDefault - implemented
ExecuteScalar + target - implemented
ExecuteScalarList - implemented as ExecuteList(params string[] proplistFields)