Fix script generated for SQL Assessment results (#1058)

* INSERT VALUES has the limit of 1000 rows. Replace with derived table.
* Remove NOT NULL restriction from the generated table.
* Fix line endings in SQL Assessment source files.
This commit is contained in:
Aleksei Guzev
2020-08-28 20:17:54 +03:00
committed by GitHub
parent 0b905fef75
commit 07700560a6
8 changed files with 1222 additions and 1212 deletions

View File

@@ -1,129 +1,129 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using Microsoft.SqlServer.Management.Assessment;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class AssessmentParams
{
/// <summary>
/// Gets or sets the owner uri to get connection from
/// </summary>
public string OwnerUri { get; set; }
/// <summary>
/// Gets or sets the target type
/// </summary>
public SqlObjectType TargetType { get; set; }
}
/// <summary>
/// Describes an item returned by SQL Assessment RPC methods
/// </summary>
public class AssessmentItemInfo
{
/// <summary>
/// Gets or sets assessment ruleset version.
/// </summary>
public string RulesetVersion { get; set; }
/// <summary>
/// Gets or sets assessment ruleset name
/// </summary>
public string RulesetName { get; set; }
/// <summary>
/// Gets or sets assessed target's type.
/// Supported values: 1 - server, 2 - database.
/// </summary>
public SqlObjectType TargetType { get; set; }
/// <summary>
/// Gets or sets the assessed object's name.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets or sets check's ID.
/// </summary>
public string CheckId { get; set; }
/// <summary>
/// Gets or sets tags assigned to this item.
/// </summary>
public string[] Tags { get; set; }
/// <summary>
/// Gets or sets a display name for this item.
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets a brief description of the item's purpose.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> containing
/// an link to a page providing detailed explanation
/// of the best practice.
/// </summary>
public string HelpLink { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> indicating
/// severity level assigned to this items.
/// Values are: "Information", "Warning", "Critical".
/// </summary>
public string Level { get; set; }
}
/// <summary>
/// Generic SQL Assessment Result
/// </summary>
/// <typeparam name="T">
/// Result item's type derived from <see cref="AssessmentItemInfo"/>
/// </typeparam>
public class AssessmentResultData<T>
where T : AssessmentItemInfo
{
/// <summary>
/// Gets the collection of assessment results.
/// </summary>
public List<T> Items { get; } = new List<T>();
/// <summary>
/// Gets or sets SQL Assessment API version.
/// </summary>
public string ApiVersion { get; set; }
}
/// <summary>
/// Generic SQL Assessment Result
/// </summary>
/// <typeparam name="T">
/// Result item's type derived from <see cref="AssessmentItemInfo"/>
/// </typeparam>
public class AssessmentResult<T> : AssessmentResultData<T>
where T : AssessmentItemInfo
{
/// <summary>
/// Gets or sets a value indicating
/// if assessment operation was successful.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets or sets an status message for the operation.
/// </summary>
public string ErrorMessage { get; set; }
}
}
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using Microsoft.SqlServer.Management.Assessment;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class AssessmentParams
{
/// <summary>
/// Gets or sets the owner uri to get connection from
/// </summary>
public string OwnerUri { get; set; }
/// <summary>
/// Gets or sets the target type
/// </summary>
public SqlObjectType TargetType { get; set; }
}
/// <summary>
/// Describes an item returned by SQL Assessment RPC methods
/// </summary>
public class AssessmentItemInfo
{
/// <summary>
/// Gets or sets assessment ruleset version.
/// </summary>
public string RulesetVersion { get; set; }
/// <summary>
/// Gets or sets assessment ruleset name
/// </summary>
public string RulesetName { get; set; }
/// <summary>
/// Gets or sets assessed target's type.
/// Supported values: 1 - server, 2 - database.
/// </summary>
public SqlObjectType TargetType { get; set; }
/// <summary>
/// Gets or sets the assessed object's name.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets or sets check's ID.
/// </summary>
public string CheckId { get; set; }
/// <summary>
/// Gets or sets tags assigned to this item.
/// </summary>
public string[] Tags { get; set; }
/// <summary>
/// Gets or sets a display name for this item.
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets a brief description of the item's purpose.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> containing
/// an link to a page providing detailed explanation
/// of the best practice.
/// </summary>
public string HelpLink { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> indicating
/// severity level assigned to this items.
/// Values are: "Information", "Warning", "Critical".
/// </summary>
public string Level { get; set; }
}
/// <summary>
/// Generic SQL Assessment Result
/// </summary>
/// <typeparam name="T">
/// Result item's type derived from <see cref="AssessmentItemInfo"/>
/// </typeparam>
public class AssessmentResultData<T>
where T : AssessmentItemInfo
{
/// <summary>
/// Gets the collection of assessment results.
/// </summary>
public List<T> Items { get; } = new List<T>();
/// <summary>
/// Gets or sets SQL Assessment API version.
/// </summary>
public string ApiVersion { get; set; }
}
/// <summary>
/// Generic SQL Assessment Result
/// </summary>
/// <typeparam name="T">
/// Result item's type derived from <see cref="AssessmentItemInfo"/>
/// </typeparam>
public class AssessmentResult<T> : AssessmentResultData<T>
where T : AssessmentItemInfo
{
/// <summary>
/// Gets or sets a value indicating
/// if assessment operation was successful.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets or sets an status message for the operation.
/// </summary>
public string ErrorMessage { get; set; }
}
}

View File

@@ -1,56 +1,56 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class GenerateScriptParams
{
/// <summary>
/// Gets or sets a list of assessment result items
/// to be written to a table
/// </summary>
public List<AssessmentResultItem> Items { get; set; }
public TaskExecutionMode TaskExecutionMode { get; set; }
public string TargetServerName { get; set; }
public string TargetDatabaseName { get; set; }
}
public class GenerateScriptResult
{
/// <summary>
/// Gets or sets a value indicating
/// if assessment operation was successful
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets or sets an status message for the operation
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Gets or sets script text
/// </summary>
public string Script { get; set; }
}
public class GenerateScriptRequest
{
public static readonly
RequestType<GenerateScriptParams, ResultStatus> Type =
RequestType<GenerateScriptParams, ResultStatus>.Create("assessment/generateScript");
}
}
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class GenerateScriptParams
{
/// <summary>
/// Gets or sets a list of assessment result items
/// to be written to a table
/// </summary>
public List<AssessmentResultItem> Items { get; set; }
public TaskExecutionMode TaskExecutionMode { get; set; }
public string TargetServerName { get; set; }
public string TargetDatabaseName { get; set; }
}
public class GenerateScriptResult
{
/// <summary>
/// Gets or sets a value indicating
/// if assessment operation was successful
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets or sets an status message for the operation
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Gets or sets script text
/// </summary>
public string Script { get; set; }
}
public class GenerateScriptRequest
{
public static readonly
RequestType<GenerateScriptParams, ResultStatus> Type =
RequestType<GenerateScriptParams, ResultStatus>.Create("assessment/generateScript");
}
}

