-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathParameterFormatter.cs
More file actions
67 lines (62 loc) · 1.77 KB
/
ParameterFormatter.cs
File metadata and controls
67 lines (62 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Text;
using JsonApiDotNetCore.Resources;
namespace DapperExample.TranslationToSql;
/// <summary>
/// Converts a SQL parameter into human-readable text. Used for diagnostic purposes.
/// </summary>
internal sealed class ParameterFormatter
{
private static readonly HashSet<Type> SimpleTypes =
[
typeof(bool),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(short),
typeof(ushort),
typeof(sbyte),
typeof(float),
typeof(double),
typeof(decimal)
];
public string Format(string parameterName, object? parameterValue)
{
StringBuilder builder = new();
builder.Append($"{parameterName} = ");
WriteValue(parameterValue, builder);
return builder.ToString();
}
private void WriteValue(object? parameterValue, StringBuilder builder)
{
if (parameterValue == null)
{
builder.Append("null");
}
else if (parameterValue is char)
{
builder.Append($"'{parameterValue}'");
}
else if (parameterValue is byte byteValue)
{
builder.Append($"0x{byteValue:X2}");
}
else if (parameterValue is Enum)
{
builder.Append($"{parameterValue.GetType().Name}.{parameterValue}");
}
else
{
string value = (string)RuntimeTypeConverter.ConvertType(parameterValue, typeof(string))!;
if (SimpleTypes.Contains(parameterValue.GetType()))
{
builder.Append(value);
}
else
{
string escapedValue = value.Replace("'", "''");
builder.Append($"'{escapedValue}'");
}
}
}
}