Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use connection.CreateCommand instead of new SqlCommand() with connection setter #434

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(CommandText = "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
23 changes: 12 additions & 11 deletions src/SqlClient/ISqlCommand.fs
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,24 @@ 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()
true, cmd
| Choice2Of3 instance ->
let cmd = instance.CreateCommand()
false, cmd
| Choice3Of3 tran ->
cmd.Transaction <- tran
cmd.Connection <- tran.Connection
false
let cmd = tran.Connection.CreateCommand(Transaction = tran)
false, cmd

do
cmd.CommandTimeout <- commandTimeout
cmd.CommandText <- cfg.SqlStatement
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
Loading