Schema compare cancel operation (#826)

* First cut of schema compare cancel (private nuget)

* Update Dacfx nuget to a published version
This commit is contained in:
udeeshagautam
2019-06-14 18:19:36 -07:00
committed by GitHub
parent 432e054d55
commit 3e1f186891
13 changed files with 168 additions and 13 deletions

11
src/Microsoft.SqlTools.ServiceLayer/Localization/sr.cs Executable file → Normal file
View File

@@ -2941,6 +2941,14 @@ namespace Microsoft.SqlTools.ServiceLayer
} }
} }
public static string SchemaCompareSessionNotFound
{
get
{
return Keys.GetString(Keys.SchemaCompareSessionNotFound);
}
}
public static string ConnectionServiceListDbErrorNotConnected(string uri) public static string ConnectionServiceListDbErrorNotConnected(string uri)
{ {
return Keys.GetString(Keys.ConnectionServiceListDbErrorNotConnected, uri); return Keys.GetString(Keys.ConnectionServiceListDbErrorNotConnected, uri);
@@ -4281,6 +4289,9 @@ namespace Microsoft.SqlTools.ServiceLayer
public const string OpenScmpConnectionBasedModelParsingError = "OpenScmpConnectionBasedModelParsingError"; public const string OpenScmpConnectionBasedModelParsingError = "OpenScmpConnectionBasedModelParsingError";
public const string SchemaCompareSessionNotFound = "SchemaCompareSessionNotFound";
private Keys() private Keys()
{ } { }

View File

@@ -1723,4 +1723,7 @@
<value>Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}'</value> <value>Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}'</value>
<comment></comment> <comment></comment>
</data> </data>
<data name="SchemaCompareSessionNotFound" xml:space="preserve">
<value>Could not find the schema compare session to cancel</value>
</data>
</root> </root>

View File

@@ -798,3 +798,4 @@ ExtractInvalidVersion = Invalid version '{0}' passed. Version must be in the for
PublishChangesTaskName = Apply schema compare changes PublishChangesTaskName = Apply schema compare changes
SchemaCompareExcludeIncludeNodeNotFound = Failed to find the specified change in the model SchemaCompareExcludeIncludeNodeNotFound = Failed to find the specified change in the model
OpenScmpConnectionBasedModelParsingError = Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}' OpenScmpConnectionBasedModelParsingError = Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}'
SchemaCompareSessionNotFound = Could not find the schema compare session to cancel

View File

@@ -2001,6 +2001,11 @@
<target state="new">Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}'</target> <target state="new">Error encountered while trying to parse connection information for endpoint '{0}' with error message '{1}'</target>
<note></note> <note></note>
</trans-unit> </trans-unit>
<trans-unit id="SchemaCompareSessionNotFound">
<source>Could not find the schema compare session to cancel</source>
<target state="new">Could not find the schema compare session to cancel</target>
<note></note>
</trans-unit>
</body> </body>
</file> </file>
</xliff> </xliff>

View File

@@ -23,7 +23,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" /> <PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4316.1-preview" /> <PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4451.1-preview" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.6.0-preview3-26501-04" /> <PackageReference Include="System.Text.Encoding.CodePages" Version="4.6.0-preview3-26501-04" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -0,0 +1,30 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare.Contracts
{
/// <summary>
/// Parameters for a schema compare cancel request
/// </summary>
public class SchemaCompareCancelParams
{
/// <summary>
/// Operation id of the schema compare operation
/// </summary>
public string OperationId { get; set; }
}
/// <summary>
/// Defines the Schema Compare cancel comparison request type
/// </summary>
class SchemaCompareCancellationRequest
{
public static readonly RequestType<SchemaCompareCancelParams, ResultStatus> Type =
RequestType<SchemaCompareCancelParams, ResultStatus>.Create("schemaCompare/cancel");
}
}

View File

@@ -57,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
try try
{ {
this.ScriptGenerationResult = this.ComparisonResult.GenerateScript(this.Parameters.TargetDatabaseName); this.ScriptGenerationResult = this.ComparisonResult.GenerateScript(this.Parameters.TargetDatabaseName, this.CancellationToken);
// tests don't create a SqlTask, so only add the script when the SqlTask isn't null // tests don't create a SqlTask, so only add the script when the SqlTask isn't null
if (this.SqlTask != null) if (this.SqlTask != null)
@@ -81,6 +81,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
// The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled // The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled
public void Cancel() public void Cancel()
{ {
this.cancellation.Cancel();
} }
/// <summary> /// <summary>

View File

@@ -58,6 +58,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
// The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled // The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled
public void Cancel() public void Cancel()
{ {
this.cancellation.Cancel();
} }
/// <summary> /// <summary>
@@ -91,19 +92,31 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
comparison.Options = SchemaCompareUtils.CreateSchemaCompareOptions(this.Parameters.DeploymentOptions); comparison.Options = SchemaCompareUtils.CreateSchemaCompareOptions(this.Parameters.DeploymentOptions);
} }
this.ComparisonResult = comparison.Compare(); // for testing
schemaCompareStarted?.Invoke(this, new EventArgs());
this.ComparisonResult = comparison.Compare(this.CancellationToken);
// try one more time if it didn't work the first time // try one more time if it didn't work the first time
if (!this.ComparisonResult.IsValid) if (!this.ComparisonResult.IsValid)
{ {
this.ComparisonResult = comparison.Compare(); this.ComparisonResult = comparison.Compare(this.CancellationToken);
}
// Since DacFx does not throw on schema comparison cancellation, throwing here explicitly to ensure consistency of behavior
if (!this.ComparisonResult.IsValid && this.CancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(this.CancellationToken);
} }
this.Differences = new List<DiffEntry>(); this.Differences = new List<DiffEntry>();
foreach (SchemaDifference difference in this.ComparisonResult.Differences) if (this.ComparisonResult.Differences != null)
{ {
DiffEntry diffEntry = SchemaCompareUtils.CreateDiffEntry(difference, null); foreach (SchemaDifference difference in this.ComparisonResult.Differences)
this.Differences.Add(diffEntry); {
DiffEntry diffEntry = SchemaCompareUtils.CreateDiffEntry(difference, null);
this.Differences.Add(diffEntry);
}
} }
} }
catch (Exception e) catch (Exception e)
@@ -113,5 +126,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
throw; throw;
} }
} }
internal event EventHandler<EventArgs> schemaCompareStarted;
} }
} }

View File

@@ -54,7 +54,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
try try
{ {
this.PublishResult = this.ComparisonResult.PublishChangesToTarget(); this.PublishResult = this.ComparisonResult.PublishChangesToTarget(this.CancellationToken);
} }
catch (Exception e) catch (Exception e)
{ {
@@ -67,6 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
// The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled // The schema compare public api doesn't currently take a cancellation token so the operation can't be cancelled
public void Cancel() public void Cancel()
{ {
this.cancellation.Cancel();
} }
} }
} }

View File

@@ -14,6 +14,7 @@ using Microsoft.SqlServer.Dac.Compare;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Microsoft.SqlTools.Utility; using Microsoft.SqlTools.Utility;
using System.Diagnostics; using System.Diagnostics;
using System.Threading;
namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
{ {
@@ -27,6 +28,8 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
private static readonly Lazy<SchemaCompareService> instance = new Lazy<SchemaCompareService>(() => new SchemaCompareService()); private static readonly Lazy<SchemaCompareService> instance = new Lazy<SchemaCompareService>(() => new SchemaCompareService());
private Lazy<ConcurrentDictionary<string, SchemaComparisonResult>> schemaCompareResults = private Lazy<ConcurrentDictionary<string, SchemaComparisonResult>> schemaCompareResults =
new Lazy<ConcurrentDictionary<string, SchemaComparisonResult>>(() => new ConcurrentDictionary<string, SchemaComparisonResult>()); new Lazy<ConcurrentDictionary<string, SchemaComparisonResult>>(() => new ConcurrentDictionary<string, SchemaComparisonResult>());
private Lazy<ConcurrentDictionary<string, Action>> currentComparisonCancellationAction =
new Lazy<ConcurrentDictionary<string, Action>>(() => new ConcurrentDictionary<string, Action>());
// For testability // For testability
internal Task CurrentSchemaCompareTask; internal Task CurrentSchemaCompareTask;
@@ -46,6 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
public void InitializeService(ServiceHost serviceHost) public void InitializeService(ServiceHost serviceHost)
{ {
serviceHost.SetRequestHandler(SchemaCompareRequest.Type, this.HandleSchemaCompareRequest); serviceHost.SetRequestHandler(SchemaCompareRequest.Type, this.HandleSchemaCompareRequest);
serviceHost.SetRequestHandler(SchemaCompareCancellationRequest.Type, this.HandleSchemaCompareCancelRequest);
serviceHost.SetRequestHandler(SchemaCompareGenerateScriptRequest.Type, this.HandleSchemaCompareGenerateScriptRequest); serviceHost.SetRequestHandler(SchemaCompareGenerateScriptRequest.Type, this.HandleSchemaCompareGenerateScriptRequest);
serviceHost.SetRequestHandler(SchemaComparePublishChangesRequest.Type, this.HandleSchemaComparePublishChangesRequest); serviceHost.SetRequestHandler(SchemaComparePublishChangesRequest.Type, this.HandleSchemaComparePublishChangesRequest);
serviceHost.SetRequestHandler(SchemaCompareIncludeExcludeNodeRequest.Type, this.HandleSchemaCompareIncludeExcludeNodeRequest); serviceHost.SetRequestHandler(SchemaCompareIncludeExcludeNodeRequest.Type, this.HandleSchemaCompareIncludeExcludeNodeRequest);
@@ -78,6 +82,7 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
try try
{ {
operation = new SchemaCompareOperation(parameters, sourceConnInfo, targetConnInfo); operation = new SchemaCompareOperation(parameters, sourceConnInfo, targetConnInfo);
currentComparisonCancellationAction.Value[operation.OperationId] = operation.Cancel;
operation.Execute(parameters.TaskExecutionMode); operation.Execute(parameters.TaskExecutionMode);
// add result to dictionary of results // add result to dictionary of results
@@ -110,6 +115,40 @@ namespace Microsoft.SqlTools.ServiceLayer.SchemaCompare
} }
} }
/// <summary>
/// Handles schema compare cancel request
/// </summary>
/// <returns></returns>
public async Task HandleSchemaCompareCancelRequest(SchemaCompareCancelParams parameters, RequestContext<ResultStatus> requestContext)
{
try
{
Action cancelAction = null;
if (currentComparisonCancellationAction.Value.TryRemove(parameters.OperationId, out cancelAction))
{
if(cancelAction != null)
{
cancelAction.Invoke();
await requestContext.SendResult(new ResultStatus()
{
Success = true,
ErrorMessage = null
});
}
}
await requestContext.SendResult(new ResultStatus()
{
Success = false,
ErrorMessage = SR.SchemaCompareSessionNotFound
});
}
catch (Exception e)
{
await requestContext.SendError(e);
}
}
/// <summary> /// <summary>
/// Handles request for schema compare generate deploy script /// Handles request for schema compare generate deploy script
/// </summary> /// </summary>

View File

@@ -35,7 +35,7 @@
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" /> <PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4316.1-preview" /> <PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4451.1-preview" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -35,7 +35,7 @@
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" /> <PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4316.1-preview" /> <PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4451.1-preview" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -626,6 +626,56 @@ CREATE TABLE [dbo].[table3]
} }
} }
/// <summary>
/// Verify the schema compare cancel
/// </summary>
[Fact]
public async void SchemaCompareCancelCompareOperation()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");
try
{
SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();
sourceInfo.EndpointType = SchemaCompareEndpointType.Database;
sourceInfo.DatabaseName = sourceDb.DatabaseName;
targetInfo.EndpointType = SchemaCompareEndpointType.Database;
targetInfo.DatabaseName = targetDb.DatabaseName;
var schemaCompareParams = new SchemaCompareParams
{
SourceEndpointInfo = sourceInfo,
TargetEndpointInfo = targetInfo
};
SchemaCompareOperation schemaCompareOperation = new SchemaCompareOperation(schemaCompareParams, result.ConnectionInfo, result.ConnectionInfo);
schemaCompareOperation.schemaCompareStarted += (sender, e) => { schemaCompareOperation.Cancel(); };
try
{
Task cTask = Task.Factory.StartNew(() => schemaCompareOperation.Execute(TaskExecutionMode.Execute));
cTask.Wait();
Assert.False(cTask.IsCompletedSuccessfully, "schema compare task should not complete after cancel");
}
catch (Exception ex)
{
Assert.NotNull(ex.InnerException);
Assert.True(ex.InnerException is OperationCanceledException, $"Exception is expected to be Operation cancelled but actually is {ex.InnerException}");
}
Assert.Null(schemaCompareOperation.ComparisonResult.Differences);
}
finally
{
sourceDb.Cleanup();
targetDb.Cleanup();
}
}
private void ValidateSchemaCompareWithExcludeIncludeResults(SchemaCompareOperation schemaCompareOperation) private void ValidateSchemaCompareWithExcludeIncludeResults(SchemaCompareOperation schemaCompareOperation)
{ {
schemaCompareOperation.Execute(TaskExecutionMode.Execute); schemaCompareOperation.Execute(TaskExecutionMode.Execute);
@@ -732,7 +782,6 @@ CREATE TABLE [dbo].[table3]
Assert.True(initialScript.Length == afterIncludeScript.Length, $"Changes should be same as inital since we included what we excluded, before {initialScript}, now {afterIncludeScript}"); Assert.True(initialScript.Length == afterIncludeScript.Length, $"Changes should be same as inital since we included what we excluded, before {initialScript}, now {afterIncludeScript}");
} }
private async Task CreateAndOpenScmp(SchemaCompareEndpointType sourceEndpointType, SchemaCompareEndpointType targetEndpointType) private async Task CreateAndOpenScmp(SchemaCompareEndpointType sourceEndpointType, SchemaCompareEndpointType targetEndpointType)
{ {
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareOpenScmpSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareOpenScmpSource");