Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

BREAKING CHANGE: SqlDatabasePermission: Refactored resource (class-based resource) #1769

Merged
merged 99 commits into from
Jul 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
99 commits
Select commit Hold shift + click to select a range
b24bb04
Initial class-based resource
johlju Jun 21, 2022
42b1886
Fix missing strings and private functions
johlju Jun 22, 2022
18d5a40
remove MOF resource schema and README.md
johlju Jun 26, 2022
b88382c
Update files
johlju Jun 26, 2022
ed3d5d0
Add unit test for class resource
johlju Jun 27, 2022
259d7e6
Fix working resource
johlju Jun 27, 2022
9be8855
fix todo comment
johlju Jun 27, 2022
e218d00
Fix unit tests for classes
johlju Jun 28, 2022
76757b4
Add public functions
johlju Jun 29, 2022
fe16b77
remove coverage file
johlju Jun 30, 2022
96cebac
Modify files
johlju Jun 30, 2022
8a25e3d
push latest changes
johlju Jun 30, 2022
dba7a6d
Fix code
johlju Jul 1, 2022
72b8669
Fix code
johlju Jul 1, 2022
f1d4855
Fix code changes
johlju Jul 1, 2022
9ba5db2
Fix comment
johlju Jul 1, 2022
9b695d4
Fix comment
johlju Jul 1, 2022
9f6ce99
Fix code
johlju Jul 2, 2022
90df25e
Update CHANGELOG.md
johlju Jul 2, 2022
6f8f934
Fix comment in azure-pipelines.yml
johlju Jul 2, 2022
a9d04b7
Fix unit tests
johlju Jul 2, 2022
49f88b6
Fix code
johlju Jul 3, 2022
4d76980
Fix unit tests
johlju Jul 4, 2022
5e790f6
Fix unit test
johlju Jul 4, 2022
97cc7c1
Fix unit tests
johlju Jul 5, 2022
8e663e3
Update unit tests
johlju Jul 5, 2022
f1909b5
update comment
johlju Jul 5, 2022
ee21b27
FIx CONTRIBUTING.md
johlju Jul 6, 2022
b6aeaac
Fix unit test
johlju Jul 6, 2022
a4e0881
Fix unit tests
johlju Jul 7, 2022
9c052ec
Fix code
johlju Jul 8, 2022
9c87a75
Fix unit test
johlju Jul 9, 2022
2358579
Fix public function
johlju Jul 10, 2022
a453a89
Fix examples
johlju Jul 11, 2022
f99e2fd
Fix class
johlju Jul 11, 2022
7463533
Fix unsupported RunAsCredential
johlju Jul 11, 2022
a9bd750
Fix RunAsCredential not supported
johlju Jul 11, 2022
2388fd6
Fix example
johlju Jul 11, 2022
765c891
Fix example
johlju Jul 11, 2022
32bbba8
Fix HQRM
johlju Jul 12, 2022
c5f85f9
Fix HQRM and unit test
johlju Jul 12, 2022
fb89a96
Fix Set
johlju Jul 12, 2022
cd09bef
Fix code
johlju Jul 14, 2022
7046270
Fix code
johlju Jul 14, 2022
541415b
Fix code
johlju Jul 17, 2022
a38dc5f
Add Permisson, PermissionToInclude and PermissionToExclude
johlju Jul 18, 2022
dc72ac3
Fix Include and Exclude
johlju Jul 19, 2022
9c71eda
Fix working code
johlju Jul 20, 2022
f4176af
Fix unit tests
johlju Jul 20, 2022
8fff2bc
Fix unit tests
johlju Jul 21, 2022
2af2835
Fix/issue 1555 integration (#18)
johlju Jul 22, 2022
64264f4
Fix integration test
johlju Jul 22, 2022
ab79f8b
Fix integration test (Invoke-DscResource)
johlju Jul 22, 2022
97f9a70
Fic integraton test
johlju Jul 23, 2022
be5a636
Fix integration tests
johlju Jul 23, 2022
cc1f4e0
Fix integration test
johlju Jul 23, 2022
3c6fd60
Fix integration tests
johlju Jul 23, 2022
73daab7
Fix integration tests
johlju Jul 23, 2022
245b4ec
Fix integration tests
johlju Jul 23, 2022
ede6d7c
Fix integration test
johlju Jul 23, 2022
f520fe0
Fix integration test
johlju Jul 23, 2022
b7aac63
Fix integration tests
johlju Jul 23, 2022
a1516e1
Fix integration tests
johlju Jul 23, 2022
2c8a180
Fic integration tests
johlju Jul 24, 2022
093e007
Fix integration tests
johlju Jul 24, 2022
0fdfed0
Fix CHANGELOG.md
johlju Jul 24, 2022
43cd0ee
Fix comment-based help and examples
johlju Jul 24, 2022
07446cf
Fix integration test
johlju Jul 24, 2022
2549513
Fix integration test
johlju Jul 24, 2022
1885723
Fix integration tests
johlju Jul 24, 2022
1d7200b
Fix integration test
johlju Jul 24, 2022
f6153e0
Fix integration tests
johlju Jul 24, 2022
a607751
Fix integration tests
johlju Jul 24, 2022
b21f174
Fix integration tests
johlju Jul 24, 2022
7ca699e
Fix integration tests
johlju Jul 24, 2022
5830acf
Cleanup class DatabasePermission
johlju Jul 25, 2022
4f58f56
Cleanup tests
johlju Jul 25, 2022
3e64589
Cleanup Test-ResourceHasProperty
johlju Jul 25, 2022
8c6d501
Fix CONTRIBUTING.md
johlju Jul 25, 2022
b052164
Update comment
johlju Jul 25, 2022
ce72462
Cleanup Set-SqlDscDatabasePermission
johlju Jul 25, 2022
86b9fb0
Improved SqlDatabasePermission
johlju Jul 25, 2022
22c41d9
Remove forced Verbose statements from ResourceBase
johlju Jul 25, 2022
3910dbb
Cleanup SMO stubs
johlju Jul 26, 2022
513b843
Move code to ConvertTo-DatabasePermission
johlju Jul 26, 2022
ccd59c8
Add function ConvertFrom-DatabasePermission
johlju Jul 26, 2022
e666a52
Rename public functions
johlju Jul 26, 2022
f0fda2c
Cleanup SqlDatabasePermission
johlju Jul 26, 2022
357b0c3
Cleanup SqlDatabasePermission
johlju Jul 27, 2022
b37aa7c
Cleanup ResourceBase
johlju Jul 27, 2022
ebb69be
Fix localized strings in SqlDatabasePermission
johlju Jul 27, 2022
8dc8391
Add private function ConvertTo-Reason
johlju Jul 27, 2022
0857a35
Revert using newer pester code coverage
johlju Jul 27, 2022
2876c4c
Use breakpoints for Pester coverage
johlju Jul 27, 2022
fdc75be
Fix style formatting
johlju Jul 28, 2022
7c5058b
Update CHANGELOG.md
johlju Jul 28, 2022
d6fb311
Merge branch 'main' into fix/issue-1555
johlju Jul 28, 2022
fcb2ddc
Fix review comments
johlju Jul 29, 2022
ce11053
Fix remove built module from HQRM tests
johlju Jul 29, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 47 additions & 41 deletions .vscode/analyzersettings.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,49 @@
IncludeDefaultRules = $true
IncludeRules = @(
# DSC Community style guideline rules from the module ScriptAnalyzer.
'PSAvoidDefaultValueForMandatoryParameter',
'PSAvoidDefaultValueSwitchParameter',
'PSAvoidInvokingEmptyMembers',
'PSAvoidNullOrEmptyHelpMessageAttribute',
'PSAvoidUsingCmdletAliases',
'PSAvoidUsingComputerNameHardcoded',
'PSAvoidUsingDeprecatedManifestFields',
'PSAvoidUsingEmptyCatchBlock',
'PSAvoidUsingInvokeExpression',
'PSAvoidUsingPositionalParameters',
'PSAvoidShouldContinueWithoutForce',
'PSAvoidUsingWMICmdlet',
'PSAvoidUsingWriteHost',
'PSDSCReturnCorrectTypesForDSCFunctions',
'PSDSCStandardDSCFunctionsInResource',
'PSDSCUseIdenticalMandatoryParametersForDSC',
'PSDSCUseIdenticalParametersForDSC',
'PSMisleadingBacktick',
'PSMissingModuleManifestField',
'PSPossibleIncorrectComparisonWithNull',
'PSProvideCommentHelp',
'PSReservedCmdletChar',
'PSReservedParams',
'PSUseApprovedVerbs',
'PSUseCmdletCorrectly',
'PSUseOutputTypeCorrectly',
'PSAvoidGlobalVars',
'PSAvoidUsingConvertToSecureStringWithPlainText',
'PSAvoidUsingPlainTextForPassword',
'PSAvoidUsingUsernameAndPasswordParams',
'PSDSCUseVerboseMessageInDSCResource',
'PSShouldProcess',
'PSUseDeclaredVarsMoreThanAssignments',
'PSUsePSCredentialType',
'PSAvoidDefaultValueForMandatoryParameter'
'PSAvoidDefaultValueSwitchParameter'
'PSAvoidInvokingEmptyMembers'
'PSAvoidNullOrEmptyHelpMessageAttribute'
'PSAvoidUsingCmdletAliases'
'PSAvoidUsingComputerNameHardcoded'
'PSAvoidUsingDeprecatedManifestFields'
'PSAvoidUsingEmptyCatchBlock'
'PSAvoidUsingInvokeExpression'
'PSAvoidUsingPositionalParameters'
'PSAvoidShouldContinueWithoutForce'
'PSAvoidUsingWMICmdlet'
'PSAvoidUsingWriteHost'
'PSDSCReturnCorrectTypesForDSCFunctions'
'PSDSCStandardDSCFunctionsInResource'
'PSDSCUseIdenticalMandatoryParametersForDSC'
'PSDSCUseIdenticalParametersForDSC'
'PSMisleadingBacktick'
'PSMissingModuleManifestField'
'PSPossibleIncorrectComparisonWithNull'
'PSProvideCommentHelp'
'PSReservedCmdletChar'
'PSReservedParams'
'PSUseApprovedVerbs'
'PSUseCmdletCorrectly'
'PSUseOutputTypeCorrectly'
'PSAvoidGlobalVars'
'PSAvoidUsingConvertToSecureStringWithPlainText'
'PSAvoidUsingPlainTextForPassword'
'PSAvoidUsingUsernameAndPasswordParams'
'PSDSCUseVerboseMessageInDSCResource'
'PSShouldProcess'
'PSUseDeclaredVarsMoreThanAssignments'
'PSUsePSCredentialType'

# Additional rules from the module ScriptAnalyzer
'PSUseConsistentWhitespace',
'UseCorrectCasing',
'PSPlaceOpenBrace',
'PSPlaceCloseBrace',
'AlignAssignmentStatement',
'AvoidUsingDoubleQuotesForConstantString',
'PSUseConsistentWhitespace'
'UseCorrectCasing'
'PSPlaceOpenBrace'
'PSPlaceCloseBrace'
'AlignAssignmentStatement'
'AvoidUsingDoubleQuotesForConstantString'
'UseShouldProcessForStateChangingFunctions'

# Rules from the modules DscResource.AnalyzerRules and SqlServerDsc.AnalyzerRules
'Measure-*'
Expand All @@ -70,6 +71,11 @@
'UseSyntacticallyCorrectExamples'
)

# TODO: This is not excluded correctly, see test QA/ScriptAnalyzer.Tests.ps1 for more information.
ExcludeRules = @(
'TypeNotFound'
)

Rules = @{
PSUseConsistentWhitespace = @{
Enable = $true
Expand All @@ -80,7 +86,7 @@
CheckSeparator = $true
CheckPipe = $true
CheckPipeForRedundantWhitespace = $true
CheckParameter = $true
CheckParameter = $false
}

PSPlaceOpenBrace = @{
Expand Down
63 changes: 63 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the existing DSC Community rules and style guideline were added.
- Added the Visual Studio Code extension _Code Spell Checker_ to the list
of recommended Visual Studio Code extensions.
- Added a file `prefix.ps1` which content is placed first in the built module
(.psm1). This file imports dependent modules, and imports localized strings
used by private and public commands.
- The following classes were added to the module:
- `DatabasePermission` - complex type for the DSC resource SqlDatabasePermission.
- `Ensure` - Enum to be used for the property `Ensure` in class-based
resources.
- `Reason` - Used by method `Get()` to return the reason a property is not
in desired state.
- `ResourceBase` - class that can be inherited by class-based resource and
provides functionality meant simplify the creating of class-based resource.
- The following private functions were added to the module (see comment-based
help for more information):
- `ConvertFrom-CompareResult`
- `ConvertTo-Reason`
- `Get-ClassName`
- `Get-DscProperty`
- `Get-LocalizedDataRecursive`
- `Test-ResourceHasDscProperty`
- `Test-ResourceDscPropertyIsAssigned`
- The following public functions were added to the module (see comment-based
help for more information):
- `Connect-SqlDscDatabaseEngine`
- `ConvertFrom-SqlDscDatabasePermission`
- `ConvertTo-SqlDscDatabasePermission`
- `Get-SqlDscDatabasePermission`
- `Set-SqlDscDatabasePermission`
- `Test-SqlDscIsDatabasePrincipal`
- CommonTestHelper
- `Import-SqlModuleStub`
- Added the optional parameter **PasThru** that, if used, will return the
Expand All @@ -59,8 +87,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Bumped Stale task to v5 in the GitHub workflow.
- Make it possible to publish code coverage on failed test runs, and
when re-run a fail job.
- Exclude Script Analyzer rule **TypeNotFound** in the file `.vscode/analyzersettings.psd1`.
- Update CONTRIBUTING.md describing error handling in commands and class-based
resources.
- The QA tests are now run in Windows PowerShell due to a bug in PowerShell 7
that makes class-based resource using inheritance to not work.
- The QA test are excluding the rule **TypeNotFound** because it cannot
run on the source files (there is a new issue that is tracking so this
rule is only run on the built module).
- The Pester code coverage has been switched to use the older functionality
that uses breakpoints to calculate coverage. Newer functionality sometimes
throw an exception when used in conjunction with class-based resources.¨
- The SMO stubs (used in the unit tests) was updated to remove a bug related
to the type `DatabasePermissionInfo` when used with the type `DatabasePermissionSet`.
The stubs suggested that the property `PermissionType` (of type `DatabasePermissionSet`)
in `DatabasePermissionInfo` should have been a array `DatabasePermissionSet[]`.
This conflicted with real SMO as it does not pass an array, but instead
a single `DatabasePermissionSet`. The stubs was modified to mimic the
real SMO. At the same time some old mock code in the SMO stubs was removed
as it was no longer in use.
- Wiki
- add introduction and links to DSC technology
- SqlServerDsc.Common
- The parameter `SetupCredential` of the function `Connect-SQL` was renamed
to `Credential` and the parameter name `SetupCredential` was made a
parameter alias.
- SqlLogin
- BREAKING CHANGE: The parameters `LoginMustChangePassword`, `LoginPasswordExpirationEnabled`,
and `LoginPasswordPolicyEnforced` no longer have a default value of `$true`.
Expand Down Expand Up @@ -128,6 +179,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- BREAKING CHANGE: The parameter `IsHadrEnabled` is no longer returned by
`Get-TargetResource`. The `Ensure` parameter now returns `Present` if
Always On HADR is enabled and `Absent` if it is disabled.
- SqlDatabasePermission
- BREAKING CHANGE: The resource has been refactored. The parameters
`ParameterState` and `Permissions` has been replaced by parameters
`Permission`, `PermissionToInclude`, and `PermissionToExclude`. These
permissions parameters are now an instance of the type `DatabasePermission`.
The type `DatabasePermission` contains two properties; `State` and
`Permission`.
- The resource was refactored into a class-based resource.

### Fixed

Expand Down Expand Up @@ -203,6 +262,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
step for each iteration. A line of code was moved outside of the loop.
- The `SourcePath` parameter is now mandatory for all `*-TargetResource`
([issue #1755](https://github.com/dsccommunity/SqlServerDsc/issues/1755)).
- SqlDatabasePermission
- It is no longer possible to have one permission that has two different
states in the same configuration, e.g. denying and granting `update`
in the same configuration.

## [15.2.0] - 2021-09-01

Expand Down
102 changes: 101 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ class DSC_SqlConfiguration : OMI_BaseResource
### Composite or class-based resource

Any composite (with a Configuration) or class-based resources should be prefixed
with just 'Sql'
with 'Sql'

### Localization

Expand Down Expand Up @@ -277,3 +277,103 @@ SQL Server 2016, SQL Server 2017 and SQL Server 2019.

When sending in a Pull Request (PR) all example files will be tested so they can
be compiled to a .mof file. If the tests find any errors the build will fail.

### Class-based DSC resource

#### Terminating Error

A terminating error is an error that prevents the resource to continue further.
If a DSC resource shall throw an terminating error the commands of the module
**DscResource.Common** shall be used primarily; [`New-InvalidArgumentException`](https://github.com/dsccommunity/DscResource.Common#new-invalidargumentexception),
[`New-InvalidDataExcpetion`](https://github.com/dsccommunity/DscResource.Common#new-invaliddataexception),
[`New-InvalidOperationException`](https://github.com/dsccommunity/DscResource.Common#new-invalidoperationexception),
[`New-InvalidResultException`](https://github.com/dsccommunity/DscResource.Common#new-invalidresultexception),
or [`New-NotImplementedException`](https://github.com/dsccommunity/DscResource.Common#new-notimplementedexception).
If neither of those commands works in the scenarion then `throw` shall be used.

### Commands

Commands are publicly exported commands from the module, and the source for
commands are located in the folder `./source/Public`.

#### Non-Terminating Error

A non-terminating error should only be used when a command shall be able to
handle (ignoring) an error and continue processing and still give the user
an expected outcome.

With a non-terminating error the user is able to decide whether the command
should throw or continue processing on error. The user can pass the
parameter and value `-ErrorAction 'SilentlyContinue'` to the command to
ignore the error and allowing the command to continue, for example the
command could then return `$null`. But if the user passes the parameter
and value `-ErrorAction 'Stop'` the same error will throw a terminating
error telling the user the expected outcome could not be achieved.

The below example checks to see if a database exist, if it doesn't a
non-terminating error are called. The user is able to either ignore the
error or have it throw depending on what value the user specifies
in parameter `ErrorAction` (or `$ErrorActionPreference`).

```powershell
if (-not $databaseExist)
{
$errorMessage = $script:localizedData.MissingDatabase -f $DatabaseName

Write-Error -Message $errorMessage -Category 'InvalidOperation' -ErrorId 'GS0001' -TargetObject $DatabaseName
}
```

#### Terminating Error

A terminating error is an error that the user are not able to ignore by
passing a parameter to the command (like for non-terminating errors).

If a command shall throw an terminating error the statement `throw` shall
not be used, neither shall the command `Write-Error` be used with the parameter
`-ErrorAction `Stop``. Instead the method `$PSCmdlet.ThrowTerminatingError()`
shall be used to throw a terminating error.


>**NOTE:** Below output assumes `$ErrorView` is set to `'NormalView'` in the
>PowerShell session.

When using `throw` it will fail on the line with the throw statement
making it look like it is that statement inside the function that failed,
which is not correct since it is either a previous command or evaluation
that failed resulting in the line with the `throw` being called. This is
an example when using `throw`:

```plaintext
Exception:
Line |
2 | throw 'My error'
| ~~~~~~~~~~~~~~~~
| My error
```

When instead using `$PSCmdlet.ThrowTerminatingError()`:

```powershell
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
'MyError',
'GS0001',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
'MyObjectOrValue'
)
)
```

The result from `$PSCmdlet.ThrowTerminatingError()` shows that the command
failed (in this example `Get-Something`) and returns a clear category and
error code.

```plaintext
Get-Something : My Error
At line:1 char:1
+ Get-Something
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (MyObjectOrValue:String) [Get-Something], Exception
+ FullyQualifiedErrorId : GS0001,Get-Something
```
8 changes: 6 additions & 2 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ stages:
buildType: 'current'
artifactName: $(buildArtifactName)
targetPath: '$(Build.SourcesDirectory)/$(buildFolderName)'
- pwsh: |
# This task need to use Windows PowerShell due to a bug in PS7 that cannot
# find/use class-based DSC resources that uses inheritance, which result in
# the examples cannot compile. See the following issue for more information:
# https://github.com/dsccommunity/DnsServerDsc/issues/268#issuecomment-918505230
- powershell: |
# Workaround for issue https://github.com/dsccommunity/DscResource.Test/issues/100
./build.ps1 -Task noop

Expand All @@ -78,7 +82,7 @@ stages:
$pesterConfig.Output.Verbosity = 'Detailed'

Invoke-Pester -Configuration $pesterConfig
name: qualitytest
name: qualityTest
displayName: 'Run SqlServerDsc QA Test'
- task: PowerShell@2
name: test
Expand Down
7 changes: 6 additions & 1 deletion build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ CopyPaths:
- DSCResources
- en-US
- Modules
Prefix: prefix.ps1
Encoding: UTF8
VersionedOutputDirectory: true

Expand Down Expand Up @@ -88,7 +89,9 @@ Pester:
CoveragePercentTarget: 85
OutputPath: JaCoCo_coverage.xml
OutputEncoding: ascii
UseBreakpoints: false
# There is a bug in Pester when running unit tests for classes when 'UseBreakpoints' is turned off.
# See error in gist: https://gist.github.com/johlju/c16dfd9587c7e066e8825fc54b33a703
UseBreakpoints: true
TestResult:
OutputFormat: NUnitXML
OutputEncoding: ascii
Expand Down Expand Up @@ -116,6 +119,8 @@ DscTest:
- output
ExcludeModuleFile:
- Modules/DscResource.Common
# Must exclude built module file because it should not be tested like MOF-based resources
- SqlServerDsc.psm1
MainGitBranch: main

####################################################
Expand Down
Loading