@@ -5,12 +5,11 @@ module CoreExt
5
5
module Explain
6
6
7
7
SQLSERVER_STATEMENT_PREFIX = 'EXEC sp_executesql ' . freeze
8
- SQLSERVER_PARAM_MATCHER = /@\d + = (.*)/
9
- SQLSERVER_NATIONAL_STRING_MATCHER = /N'(.*)'/m
8
+ SQLSERVER_STATEMENT_REGEXP = /N'(.+)', N'(.+)', (.+)/
10
9
11
10
def exec_explain ( queries )
12
11
unprepared_queries = queries . map do |( sql , binds ) |
13
- [ unprepare_sqlserver_statement ( sql ) , binds ]
12
+ [ unprepare_sqlserver_statement ( sql , binds ) , binds ]
14
13
end
15
14
super ( unprepared_queries )
16
15
end
@@ -19,22 +18,19 @@ def exec_explain(queries)
19
18
20
19
# This is somewhat hacky, but it should reliably reformat our prepared sql statment
21
20
# which uses sp_executesql to just the first argument, then unquote it. Likewise our
22
- # `sp_executesql` method should substitude the @n args withe the quoted values.
23
- def unprepare_sqlserver_statement ( sql )
24
- if sql . starts_with? ( SQLSERVER_STATEMENT_PREFIX )
25
- executesql = sql . from ( SQLSERVER_STATEMENT_PREFIX . length )
26
- args = executesql . split ( ', ' )
27
- unprepared_sql = args . shift . strip . match ( SQLSERVER_NATIONAL_STRING_MATCHER ) [ 1 ]
28
- unprepared_sql = Utils . unquote_string ( unprepared_sql )
29
- args = args . from ( args . length / 2 )
30
- args . each_with_index do |arg , index |
31
- value = arg . match ( SQLSERVER_PARAM_MATCHER ) [ 1 ]
32
- unprepared_sql . sub! "@#{ index } " , value
33
- end
34
- unprepared_sql
35
- else
36
- sql
21
+ # `sp_executesql` method should substitude the @n args with the quoted values.
22
+ def unprepare_sqlserver_statement ( sql , binds )
23
+ return sql unless sql . starts_with? ( SQLSERVER_STATEMENT_PREFIX )
24
+
25
+ executesql = sql . from ( SQLSERVER_STATEMENT_PREFIX . length )
26
+ executesql = executesql . match ( SQLSERVER_STATEMENT_REGEXP ) . to_a [ 1 ]
27
+
28
+ binds . each_with_index do |bind , index |
29
+ value = connection . quote ( bind )
30
+ executesql = executesql . sub ( "@#{ index } " , value )
37
31
end
32
+
33
+ executesql
38
34
end
39
35
40
36
end
0 commit comments