Edit Data: Better errors for possible truncation (#514)

* Fix to make sql exceptions surface properly to user (with important notes!)

* Adding support for detecting column size issues when updating a cell

* Adding unit tests for the exception on read scenario
This commit is contained in:
Benjamin Russell
2017-10-21 11:08:40 -07:00
committed by Karl Burtram
parent 9499d73cec
commit e9bc97e290
37 changed files with 445 additions and 343 deletions

View File

View File

View File

@@ -49,10 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement
} }
else if (columnType == typeof(string)) else if (columnType == typeof(string))
{ {
// Special case for strings because the string value should stay the same as provided ProcessTextCell(valueAsString);
// If user typed 'NULL' they mean NULL as text
Value = valueAsString == TextNullString ? NullString : valueAsString;
ValueAsString = valueAsString;
} }
else if (columnType == typeof(Guid)) else if (columnType == typeof(Guid))
{ {
@@ -245,6 +242,23 @@ namespace Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement
ValueAsString = NullString; ValueAsString = NullString;
} }
private void ProcessTextCell(string valueAsString)
{
// Special case for strings because the string value should stay the same as provided
// If user typed 'NULL' they mean NULL as text
Value = valueAsString == TextNullString ? NullString : valueAsString;
// Make sure that the value fits inside the size of the column
if (Column.ColumnSize.HasValue && valueAsString.Length > Column.ColumnSize)
{
string columnSizeString = $"({Column.ColumnSize.Value})";
string columnTypeString = Column.DataTypeName.ToUpperInvariant() + columnSizeString;
throw new FormatException(SR.EditDataValueTooLarge(valueAsString, columnTypeString));
}
ValueAsString = valueAsString;
}
#endregion #endregion
} }
} }

View File

@@ -3651,6 +3651,11 @@ namespace Microsoft.SqlTools.ServiceLayer
return Keys.GetString(Keys.EditDataUnsupportedObjectType, typeName); return Keys.GetString(Keys.EditDataUnsupportedObjectType, typeName);
} }
public static string EditDataValueTooLarge(string value, string columnType)
{
return Keys.GetString(Keys.EditDataValueTooLarge, value, columnType);
}
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Keys public class Keys
{ {
@@ -3932,6 +3937,9 @@ namespace Microsoft.SqlTools.ServiceLayer
public const string EditDataNullNotAllowed = "EditDataNullNotAllowed"; public const string EditDataNullNotAllowed = "EditDataNullNotAllowed";
public const string EditDataValueTooLarge = "EditDataValueTooLarge";
public const string EE_BatchSqlMessageNoProcedureInfo = "EE_BatchSqlMessageNoProcedureInfo"; public const string EE_BatchSqlMessageNoProcedureInfo = "EE_BatchSqlMessageNoProcedureInfo";

View File

@@ -495,6 +495,11 @@
<value>NULL is not allowed for this column</value> <value>NULL is not allowed for this column</value>
<comment></comment> <comment></comment>
</data> </data>
<data name="EditDataValueTooLarge" xml:space="preserve">
<value>Value {0} is too large to fit in column of type {1}</value>
<comment>.
Parameters: 0 - value (string), 1 - columnType (string) </comment>
</data>
<data name="EE_BatchSqlMessageNoProcedureInfo" xml:space="preserve"> <data name="EE_BatchSqlMessageNoProcedureInfo" xml:space="preserve">
<value>Msg {0}, Level {1}, State {2}, Line {3}</value> <value>Msg {0}, Level {1}, State {2}, Line {3}</value>
<comment></comment> <comment></comment>

View File

@@ -232,6 +232,8 @@ EditDataTimeOver24Hrs = TIME column values must be between 00:00:00.0000000 and
EditDataNullNotAllowed = NULL is not allowed for this column EditDataNullNotAllowed = NULL is not allowed for this column
EditDataValueTooLarge(string value, string columnType) = Value {0} is too large to fit in column of type {1}
############################################################################ ############################################################################
# DacFx Resources # DacFx Resources

View File

@@ -2305,6 +2305,12 @@
<target state="new">For directory {0} a file with name {1} already exists</target> <target state="new">For directory {0} a file with name {1} already exists</target>
<note></note> <note></note>
</trans-unit> </trans-unit>
<trans-unit id="EditDataValueTooLarge">
<source>Value {0} is too large to fit in column of type {1}</source>
<target state="new">Value {0} is too large to fit in column of type {1}</target>
<note>.
Parameters: 0 - value (string), 1 - columnType (string) </note>
</trans-unit>
</body> </body>
</file> </file>
</xliff> </xliff>

View File

@@ -616,19 +616,23 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution
{ {
throw new InvalidOperationException(SR.QueryServiceResultSetNotRead); throw new InvalidOperationException(SR.QueryServiceResultSetNotRead);
} }
if (!dbDataReader.HasRows) // NOTE: We are no longer checking to see if the data reader has rows before reading
// b/c of a quirk in SqlClient. In some scenarios, a SqlException isn't thrown until we
// read. In order to get appropriate errors back to the user, we'll read first.
// Returning false from .ReadAsync means there aren't any rows.
// Create a storage data reader, read it, make sure there were results
StorageDataReader dataReader = new StorageDataReader(dbDataReader);
if (!await dataReader.ReadAsync(CancellationToken.None))
{ {
throw new InvalidOperationException(SR.QueryServiceResultSetAddNoRows); throw new InvalidOperationException(SR.QueryServiceResultSetAddNoRows);
} }
StorageDataReader dataReader = new StorageDataReader(dbDataReader);
using (IFileStreamWriter writer = fileStreamFactory.GetWriter(outputFileName)) using (IFileStreamWriter writer = fileStreamFactory.GetWriter(outputFileName))
{ {
// Write the row to the end of the file // Write the row to the end of the file
long currentFileOffset = totalBytesWritten; long currentFileOffset = totalBytesWritten;
writer.Seek(currentFileOffset); writer.Seek(currentFileOffset);
await dataReader.ReadAsync(CancellationToken.None);
totalBytesWritten += writer.WriteRow(dataReader); totalBytesWritten += writer.WriteRow(dataReader);
return currentFileOffset; return currentFileOffset;
} }

View File

@@ -36,7 +36,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var commandMockSetup = commandMock.Protected() var commandMockSetup = commandMock.Protected()
.Setup<DbDataReader>("ExecuteDbDataReader", It.IsAny<CommandBehavior>()); .Setup<DbDataReader>("ExecuteDbDataReader", It.IsAny<CommandBehavior>());
commandMockSetup.Returns(() => new TestDbDataReader(data)); commandMockSetup.Returns(() => new TestDbDataReader(data, false));
return commandMock.Object; return commandMock.Object;
} }

