Skip to content

Commit 2a87b57

Browse files
authored
Improve ToTraceString
Fixes some annoying issues with the query generated by `ToTraceString`: - `tinyint` and `xml` data formats have a width specifier (1 and -1 respectively), but MSSQL doesn't recognize it in input - date/time parameters are printed in local formats, which may or may not be accepted by the server - parameter values aren't escaped if they contain `'`
1 parent 37a6ae5 commit 2a87b57

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/SqlClient/ISqlCommand.fs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,11 @@ type ``ISqlCommand Implementation``(cfg: DesignTimeConfig, connection: Connectio
134134
member this.ToTraceString parameters =
135135
``ISqlCommand Implementation``.SetParameters(cmd, parameters)
136136
let parameterDefinition (p : SqlParameter) =
137-
if p.Size <> 0 then
137+
// tinyint and Xml have size 1 and -1 respectively, but MSSQL will throw if they are specified
138+
if p.Size <> 0 &&
139+
p.SqlDbType <> SqlDbType.Xml &&
140+
p.SqlDbType <> SqlDbType.TinyInt then
141+
138142
sprintf "%s %A(%d)" p.ParameterName p.SqlDbType p.Size
139143
else
140144
sprintf "%s %A" p.ParameterName p.SqlDbType
@@ -153,7 +157,17 @@ type ``ISqlCommand Implementation``(cfg: DesignTimeConfig, connection: Connectio
153157
if parameters.Length > 0
154158
then
155159
yield parameters
156-
|> Seq.map(fun (name,value) -> sprintf "%s='%O'" name value)
160+
|> Seq.map(fun (name,value) ->
161+
let printedValue =
162+
match value with
163+
// print dates in roundtrip ISO8601 format "O"
164+
| :? System.DateTime as d -> d.ToString("O")
165+
// print timespans in constant format "c
166+
| :? System.TimeSpan as t -> t.ToString("c")
167+
| v -> sprintf "%O" v
168+
// escapes the resulting value
169+
sprintf "%s='%s'" name (printedValue.Replace("'", "''"))
170+
)
157171
|> String.concat ","
158172
} |> String.concat "," //Using string.concat to handle annoying case with no parameters
159173

0 commit comments

Comments
 (0)