View File

@@ -1,33 +1,33 @@
//
// 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;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class GetAssessmentItemsParams : AssessmentParams
{
// a placeholder for future specialization
}
/// <summary>
/// Describes a check used to assess SQL Server objects.
/// </summary>
public class CheckInfo : AssessmentItemInfo
{
// a placeholder for future specialization
}
public class GetAssessmentItemsRequest
{
public static readonly RequestType<GetAssessmentItemsParams, AssessmentResult<CheckInfo>> Type =
RequestType<GetAssessmentItemsParams, AssessmentResult<CheckInfo>>.Create(
"assessment/getAssessmentItems");
}
}
//
// 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;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class GetAssessmentItemsParams : AssessmentParams
{
// a placeholder for future specialization
}
/// <summary>
/// Describes a check used to assess SQL Server objects.
/// </summary>
public class CheckInfo : AssessmentItemInfo
{
// a placeholder for future specialization
}
public class GetAssessmentItemsRequest
{
public static readonly RequestType<GetAssessmentItemsParams, AssessmentResult<CheckInfo>> Type =
RequestType<GetAssessmentItemsParams, AssessmentResult<CheckInfo>>.Create(
"assessment/getAssessmentItems");
}
}

View File

@@ -1,82 +1,82 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class InvokeParams : AssessmentParams
{
// a placeholder for future specialization
}
/// <summary>
/// SQL Assessment result item kind.
/// </summary>
/// <remarks>
/// SQL Assessment run is a set of checks. Every check
/// may return a result item. Normally it is a note containing
/// recommendations on improving target's configuration.
/// But some checks may fail to obtain data due to access
/// restrictions or data integrity. In this case
/// the check produces an error or a warning.
/// </remarks>
public enum AssessmentResultItemKind
{
/// <summary>
/// SQL Assessment item contains recommendation
/// </summary>
Note = 0,
/// <summary>
/// SQL Assessment item contains a warning on
/// limited assessment capabilities
/// </summary>
Warning = 1,
/// <summary>
/// SQL Assessment item contain a description of
/// error occured in the course of assessment run
/// </summary>
Error = 2
}
/// <summary>
/// Describes an assessment result item
/// containing a recommendation based on best practices.
/// </summary>
public class AssessmentResultItem : AssessmentItemInfo
{
/// <summary>
/// Gets or sets a message to the user
/// containing the recommendation.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets result type:
/// 0 - real result, 1 - warning, 2 - error.
/// </summary>
public AssessmentResultItemKind Kind { get; set; }
/// <summary>
/// Gets or sets date and time
/// when the item had been acquired.
/// </summary>
public DateTimeOffset Timestamp { get; set; }
}
public class InvokeRequest
{
public static readonly
RequestType<InvokeParams, AssessmentResult<AssessmentResultItem>> Type =
RequestType<InvokeParams, AssessmentResult<AssessmentResultItem>>.Create("assessment/invoke");
}
}
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts
{
/// <summary>
/// Parameters for executing a query from a provided string
/// </summary>
public class InvokeParams : AssessmentParams
{
// a placeholder for future specialization
}
/// <summary>
/// SQL Assessment result item kind.
/// </summary>
/// <remarks>
/// SQL Assessment run is a set of checks. Every check
/// may return a result item. Normally it is a note containing
/// recommendations on improving target's configuration.
/// But some checks may fail to obtain data due to access
/// restrictions or data integrity. In this case
/// the check produces an error or a warning.
/// </remarks>
public enum AssessmentResultItemKind
{
/// <summary>
/// SQL Assessment item contains recommendation
/// </summary>
Note = 0,
/// <summary>
/// SQL Assessment item contains a warning on
/// limited assessment capabilities
/// </summary>
Warning = 1,
/// <summary>
/// SQL Assessment item contain a description of
/// error occured in the course of assessment run
/// </summary>
Error = 2
}
/// <summary>
/// Describes an assessment result item
/// containing a recommendation based on best practices.
/// </summary>
public class AssessmentResultItem : AssessmentItemInfo
{
/// <summary>
/// Gets or sets a message to the user
/// containing the recommendation.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets result type:
/// 0 - real result, 1 - warning, 2 - error.
/// </summary>
public AssessmentResultItemKind Kind { get; set; }
/// <summary>
/// Gets or sets date and time
/// when the item had been acquired.
/// </summary>
public DateTimeOffset Timestamp { get; set; }
}
public class InvokeRequest
{
public static readonly
RequestType<InvokeParams, AssessmentResult<AssessmentResultItem>> Type =
RequestType<InvokeParams, AssessmentResult<AssessmentResultItem>>.Create("assessment/invoke");
}
}

View File

@@ -27,8 +27,8 @@ namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment
/// <summary>
/// Gets the unique id associated with this instance.
/// </summary>
public string OperationId { get; set; }
public string OperationId { get; set; }
/// <summary>
/// Gets the parameters containing assessment results
/// to be stored in a data table.
@@ -44,8 +44,8 @@ namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment
/// <summary>
/// Gets or sets the sql task that's executing the operation
/// </summary>
public SqlTask SqlTask { get; set; }
public SqlTask SqlTask { get; set; }
public GenerateScriptOperation(GenerateScriptParams parameters)
{
Validate.IsNotNull(nameof(parameters), parameters);
@@ -92,24 +92,29 @@ namespace Microsoft.SqlTools.ServiceLayer.SqlAssessment
CancellationToken cancellationToken)
{
const string scriptPrologue =
@"IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'AssessmentResult'))
BEGIN
CREATE TABLE [dbo].[AssessmentResult](
[CheckName] [nvarchar](max) NOT NULL,
[CheckId] [nvarchar](max) NOT NULL,
[RulesetName] [nvarchar](max) NOT NULL,
[RulesetVersion] [nvarchar](max) NOT NULL,
[Severity] [nvarchar](max) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[TargetPath] [nvarchar](max) NOT NULL,
[TargetType] [nvarchar](max) NOT NULL,
[HelpLink] [nvarchar](max) NOT NULL,
[Timestamp] [datetimeoffset](7) NOT NULL
)
END
GO
INSERT INTO [dbo].[AssessmentResult] ([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])
VALUES";
@"IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'AssessmentResult'))
BEGIN
CREATE TABLE [dbo].[AssessmentResult](
[CheckName] [nvarchar](max),
[CheckId] [nvarchar](max),
[RulesetName] [nvarchar](max),
[RulesetVersion] [nvarchar](max),
[Severity] [nvarchar](max),
[Message] [nvarchar](max),
[TargetPath] [nvarchar](max),
[TargetType] [nvarchar](max),
[HelpLink] [nvarchar](max),
[Timestamp] [datetimeoffset](7)
)
END
GO
INSERT INTO [dbo].[AssessmentResult] ([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])
SELECT rpt.[CheckName],rpt.[CheckId],rpt.[RulesetName],rpt.[RulesetVersion],rpt.[Severity],rpt.[Message],rpt.[TargetPath],rpt.[TargetType],rpt.[HelpLink],rpt.[Timestamp]
FROM (VALUES ";
const string scriptEpilogue =
@"
) rpt([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])";
var sb = new StringBuilder();
if (generateScriptParams.Items != null)
@@ -122,11 +127,14 @@ VALUES";
if (item.Kind == AssessmentResultItemKind.Note)
{
sb.Append(
$"\r\n('{CUtils.EscapeStringSQuote(item.DisplayName)}','{CUtils.EscapeStringSQuote(item.CheckId)}','{CUtils.EscapeStringSQuote(item.RulesetName)}','{item.RulesetVersion}','{item.Level}','{CUtils.EscapeStringSQuote(item.Message)}','{CUtils.EscapeStringSQuote(item.TargetName)}','{item.TargetType}','{CUtils.EscapeStringSQuote(item.HelpLink)}','{item.Timestamp:yyyy-MM-dd hh:mm:ss.fff zzz}'),");
$@"
('{CUtils.EscapeStringSQuote(item.DisplayName)}','{CUtils.EscapeStringSQuote(item.CheckId)}','{CUtils.EscapeStringSQuote(item.RulesetName)}','{item.RulesetVersion}','{item.Level}','{CUtils.EscapeStringSQuote(item.Message)}','{CUtils.EscapeStringSQuote(item.TargetName)}','{item.TargetType}','{CUtils.EscapeStringSQuote(item.HelpLink)}','{item.Timestamp:yyyy-MM-dd hh:mm:ss.fff zzz}'),");
}
}
sb.Length -= 1;
sb.Append(scriptEpilogue);
}
return sb.ToString();

