Last active
August 14, 2017 23:07
-
-
Save bgrainger/5f769e06bac7df8b15072e53145b6600 to your computer and use it in GitHub Desktop.
Formattable SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var name = "test"; | |
var state = "WA"; | |
var cmd = new MySqlConnection().CreateCommand($"SELECT * FROM Customers WHERE Name = {name} AND State = {state};"); | |
// cmd.CommandText == "SELECT * FROM Customers WHERE Name = @p0 AND State = @p1;" | |
} | |
public static class DbExtensions | |
{ | |
public static DbCommand CreateCommand(this DbConnection connection, FormattableString sql) | |
{ | |
var command = connection.CreateCommand(); | |
command.CommandText = sql.ToString(new SqlFormatProvider(command)); | |
return command; | |
} | |
} | |
public class SqlFormatProvider : IFormatProvider | |
{ | |
public SqlFormatProvider(DbCommand command) => Formatter = new SqlFormatter(command); | |
public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? Formatter : null; | |
private SqlFormatter Formatter { get;} | |
private class SqlFormatter : ICustomFormatter | |
{ | |
public SqlFormatter(DbCommand command) => Command = command; | |
public string Format(string format, object arg, IFormatProvider formatProvider) | |
{ | |
if (format != null) | |
throw new NotSupportedException($"Custom format '{format}' is not supported."); | |
var parameter = Command.CreateParameter(); | |
parameter.ParameterName = "@p" + command.Parameters.Count.ToString(); | |
parameter.Value = arg; | |
Command.Parameters.Add(parameter); | |
return parameter.ParameterName; | |
} | |
DbCommand Command { get; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment