Skip to content

Commit

Permalink
use connection.CreateCommand instead of new SqlCommand() with connect…
Browse files Browse the repository at this point in the history
…ion setter
  • Loading branch information
smoothdeveloper committed Dec 3, 2023
1 parent 50497fb commit 1d54fff
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 36 deletions.
9 changes: 4 additions & 5 deletions build.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ Target.create "DeployTestDB" (fun _ ->
do //attach
let dbIsMissing =
let query = sprintf "SELECT COUNT(*) FROM sys.databases WHERE name = '%s'" database
use cmd = new SqlCommand(query, conn)
use cmd = conn.CreateCommand(CommandText = query)
cmd.ExecuteScalar() = box 0

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


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

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

Expand Down
2 changes: 1 addition & 1 deletion docs/content/faq.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ type SqlDataReader with
let xs =
use conn = new SqlConnection(connectionString)
conn.Open()
let cmd = new System.Data.SqlClient.SqlCommand(getDatesQuery, conn)
let cmd = conn.CreateCommand(CommandText = getDatesQuery)
cmd.ExecuteReader().ToRecords<GetDates.Record>()
|> Seq.toArray

Expand Down
14 changes: 7 additions & 7 deletions src/SqlClient.DesignTime/DesignTime.fs
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,9 @@ type DesignTime private() =
unbox cursor.["suggested_scale"] |> unbox<byte>
)

static member internal ExtractParameters(connection, commandText: string, allParametersOptional) =
static member internal ExtractParameters(connection : SqlConnection, commandText: string, allParametersOptional) =

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

let parameters =
Expand Down Expand Up @@ -700,7 +700,7 @@ type DesignTime private() =
rowType

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

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

Expand Down Expand Up @@ -758,14 +758,14 @@ type DesignTime private() =
cmd.Raw.Connection @@>

<@@ do
use create = new SqlCommand(tempTableDefinitions, (%%connection : SqlConnection))
use create = (%%connection : SqlConnection).CreateCommand(CommandText = tempTableDefinitions)
create.ExecuteNonQuery() |> ignore

(%%loadValues exprArgs connection)
ignore() @@>)

// 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.
use cmd = new SqlCommand(tempTableRegex.Replace(tempTableDefinitions, Prefixes.tempTable+connectionId+"$1"), connection)
use cmd = connection.CreateCommand(CommandText = tempTableRegex.Replace(tempTableDefinitions, Prefixes.tempTable+connectionId+"$1"))
cmd.ExecuteScalar() |> ignore

// Only replace temp tables we find in our list.
Expand Down
2 changes: 1 addition & 1 deletion src/SqlClient.DesignTime/Scripts/XE.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ do
ALTER EVENT SESSION [%s] ON SERVER STATE = START
END
" xeSession xeSession targetDatabase targetDatabase targetDatabase xeSession xeSession
use cmd = new System.Data.SqlClient.SqlCommand(createSession, conn)
use cmd = conn.CreateCommand(CommandText = createSession)
cmd.ExecuteNonQuery() |> ignore

do
Expand Down
16 changes: 8 additions & 8 deletions src/SqlClient.DesignTime/SqlClientExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ type SqlConnection with

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

member internal this.GetRoutines( schema, isSqlAzure) =
Expand Down Expand Up @@ -282,7 +282,7 @@ type SqlConnection with
[Schema] = @schema
" descriptionSelector

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

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

[
use cmd = new SqlCommand(query, this)
use cmd = this.CreateCommand(CommandText = query)
use cursor = cmd.ExecuteReader()
while cursor.Read() do
let name = string cursor.["name"]
Expand Down Expand Up @@ -445,7 +445,7 @@ type SqlConnection with
OUTER APPLY %s AS XProp
WHERE
[Schema] = '%s'" descriptionSelector schema
use cmd = new SqlCommand(getTablesQuery, this)
use cmd = this.CreateCommand(CommandText = getTablesQuery)
cmd.ExecuteQuery(fun x ->
string x.["Name"],
string x.["BaseTableName"],
Expand All @@ -455,7 +455,7 @@ type SqlConnection with

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

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

let sqlEngineTypes, tableVariableTypes =
use cmd = new SqlCommand("""
use cmd = this.CreateCommand(CommandText = """
select
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
from
Expand All @@ -531,7 +531,7 @@ order by
, tt.user_type_id
, c.user_type_id
"""
, this)
)
use reader = cmd.ExecuteReader()

[| while reader.Read() do
Expand Down
2 changes: 1 addition & 1 deletion src/SqlClient.DesignTime/SqlClientProvider.fs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ type SqlProgrammabilityProvider(config : TypeProviderConfig) as this =
columns.column_id
" descriptionSelector

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

Expand Down
4 changes: 2 additions & 2 deletions src/SqlClient/Extensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ module Extensions =
Async.AwaitTask(this.ExecuteNonQueryAsync())
#endif

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

member internal this.ExecuteQuery mapper =
seq {
Expand All @@ -63,7 +63,7 @@ module Extensions =

member this.IsSqlAzure =
assert (this.State = ConnectionState.Open)
use cmd = new SqlCommand("SELECT SERVERPROPERTY('edition')", this)
use cmd = this.CreateCommand(CommandText = "SELECT SERVERPROPERTY('edition')")
cmd.ExecuteScalar().Equals("SQL Azure")


Expand Down
21 changes: 10 additions & 11 deletions src/SqlClient/ISqlCommand.fs
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,22 @@ type internal Connection = Choice<string, SqlConnection, SqlTransaction>

[<CompilerMessageAttribute("This API supports the FSharp.Data.SqlClient infrastructure and is not intended to be used directly from your code.", 101, IsHidden = true)>]
type ``ISqlCommand Implementation``(cfg: DesignTimeConfig, connection: Connection, commandTimeout) =
let cmd = new SqlCommand(cfg.SqlStatement, CommandTimeout = commandTimeout)
let manageConnection =
let manageConnection, cmd =
match connection with
| Choice1Of3 connectionString ->
cmd.Connection <- new SqlConnection(connectionString)
true
| Choice2Of3 instance ->
cmd.Connection <- instance
false
let connection = new SqlConnection(connectionString)
let cmd = connection.CreateCommand(CommandTimeout = commandTimeout)
true, cmd
| Choice2Of3 instance ->
let cmd = instance.CreateCommand(CommandTimeout = commandTimeout)
false, cmd
| Choice3Of3 tran ->
cmd.Transaction <- tran
cmd.Connection <- tran.Connection
false
let cmd = tran.Connection.CreateCommand(Transaction = tran, Connection = tran.Connection, CommandTimeout = commandTimeout)
false, cmd

do
cmd.CommandType <- if cfg.IsStoredProcedure then CommandType.StoredProcedure else CommandType.Text
cmd.Parameters.AddRange( cfg.Parameters)
cmd.Parameters.AddRange(cfg.Parameters)

let getReaderBehavior() =
seq {
Expand Down

0 comments on commit 1d54fff

Please sign in to comment.