View File

@@ -1,225 +1,225 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Assessment;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
{
public class SqlAssessmentServiceTests
{
private delegate Task<List<TResult>> AssessmentMethod<TResult>(SqlObjectLocator locator);
private static readonly string[] AllowedSeverityLevels = { "Information", "Warning", "Critical" };
[Test]
public async Task InvokeSqlAssessmentServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();
Debug.Assert(connection != null, "Live connection is always expected providing a connection");
var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
var response = await CallAssessment<AssessmentResultItem>(
nameof(SqlAssessmentService.InvokeSqlAssessment),
SqlObjectType.Server,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task GetAssessmentItemsServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();
Debug.Assert(connection != null, "Live connection is always expected providing a connection");
var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
var response = await CallAssessment<CheckInfo>(
nameof(SqlAssessmentService.GetAssessmentItems),
SqlObjectType.Server,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items)
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task GetAssessmentItemsDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
var response = await CallAssessment<CheckInfo>(
nameof(SqlAssessmentService.GetAssessmentItems),
SqlObjectType.Database,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items)
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task InvokeSqlAssessmentIDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
var response = await CallAssessment<AssessmentResultItem>(
nameof(SqlAssessmentService.InvokeSqlAssessment),
SqlObjectType.Database,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{
AssertInfoPresent(i);
}
});
}
private static async Task<AssessmentResult<TResult>> CallAssessment<TResult>(
string methodName,
SqlObjectType sqlObjectType,
LiveConnectionHelper.TestConnectionResult liveConnection)
where TResult : AssessmentItemInfo
{
var connInfo = liveConnection.ConnectionInfo;
AssessmentResult<TResult> response;
using (var service = new SqlAssessmentService(
TestServiceProvider.Instance.ConnectionService,
TestServiceProvider.Instance.WorkspaceService))
{
AddTestRules(service);
string randomUri = Guid.NewGuid().ToString();
AssessmentParams requestParams =
new AssessmentParams { OwnerUri = randomUri, TargetType = sqlObjectType };
ConnectParams connectParams = new ConnectParams
{
OwnerUri = requestParams.OwnerUri,
Connection = connInfo.ConnectionDetails,
Type = ConnectionType.Default
};
var methodInfo = typeof(SqlAssessmentService).GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(methodInfo);
var func = (AssessmentMethod<TResult>)Delegate.CreateDelegate(
typeof(AssessmentMethod<TResult>),
service,
methodInfo);
response = await service.CallAssessmentEngine<TResult>(
requestParams,
connectParams,
randomUri,
t => func(t));
}
Assert.NotNull(response);
if (response.Success)
{
Assert.That(response.Items.Select(i => i.TargetType), Has.All.EqualTo(sqlObjectType));
Assert.That(response.Items.Select(i => i.Level), Has.All.AnyOf(AllowedSeverityLevels));
}
return response;
}
private static void AddTestRules(SqlAssessmentService service)
{
const string TestRuleset = @"
{
'name': 'Tags & Checks',
'version': '0.3',
'schemaVersion': '1.0',
'rules': [
{
'id': 'ServerRule',
'itemType': 'definition',
'tags': [ 'Test' ],
'displayName': 'Test server check',
'description': 'This check always fails for testing purposes.',
'message': 'This check intentionally fails',
'target': { 'type': 'Server' }
},
{
'id': 'DatabaseRule',
'itemType': 'definition',
'tags': [ 'Test' ],
'displayName': 'Test server check',
'description': 'This check always fails for testing purposes.',
'message': 'This check intentionally fails',
'target': { 'type': 'Database' }
}
]
}
";
using (var reader = new StringReader(TestRuleset))
{
service.Engine.PushRuleFactoryJson(reader);
}
}
private void AssertInfoPresent(AssessmentItemInfo item)
{
Assert.Multiple(() =>
{
Assert.That(item.CheckId, Is.Not.Null.Or.Empty);
Assert.That(item.DisplayName, Is.Not.Null.Or.Empty);
Assert.That(item.Description, Is.Not.Null.Or.Empty);
Assert.NotNull(item.Tags);
Assert.That(item.Tags, Has.All.Not.Null.Or.Empty);
});
}
}
}
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Assessment;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
{
public class SqlAssessmentServiceTests
{
private delegate Task<List<TResult>> AssessmentMethod<TResult>(SqlObjectLocator locator);
private static readonly string[] AllowedSeverityLevels = { "Information", "Warning", "Critical" };
[Test]
public async Task InvokeSqlAssessmentServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();
Debug.Assert(connection != null, "Live connection is always expected providing a connection");
var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
var response = await CallAssessment<AssessmentResultItem>(
nameof(SqlAssessmentService.InvokeSqlAssessment),
SqlObjectType.Server,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task GetAssessmentItemsServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();
Debug.Assert(connection != null, "Live connection is always expected providing a connection");
var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
var response = await CallAssessment<CheckInfo>(
nameof(SqlAssessmentService.GetAssessmentItems),
SqlObjectType.Server,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items)
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task GetAssessmentItemsDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
var response = await CallAssessment<CheckInfo>(
nameof(SqlAssessmentService.GetAssessmentItems),
SqlObjectType.Database,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items)
{
AssertInfoPresent(i);
}
});
}
[Test]
public async Task InvokeSqlAssessmentIDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
var response = await CallAssessment<AssessmentResultItem>(
nameof(SqlAssessmentService.InvokeSqlAssessment),
SqlObjectType.Database,
liveConnection);
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{
AssertInfoPresent(i);
}
});
}
private static async Task<AssessmentResult<TResult>> CallAssessment<TResult>(
string methodName,
SqlObjectType sqlObjectType,
LiveConnectionHelper.TestConnectionResult liveConnection)
where TResult : AssessmentItemInfo
{
var connInfo = liveConnection.ConnectionInfo;
AssessmentResult<TResult> response;
using (var service = new SqlAssessmentService(
TestServiceProvider.Instance.ConnectionService,
TestServiceProvider.Instance.WorkspaceService))
{
AddTestRules(service);
string randomUri = Guid.NewGuid().ToString();
AssessmentParams requestParams =
new AssessmentParams { OwnerUri = randomUri, TargetType = sqlObjectType };
ConnectParams connectParams = new ConnectParams
{
OwnerUri = requestParams.OwnerUri,
Connection = connInfo.ConnectionDetails,
Type = ConnectionType.Default
};
var methodInfo = typeof(SqlAssessmentService).GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(methodInfo);
var func = (AssessmentMethod<TResult>)Delegate.CreateDelegate(
typeof(AssessmentMethod<TResult>),
service,
methodInfo);
response = await service.CallAssessmentEngine<TResult>(
requestParams,
connectParams,
randomUri,
t => func(t));
}
Assert.NotNull(response);
if (response.Success)
{
Assert.That(response.Items.Select(i => i.TargetType), Has.All.EqualTo(sqlObjectType));
Assert.That(response.Items.Select(i => i.Level), Has.All.AnyOf(AllowedSeverityLevels));
}
return response;
}
private static void AddTestRules(SqlAssessmentService service)
{
const string TestRuleset = @"
{
'name': 'Tags & Checks',
'version': '0.3',
'schemaVersion': '1.0',
'rules': [
{
'id': 'ServerRule',
'itemType': 'definition',
'tags': [ 'Test' ],
'displayName': 'Test server check',
'description': 'This check always fails for testing purposes.',
'message': 'This check intentionally fails',
'target': { 'type': 'Server' }
},
{
'id': 'DatabaseRule',
'itemType': 'definition',
'tags': [ 'Test' ],
'displayName': 'Test server check',
'description': 'This check always fails for testing purposes.',
'message': 'This check intentionally fails',
'target': { 'type': 'Database' }
}
]
}
";
using (var reader = new StringReader(TestRuleset))
{
service.Engine.PushRuleFactoryJson(reader);
}
}
private void AssertInfoPresent(AssessmentItemInfo item)
{
Assert.Multiple(() =>
{
Assert.That(item.CheckId, Is.Not.Null.Or.Empty);
Assert.That(item.DisplayName, Is.Not.Null.Or.Empty);
Assert.That(item.Description, Is.Not.Null.Or.Empty);
Assert.NotNull(item.Tags);
Assert.That(item.Tags, Has.All.Not.Null.Or.Empty);
});
}
}
}

View File

@@ -1,157 +1,159 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Assessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Moq;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlAssessment
{
public class GenerateScriptOperationTests
{
private static readonly GenerateScriptParams SampleParams = new GenerateScriptParams
{
Items = new List<AssessmentResultItem>
{
new AssessmentResultItem
{
CheckId = "C1",
Description = "Desc1",
DisplayName = "DN1",
HelpLink = "HL1",
Kind = AssessmentResultItemKind.Note,
Level = "Information",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.Zero),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C-2",
Description = "Desc2",
DisplayName = "D N2",
HelpLink = "http://HL2",
Kind = AssessmentResultItemKind.Warning,
Level = "Warning",
Message = "Msg'1",
TargetName = "proj[*]_devW",
TargetType = SqlObjectType.Database,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromHours(3)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C'3",
Description = "Des'c3",
DisplayName = "D'N1",
HelpLink = "HL'1",
Kind = AssessmentResultItemKind.Error,
Level = "Critical",
Message = "Msg'1",
TargetName = "proj[*]_devE",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromMinutes(-90)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C-2",
Description = "Desc2",
DisplayName = "D N2",
HelpLink = "http://HL2",
Kind = AssessmentResultItemKind.Note,
Level = "Warning",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Database,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromHours(3)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C'3",
Description = "Des'c3",
DisplayName = "D'N1",
HelpLink = "HL'1",
Kind = AssessmentResultItemKind.Note,
Level = "Critical",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromMinutes(-90)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
}
}
};
private const string SampleScript =
@"IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'AssessmentResult'))
BEGIN
CREATE TABLE [dbo].[AssessmentResult](
[CheckName] [nvarchar](max) NOT NULL,
[CheckId] [nvarchar](max) NOT NULL,
[RulesetName] [nvarchar](max) NOT NULL,
[RulesetVersion] [nvarchar](max) NOT NULL,
[Severity] [nvarchar](max) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[TargetPath] [nvarchar](max) NOT NULL,
[TargetType] [nvarchar](max) NOT NULL,
[HelpLink] [nvarchar](max) NOT NULL,
[Timestamp] [datetimeoffset](7) NOT NULL
)
END
GO
INSERT INTO [dbo].[AssessmentResult] ([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])
VALUES
('DN1','C1','Microsoft Ruleset','1.3','Information','Msg''1','proj[*]_dev','Server','HL1','2001-05-25 01:42:00.000 +00:00'),
('D N2','C-2','Microsoft Ruleset','1.3','Warning','Msg''1','proj[*]_dev','Database','http://HL2','2001-05-25 01:42:00.000 +03:00'),
('D''N1','C''3','Microsoft Ruleset','1.3','Critical','Msg''1','proj[*]_dev','Server','HL''1','2001-05-25 01:42:00.000 -01:30')";
[Test]
public void GenerateScriptTest()
{
var scriptText = GenerateScriptOperation.GenerateScript(SampleParams, CancellationToken.None);
Assert.AreEqual(SampleScript, scriptText);
}
[Test]
public void ExecuteTest()
{
var subject = new GenerateScriptOperation(SampleParams);
var taskMetadata = new TaskMetadata();
using (var sqlTask = new SqlTask(taskMetadata, DummyOpFunction, DummyOpFunction))
{
subject.SqlTask = sqlTask;
sqlTask.ScriptAdded += ValidateScriptAdded;
subject.Execute(TaskExecutionMode.Script);
}
}
private void ValidateScriptAdded(object sender, TaskEventArgs<TaskScript> e)
{
Assert.AreEqual(SqlTaskStatus.Succeeded, e.TaskData.Status);
Assert.AreEqual(SampleScript, e.TaskData.Script);
}
private static Task<TaskResult> DummyOpFunction(SqlTask _)
{
return Task.FromResult(new TaskResult() {TaskStatus = SqlTaskStatus.Succeeded});
}
}
}
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Assessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Moq;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlAssessment
{
public class GenerateScriptOperationTests
{
private static readonly GenerateScriptParams SampleParams = new GenerateScriptParams
{
Items = new List<AssessmentResultItem>
{
new AssessmentResultItem
{
CheckId = "C1",
Description = "Desc1",
DisplayName = "DN1",
HelpLink = "HL1",
Kind = AssessmentResultItemKind.Note,
Level = "Information",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.Zero),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C-2",
Description = "Desc2",
DisplayName = "D N2",
HelpLink = "http://HL2",
Kind = AssessmentResultItemKind.Warning,
Level = "Warning",
Message = "Msg'1",
TargetName = "proj[*]_devW",
TargetType = SqlObjectType.Database,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromHours(3)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C'3",
Description = "Des'c3",
DisplayName = "D'N1",
HelpLink = "HL'1",
Kind = AssessmentResultItemKind.Error,
Level = "Critical",
Message = "Msg'1",
TargetName = "proj[*]_devE",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromMinutes(-90)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C-2",
Description = "Desc2",
DisplayName = "D N2",
HelpLink = "http://HL2",
Kind = AssessmentResultItemKind.Note,
Level = "Warning",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Database,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromHours(3)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
},
new AssessmentResultItem
{
CheckId = "C'3",
Description = "Des'c3",
DisplayName = "D'N1",
HelpLink = "HL'1",
Kind = AssessmentResultItemKind.Note,
Level = "Critical",
Message = "Msg'1",
TargetName = "proj[*]_dev",
TargetType = SqlObjectType.Server,
Timestamp = new DateTimeOffset(2001, 5, 25, 13, 42, 00, TimeSpan.FromMinutes(-90)),
RulesetName = "Microsoft Ruleset",
RulesetVersion = "1.3"
}
}
};
private const string SampleScript =
@"IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'AssessmentResult'))
BEGIN
CREATE TABLE [dbo].[AssessmentResult](
[CheckName] [nvarchar](max),
[CheckId] [nvarchar](max),
[RulesetName] [nvarchar](max),
[RulesetVersion] [nvarchar](max),
[Severity] [nvarchar](max),
[Message] [nvarchar](max),
[TargetPath] [nvarchar](max),
[TargetType] [nvarchar](max),
[HelpLink] [nvarchar](max),
[Timestamp] [datetimeoffset](7)
)
END
GO
INSERT INTO [dbo].[AssessmentResult] ([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])
SELECT rpt.[CheckName],rpt.[CheckId],rpt.[RulesetName],rpt.[RulesetVersion],rpt.[Severity],rpt.[Message],rpt.[TargetPath],rpt.[TargetType],rpt.[HelpLink],rpt.[Timestamp]
FROM (VALUES
('DN1','C1','Microsoft Ruleset','1.3','Information','Msg''1','proj[*]_dev','Server','HL1','2001-05-25 01:42:00.000 +00:00'),
('D N2','C-2','Microsoft Ruleset','1.3','Warning','Msg''1','proj[*]_dev','Database','http://HL2','2001-05-25 01:42:00.000 +03:00'),
('D''N1','C''3','Microsoft Ruleset','1.3','Critical','Msg''1','proj[*]_dev','Server','HL''1','2001-05-25 01:42:00.000 -01:30')
) rpt([CheckName],[CheckId],[RulesetName],[RulesetVersion],[Severity],[Message],[TargetPath],[TargetType],[HelpLink],[Timestamp])";
[Test]
public void GenerateScriptTest()
{
var scriptText = GenerateScriptOperation.GenerateScript(SampleParams, CancellationToken.None);
Assert.AreEqual(SampleScript, scriptText);
}
[Test]
public void ExecuteTest()
{
var subject = new GenerateScriptOperation(SampleParams);
var taskMetadata = new TaskMetadata();
using (var sqlTask = new SqlTask(taskMetadata, DummyOpFunction, DummyOpFunction))
{
subject.SqlTask = sqlTask;
sqlTask.ScriptAdded += ValidateScriptAdded;
subject.Execute(TaskExecutionMode.Script);
}
}
private void ValidateScriptAdded(object sender, TaskEventArgs<TaskScript> e)
{
Assert.AreEqual(SqlTaskStatus.Succeeded, e.TaskData.Status);
Assert.AreEqual(SampleScript, e.TaskData.Script);
}
private static Task<TaskResult> DummyOpFunction(SqlTask _)
{
return Task.FromResult(new TaskResult() {TaskStatus = SqlTaskStatus.Succeeded});
}
}
}