1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Data ;
4+ using System . Data . Common ;
5+ using System . Linq ;
6+ using System . Text ;
7+
8+ namespace SmartSql . Utils
9+ {
10+ public static class ExecutionContextExtensions
11+ {
12+ public static string FormatSql ( this ExecutionContext executionContext , bool withParameterValue )
13+ {
14+ StringBuilder stringBuilder = new StringBuilder ( ) ;
15+ var sourceParameters = executionContext . Request . Parameters . DbParameters . Values ;
16+ string dbParameterStr = string . Join ( "," , sourceParameters . Select ( p => $ "{ p . ParameterName } ={ p . Value } ") ) ;
17+ stringBuilder . AppendFormat ( "Statement.Id:[{0}]," , executionContext . Request . FullSqlId ) ;
18+ stringBuilder . Append ( "Sql:" ) ;
19+ stringBuilder . AppendLine ( ) ;
20+ stringBuilder . Append ( executionContext . Request . RealSql ) ;
21+ stringBuilder . AppendLine ( ) ;
22+ stringBuilder . AppendFormat ( "Parameters:[{0}]" , dbParameterStr ) ;
23+
24+ if ( ! withParameterValue )
25+ {
26+ return stringBuilder . ToString ( ) ;
27+ }
28+
29+ stringBuilder . AppendLine ( ) ;
30+ stringBuilder . Append ( "Sql with parameter value: " ) ;
31+ stringBuilder . AppendLine ( ) ;
32+ string realSql = FormatSqlWithParameters ( executionContext ) ;
33+ stringBuilder . Append ( realSql ) ;
34+
35+ return stringBuilder . ToString ( ) ;
36+ }
37+
38+ private static string FormatSqlWithParameters ( this ExecutionContext executionContext )
39+ {
40+ var sourceParameters = executionContext . Request . Parameters . DbParameters . Values ;
41+ return executionContext . SmartSqlConfig . SqlParamAnalyzer . Replace ( executionContext . Request . RealSql ,
42+ ( paramName , nameWithPrefix ) =>
43+ {
44+ var paramNameCompare = executionContext . SmartSqlConfig . Settings . IgnoreParameterCase
45+ ? StringComparison . CurrentCultureIgnoreCase
46+ : StringComparison . CurrentCulture ;
47+ var dbParam =
48+ sourceParameters . FirstOrDefault (
49+ m => String . Equals ( m . ParameterName , paramName , paramNameCompare ) ) ;
50+ if ( dbParam == null )
51+ {
52+ return nameWithPrefix ;
53+ }
54+
55+ if ( dbParam . Value == DBNull . Value )
56+ {
57+ return "NULL" ;
58+ }
59+
60+ switch ( dbParam . DbType )
61+ {
62+ case DbType . AnsiString :
63+ case DbType . AnsiStringFixedLength :
64+ case DbType . DateTime :
65+ case DbType . DateTime2 :
66+ case DbType . DateTimeOffset :
67+ case DbType . Guid :
68+ case DbType . String :
69+ case DbType . StringFixedLength :
70+ case DbType . Time :
71+ case DbType . Xml :
72+ {
73+ return $ "'{ dbParam . Value } '";
74+ }
75+
76+ case DbType . Boolean :
77+ {
78+ return ( ( bool ) dbParam . Value ) ? "1" : "0" ;
79+ }
80+ }
81+
82+ return dbParam . Value . ToString ( ) ;
83+ } ) ;
84+ }
85+ }
86+ }
0 commit comments