Skip to content

Commit c8602cf

Browse files
use connection.CreateCommand instead of new SqlCommand() with connection setter (#434)
1 parent 50497fb commit c8602cf

File tree

8 files changed

+36
-36
lines changed

8 files changed

+36
-36
lines changed

build.fsx

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ Target.create "DeployTestDB" (fun _ ->
161161
do //attach
162162
let dbIsMissing =
163163
let query = sprintf "SELECT COUNT(*) FROM sys.databases WHERE name = '%s'" database
164-
use cmd = new SqlCommand(query, conn)
164+
use cmd = conn.CreateCommand(CommandText = query)
165165
cmd.ExecuteScalar() = box 0
166166

167167
if dbIsMissing
@@ -176,20 +176,19 @@ Target.create "DeployTestDB" (fun _ ->
176176

177177

178178
let dataPath =
179-
use cmd = new SqlCommand("SELECT SERVERPROPERTY('InstanceDefaultDataPath')", conn)
179+
use cmd = conn.CreateCommand(CommandText = "SELECT SERVERPROPERTY('InstanceDefaultDataPath')")
180180
cmd.ExecuteScalar() |> string
181181
do
182182
let destFileName = dataPath @@ Path.GetFileName(sourceMdf)
183183
File.Copy(sourceMdf, destFileName, overwrite = true)
184184
File.Delete( sourceMdf)
185-
use cmd = new SqlCommand(Connection = conn)
186-
cmd.CommandText <- sprintf "CREATE DATABASE [%s] ON ( FILENAME = N'%s' ) FOR ATTACH" database destFileName
185+
use cmd = conn.CreateCommand(CommandText = sprintf "CREATE DATABASE [%s] ON ( FILENAME = N'%s' ) FOR ATTACH" database destFileName)
187186
cmd.ExecuteNonQuery() |> ignore
188187

189188
do //create extra object to test corner case
190189
let script = File.ReadAllText(testsSourceRoot @@ "extensions.sql")
191190
for batch in script.Split([|"GO";"go"|], StringSplitOptions.RemoveEmptyEntries) do
192-
use cmd = new SqlCommand(batch, conn)
191+
use cmd = conn.CreateCommand(CommandText = batch)
193192
cmd.ExecuteNonQuery() |> ignore
194193
)
195194

docs/content/faq.fsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ type SqlDataReader with
120120
let xs =
121121
use conn = new SqlConnection(connectionString)
122122
conn.Open()
123-
let cmd = new System.Data.SqlClient.SqlCommand(getDatesQuery, conn)
123+
let cmd = conn.CreateCommand(CommandText = getDatesQuery)
124124
cmd.ExecuteReader().ToRecords<GetDates.Record>()
125125
|> Seq.toArray
126126

src/SqlClient.DesignTime/DesignTime.fs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -406,9 +406,9 @@ type DesignTime private() =
406406
unbox cursor.["suggested_scale"] |> unbox<byte>
407407
)
408408

409-
static member internal ExtractParameters(connection, commandText: string, allParametersOptional) =
409+
static member internal ExtractParameters(connection : SqlConnection, commandText: string, allParametersOptional) =
410410

411-
use cmd = new SqlCommand("sys.sp_describe_undeclared_parameters", connection, CommandType = CommandType.StoredProcedure)
411+
use cmd = connection.CreateCommand(CommandText = "sys.sp_describe_undeclared_parameters", CommandType = CommandType.StoredProcedure)
412412
cmd.Parameters.AddWithValue("@tsql", commandText) |> ignore
413413

414414
let parameters =
@@ -700,7 +700,7 @@ type DesignTime private() =
700700
rowType
701701

702702
// Changes any temp tables in to a global temp table (##name) then creates them on the open connection.
703-
static member internal SubstituteTempTables(connection, commandText: string, tempTableDefinitions : string, connectionId, unitsOfMeasurePerSchema) =
703+
static member internal SubstituteTempTables(connection : SqlConnection, commandText: string, tempTableDefinitions : string, connectionId, unitsOfMeasurePerSchema) =
704704
// Extract and temp tables
705705
let tempTableRegex = Regex("#([a-z0-9\-_]+)", RegexOptions.IgnoreCase)
706706
let tempTableNames =
@@ -714,13 +714,13 @@ type DesignTime private() =
714714
| _ ->
715715
// Create temp table(s), extracts the columns then drop it.
716716
let tableTypes =
717-
use create = new SqlCommand(tempTableDefinitions, connection)
717+
use create = connection.CreateCommand(CommandText = tempTableDefinitions)
718718
create.ExecuteScalar() |> ignore
719719

720720
tempTableNames
721721
|> List.map(fun name ->
722722
let cols = DesignTime.GetOutputColumns(connection, "SELECT * FROM #"+name, [], isStoredProcedure = false)
723-
use drop = new SqlCommand("DROP TABLE #"+name, connection)
723+
use drop = connection.CreateCommand(CommandText = "DROP TABLE #"+name)
724724
drop.ExecuteScalar() |> ignore
725725
DesignTime.CreateTempTableRecord(name, cols, unitsOfMeasurePerSchema), cols)
726726

@@ -758,14 +758,14 @@ type DesignTime private() =
758758
cmd.Raw.Connection @@>
759759

760760
<@@ do
761-
use create = new SqlCommand(tempTableDefinitions, (%%connection : SqlConnection))
761+
use create = (%%connection : SqlConnection).CreateCommand(CommandText = tempTableDefinitions)
762762
create.ExecuteNonQuery() |> ignore
763763

764764
(%%loadValues exprArgs connection)
765765
ignore() @@>)
766766

767767
// Create the temp table(s) but as a global temp table with a unique name. This can be used later down stream on the open connection.
768-
use cmd = new SqlCommand(tempTableRegex.Replace(tempTableDefinitions, Prefixes.tempTable+connectionId+"$1"), connection)
768+
use cmd = connection.CreateCommand(CommandText = tempTableRegex.Replace(tempTableDefinitions, Prefixes.tempTable+connectionId+"$1"))
769769
cmd.ExecuteScalar() |> ignore
770770

771771
// Only replace temp tables we find in our list.

src/SqlClient.DesignTime/Scripts/XE.fsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ do
5555
ALTER EVENT SESSION [%s] ON SERVER STATE = START
5656
END
5757
" xeSession xeSession targetDatabase targetDatabase targetDatabase xeSession xeSession
58-
use cmd = new System.Data.SqlClient.SqlCommand(createSession, conn)
58+
use cmd = conn.CreateCommand(CommandText = createSession)
5959
cmd.ExecuteNonQuery() |> ignore
6060

6161
do

src/SqlClient.DesignTime/SqlClientExtensions.fs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ type SqlConnection with
217217

218218
member internal this.GetUserSchemas() =
219219
use __ = this.UseLocally()
220-
use cmd = new SqlCommand("SELECT name FROM sys.schemas WHERE principal_id = 1", this)
220+
use cmd = this.CreateCommand(CommandText = "SELECT name FROM sys.schemas WHERE principal_id = 1")
221221
cmd.ExecuteQuery(fun record -> record.GetString(0)) |> Seq.toList
222222

223223
member internal this.GetRoutines( schema, isSqlAzure) =
@@ -282,7 +282,7 @@ type SqlConnection with
282282
[Schema] = @schema
283283
" descriptionSelector
284284

285-
use cmd = new SqlCommand(getRoutinesQuery, this)
285+
use cmd = this.CreateCommand(CommandText = getRoutinesQuery)
286286
cmd.Parameters.AddWithValue("@schema", schema) |> ignore
287287

288288
cmd.ExecuteQuery(fun x ->
@@ -355,7 +355,7 @@ type SqlConnection with
355355
AND OBJECT_ID('%s.%s') = object_id" descriptionSelector <|| routine.BaseObject
356356

357357
[
358-
use cmd = new SqlCommand(query, this)
358+
use cmd = this.CreateCommand(CommandText = query)
359359
use cursor = cmd.ExecuteReader()
360360
while cursor.Read() do
361361
let name = string cursor.["name"]
@@ -445,7 +445,7 @@ type SqlConnection with
445445
OUTER APPLY %s AS XProp
446446
WHERE
447447
[Schema] = '%s'" descriptionSelector schema
448-
use cmd = new SqlCommand(getTablesQuery, this)
448+
use cmd = this.CreateCommand(CommandText = getTablesQuery)
449449
cmd.ExecuteQuery(fun x ->
450450
string x.["Name"],
451451
string x.["BaseTableName"],
@@ -455,7 +455,7 @@ type SqlConnection with
455455

456456
member internal this.GetFullQualityColumnInfo commandText =
457457
assert (this.State = ConnectionState.Open)
458-
use cmd = new SqlCommand("sys.sp_describe_first_result_set", this, CommandType = CommandType.StoredProcedure)
458+
use cmd = this.CreateCommand(CommandText = "sys.sp_describe_first_result_set", CommandType = CommandType.StoredProcedure)
459459
cmd.Parameters.AddWithValue("@tsql", commandText) |> ignore
460460
cmd.ExecuteQuery(fun cursor ->
461461
let user_type_id = cursor.TryGetValue "user_type_id"
@@ -481,7 +481,7 @@ type SqlConnection with
481481
member internal this.FallbackToSETFMONLY(commandText, commandType, parameters: Parameter list) =
482482
assert (this.State = ConnectionState.Open)
483483

484-
use cmd = new SqlCommand(commandText, this, CommandType = commandType)
484+
use cmd = this.CreateCommand(CommandText = commandText, CommandType = commandType)
485485
for p in parameters do
486486
cmd.Parameters.Add(p.Name, p.TypeInfo.SqlDbType) |> ignore
487487
use reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)
@@ -515,7 +515,7 @@ type SqlConnection with
515515
assert (this.State = ConnectionState.Open)
516516

517517
let sqlEngineTypes, tableVariableTypes =
518-
use cmd = new SqlCommand("""
518+
use cmd = this.CreateCommand(CommandText = """
519519
select
520520
t.name, t.system_type_id, t.user_type_id, t.is_table_type, s.name as schema_name, t.is_user_defined, t.[precision], t.scale
521521
from
@@ -531,7 +531,7 @@ order by
531531
, tt.user_type_id
532532
, c.user_type_id
533533
"""
534-
, this)
534+
)
535535
use reader = cmd.ExecuteReader()
536536

537537
[| while reader.Read() do

src/SqlClient.DesignTime/SqlClientProvider.fs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ type SqlProgrammabilityProvider(config : TypeProviderConfig) as this =
282282
columns.column_id
283283
" descriptionSelector
284284

285-
let cmd = new SqlCommand(query, conn)
285+
let cmd = conn.CreateCommand(CommandText = query)
286286
cmd.Parameters.AddWithValue("@tableName", baseTableName) |> ignore
287287
cmd.Parameters.AddWithValue("@schema", baseSchemaName) |> ignore
288288

src/SqlClient/Extensions.fs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ module Extensions =
4040
Async.AwaitTask(this.ExecuteNonQueryAsync())
4141
#endif
4242

43-
static member internal DefaultTimeout = (new SqlCommand()).CommandTimeout
43+
static member internal DefaultTimeout = 30 // used to be (new SqlCommand()).CommandTimeout , both System.Data.SqlClient and Microsoft.Data.SqlClient default to 30
4444

4545
member internal this.ExecuteQuery mapper =
4646
seq {
@@ -63,7 +63,7 @@ module Extensions =
6363

6464
member this.IsSqlAzure =
6565
assert (this.State = ConnectionState.Open)
66-
use cmd = new SqlCommand("SELECT SERVERPROPERTY('edition')", this)
66+
use cmd = this.CreateCommand(CommandText = "SELECT SERVERPROPERTY('edition')")
6767
cmd.ExecuteScalar().Equals("SQL Azure")
6868

6969

src/SqlClient/ISqlCommand.fs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,23 +53,24 @@ type internal Connection = Choice<string, SqlConnection, SqlTransaction>
5353

5454
[<CompilerMessageAttribute("This API supports the FSharp.Data.SqlClient infrastructure and is not intended to be used directly from your code.", 101, IsHidden = true)>]
5555
type ``ISqlCommand Implementation``(cfg: DesignTimeConfig, connection: Connection, commandTimeout) =
56-
let cmd = new SqlCommand(cfg.SqlStatement, CommandTimeout = commandTimeout)
57-
let manageConnection =
56+
let manageConnection, cmd =
5857
match connection with
5958
| Choice1Of3 connectionString ->
60-
cmd.Connection <- new SqlConnection(connectionString)
61-
true
62-
| Choice2Of3 instance ->
63-
cmd.Connection <- instance
64-
false
59+
let connection = new SqlConnection(connectionString)
60+
let cmd = connection.CreateCommand()
61+
true, cmd
62+
| Choice2Of3 instance ->
63+
let cmd = instance.CreateCommand()
64+
false, cmd
6565
| Choice3Of3 tran ->
66-
cmd.Transaction <- tran
67-
cmd.Connection <- tran.Connection
68-
false
66+
let cmd = tran.Connection.CreateCommand(Transaction = tran)
67+
false, cmd
6968

7069
do
70+
cmd.CommandTimeout <- commandTimeout
71+
cmd.CommandText <- cfg.SqlStatement
7172
cmd.CommandType <- if cfg.IsStoredProcedure then CommandType.StoredProcedure else CommandType.Text
72-
cmd.Parameters.AddRange( cfg.Parameters)
73+
cmd.Parameters.AddRange(cfg.Parameters)
7374

7475
let getReaderBehavior() =
7576
seq {

0 commit comments

Comments
 (0)