Skip to content

Commit

Permalink
Merge pull request #42 from FrendsPlatform/issue-41
Browse files Browse the repository at this point in the history
ExecuteQuery - Removed SqlConnection.ClearAllPools() to make the Task more efficient
  • Loading branch information
Svenskapojkarna authored Mar 8, 2024
2 parents ab36551 + d48892a commit 939ed11
Show file tree
Hide file tree
Showing 12 changed files with 137 additions and 359 deletions.
7 changes: 7 additions & 0 deletions Frends.MicrosoftSQL.ExecuteQuery/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## [1.2.1] - 2024-03-01
### Changed
- Removed finally block from the Task so that the SQLConnection pool is not touched after every call to the ExecuteQuery method.
### Updated
- Newtonsoft.Json to version 13.0.3
- System.Data.SqlClient to version 4.8.6

## [1.2.0] - 2023-11-30
### Changed
- [Breaking] QueryParameter.Value type to object so that binary data can be used.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,50 +1,13 @@
using Frends.MicrosoftSQL.ExecuteQuery.Definitions;
using Frends.MicrosoftSQL.ExecuteQuery.Tests.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;

namespace Frends.MicrosoftSQL.ExecuteQuery.Tests;

[TestClass]
public class AutoUnitTests
public class AutoUnitTests : ExecuteQueryTestBase
{
/*
docker-compose up -d
How to use via terminal:
docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!"
SELECT * FROM TestTable
GO
*/

private static readonly string _connString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!";
private static readonly string _tableName = "TestTable";

[TestInitialize]
public void Init()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var createTable = connection.CreateCommand();
createTable.CommandText = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN CREATE TABLE {_tableName} ( Id int, LastName varchar(255), FirstName varchar(255) ); END";
createTable.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}

[TestCleanup]
public void CleanUp()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var createTable = connection.CreateCommand();
createTable.CommandText = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END";
createTable.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}

[TestMethod]
public async Task TestExecuteQuery_Auto()
{
Expand Down Expand Up @@ -113,7 +76,7 @@ public async Task TestExecuteQuery_Auto()
Assert.AreEqual(3, insert.RecordsAffected);
Assert.IsNull(insert.ErrorMessage);
Assert.AreEqual(3, (int)insert.Data["AffectedRows"]);
Assert.AreEqual(3, GetRowCount()); // Make sure rows inserted before moving on.
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // Make sure rows inserted before moving on.

// Select all
var select = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Expand All @@ -127,7 +90,7 @@ public async Task TestExecuteQuery_Auto()
Assert.AreEqual("Forst", (string)select.Data[1]["FirstName"]);
Assert.AreEqual("Hiiri", (string)select.Data[2]["LastName"]);
Assert.AreEqual("Mikki", (string)select.Data[2]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Select single
var selectSingle = await MicrosoftSQL.ExecuteQuery(inputSelectSingle, options, default);
Expand All @@ -137,29 +100,29 @@ public async Task TestExecuteQuery_Auto()
Assert.AreEqual(typeof(JArray), selectSingle.Data.GetType());
Assert.AreEqual("Suku", (string)selectSingle.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)selectSingle.Data[0]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Update
var update = await MicrosoftSQL.ExecuteQuery(inputUpdate, options, default);
Assert.IsTrue(update.Success);
Assert.AreEqual(1, update.RecordsAffected);
Assert.IsNull(update.ErrorMessage);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check
var checkUpdateResult = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Assert.AreEqual("Suku", (string)checkUpdateResult.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)checkUpdateResult.Data[0]["FirstName"]);
Assert.AreEqual("Edit", (string)checkUpdateResult.Data[1]["LastName"]);
Assert.AreEqual("Forst", (string)checkUpdateResult.Data[1]["FirstName"]);
Assert.AreEqual("Hiiri", (string)checkUpdateResult.Data[2]["LastName"]);
Assert.AreEqual("Mikki", (string)checkUpdateResult.Data[2]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Delete
var delete = await MicrosoftSQL.ExecuteQuery(inputDelete, options, default);
Assert.IsTrue(delete.Success);
Assert.AreEqual(1, delete.RecordsAffected);
Assert.IsNull(delete.ErrorMessage);
Assert.AreEqual(2, GetRowCount()); // double check
Assert.AreEqual(2, Helper.GetRowCount(_connString, _tableName)); // double check
var checkDeleteResult = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Assert.AreEqual("Suku", (string)checkDeleteResult.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)checkDeleteResult.Data[0]["FirstName"]);
Expand All @@ -169,16 +132,4 @@ public async Task TestExecuteQuery_Auto()
CleanUp();
}
}

private static int GetRowCount()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var getRows = connection.CreateCommand();
getRows.CommandText = $"SELECT COUNT(*) FROM {_tableName}";
var count = (int)getRows.ExecuteScalar();
connection.Close();
connection.Dispose();
return count;
}
}
Original file line number Diff line number Diff line change
@@ -1,63 +1,35 @@
using Frends.MicrosoftSQL.ExecuteQuery.Definitions;
using Frends.MicrosoftSQL.ExecuteQuery.Tests.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.SqlClient;

namespace Frends.MicrosoftSQL.ExecuteQuery.Tests;

[TestClass]
public class ExceptionUnitTests
public class ExceptionUnitTests : ExecuteQueryTestBase
{
/*
docker-compose up
How to use via terminal:
docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!"
SELECT * FROM TestTable
GO
*/

private static readonly string _connString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!";
private static readonly string _tableName = "TestTable";
private Input input = new();
private Options options = new();

[TestInitialize]
public void Init()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var createTable = connection.CreateCommand();
createTable.CommandText = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN CREATE TABLE {_tableName} ( Id int, LastName varchar(255), FirstName varchar(255) ); END";
createTable.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}

[TestCleanup]
public void CleanUp()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var createTable = connection.CreateCommand();
createTable.CommandText = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END";
createTable.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}

[TestMethod]
public async Task TestExecuteQuery_Invalid_Creds_ThrowError()
public void SetUp()
{
var input = new Input()
input = new Input()
{
ConnectionString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=WrongPassWord",
ConnectionString = _connString,
};

var options = new Options()
options = new Options()
{
SqlTransactionIsolationLevel = SqlTransactionIsolationLevel.ReadCommitted,
CommandTimeoutSeconds = 2,
ThrowErrorOnFailure = true
};
}

[TestMethod]
public async Task TestExecuteQuery_Invalid_Creds_ThrowError()
{
input.ConnectionString = Helper.GetInvalidConnectionString();

var ex = await Assert.ThrowsExceptionAsync<Exception>(() => MicrosoftSQL.ExecuteQuery(input, options, default));
Assert.IsTrue(ex.Message.Contains("Login failed for user 'SA'."));
Expand All @@ -66,17 +38,8 @@ public async Task TestExecuteQuery_Invalid_Creds_ThrowError()
[TestMethod]
public async Task TestExecuteQuery_Invalid_Creds_ReturnErrorMessage()
{
var input = new Input()
{
ConnectionString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=WrongPassWord",
};

var options = new Options()
{
SqlTransactionIsolationLevel = SqlTransactionIsolationLevel.ReadCommitted,
CommandTimeoutSeconds = 2,
ThrowErrorOnFailure = false
};
options.ThrowErrorOnFailure = false;
input.ConnectionString = Helper.GetInvalidConnectionString();

var result = await MicrosoftSQL.ExecuteQuery(input, options, default);
Assert.IsFalse(result.Success);
Expand All @@ -87,19 +50,8 @@ public async Task TestExecuteQuery_Invalid_Creds_ReturnErrorMessage()
[TestMethod]
public void TestExecuteQuery_ExceptionIsThrownWhenQueryFails()
{
var input = new Input()
{
Query = $"INSERT INTO {_tableName} VALUES (1, Unit, Tests, 456)",
ExecuteType = ExecuteTypes.NonQuery,
ConnectionString = _connString,
};

var options = new Options()
{
SqlTransactionIsolationLevel = SqlTransactionIsolationLevel.ReadCommitted,
CommandTimeoutSeconds = 2,
ThrowErrorOnFailure = true
};
input.Query = $"INSERT INTO {_tableName} VALUES (1, Unit, Tests, 456)";
input.ExecuteType = ExecuteTypes.NonQuery;

var ex = Assert.ThrowsExceptionAsync<Exception>(async () => await MicrosoftSQL.ExecuteQuery(input, options, default));
Assert.IsTrue(ex.Result.Message.Contains("System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Unit'."));
Expand All @@ -108,19 +60,10 @@ public void TestExecuteQuery_ExceptionIsThrownWhenQueryFails()
[TestMethod]
public async Task TestExecuteQuery_ErrorMessageWhenQueryFails()
{
var input = new Input()
{
Query = $"INSERT INTO {_tableName} VALUES (1, Unit, Tests, 456)",
ExecuteType = ExecuteTypes.NonQuery,
ConnectionString = _connString,
};
input.Query = $"INSERT INTO {_tableName} VALUES (1, Unit, Tests, 456)";
input.ExecuteType = ExecuteTypes.NonQuery;

var options = new Options()
{
SqlTransactionIsolationLevel = SqlTransactionIsolationLevel.ReadCommitted,
CommandTimeoutSeconds = 2,
ThrowErrorOnFailure = false
};
options.ThrowErrorOnFailure = false;

var result = await MicrosoftSQL.ExecuteQuery(input, options, default);
Assert.IsFalse(result.Success);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,14 @@
using Frends.MicrosoftSQL.ExecuteQuery.Definitions;
using Frends.MicrosoftSQL.ExecuteQuery.Tests.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;

namespace Frends.MicrosoftSQL.ExecuteQuery.Tests;

[TestClass]
public class ExecuteReaderUnitTests
public class ExecuteReaderUnitTests : ExecuteQueryTestBase
{
/*
docker-compose up
How to use via terminal:
docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!"
SELECT * FROM TestTable
GO
*/

private static readonly string _connString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!";
private static readonly string _tableName = "TestTable";

[TestInitialize]
public void Init()
{
var command = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN CREATE TABLE {_tableName} ( Id int, LastName varchar(255), FirstName varchar(255) ); END";
ExecuteQuery(command);
}

[TestCleanup]
public void CleanUp()
{
var command = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END";
ExecuteQuery(command);
}

[TestMethod]
public async Task TestExecuteQuery_ExecuteReader()
{
Expand Down Expand Up @@ -102,7 +76,7 @@ public async Task TestExecuteQuery_ExecuteReader()
Assert.IsTrue(insert.Success);
Assert.AreEqual(3, insert.RecordsAffected);
Assert.IsNull(insert.ErrorMessage);
Assert.AreEqual(3, GetRowCount()); // Make sure rows inserted before moving on.
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // Make sure rows inserted before moving on.

// Select all
var select = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Expand All @@ -116,7 +90,7 @@ public async Task TestExecuteQuery_ExecuteReader()
Assert.AreEqual("Forst", (string)select.Data[1]["FirstName"]);
Assert.AreEqual("Hiiri", (string)select.Data[2]["LastName"]);
Assert.AreEqual("Mikki", (string)select.Data[2]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Select single
var selectSingle = await MicrosoftSQL.ExecuteQuery(inputSelectSingle, options, default);
Expand All @@ -126,29 +100,29 @@ public async Task TestExecuteQuery_ExecuteReader()
Assert.AreEqual(typeof(JArray), selectSingle.Data.GetType());
Assert.AreEqual("Suku", (string)selectSingle.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)selectSingle.Data[0]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Update
var update = await MicrosoftSQL.ExecuteQuery(inputUpdate, options, default);
Assert.IsTrue(update.Success);
Assert.AreEqual(1, update.RecordsAffected);
Assert.IsNull(update.ErrorMessage);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check
var checkUpdateResult = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Assert.AreEqual("Suku", (string)checkUpdateResult.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)checkUpdateResult.Data[0]["FirstName"]);
Assert.AreEqual("Edit", (string)checkUpdateResult.Data[1]["LastName"]);
Assert.AreEqual("Forst", (string)checkUpdateResult.Data[1]["FirstName"]);
Assert.AreEqual("Hiiri", (string)checkUpdateResult.Data[2]["LastName"]);
Assert.AreEqual("Mikki", (string)checkUpdateResult.Data[2]["FirstName"]);
Assert.AreEqual(3, GetRowCount()); // double check
Assert.AreEqual(3, Helper.GetRowCount(_connString, _tableName)); // double check

// Delete
var delete = await MicrosoftSQL.ExecuteQuery(inputDelete, options, default);
Assert.IsTrue(delete.Success);
Assert.AreEqual(1, delete.RecordsAffected);
Assert.IsNull(delete.ErrorMessage);
Assert.AreEqual(2, GetRowCount()); // double check
Assert.AreEqual(2, Helper.GetRowCount(_connString, _tableName)); // double check
var checkDeleteResult = await MicrosoftSQL.ExecuteQuery(inputSelect, options, default);
Assert.AreEqual("Suku", (string)checkDeleteResult.Data[0]["LastName"]);
Assert.AreEqual("Etu", (string)checkDeleteResult.Data[0]["FirstName"]);
Expand Down Expand Up @@ -203,18 +177,6 @@ public async Task ExecuteQueryTestWithBinaryData()
Assert.AreEqual(Convert.ToBase64String(binary), Convert.ToBase64String((byte[])result.Data[0]["Data"]));
}

private static int GetRowCount()
{
using var connection = new SqlConnection(_connString);
connection.Open();
var getRows = connection.CreateCommand();
getRows.CommandText = $"SELECT COUNT(*) FROM {_tableName}";
var count = (int)getRows.ExecuteScalar();
connection.Close();
connection.Dispose();
return count;
}

private static void ExecuteQuery(string command)
{
using var connection = new SqlConnection(_connString);
Expand Down
Loading

0 comments on commit 939ed11

Please sign in to comment.