View File

@@ -36,7 +36,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{ {
// If: I attempt to create a CellUpdate to set it to NULL // If: I attempt to create a CellUpdate to set it to NULL
const string nullString = "NULL"; const string nullString = "NULL";
DbColumnWrapper col = GetWrapper<string>("ntext", true); DbColumnWrapper col = GetWrapper<string>("ntext");
CellUpdate cu = new CellUpdate(col, nullString); CellUpdate cu = new CellUpdate(col, nullString);
// Then: The value should be a DBNull and the string value should be the same as what // Then: The value should be a DBNull and the string value should be the same as what
@@ -69,6 +69,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
Assert.Equal(col, cu.Column); Assert.Equal(col, cu.Column);
} }
[Theory]
[InlineData("This is way too long")]
[InlineData("TooLong")]
public void StringTooLongTest(string value)
{
// If: I attempt to create a CellUpdate to set it to a large string
// Then: I should get an exception thrown
DbColumnWrapper col = GetWrapper<string>("nvarchar", false, 6);
Assert.Throws<FormatException>(() => new CellUpdate(col, value));
}
[Theory] [Theory]
[MemberData(nameof(ByteArrayTestParams))] [MemberData(nameof(ByteArrayTestParams))]
public void ByteArrayTest(string strValue, byte[] expectedValue, string expectedString) public void ByteArrayTest(string strValue, byte[] expectedValue, string expectedString)
@@ -274,16 +285,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
Assert.True(ec.IsDirty); Assert.True(ec.IsDirty);
} }
private static DbColumnWrapper GetWrapper<T>(string dataTypeName, bool allowNull = true) private static DbColumnWrapper GetWrapper<T>(string dataTypeName, bool allowNull = true, int? colSize = null)
{ {
return new DbColumnWrapper(new CellUpdateTestDbColumn(typeof(T), dataTypeName, allowNull)); return new DbColumnWrapper(new CellUpdateTestDbColumn(typeof(T), dataTypeName, allowNull, colSize));
} }
private class CellUpdateTestDbColumn : DbColumn private class CellUpdateTestDbColumn : DbColumn
{ {
public CellUpdateTestDbColumn(Type dataType, string dataTypeName, bool allowNull = true) public CellUpdateTestDbColumn(Type dataType, string dataTypeName, bool allowNull = true, int? colSize = null)
{ {
AllowDBNull = allowNull; AllowDBNull = allowNull;
ColumnSize = colSize;
DataType = dataType; DataType = dataType;
DataTypeName = dataTypeName; DataTypeName = dataTypeName;
} }

View File

@@ -118,7 +118,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
? Enumerable.Repeat(new object[] { "id", "1", "2", "3" }, rowCount) ? Enumerable.Repeat(new object[] { "id", "1", "2", "3" }, rowCount)
: Enumerable.Repeat(new object[] { "1", "2", "3" }, rowCount); : Enumerable.Repeat(new object[] { "1", "2", "3" }, rowCount);
var testResultSet = new TestResultSet(columns, rows); var testResultSet = new TestResultSet(columns, rows);
var reader = new TestDbDataReader(new[] { testResultSet }); var reader = new TestDbDataReader(new[] { testResultSet }, false);
var resultSet = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory()); var resultSet = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());
await resultSet.ReadResultToEnd(reader, CancellationToken.None); await resultSet.ReadResultToEnd(reader, CancellationToken.None);
return resultSet; return resultSet;
@@ -130,7 +130,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
? new[] {new object[] {"id", "q", "q", "q"}} ? new[] {new object[] {"id", "q", "q", "q"}}
: new[] {new object[] {"q", "q", "q"}}; : new[] {new object[] {"q", "q", "q"}};
var testResultSet = new TestResultSet(columns, rows); var testResultSet = new TestResultSet(columns, rows);
return new TestDbDataReader(new [] {testResultSet}); return new TestDbDataReader(new [] {testResultSet}, false);
} }
public static void AddCells(RowEditBase rc, bool includeIdentity) public static void AddCells(RowEditBase rc, bool includeIdentity)

View File

@@ -293,7 +293,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
}}; }};
object[][] rows = {}; object[][] rows = {};
var testResultSet = new TestResultSet(cols, rows); var testResultSet = new TestResultSet(cols, rows);
var testReader = new TestDbDataReader(new[] {testResultSet}); var testReader = new TestDbDataReader(new[] {testResultSet}, false);
var rs = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory()); var rs = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());
await rs.ReadResultToEnd(testReader, CancellationToken.None); await rs.ReadResultToEnd(testReader, CancellationToken.None);

View File

@@ -243,7 +243,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{ {
object[][] rows = {row}; object[][] rows = {row};
var testResultSet = new TestResultSet(columns, rows); var testResultSet = new TestResultSet(columns, rows);
var testReader = new TestDbDataReader(new [] {testResultSet}); var testReader = new TestDbDataReader(new [] {testResultSet}, false);
var resultSet = new ResultSet(0,0, MemoryFileSystem.GetFileStreamFactory()); var resultSet = new ResultSet(0,0, MemoryFileSystem.GetFileStreamFactory());
await resultSet.ReadResultToEnd(testReader, CancellationToken.None); await resultSet.ReadResultToEnd(testReader, CancellationToken.None);
return resultSet; return resultSet;

View File

@@ -83,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
}; };
object[][] rows = { new object[]{new byte[] {0x00}}}; object[][] rows = { new object[]{new byte[] {0x00}}};
var testResultSet = new TestResultSet(cols, rows); var testResultSet = new TestResultSet(cols, rows);
var testReader = new TestDbDataReader(new[] { testResultSet }); var testReader = new TestDbDataReader(new[] { testResultSet }, false);
var rs = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory()); var rs = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());
rs.ReadResultToEnd(testReader, CancellationToken.None).Wait(); rs.ReadResultToEnd(testReader, CancellationToken.None).Wait();

View File

@@ -363,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
.Returns(etm); .Returns(etm);
// ... Create a query execution service that will return a successful query // ... Create a query execution service that will return a successful query
var qes = QueryExecution.Common.GetPrimedExecutionService(mockQueryResults, true, false, null); var qes = QueryExecution.Common.GetPrimedExecutionService(mockQueryResults, true, false, false, null);
// ... Create a connection service that doesn't throw when asked for a connection // ... Create a connection service that doesn't throw when asked for a connection
var cs = new Mock<ConnectionService>(); var cs = new Mock<ConnectionService>();

View File

@@ -81,7 +81,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
}; };
// @TODO: Fix when the connection service is fixed // @TODO: Fix when the connection service is fixed
ConnectionInfo ci = QueryExecution.Common.CreateConnectedConnectionInfo(results, false); ConnectionInfo ci = QueryExecution.Common.CreateConnectedConnectionInfo(results, false, false);
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci; ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
var fsf = MemoryFileSystem.GetFileStreamFactory(); var fsf = MemoryFileSystem.GetFileStreamFactory();

View File

@@ -146,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
object defaultReturnObject = new object(); object defaultReturnObject = new object();
var queueItem = this.bindingQueue.QueueBindingOperation( var queueItem = this.bindingQueue.QueueBindingOperation(
key: "testkey", key: "testkey",
bindOperation: (context, CancellationToken) => throw new Exception("Unhandled!!"), bindOperation: (context, CancellationToken) => { throw new Exception("Unhandled!!"); },
timeoutOperation: TestTimeoutOperation, timeoutOperation: TestTimeoutOperation,
errorHandler: (exception) => { errorHandler: (exception) => {
isExceptionHandled = true; isExceptionHandled = true;

View File

@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I request a query (doesn't matter what kind) and execute it // ... I request a query (doesn't matter what kind) and execute it
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
@@ -53,7 +53,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I request a query (doesn't matter what kind) and wait for execution // ... I request a query (doesn't matter what kind) and wait for execution
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri}; var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
@@ -82,7 +82,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I request to cancel a query that doesn't exist // ... I request to cancel a query that doesn't exist
var workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>(); var workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>();
var queryService = Common.GetPrimedExecutionService(null, false, false, workspaceService.Object); var queryService = Common.GetPrimedExecutionService(null, false, false, false, workspaceService.Object);
var cancelParams = new QueryCancelParams { OwnerUri = "Doesn't Exist" }; var cancelParams = new QueryCancelParams { OwnerUri = "Doesn't Exist" };
var cancelRequest = new EventFlowValidator<QueryCancelResult>() var cancelRequest = new EventFlowValidator<QueryCancelResult>()

View File

@@ -1,6 +1,7 @@
// //
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Data; using System.Data;
@@ -24,7 +25,7 @@ using HostingProtocol = Microsoft.SqlTools.Hosting.Protocol;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{ {
public class Common public static class Common
{ {
#region Constants #region Constants
@@ -38,8 +39,6 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
public const int StandardRows = 5; public const int StandardRows = 5;
public const string UdtQuery = "SELECT hierarchyid::Parse('/')";
public const SelectionData WholeDocument = null; public const SelectionData WholeDocument = null;
public static readonly ConnectionDetails StandardConnectionDetails = new ConnectionDetails public static readonly ConnectionDetails StandardConnectionDetails = new ConnectionDetails
@@ -72,29 +71,29 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
public static Batch GetBasicExecutedBatch() public static Batch GetBasicExecutedBatch()
{ {
Batch batch = new Batch(Test.Common.Constants.StandardQuery, SubsectionDocument, 1, Batch batch = new Batch(Constants.StandardQuery, SubsectionDocument, 1,
MemoryFileSystem.GetFileStreamFactory()); MemoryFileSystem.GetFileStreamFactory());
batch.Execute(CreateTestConnection(StandardTestDataSet, false), CancellationToken.None).Wait(); batch.Execute(CreateTestConnection(StandardTestDataSet, false, false), CancellationToken.None).Wait();
return batch; return batch;
} }
public static Batch GetExecutedBatchWithExecutionPlan() public static Batch GetExecutedBatchWithExecutionPlan()
{ {
Batch batch = new Batch(Test.Common.Constants.StandardQuery, SubsectionDocument, 1, Batch batch = new Batch(Constants.StandardQuery, SubsectionDocument, 1,
MemoryFileSystem.GetFileStreamFactory()); MemoryFileSystem.GetFileStreamFactory());
batch.Execute(CreateTestConnection(ExecutionPlanTestDataSet, false), CancellationToken.None).Wait(); batch.Execute(CreateTestConnection(ExecutionPlanTestDataSet, false, false), CancellationToken.None).Wait();
return batch; return batch;
} }
public static Query GetBasicExecutedQuery() public static Query GetBasicExecutedQuery()
{ {
ConnectionInfo ci = CreateConnectedConnectionInfo(StandardTestDataSet, false); ConnectionInfo ci = CreateConnectedConnectionInfo(StandardTestDataSet, false, false);
// Query won't be able to request a new query DbConnection unless the ConnectionService has a // Query won't be able to request a new query DbConnection unless the ConnectionService has a
// ConnectionInfo with the same URI as the query, so we will manually set it // ConnectionInfo with the same URI as the query, so we will manually set it
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci; ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
Query query = new Query(Test.Common.Constants.StandardQuery, ci, new QueryExecutionSettings(), Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(),
MemoryFileSystem.GetFileStreamFactory()); MemoryFileSystem.GetFileStreamFactory());
query.Execute(); query.Execute();
query.ExecutionTask.Wait(); query.ExecutionTask.Wait();
@@ -103,13 +102,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
public static Query GetBasicExecutedQuery(QueryExecutionSettings querySettings) public static Query GetBasicExecutedQuery(QueryExecutionSettings querySettings)
{ {
ConnectionInfo ci = CreateConnectedConnectionInfo(StandardTestDataSet, false); ConnectionInfo ci = CreateConnectedConnectionInfo(StandardTestDataSet, false, false);
// Query won't be able to request a new query DbConnection unless the ConnectionService has a // Query won't be able to request a new query DbConnection unless the ConnectionService has a
// ConnectionInfo with the same URI as the query, so we will manually set it // ConnectionInfo with the same URI as the query, so we will manually set it
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci; ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
Query query = new Query(Test.Common.Constants.StandardQuery, ci, querySettings, Query query = new Query(Constants.StandardQuery, ci, querySettings,
MemoryFileSystem.GetFileStreamFactory()); MemoryFileSystem.GetFileStreamFactory());
query.Execute(); query.Execute();
query.ExecutionTask.Wait(); query.ExecutionTask.Wait();
@@ -135,14 +134,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
#region DbConnection Mocking #region DbConnection Mocking
public static DbCommand CreateTestCommand(TestResultSet[] data, bool throwOnRead) private static DbCommand CreateTestCommand(TestResultSet[] data, bool throwOnExecute, bool throwOnRead)
{ {
var commandMock = new Mock<DbCommand> { CallBase = true }; var commandMock = new Mock<DbCommand> { CallBase = true };
var commandMockSetup = commandMock.Protected() var commandMockSetup = commandMock.Protected()
.Setup<DbDataReader>("ExecuteDbDataReader", It.IsAny<CommandBehavior>()); .Setup<DbDataReader>("ExecuteDbDataReader", It.IsAny<CommandBehavior>());
// Setup the expected behavior // Setup the expected execute behavior
if (throwOnRead) if (throwOnExecute)
{ {
var mockException = new Mock<DbException>(); var mockException = new Mock<DbException>();
mockException.SetupGet(dbe => dbe.Message).Returns("Message"); mockException.SetupGet(dbe => dbe.Message).Returns("Message");
@@ -150,19 +149,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
} }
else else
{ {
commandMockSetup.Returns(new TestDbDataReader(data)); commandMockSetup.Returns(new TestDbDataReader(data, throwOnRead));
} }
return commandMock.Object; return commandMock.Object;
} }
public static DbConnection CreateTestConnection(TestResultSet[] data, bool throwOnRead) private static DbConnection CreateTestConnection(TestResultSet[] data, bool throwOnExecute, bool throwOnRead)
{ {
var connectionMock = new Mock<DbConnection> { CallBase = true }; var connectionMock = new Mock<DbConnection> { CallBase = true };
connectionMock.Protected() connectionMock.Protected()
.Setup<DbCommand>("CreateDbCommand") .Setup<DbCommand>("CreateDbCommand")
.Returns(() => CreateTestCommand(data, throwOnRead)); .Returns(() => CreateTestCommand(data, throwOnExecute, throwOnRead));
connectionMock.Setup(dbc => dbc.Open()) connectionMock.Setup(dbc => dbc.Open())
.Callback(() => connectionMock.SetupGet(dbc => dbc.State).Returns(ConnectionState.Open)); .Callback(() => connectionMock.SetupGet(dbc => dbc.State).Returns(ConnectionState.Open));
connectionMock.Setup(dbc => dbc.Close()) connectionMock.Setup(dbc => dbc.Close())
@@ -171,34 +170,38 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
return connectionMock.Object; return connectionMock.Object;
} }
public static ISqlConnectionFactory CreateMockFactory(TestResultSet[] data, bool throwOnRead) private static ISqlConnectionFactory CreateMockFactory(TestResultSet[] data, bool throwOnExecute, bool throwOnRead)
{ {
var mockFactory = new Mock<ISqlConnectionFactory>(); var mockFactory = new Mock<ISqlConnectionFactory>();
mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>())) mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>()))
.Returns(() => CreateTestConnection(data, throwOnRead)); .Returns(() => CreateTestConnection(data, throwOnExecute, throwOnRead));
return mockFactory.Object; return mockFactory.Object;
} }
public static ConnectionInfo CreateTestConnectionInfo(TestResultSet[] data, bool throwOnRead) public static ConnectionInfo CreateTestConnectionInfo(TestResultSet[] data, bool throwOnExecute, bool throwOnRead)
{ {
// Create a connection info and add the default connection to it // Create a connection info and add the default connection to it
ISqlConnectionFactory factory = CreateMockFactory(data, throwOnRead); ISqlConnectionFactory factory = CreateMockFactory(data, throwOnExecute, throwOnRead);
ConnectionInfo ci = new ConnectionInfo(factory, Test.Common.Constants.OwnerUri, StandardConnectionDetails); ConnectionInfo ci = new ConnectionInfo(factory, Constants.OwnerUri, StandardConnectionDetails);
ci.ConnectionTypeToConnectionMap[ConnectionType.Default] = factory.CreateSqlConnection(null); ci.ConnectionTypeToConnectionMap[ConnectionType.Default] = factory.CreateSqlConnection(null);
return ci; return ci;
} }
public static ConnectionInfo CreateConnectedConnectionInfo(TestResultSet[] data, bool throwOnRead, string type = ConnectionType.Default) public static ConnectionInfo CreateConnectedConnectionInfo(
TestResultSet[] data,
bool throwOnExecute,
bool throwOnRead,
string type = ConnectionType.Default)
{ {
ConnectionService connectionService = ConnectionService.Instance; ConnectionService connectionService = ConnectionService.Instance;
connectionService.OwnerToConnectionMap.Clear(); connectionService.OwnerToConnectionMap.Clear();
connectionService.ConnectionFactory = CreateMockFactory(data, throwOnRead); connectionService.ConnectionFactory = CreateMockFactory(data, throwOnExecute, throwOnRead);
ConnectParams connectParams = new ConnectParams ConnectParams connectParams = new ConnectParams
{ {
Connection = StandardConnectionDetails, Connection = StandardConnectionDetails,
OwnerUri = Test.Common.Constants.OwnerUri, OwnerUri = Constants.OwnerUri,
Type = type Type = type
}; };
@@ -210,8 +213,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
#region Service Mocking #region Service Mocking
public static QueryExecutionService GetPrimedExecutionService(TestResultSet[] data, public static QueryExecutionService GetPrimedExecutionService(
bool isConnected, bool throwOnRead, WorkspaceService<SqlToolsSettings> workspaceService, TestResultSet[] data,
bool isConnected,
bool throwOnExecute,
bool throwOnRead,
WorkspaceService<SqlToolsSettings> workspaceService,
out ConcurrentDictionary<string, byte[]> storage) out ConcurrentDictionary<string, byte[]> storage)
{ {
// Create a place for the temp "files" to be written // Create a place for the temp "files" to be written
@@ -219,7 +226,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// Mock the connection service // Mock the connection service
var connectionService = new Mock<ConnectionService>(); var connectionService = new Mock<ConnectionService>();
ConnectionInfo ci = CreateConnectedConnectionInfo(data, throwOnRead); ConnectionInfo ci = CreateConnectedConnectionInfo(data, throwOnExecute, throwOnRead);
ConnectionInfo outValMock; ConnectionInfo outValMock;
connectionService connectionService
.Setup(service => service.TryFindConnection(It.IsAny<string>(), out outValMock)) .Setup(service => service.TryFindConnection(It.IsAny<string>(), out outValMock))
@@ -229,10 +236,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
return new QueryExecutionService(connectionService.Object, workspaceService) { BufferFileStreamFactory = MemoryFileSystem.GetFileStreamFactory(storage) }; return new QueryExecutionService(connectionService.Object, workspaceService) { BufferFileStreamFactory = MemoryFileSystem.GetFileStreamFactory(storage) };
} }
public static QueryExecutionService GetPrimedExecutionService(TestResultSet[] data, bool isConnected, bool throwOnRead, WorkspaceService<SqlToolsSettings> workspaceService) public static QueryExecutionService GetPrimedExecutionService(
TestResultSet[] data,
bool isConnected,
bool throwOnExecute,
bool throwOnRead,
WorkspaceService<SqlToolsSettings> workspaceService)
{ {
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
return GetPrimedExecutionService(data, isConnected, throwOnRead, workspaceService, out storage); return GetPrimedExecutionService(data, isConnected, throwOnExecute, throwOnRead, workspaceService, out storage);
} }
public static WorkspaceService<SqlToolsSettings> GetPrimedWorkspaceService(string query) public static WorkspaceService<SqlToolsSettings> GetPrimedWorkspaceService(string query)

View File

@@ -40,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I request a query (doesn't matter what kind) // ... I request a query (doesn't matter what kind)
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri}; var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object); await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
@@ -65,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I attempt to dispose a query that doesn't exist // ... I attempt to dispose a query that doesn't exist
var workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>(); var workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>();
var queryService = Common.GetPrimedExecutionService(null, false, false, workspaceService.Object); var queryService = Common.GetPrimedExecutionService(null, false, false, false, workspaceService.Object);
var disposeParams = new QueryDisposeParams {OwnerUri = Constants.OwnerUri}; var disposeParams = new QueryDisposeParams {OwnerUri = Constants.OwnerUri};
var disposeRequest = new EventFlowValidator<QueryDisposeResult>() var disposeRequest = new EventFlowValidator<QueryDisposeResult>()
@@ -83,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// Setup: // Setup:
// ... We need a query service // ... We need a query service
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
// If: // If:
// ... I execute some bogus query // ... I execute some bogus query

View File

@@ -71,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
b => batchEndCalls++, b => batchEndCalls++,
m => messages.Add(m), m => messages.Add(m),
r => resultSetCalls++); r => resultSetCalls++);
await batch.Execute(GetConnection(Common.CreateTestConnectionInfo(null, false)), CancellationToken.None); await batch.Execute(GetConnection(Common.CreateTestConnectionInfo(null, false, false)), CancellationToken.None);
// Then: // Then:
// ... Callbacks should have been called the appropriate number of times // ... Callbacks should have been called the appropriate number of times
@@ -97,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// ... Build a data set to return // ... Build a data set to return
const int resultSets = 1; const int resultSets = 1;
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false); ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false, false);
// If I execute a query that should get one result set // If I execute a query that should get one result set
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -133,7 +133,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// ... Build a data set to return // ... Build a data set to return
const int resultSets = 2; const int resultSets = 2;
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false); ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false, false);
// If I execute a query that should get two result sets // If I execute a query that should get two result sets
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -167,7 +167,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
List<ResultMessage> messages = new List<ResultMessage>(); List<ResultMessage> messages = new List<ResultMessage>();
// If I execute a batch that is invalid // If I execute a batch that is invalid
var ci = Common.CreateTestConnectionInfo(null, true); var ci = Common.CreateTestConnectionInfo(null, true, false);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory); Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
BatchCallbackHelper(batch, BatchCallbackHelper(batch,
@@ -200,7 +200,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{ {
// Setup: Build a data set to return // Setup: Build a data set to return
const int resultSets = 1; const int resultSets = 1;
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false); ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false, false);
// If I execute a batch // If I execute a batch
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();

View File

@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{ {
// If: // If:
// ... I create a query // ... I create a query
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false); ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory); Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
@@ -53,7 +53,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// Then: // Then:
// ... It should throw an exception // ... It should throw an exception
Assert.Throws<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
new Query("Some query", Common.CreateTestConnectionInfo(null, false), null, MemoryFileSystem.GetFileStreamFactory())); new Query("Some query", Common.CreateTestConnectionInfo(null, false, false), null, MemoryFileSystem.GetFileStreamFactory()));
} }
[Fact] [Fact]
@@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// Then: // Then:
// ... It should throw an exception // ... It should throw an exception
Assert.Throws<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
new Query("Some query", Common.CreateTestConnectionInfo(null, false), new QueryExecutionSettings(), null)); new Query("Some query", Common.CreateTestConnectionInfo(null, false, false), new QueryExecutionSettings(), null));
} }
[Fact] [Fact]
@@ -78,7 +78,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from a single batch (without separator) // ... I create a query from a single batch (without separator)
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false); ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory); Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query, BatchCallbackHelper(query,
@@ -114,7 +114,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from a single batch that does nothing // ... I create a query from a single batch that does nothing
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false); ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Common.NoOpQuery, ci, new QueryExecutionSettings(), fileStreamFactory); Query query = new Query(Common.NoOpQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query, BatchCallbackHelper(query,
@@ -149,7 +149,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from two batches (with separator) // ... I create a query from two batches (with separator)
ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false); ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false, false);
string queryText = string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery); string queryText = string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -190,7 +190,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from a two batches (with separator) // ... I create a query from a two batches (with separator)
ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false); ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false, false);
string queryText = string.Format("{0}\r\nGO\r\n{1}", Constants.StandardQuery, Common.NoOpQuery); string queryText = string.Format("{0}\r\nGO\r\n{1}", Constants.StandardQuery, Common.NoOpQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory); Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);
@@ -226,7 +226,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from a two batches (with separator) // ... I create a query from a two batches (with separator)
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false); ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
string queryText = string.Format("{0}\r\nGO\r\n{1}", Common.NoOpQuery, Common.NoOpQuery); string queryText = string.Format("{0}\r\nGO\r\n{1}", Common.NoOpQuery, Common.NoOpQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory); Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);
@@ -261,7 +261,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I create a query from an invalid batch // ... I create a query from an invalid batch
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, true); ConnectionInfo ci = Common.CreateTestConnectionInfo(null, true, false);
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci; ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();

View File

@@ -285,6 +285,28 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
Assert.Equal(Common.StandardRows, resultSet.RowCount); Assert.Equal(Common.StandardRows, resultSet.RowCount);
} }
[Fact]
public async Task AddRowThrowsOnRead()
{
// Setup:
// ... Create a standard result set with standard data
var fileFactory = MemoryFileSystem.GetFileStreamFactory();
var mockReader = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, fileFactory);
await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);
// ... Create a mock reader that will throw on read
var throwingReader = GetReader(new[] {new TestResultSet(5, 0)}, true, Constants.StandardQuery);
// If: I add a row with a reader that throws on read
// Then:
// ... I should get an exception
await Assert.ThrowsAnyAsync<DbException>(() => resultSet.AddRow(throwingReader));
// ... The row count should not have changed
Assert.Equal(Common.StandardRows, resultSet.RowCount);
}
[Fact] [Fact]
public async Task AddRowSuccess() public async Task AddRowSuccess()
{ {
@@ -363,7 +385,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
private static DbDataReader GetReader(TestResultSet[] dataSet, bool throwOnRead, string query) private static DbDataReader GetReader(TestResultSet[] dataSet, bool throwOnRead, string query)
{ {
var info = Common.CreateTestConnectionInfo(dataSet, throwOnRead); var info = Common.CreateTestConnectionInfo(dataSet, false, throwOnRead);
var connection = info.Factory.CreateSqlConnection(ConnectionService.BuildConnectionString(info.ConnectionDetails)); var connection = info.Factory.CreateSqlConnection(ConnectionService.BuildConnectionString(info.ConnectionDetails));
var command = connection.CreateCommand(); var command = connection.CreateCommand();
command.CommandText = query; command.CommandText = query;

View File

@@ -204,7 +204,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a valid query with all batches as no op // ... I request to execute a valid query with all batches as no op
var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Common.NoOpQuery)); var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Common.NoOpQuery));
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri }; var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri };
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -239,7 +239,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a valid query with no results // ... I request to execute a valid query with no results
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri}; var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri};
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -266,8 +266,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a valid query with results // ... I request to execute a valid query with results
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, workspaceService);
workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -295,7 +294,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// ... I request to execute a valid query with one batch and multiple result sets // ... I request to execute a valid query with one batch and multiple result sets
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var dataset = new[] {Common.StandardTestResultSet, Common.StandardTestResultSet}; var dataset = new[] {Common.StandardTestResultSet, Common.StandardTestResultSet};
var queryService = Common.GetPrimedExecutionService(dataset, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(dataset, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -322,7 +321,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request a to execute a valid query with multiple batches // ... I request a to execute a valid query with multiple batches
var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery)); var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery));
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -354,7 +353,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a query using a file URI that isn't connected // ... I request to execute a query using a file URI that isn't connected
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, false, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, false, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = "notConnected", QuerySelection = Common.WholeDocument }; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = "notConnected", QuerySelection = Common.WholeDocument };
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -376,7 +375,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a query // ... I request to execute a query
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
// Note, we don't care about the results of the first request // Note, we don't care about the results of the first request
@@ -404,7 +403,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a query // ... I request to execute a query
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
// Note, we don't care about the results of the first request // Note, we don't care about the results of the first request
@@ -435,7 +434,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// If: // If:
// ... I request to execute a query that is invalid // ... I request to execute a query that is invalid
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery); var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, true, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams {OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument}; var queryParams = new ExecuteDocumentSelectionParams {OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>() var efv = new EventFlowValidator<ExecuteRequestResult>()
@@ -458,7 +457,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
// [Fact] // [Fact]
public async Task SimpleExecuteErrorWithNoResultsTest() public async Task SimpleExecuteErrorWithNoResultsTest()
{ {
var queryService = Common.GetPrimedExecutionService(null, true, false, null); var queryService = Common.GetPrimedExecutionService(null, true, false, false, null);
var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery }; var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery };
var efv = new EventFlowValidator<SimpleExecuteResult>() var efv = new EventFlowValidator<SimpleExecuteResult>()
.AddSimpleExecuteErrorValidator(SR.QueryServiceResultSetHasNoResults) .AddSimpleExecuteErrorValidator(SR.QueryServiceResultSetHasNoResults)
@@ -480,7 +479,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
[Fact] [Fact]
public async Task SimpleExecuteVerifyResultsTest() public async Task SimpleExecuteVerifyResultsTest()
{ {
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, null); var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, null);
var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery }; var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery };
var efv = new EventFlowValidator<SimpleExecuteResult>() var efv = new EventFlowValidator<SimpleExecuteResult>()
.AddSimpleExecuteQueryResultValidator(Common.StandardTestDataSet) .AddSimpleExecuteQueryResultValidator(Common.StandardTestDataSet)
@@ -504,7 +503,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
[Fact] [Fact]
public async Task SimpleExecuteMultipleQueriesTest() public async Task SimpleExecuteMultipleQueriesTest()
{ {
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, null); var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, null);
var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery }; var queryParams = new SimpleExecuteParams { OwnerUri = Constants.OwnerUri, QueryString = Constants.StandardQuery };
var efv1 = new EventFlowValidator<SimpleExecuteResult>() var efv1 = new EventFlowValidator<SimpleExecuteResult>()
.AddSimpleExecuteQueryResultValidator(Common.StandardTestDataSet) .AddSimpleExecuteQueryResultValidator(Common.StandardTestDataSet)

View File

@@ -139,7 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that has results in the form of an execution plan // ... I have a query that has results in the form of an execution plan
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams var executeParams = new ExecuteDocumentSelectionParams
{ {
QuerySelection = null, QuerySelection = null,
@@ -173,7 +173,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I ask for an execution plan for a file that hasn't executed a query // ... I ask for an execution plan for a file that hasn't executed a query
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 }; var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>() var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>()
.AddStandardErrorValidation() .AddStandardErrorValidation()
@@ -188,7 +188,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that hasn't finished executing (doesn't matter what) // ... I have a query that hasn't finished executing (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams var executeParams = new ExecuteDocumentSelectionParams
{ {
QuerySelection = null, QuerySelection = null,
@@ -219,7 +219,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that doesn't have any result sets // ... I have a query that doesn't have any result sets
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams var executeParams = new ExecuteDocumentSelectionParams
{ {
QuerySelection = null, QuerySelection = null,

View File

@@ -93,7 +93,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
ResultSet rs = new ResultSet( ResultSet rs = new ResultSet(
Common.Ordinal, Common.Ordinal, Common.Ordinal, Common.Ordinal,
resultFactory); resultFactory);
await rs.ReadResultToEnd(GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery), CancellationToken.None); await rs.ReadResultToEnd(GetReader(Common.StandardTestDataSet, Constants.StandardQuery), CancellationToken.None);
// ... Create a mock writer for writing the save as file // ... Create a mock writer for writing the save as file
Mock<IFileStreamWriter> saveWriter = GetMockWriter(); Mock<IFileStreamWriter> saveWriter = GetMockWriter();
@@ -125,7 +125,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
ResultSet rs = new ResultSet( ResultSet rs = new ResultSet(
Common.Ordinal, Common.Ordinal, Common.Ordinal, Common.Ordinal,
resultFactory); resultFactory);
await rs.ReadResultToEnd(GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery), CancellationToken.None); await rs.ReadResultToEnd(GetReader(Common.StandardTestDataSet, Constants.StandardQuery), CancellationToken.None);
// ... Create a mock writer for writing the save as file // ... Create a mock writer for writing the save as file
Mock<IFileStreamWriter> saveWriter = GetMockWriter(); Mock<IFileStreamWriter> saveWriter = GetMockWriter();
@@ -171,9 +171,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
return mockFactory.Object; return mockFactory.Object;
} }
private static DbDataReader GetReader(TestResultSet[] dataSet, bool throwOnRead, string query) private static DbDataReader GetReader(TestResultSet[] dataSet, string query)
{ {
var info = Common.CreateTestConnectionInfo(dataSet, throwOnRead); var info = Common.CreateTestConnectionInfo(dataSet, false, false);
var connection = info.Factory.CreateSqlConnection(ConnectionService.BuildConnectionString(info.ConnectionDetails)); var connection = info.Factory.CreateSqlConnection(ConnectionService.BuildConnectionString(info.ConnectionDetails));
var command = connection.CreateCommand(); var command = connection.CreateCommand();
command.CommandText = query; command.CommandText = query;

View File

@@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{ {
// Given: A working query and workspace service // Given: A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null);
QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, ws); QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, false, ws);
// If: I attempt to save a result set from a query that doesn't exist // If: I attempt to save a result set from a query that doesn't exist
SaveResultsAsCsvRequestParams saveParams = new SaveResultsAsCsvRequestParams SaveResultsAsCsvRequestParams saveParams = new SaveResultsAsCsvRequestParams
@@ -55,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
@@ -100,7 +100,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri}; var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
@@ -142,7 +142,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{ {
// Given: A working query and workspace service // Given: A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null);
QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, ws); QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, false, ws);
// If: I attempt to save a result set from a query that doesn't exist // If: I attempt to save a result set from a query that doesn't exist
SaveResultsAsJsonRequestParams saveParams = new SaveResultsAsJsonRequestParams SaveResultsAsJsonRequestParams saveParams = new SaveResultsAsJsonRequestParams
@@ -167,7 +167,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
@@ -210,7 +210,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
@@ -251,7 +251,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{ {
// Given: A working query and workspace service // Given: A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null);
QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, ws); QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, false, ws);
// If: I attempt to save a result set from a query that doesn't exist // If: I attempt to save a result set from a query that doesn't exist
SaveResultsAsExcelRequestParams saveParams = new SaveResultsAsExcelRequestParams SaveResultsAsExcelRequestParams saveParams = new SaveResultsAsExcelRequestParams
@@ -276,7 +276,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
@@ -319,7 +319,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
// ... A working query and workspace service // ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery); WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
ConcurrentDictionary<string, byte[]> storage; ConcurrentDictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage); QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, ws, out storage);
// ... The query execution service has executed a query with results // ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };

View File

@@ -132,7 +132,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that has results (doesn't matter what) // ... I have a query that has results (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri}; var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object); await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
@@ -156,7 +156,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I ask for a set of results for a file that hasn't executed a query // ... I ask for a set of results for a file that hasn't executed a query
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 }; var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetRequest = new EventFlowValidator<SubsetResult>() var subsetRequest = new EventFlowValidator<SubsetResult>()
.AddStandardErrorValidation() .AddStandardErrorValidation()
@@ -171,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that hasn't finished executing (doesn't matter what) // ... I have a query that hasn't finished executing (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object); await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
@@ -193,7 +193,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
// If: // If:
// ... I have a query that doesn't have any result sets // ... I have a query that doesn't have any result sets
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery); var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService); var queryService = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri }; var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null); var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object); await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

View File

@@ -20,9 +20,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
public IExportableMetadata Metadata { get; set; } public IExportableMetadata Metadata { get; set; }
public ExportableStatus Status { get; } public ExportableStatus Status { get; }
IExportableMetadata IExportable.Metadata { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } IExportableMetadata IExportable.Metadata
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
ExportableStatus IExportable.Status => throw new NotImplementedException(); ExportableStatus IExportable.Status
{
get { throw new NotImplementedException(); }
}
public Task<ServiceResponse<DatabaseInstanceInfo>> GetDatabaseInstancesAsync(string serverName, CancellationToken cancellationToken) public Task<ServiceResponse<DatabaseInstanceInfo>> GetDatabaseInstancesAsync(string serverName, CancellationToken cancellationToken)
{ {

View File

@@ -8,23 +8,30 @@ using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Data.Common; using System.Data.Common;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{ {
public class TestDbException : DbException
{
}
public class TestDbDataReader : DbDataReader, IDbColumnSchemaGenerator public class TestDbDataReader : DbDataReader, IDbColumnSchemaGenerator
{ {
#region Test Specific Implementations #region Test Specific Implementations
private IEnumerable<TestResultSet> Data { get; } private IEnumerable<TestResultSet> Data { get; }
public IEnumerator<TestResultSet> ResultSetEnumerator { get; } private IEnumerator<TestResultSet> ResultSetEnumerator { get; }
private IEnumerator<object[]> RowEnumerator { get; set; } private IEnumerator<object[]> RowEnumerator { get; set; }
public TestDbDataReader(IEnumerable<TestResultSet> data) private bool ThrowOnRead { get; }
public TestDbDataReader(IEnumerable<TestResultSet> data, bool throwOnRead)
{ {
ThrowOnRead = throwOnRead;
Data = data; Data = data;
if (Data != null) if (Data != null)
{ {
@@ -59,6 +66,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
/// <returns>True if tere were more rows, false otherwise</returns> /// <returns>True if tere were more rows, false otherwise</returns>
public override bool Read() public override bool Read()
{ {
if (ThrowOnRead)
{
throw new TestDbException();
}
if (RowEnumerator == null) if (RowEnumerator == null)
{ {
RowEnumerator = ResultSetEnumerator.Current.GetEnumerator(); RowEnumerator = ResultSetEnumerator.Current.GetEnumerator();
@@ -97,11 +108,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
/// <returns>Number of cells in the current row</returns> /// <returns>Number of cells in the current row</returns>
public override int GetValues(object[] values) public override int GetValues(object[] values)
{ {
for (int i = 0; i < RowEnumerator.Current.Count(); i++) for (int i = 0; i < RowEnumerator.Current.Length; i++)
{ {
values[i] = this[i]; values[i] = this[i];
} }
return RowEnumerator.Current.Count(); return RowEnumerator.Current.Length;
} }
/// <summary> /// <summary>

View File

@@ -182,7 +182,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{ {
return new TestDbDataReader(Data); return new TestDbDataReader(Data, false);
} }
private List<DbParameter> listParams = new List<DbParameter>(); private List<DbParameter> listParams = new List<DbParameter>();