Set-SqlDscDatabaseProperty: Refactor command#2327
Conversation
WalkthroughSplit Set‑SqlDscDatabase into Set‑SqlDscDatabaseProperty (per‑property SMO Database setters) and Set‑SqlDscDatabaseOwner (owner changes via SMO.SetOwner()); add Get‑SqlDscCompatibilityLevel; add CatalogCollation to New‑SqlDscDatabase; update localization, tests, SMO stubs, and CI. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant Set-SqlDscDatabaseProperty
participant Get-SqlDscDatabase
participant SMO_Database
rect #f3f4f6
Caller->>Set-SqlDscDatabaseProperty: Invoke(ServerObject/Name or DatabaseObject + properties)
end
Set-SqlDscDatabaseProperty->>Set-SqlDscDatabaseProperty: Validate CompatibilityLevel / Collation
alt ServerObjectSet
Set-SqlDscDatabaseProperty->>Get-SqlDscDatabase: Resolve target database (Refresh optional)
Get-SqlDscDatabase-->>Set-SqlDscDatabaseProperty: SMO.Database
else DatabaseObjectSet
Note right of Set-SqlDscDatabaseProperty: Use provided DatabaseObject
end
loop For each bound property
Set-SqlDscDatabaseProperty->>SMO_Database: Check property & compare current value
alt value differs
Set-SqlDscDatabaseProperty->>SMO_Database: Set property
else
Note right of Set-SqlDscDatabaseProperty: Skip (already set)
end
end
alt any changed
Set-SqlDscDatabaseProperty->>SMO_Database: Alter()
SMO_Database-->>Set-SqlDscDatabaseProperty: Success/Error
Set-SqlDscDatabaseProperty->>Caller: Return object if PassThru
else
Set-SqlDscDatabaseProperty->>Caller: Verbose "No properties changed"
end
sequenceDiagram
participant Caller
participant Set-SqlDscDatabaseOwner
participant Get-SqlDscDatabase
participant SMO_Database
Caller->>Set-SqlDscDatabaseOwner: Invoke(ServerObject/Name or DatabaseObject + OwnerName)
Set-SqlDscDatabaseOwner->>Set-SqlDscDatabaseOwner: ShouldProcess / Force handling
alt ServerObjectSet
Set-SqlDscDatabaseOwner->>Get-SqlDscDatabase: Get database by name (Refresh optional)
Get-SqlDscDatabase-->>Set-SqlDscDatabaseOwner: SMO.Database
else DatabaseObjectSet
Note right of Set-SqlDscDatabaseOwner: Use provided DatabaseObject
end
Set-SqlDscDatabaseOwner->>SMO_Database: Call SetOwner(OwnerName) (optionally DropExistingUser)
SMO_Database-->>Set-SqlDscDatabaseOwner: Success/Error
Set-SqlDscDatabaseOwner->>Caller: Return object if PassThru / emit error
sequenceDiagram
participant Caller
participant Get-SqlDscCompatibilityLevel
participant SMO_CompatibilityLevel
Caller->>Get-SqlDscCompatibilityLevel: Invoke(ServerObject or Version)
Get-SqlDscCompatibilityLevel->>Get-SqlDscCompatibilityLevel: Determine major version
Get-SqlDscCompatibilityLevel->>SMO_CompatibilityLevel: Get enum names
Get-SqlDscCompatibilityLevel->>Get-SqlDscCompatibilityLevel: Filter supported range
alt expected max missing
Get-SqlDscCompatibilityLevel->>Caller: Emit warning (SMO older)
end
Get-SqlDscCompatibilityLevel->>Caller: Return string[] of levels
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Areas to focus review on:
Possibly related issues
Possibly related PRs
Pre-merge checks❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (3)**/*.md📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-markdown.instructions.md)
Files:
⚙️ CodeRabbit configuration file
Files:
**⚙️ CodeRabbit configuration file
Files:
azure-pipelines.yml📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Files:
🧠 Learnings (19)📓 Common learnings📚 Learning: 2025-09-16T16:35:31.909ZApplied to files:
📚 Learning: 2025-09-16T16:35:31.909ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.397ZApplied to files:
📚 Learning: 2025-10-12T11:23:30.123ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-12T11:23:30.123ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-26T13:27:07.728ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.397ZApplied to files:
📚 Learning: 2025-10-12T11:23:30.123ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.396ZApplied to files:
📚 Learning: 2025-10-26T13:26:13.397ZApplied to files:
📚 Learning: 2025-10-26T13:27:07.728ZApplied to files:
📚 Learning: 2025-10-12T11:23:30.123ZApplied to files:
📚 Learning: 2025-09-16T16:35:31.909ZApplied to files:
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
🔇 Additional comments (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1 (1)
75-77: Add -ErrorAction 'Stop' on all Get-SqlDscDatabase verification reads.Consistency with integration guidelines; ensures immediate failure visibility.
Apply this diff:
- $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop'Also applies to: 83-85, 91-93, 101-104, 113-115, 138-141
source/Public/Set-SqlDscDatabase.ps1 (3)
663-691: CompatibilityLevel validation breaks with DatabaseObjectSet parameter set.The validation at line 678 references
$ServerObject.VersionMajor, but$ServerObjectis only available in theServerObjectSetparameter set. When usingDatabaseObjectSet, this will cause an error or incorrect validation.Apply this diff to handle both parameter sets:
# Validate compatibility level if specified if ($PSBoundParameters.ContainsKey('CompatibilityLevel')) { + # Get the server object based on parameter set + $serverInstance = if ($PSCmdlet.ParameterSetName -eq 'DatabaseObjectSet') + { + $DatabaseObject.Parent + } + else + { + $ServerObject + } + $supportedCompatibilityLevels = @{ 8 = @('Version80') 9 = @('Version80', 'Version90') 10 = @('Version80', 'Version90', 'Version100') 11 = @('Version90', 'Version100', 'Version110') 12 = @('Version100', 'Version110', 'Version120') 13 = @('Version100', 'Version110', 'Version120', 'Version130') 14 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140') 15 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140', 'Version150') 16 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140', 'Version150', 'Version160') } - if ($CompatibilityLevel -notin $supportedCompatibilityLevels.$($ServerObject.VersionMajor)) + if ($CompatibilityLevel -notin $supportedCompatibilityLevels.$($serverInstance.VersionMajor)) { - $errorMessage = $script:localizedData.Set_SqlDscDatabase_InvalidCompatibilityLevel -f $CompatibilityLevel, $ServerObject.InstanceName + $errorMessage = $script:localizedData.Set_SqlDscDatabase_InvalidCompatibilityLevel -f $CompatibilityLevel, $serverInstance.InstanceName $PSCmdlet.ThrowTerminatingError(
693-709: Collation validation breaks with DatabaseObjectSet parameter set.The validation at line 696 references
$ServerObject.EnumCollations()and$ServerObject.InstanceName, but$ServerObjectis only available in theServerObjectSetparameter set.Apply this diff to handle both parameter sets:
# Validate collation if specified if ($PSBoundParameters.ContainsKey('Collation')) { - if ($Collation -notin $ServerObject.EnumCollations().Name) + # Get the server object based on parameter set + $serverInstance = if ($PSCmdlet.ParameterSetName -eq 'DatabaseObjectSet') + { + $DatabaseObject.Parent + } + else + { + $ServerObject + } + + if ($Collation -notin $serverInstance.EnumCollations().Name) { - $errorMessage = $script:localizedData.Set_SqlDscDatabase_InvalidCollation -f $Collation, $ServerObject.InstanceName + $errorMessage = $script:localizedData.Set_SqlDscDatabase_InvalidCollation -f $Collation, $serverInstance.InstanceName $PSCmdlet.ThrowTerminatingError(
1-816: Overall assessment: Generic property-setting implementation is solid but has critical parameter set bugs.The refactored implementation successfully moves from hard-coded property handling to a generic, loop-based approach that scales to 85+ properties. The core logic is sound: validate properties, compare values, update only what changed, and call Alter() once.
However, three critical bugs prevent this from working correctly with the
DatabaseObjectSetparameter set, where validation and error handling reference unavailable variables ($ServerObject,$Name,$DatabaseObject). These must be fixed before the code will function correctly.The CatalogCollation parameter also requires attention per the PR objectives to document or prevent its misuse on existing databases.
🧹 Nitpick comments (6)
CHANGELOG.md (2)
13-15: Add explicit issue reference and brief cross-link.Append “[issue #2177]” to both the OwnerName removal and the new Set-SqlDscDatabaseOwner bullets for traceability, and add a final sentence on the new bullet that this replaces ownership changes previously done via Set-SqlDscDatabase.
Also applies to: 19-22
230-249: Call out exclusions and versioning caveats for property coverage.Explicitly note that Set-SqlDscDatabase excludes properties only settable at creation (e.g., CatalogCollation) and properties requiring SMO methods (default filegroup/FT catalog/FILESTREAM), and that these are handled by dedicated commands. This aligns release notes with behavior and avoids ambiguity for callers.
Would you also confirm the dynamic parameter surface does not expose those excluded properties and add a short note here?
source/Public/Set-SqlDscDatabaseOwner.ps1 (1)
135-149: Add idempotence + standardized error handling around SetOwner().
- Skip work when the current owner already equals OwnerName.
- Wrap SetOwner() in try/catch and use $PSCmdlet.ThrowTerminatingError() with a localized message.
Apply this diff:
@@ - if ($PSCmdlet.ShouldProcess($verboseDescriptionMessage, $verboseWarningMessage, $captionMessage)) - { - Write-Debug -Message ($script:localizedData.DatabaseOwner_Updating -f $sqlDatabaseObject.Name, $OwnerName) - $sqlDatabaseObject.SetOwner($OwnerName) - Write-Debug -Message ($script:localizedData.DatabaseOwner_Updated -f $sqlDatabaseObject.Name, $OwnerName) - - if ($PassThru.IsPresent) - { - return $sqlDatabaseObject - } - } + # Early exit if already correct + if ($sqlDatabaseObject.Owner -eq $OwnerName) + { + Write-Verbose -Message ($script:localizedData.DatabaseOwner_AlreadyOwner -f $sqlDatabaseObject.Name, $OwnerName) + + if ($PassThru.IsPresent) { return $sqlDatabaseObject } + return + } + + if ($PSCmdlet.ShouldProcess($verboseDescriptionMessage, $verboseWarningMessage, $captionMessage)) + { + Write-Debug -Message ($script:localizedData.DatabaseOwner_Updating -f $sqlDatabaseObject.Name, $OwnerName) + try + { + $sqlDatabaseObject.SetOwner($OwnerName) + } + catch + { + $errorRecord = [System.Management.Automation.ErrorRecord]::new( + $_.Exception, + 'SSDDBO0001', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $sqlDatabaseObject + ) + $errorRecord.ErrorDetails = [System.Management.Automation.ErrorDetails]::new( + ($script:localizedData.DatabaseOwner_Set_Failed -f $sqlDatabaseObject.Name, $OwnerName, $_.Exception.Message) + ) + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + Write-Debug -Message ($script:localizedData.DatabaseOwner_Updated -f $sqlDatabaseObject.Name, $OwnerName) + + if ($PassThru.IsPresent) { return $sqlDatabaseObject } + }source/en-US/SqlServerDsc.strings.psd1 (1)
380-386: Add owner idempotence and failure strings to back the cmdlet changes.Please add:
@@ DatabaseOwner_Updating = Setting owner of database '{0}' to '{1}'. DatabaseOwner_Updated = Owner of database '{0}' was set to '{1}'. + DatabaseOwner_AlreadyOwner = Owner of database '{0}' is already '{1}'. (SSDDBO0002) + DatabaseOwner_Set_Failed = Failed to set owner of database '{0}' to '{1}'. {2} (SSDDBO0001) DatabaseOwner_Set_ShouldProcessVerboseDescription = Setting the owner of the database '{0}' to '{1}' on the instance '{2}'. DatabaseOwner_Set_ShouldProcessVerboseWarning = Are you sure you want to change the owner of the database '{0}' to '{1}'? # This string shall not end with full stop (.) since it is used as a title of ShouldProcess messages. DatabaseOwner_Set_ShouldProcessCaption = Set database owner on instanceThis enables clean idempotent messaging and standardized terminating error details.
source/Public/Set-SqlDscDatabase.ps1 (2)
299-301: Refactor OUTPUTS section to list each return type separately.The OUTPUTS section should list each return type with its own
.OUTPUTSkeyword and one-line description. The current format combines both cases into a single entry.Apply this diff:
- .OUTPUTS - None. But when **PassThru** is specified the output is `[Microsoft.SqlServer.Management.Smo.Database]`. + .OUTPUTS + None. + + When PassThru is not specified, no output is returned. + + .OUTPUTS + Microsoft.SqlServer.Management.Smo.Database + + When PassThru is specified, returns the updated database object.
756-779: Consider validating all properties before attempting updates.The current implementation updates properties one-by-one in a loop, calling
Write-Errorwithcontinuefor invalid properties. This allows some properties to be set while others fail, which could leave the database in a partially updated state.Consider validating all properties first, before making any changes:
$wasUpdated = $false + $invalidProperties = @() - # Set each specified property + # Validate all properties exist before attempting updates foreach ($parameterName in $boundParameters.Keys) { - # Check if property exists on the database object if ($sqlDatabaseObject.PSObject.Properties.Name -notcontains $parameterName) { - Write-Error -Message ($script:localizedData.DatabaseProperty_PropertyNotFound -f $parameterName, $sqlDatabaseObject.Name) -Category 'InvalidArgument' -ErrorId 'SSDD0001' -TargetObject $parameterName - continue + $invalidProperties += $parameterName + } + } + + # If any invalid properties found, error and return + if ($invalidProperties.Count -gt 0) + { + $errorMessage = $script:localizedData.DatabaseProperty_InvalidProperties -f ($invalidProperties -join ', '), $sqlDatabaseObject.Name + Write-Error -Message $errorMessage -Category 'InvalidArgument' -ErrorId 'SSDD0001' -TargetObject $invalidProperties + return + } + + # Set each specified property + foreach ($parameterName in $boundParameters.Keys) + { $currentValue = $sqlDatabaseObject.$parameterName $newValue = $boundParameters.$parameterName # Only update if the value is different if ($currentValue -ne $newValue) { Write-Debug -Message ($script:localizedData.Database_UpdatingProperty -f $parameterName, $newValue) $sqlDatabaseObject.$parameterName = $newValue $wasUpdated = $true } else { Write-Debug -Message ($script:localizedData.Database_PropertyAlreadySet -f $parameterName, $currentValue) } }This ensures atomicity: either all properties are valid and the update proceeds, or the function returns an error without modifying anything.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
CHANGELOG.md(2 hunks)source/Public/Set-SqlDscDatabase.ps1(4 hunks)source/Public/Set-SqlDscDatabaseOwner.ps1(1 hunks)source/en-US/SqlServerDsc.strings.psd1(1 hunks)tests/Integration/Commands/README.md(1 hunks)tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1(2 hunks)tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1(1 hunks)tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1(6 hunks)tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (20)
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/en-US/SqlServerDsc.strings.psd1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/README.mdtests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1CHANGELOG.mdsource/en-US/SqlServerDsc.strings.psd1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/en-US/SqlServerDsc.strings.psd1source/Public/Set-SqlDscDatabase.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1source/Public/Set-SqlDscDatabase.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1source/Public/Set-SqlDscDatabase.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1source/Public/Set-SqlDscDatabase.ps1
**/*.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-markdown.instructions.md)
**/*.md: Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
Use 2 spaces for indentation in Markdown documents
Use '1.' for all items in ordered lists (1/1/1 numbering style)
Disable MD013 for tables/code blocks exceeding 80 characters via an inline comment
Require empty lines before and after code blocks and headings (except before line 1)
Escape backslashes in file paths only, not inside code blocks
All fenced code blocks must specify a language identifier
Format parameter names as bold
Format values/literals as inline code
Format resource/module/product names as italic
Format commands, file names, and paths as inline code
Files:
tests/Integration/Commands/README.mdCHANGELOG.md
⚙️ CodeRabbit configuration file
**/*.md: # Markdown Style Guidelines
- Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
- Use 2 spaces for indentation
- Use '1.' for all items in ordered lists (1/1/1 numbering style)
- Disable
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
tests/Integration/Commands/README.mdCHANGELOG.md
tests/Integration/Commands/*.Integration.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
tests/Integration/Commands/*.Integration.Tests.ps1: Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Add integration tests for all public commands (and resources)Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md)
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Cover all scenarios and code paths in integration tests
Use Get-ComputerName to determine computer names in CI
Avoid using -ExpectedMessage with Should -Throw assertions
Call commands with -Force where applicable to avoid prompting
Use -ErrorAction 'Stop' on commands so failures surface immediately
Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests GuidelinesRequirements
- Location Commands:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1- Location Resources:
tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1- No mocking - real environment only
- Cover all scenarios and code paths
- Use
Get-ComputerNamefor computer names in CI- Avoid
ExpectedMessageforShould -Throwassertions- Only run integration tests in CI unless explicitly instructed.
- Call commands with
-Forceparameter where applicable (avoids prompting).- Use
-ErrorAction 'Stop'on commands so failures surface immediatelyRequired Setup Block
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' }
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Integration/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Integration/**/*.Tests.ps1: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
CHANGELOG.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-changelog.instructions.md)
CHANGELOG.md: Always update the Unreleased section in CHANGELOG.md
Use Keep a Changelog format
Describe notable changes briefly, with no more than 2 items per change type
Reference issues using the format issue #<issue_number>
No empty lines between list items in the same section
Skip adding an entry if the same change already exists in the Unreleased section
No duplicate sections or items in the Unreleased sectionAlways update the Unreleased section of CHANGELOG.md
Files:
CHANGELOG.md
⚙️ CodeRabbit configuration file
CHANGELOG.md: # Changelog Guidelines
- Always update the Unreleased section in CHANGELOG.md
- Use Keep a Changelog format
- Describe notable changes briefly, ≤2 items per change type
- Reference issues using format issue #<issue_number>
- No empty lines between list items in same section
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
source/en-US/*.strings.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/en-US/*.strings.psd1: Store command/function localization in source/en-US/{MyModuleName}.strings.psd1
Store class localization in source/en-US/{ResourceClassName}.strings.psd1
Name localization keys as Verb_FunctionName_Action using underscores (e.g., Get_Database_ConnectingToDatabase)
Define strings using ConvertFrom-StringData with entries likeKeyName = Message with {0} placeholder. (PREFIX0001)
Include string IDs in the form (PREFIX####), where PREFIX is initials from the class/function name and numbers are sequential from 0001
Files:
source/en-US/SqlServerDsc.strings.psd1
**/*.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
In module manifests, do not use NestedModules for shared commands without RootModule
Files:
source/en-US/SqlServerDsc.strings.psd1
🧠 Learnings (9)
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Applied to files:
tests/Integration/Commands/README.mdtests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
🔇 Additional comments (5)
tests/Integration/Commands/README.md (1)
95-95: Row addition looks correct in run-order table.Run order, dependencies, and instance match surrounding entries. No issues.
source/Public/Set-SqlDscDatabaseOwner.ps1 (2)
105-111: Force pattern OK.Force/ConfirmPreference pattern matches guidelines.
116-133: Server/database object retrieval looks good.Scoped -ErrorAction 'Stop' and restoration are correct.
source/en-US/SqlServerDsc.strings.psd1 (1)
370-379: Generic database property update strings look good.These support the refactor and idempotence messages.
source/Public/Set-SqlDscDatabase.ps1 (1)
541-542: CatalogCollation parameter should be creation-only or explicitly rejected.
CatalogCollationis accepted in Set-SqlDscDatabase but is absent from New-SqlDscDatabase, suggesting it's a creation-only property that cannot be modified on existing databases. The parameter is currently passed directly to SMO's Alter() method without validation or warning. When SMO attempts to modify it on an existing database, the behavior is undefined (may fail silently, throw an error, or be ignored).No validation or filtering exists to prevent this attempt. Recommend either removing the parameter from Set-SqlDscDatabase or adding explicit validation to reject/warn users about this constraint.
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
Outdated
Show resolved
Hide resolved
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
Outdated
Show resolved
Hide resolved
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2327 +/- ##
====================================
- Coverage 94% 94% -1%
====================================
Files 152 154 +2
Lines 9277 9326 +49
====================================
+ Hits 8790 8834 +44
- Misses 487 492 +5
🚀 New features to boost your workflow:
|
…improved error handling
…nly properties in Set-SqlDscDatabase
…ition of Set-SqlDscDatabaseOwner command
…ling; update localized strings for new messages
…r PassThru parameter
…ct properties for error messages
…for broader support
…atibility levels based on SQL Server version
…ould -BeTrue and Should -BeFalse for clarity
…meter validation checks for ServerObjectSet and DatabaseObjectSet
…correct parameter sets and mandatory parameters
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/Unit/Stubs/SMO.cs (1)
455-485: Preserve VersionMajor in Server.Clone()Clone omits VersionMajor, losing version context in copied instances. Copy it.
public Server Clone() { return new Server() { AvailabilityGroups = this.AvailabilityGroups, ConnectionContext = this.ConnectionContext, ComputerNamePhysicalNetBIOS = this.ComputerNamePhysicalNetBIOS, Databases = this.Databases, DisplayName = this.DisplayName, DomainInstanceName = this.DomainInstanceName, Endpoints = this.Endpoints, FilestreamLevel = this.FilestreamLevel, InstanceName = this.InstanceName, IsClustered = this.IsClustered, IsHadrEnabled = this.IsHadrEnabled, Logins = this.Logins, Name = this.Name, NetName = this.NetName, Roles = this.Roles, ServiceName = this.ServiceName, - Version = this.Version + Version = this.Version, + VersionMajor = this.VersionMajor }; }
♻️ Duplicate comments (1)
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1 (1)
255-284: Idempotence tests still rely on Alter() throwing rather than explicit assertion.As noted in the previous review, tests should explicitly track whether Alter() was invoked and assert it was not called, rather than relying on Should -Not -Throw (which hides the verification). The mock at line 273 throws, but the tests at lines 277-279 and 282-283 don't explicitly verify the call didn't happen.
Refer to the previous review comment for the suggested fix using a flag to track Alter() invocations.
🧹 Nitpick comments (7)
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1 (2)
42-43: Add -ErrorAction 'Stop' to Connect callEnsure connection failures surface immediately in CI.
- $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential + $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential -ErrorAction 'Stop'Based on learnings.
71-71: Add -ErrorAction 'Stop' on DisconnectKeep error handling consistent for teardown.
- Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject + Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop'Based on learnings.
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1 (3)
79-86: Select CompatibilityLevel dynamically (future-proof, exercises mapping)Compute the highest supported level for the target server instead of hard-coding 140.
- It 'Should set compatibility level successfully' { - # Use Version140 which is supported on all tested versions (SQL 2017+) - $null = Set-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -CompatibilityLevel 'Version140' -Force -ErrorAction 'Stop' - - # Verify the change - $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' - $updatedDb.CompatibilityLevel | Should -Be 'Version140' - } + It 'Should set compatibility level successfully' { + $targetLevel = Get-SqlDscCompatibilityLevel -ServerObject $script:serverObject -ErrorAction 'Stop' | + Sort-Object { [int]($_ -replace '^Version','') } | + Select-Object -Last 1 + + $null = Set-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -CompatibilityLevel $targetLevel -Force -ErrorAction 'Stop' + + $updatedDb = Get-SqlDscDatabase -ServerObject $script:serverObject -Name $script:testDatabaseName -ErrorAction 'Stop' + $updatedDb.CompatibilityLevel | Should -Be $targetLevel + }Based on learnings.
42-43: Add -ErrorAction 'Stop' to ConnectSurface connection failures early.
- $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential + $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential -ErrorAction 'Stop'Based on learnings.
67-67: Add -ErrorAction 'Stop' to DisconnectConsistent teardown error handling.
- Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject + Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop'Based on learnings.
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1 (1)
43-44: Add -ErrorAction 'Stop' to ConnectFollow integration guideline to surface failures immediately.
- $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential + $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential -ErrorAction 'Stop'Based on learnings.
tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1 (1)
1-1: Add Justification text to SuppressMessage (match required unit test setup)Align with the standard setup block used across the repo.
-[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]Based on learnings.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
CHANGELOG.md(2 hunks)source/Public/Get-SqlDscCompatibilityLevel.ps1(1 hunks)source/Public/Set-SqlDscDatabase.ps1(4 hunks)source/Public/Set-SqlDscDatabaseOwner.ps1(1 hunks)source/en-US/SqlServerDsc.strings.psd1(1 hunks)tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1(1 hunks)tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1(2 hunks)tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1(1 hunks)tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1(1 hunks)tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1(8 hunks)tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1(1 hunks)tests/Unit/Stubs/SMO.cs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (21)
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1tests/Unit/Stubs/SMO.cssource/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/en-US/SqlServerDsc.strings.psd1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/en-US/SqlServerDsc.strings.psd1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1tests/Unit/Stubs/SMO.cssource/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1CHANGELOG.md
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1source/en-US/SqlServerDsc.strings.psd1tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1source/Public/Get-SqlDscCompatibilityLevel.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/Integration/Commands/*.Integration.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
tests/Integration/Commands/*.Integration.Tests.ps1: Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Add integration tests for all public commands (and resources)Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md)
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Cover all scenarios and code paths in integration tests
Use Get-ComputerName to determine computer names in CI
Avoid using -ExpectedMessage with Should -Throw assertions
Call commands with -Force where applicable to avoid prompting
Use -ErrorAction 'Stop' on commands so failures surface immediately
Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests GuidelinesRequirements
- Location Commands:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1- Location Resources:
tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1- No mocking - real environment only
- Cover all scenarios and code paths
- Use
Get-ComputerNamefor computer names in CI- Avoid
ExpectedMessageforShould -Throwassertions- Only run integration tests in CI unless explicitly instructed.
- Call commands with
-Forceparameter where applicable (avoids prompting).- Use
-ErrorAction 'Stop'on commands so failures surface immediatelyRequired Setup Block
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' }
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Integration/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Integration/**/*.Tests.ps1: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
source/en-US/*.strings.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/en-US/*.strings.psd1: Store command/function localization in source/en-US/{MyModuleName}.strings.psd1
Store class localization in source/en-US/{ResourceClassName}.strings.psd1
Name localization keys as Verb_FunctionName_Action using underscores (e.g., Get_Database_ConnectingToDatabase)
Define strings using ConvertFrom-StringData with entries likeKeyName = Message with {0} placeholder. (PREFIX0001)
Include string IDs in the form (PREFIX####), where PREFIX is initials from the class/function name and numbers are sequential from 0001
Files:
source/en-US/SqlServerDsc.strings.psd1
**/*.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
In module manifests, do not use NestedModules for shared commands without RootModule
Files:
source/en-US/SqlServerDsc.strings.psd1
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Get-SqlDscCompatibilityLevel.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Get-SqlDscCompatibilityLevel.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Get-SqlDscCompatibilityLevel.ps1source/Public/Set-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.cs
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.cs: Database Engine resource classes must inherit SqlResourceBase
In Database Engine resources, add InstanceName, ServerName, and Credential to $this.ExcludeDscProperties
Database Engine resource constructors should be MyResourceName() : base () { } (no $PSScriptRoot parameter)
Files:
tests/Unit/Stubs/SMO.cs
**/*.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-markdown.instructions.md)
**/*.md: Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
Use 2 spaces for indentation in Markdown documents
Use '1.' for all items in ordered lists (1/1/1 numbering style)
Disable MD013 for tables/code blocks exceeding 80 characters via an inline comment
Require empty lines before and after code blocks and headings (except before line 1)
Escape backslashes in file paths only, not inside code blocks
All fenced code blocks must specify a language identifier
Format parameter names as bold
Format values/literals as inline code
Format resource/module/product names as italic
Format commands, file names, and paths as inline code
Files:
CHANGELOG.md
⚙️ CodeRabbit configuration file
**/*.md: # Markdown Style Guidelines
- Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
- Use 2 spaces for indentation
- Use '1.' for all items in ordered lists (1/1/1 numbering style)
- Disable
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
CHANGELOG.md
CHANGELOG.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-changelog.instructions.md)
CHANGELOG.md: Always update the Unreleased section in CHANGELOG.md
Use Keep a Changelog format
Describe notable changes briefly, with no more than 2 items per change type
Reference issues using the format issue #<issue_number>
No empty lines between list items in the same section
Skip adding an entry if the same change already exists in the Unreleased section
No duplicate sections or items in the Unreleased sectionAlways update the Unreleased section of CHANGELOG.md
Files:
CHANGELOG.md
⚙️ CodeRabbit configuration file
CHANGELOG.md: # Changelog Guidelines
- Always update the Unreleased section in CHANGELOG.md
- Use Keep a Changelog format
- Describe notable changes briefly, ≤2 items per change type
- Reference issues using format issue #<issue_number>
- No empty lines between list items in same section
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
🧠 Learnings (18)
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use Assert-MockCalled; use Should -Invoke instead
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : All public commands must include parameter set validation tests
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Applied to files:
tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
PR: dsccommunity/ActiveDirectoryDsc#741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: The PowerShell guideline "Use -BeTrue/-BeFalse; never use -Be $true/-Be $false" applies only when the actual return value is a boolean. When a cmdlet returns string values like 'True' or 'False', Should -Be 'True' is the appropriate assertion.
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
PR: dsccommunity/ActiveDirectoryDsc#741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: Test-DscConfiguration cmdlet returns string values 'True' or 'False', not boolean values. Therefore, Should -Be 'True' is correct, and Should -BeTrue would be incorrect for this cmdlet.
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Applied to files:
tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)
Applied to files:
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests
Applied to files:
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction 'Stop' on commands so failures surface immediately
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Set $ErrorActionPreference = 'Stop' before commands using -ErrorAction 'Stop'; restore previous value after (no try-catch-finally)
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Stubs/SMO.cs : Ensure SMO stub types are correctly implemented in tests/Stubs/SMO.cs for any used [Microsoft.SqlServer.Management.Smo.*] types
Applied to files:
tests/Unit/Stubs/SMO.cs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
🔇 Additional comments (4)
CHANGELOG.md (2)
13-15: LGTM: clear breaking-change note and redirection to new command.Removal is called out and linked to the owning issue; no further tweaks needed.
19-23: LGTM: Added owner command entry reads well.Accurately states SetOwner() usage and parameter sets; consistent with the removal note.
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1 (1)
70-88: Fix type assertion for string arrays$result is an array; Use -All -BeOfType or assert per element.
- $result | Should -BeOfType [System.String] + $result | Should -All -BeOfType [System.String]Repeat similarly at Lines 95-97.
- $result | Should -BeOfType [System.String] + $result | Should -All -BeOfType [System.String]Based on learnings.
⛔ Skipped due to learnings
Learnt from: johlju PR: dsccommunity/SqlServerDsc#2134 File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:178-185 Timestamp: 2025-08-15T05:37:29.255Z Learning: In PowerShell Pester tests, when piping an array to `Should -BeOfType`, PowerShell's pipeline automatically unrolls the array and checks the type of each individual element, not the array type itself. This means `$result | Should -BeOfType 'SomeType'` for an array will validate every element's type without needing the `-All` modifier.tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1 (1)
314-365: Parameter set validation tests successfully added.The required parameter set validation tests are now present for both
ServerObjectSetandDatabaseObjectSet, following the template from coding guidelines. The tests at lines 348-365 provide additional coverage for specific parameter presence/absence verification.This resolves the previous review comment requesting parameter set validation.
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
Outdated
Show resolved
Hide resolved
tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
Show resolved
Hide resolved
… of minimum compatibility level logic
…ilityLevel function
…scCompatibilityLevel tests
…erties as parameters, enhancing flexibility and usability.
…hanced versioning support
…r improved error handling
…ect-SqlDscDatabaseEngine for improved error handling
…DatabaseOwner to return the updated database object
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1 (1)
12-32: Setup/bootstrap path and noop fallback: resolved.Correct relative path and noop task guidance. Thanks for fixing.
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1 (1)
81-82: Verification reads now use -ErrorAction 'Stop'.Good hardening; avoids hidden failures in CI.
Also applies to: 90-91, 104-105, 121-122, 132-133, 143-144
🧹 Nitpick comments (4)
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1 (2)
362-377: Duplicate “When database does not exist” context.This scenario is already covered earlier (lines 291–306). Remove one to shorten runtime.
414-427: Add explicit mandatory-property checks for ServerObject and DatabaseObject.Nice to also assert Mandatory on set-specific parameters.
Apply:
+ It 'Should have ServerObject as a mandatory parameter in ServerObjectSet' { + $param = (Get-Command -Name 'Set-SqlDscDatabaseOwner').Parameters['ServerObject'] + ($param.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] -and $_.ParameterSetName -eq 'ServerObjectSet' }).Mandatory | Should -BeTrue + } + + It 'Should have DatabaseObject as a mandatory parameter in DatabaseObjectSet' { + $param = (Get-Command -Name 'Set-SqlDscDatabaseOwner').Parameters['DatabaseObject'] + ($param.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] -and $_.ParameterSetName -eq 'DatabaseObjectSet' }).Mandatory | Should -BeTrue + }source/Public/Set-SqlDscDatabaseOwner.ps1 (2)
136-143: Pass -Refresh only when explicitly requested.Avoid passing a false switch down; splat only when present for exact semantics.
Apply:
- $previousErrorActionPreference = $ErrorActionPreference - $ErrorActionPreference = 'Stop' - - $sqlDatabaseObject = $ServerObject | - Get-SqlDscDatabase -Name $Name -Refresh:$Refresh -ErrorAction 'Stop' - - $ErrorActionPreference = $previousErrorActionPreference + $previousErrorActionPreference = $ErrorActionPreference + $ErrorActionPreference = 'Stop' + + $getParams = @{ + Name = $Name + ErrorAction = 'Stop' + } + if ($PSBoundParameters.ContainsKey('Refresh')) { $getParams['Refresh'] = $true } + + $sqlDatabaseObject = $ServerObject | Get-SqlDscDatabase @getParams + + $ErrorActionPreference = $previousErrorActionPreference
155-210: Refresh on idempotent path when returning/pipeline object.For symmetry, refresh the object even when no change was needed if it will be returned or the caller passed an object.
Apply:
if ($sqlDatabaseObject.Owner -eq $OwnerName) { - Write-Debug -Message ($script:localizedData.DatabaseOwner_OwnerAlreadyCorrect -f $sqlDatabaseObject.Name, $OwnerName) + Write-Debug -Message ($script:localizedData.DatabaseOwner_OwnerAlreadyCorrect -f $sqlDatabaseObject.Name, $OwnerName) + if ($PassThru.IsPresent -or $PSCmdlet.ParameterSetName -eq 'DatabaseObjectSet') + { + $sqlDatabaseObject.Refresh() + } } else
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
source/Public/Get-SqlDscDatabase.ps1(1 hunks)source/Public/Set-SqlDscDatabaseOwner.ps1(1 hunks)tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1(2 hunks)tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Get-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Get-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Get-SqlDscDatabase.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
source/Public/Get-SqlDscDatabase.ps1tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
tests/Integration/Commands/*.Integration.Tests.ps1: Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Add integration tests for all public commands (and resources)Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md)
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Cover all scenarios and code paths in integration tests
Use Get-ComputerName to determine computer names in CI
Avoid using -ExpectedMessage with Should -Throw assertions
Call commands with -Force where applicable to avoid prompting
Use -ErrorAction 'Stop' on commands so failures surface immediately
Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests GuidelinesRequirements
- Location Commands:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1- Location Resources:
tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1- No mocking - real environment only
- Cover all scenarios and code paths
- Use
Get-ComputerNamefor computer names in CI- Avoid
ExpectedMessageforShould -Throwassertions- Only run integration tests in CI unless explicitly instructed.
- Call commands with
-Forceparameter where applicable (avoids prompting).- Use
-ErrorAction 'Stop'on commands so failures surface immediatelyRequired Setup Block
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' }
Files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
tests/Integration/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Integration/**/*.Tests.ps1: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
🧠 Learnings (8)
📚 Learning: 2025-10-11T08:18:26.062Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:18:26.062Z
Learning: In unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), when DscResource.Test module dependency is not found during BeforeDiscovery setup, the error message should instruct users to run ".\build.ps1 -Tasks noop" (not "build") because the noop task is designed for quick test environment setup. The build task is more extensive and unnecessary when tests run in a separate process, as the module should already be built before running tests.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : All public commands must include parameter set validation tests
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-10-11T08:35:56.141Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:35:56.141Z
Learning: In DSC Community projects, when writing error messages for missing DscResource.Test module dependency in unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), the policy is: new code should instruct users to run ".\build.ps1 -Tasks noop" for quick test environment setup; existing code using ".\build.ps1 -Tasks build" is acceptable but slower since it also builds the project. The `noop` task is preferred as it assumes the module is already built before running tests, especially when tests run in a separate process.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction 'Stop' on commands so failures surface immediately
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Set $ErrorActionPreference = 'Stop' before commands using -ErrorAction 'Stop'; restore previous value after (no try-catch-finally)
Applied to files:
tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
🔇 Additional comments (5)
source/Public/Get-SqlDscDatabase.ps1 (1)
91-96: Per-database Refresh: good addition for fresh state.LGTM. This keeps object state current when a single DB is targeted with -Refresh. Please keep an eye on perf on very large instances (collection + object refresh); if it shows up, consider making the per-db Refresh conditional on a future -DeepRefresh switch.
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1 (2)
220-232: Idempotence verified (no SetOwner/Alter when owner matches).Solid coverage; this guards against unnecessary server calls.
379-412: Parameter set validation tests are accurate and match source code exactly.The tests correctly validate both parameter sets:
- ServerObjectSet: Properly includes
ServerObjectandNameas mandatory parameters, withRefreshas an optional, set-specific parameter, and all other optional parameters.- DatabaseObjectSet: Correctly omits
ServerObjectandRefresh(set-specific to ServerObjectSet), including only the parameters that apply to this set.All parameter types, mandatory/optional designations, and common parameters from
SupportsShouldProcessare accurately represented in the test expectations.tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1 (1)
72-72: Disconnect after tests.Proper teardown prevents session leaks across matrix jobs.
source/Public/Set-SqlDscDatabaseOwner.ps1 (1)
83-119: API surface and binding look correct.Two clear parameter sets, mandatory OwnerName, pipeline for DatabaseObject, SupportsShouldProcess with ConfirmImpact=Medium.
…ed after owner update for accurate state representation
…baseOwner and add mandatory parameter checks for ServerObject and DatabaseObject
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1 (3)
9-11: Use the exact setup block (add Justification text).Align the SuppressMessage attribute with the required template.
[As per coding guidelines]-[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param ()
257-260: Assert localized error text instead of hardcoded English.Use localized string key via InModuleScope to avoid brittle tests and follow the guideline.
[As per coding guidelines]- It 'Should throw error when SetOwner() fails' { - { Set-SqlDscDatabaseOwner -DatabaseObject $mockDatabaseObject -OwnerName 'sa' -Force } | - Should -Throw -ExpectedMessage '*Failed to set owner of database*' - } + It 'Should throw error when SetOwner() fails' { + $expectedTemplate = InModuleScope -ScriptBlock { $script:localizedData.DatabaseOwner_SetFailed } + $expectedMessage = $expectedTemplate -f 'TestDatabase', 'sa' + + { Set-SqlDscDatabaseOwner -DatabaseObject $mockDatabaseObject -OwnerName 'sa' -Force } | + Should -Throw -ExpectedMessage ("*{0}*" -f [Regex]::Escape($expectedMessage)) + }
285-288: Do the same for Alter() failure assertion (use localized string).Mirror the localization-aware assertion here too.
[As per coding guidelines]- It 'Should throw error when Alter() fails' { - { Set-SqlDscDatabaseOwner -DatabaseObject $mockDatabaseObject -OwnerName 'sa' -Force } | - Should -Throw -ExpectedMessage '*Failed to set owner of database*' - } + It 'Should throw error when Alter() fails' { + $expectedTemplate = InModuleScope -ScriptBlock { $script:localizedData.DatabaseOwner_SetFailed } + $expectedMessage = $expectedTemplate -f 'TestDatabase', 'sa' + + { Set-SqlDscDatabaseOwner -DatabaseObject $mockDatabaseObject -OwnerName 'sa' -Force } | + Should -Throw -ExpectedMessage ("*{0}*" -f [Regex]::Escape($expectedMessage)) + }source/Public/Set-SqlDscDatabaseOwner.ps1 (1)
44-69: Add a help example for -Refresh.Improves discoverability when using ServerObjectSet on stale SMO objects.
.EXAMPLE $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' Set-SqlDscDatabaseOwner -ServerObject $serverObject -Name 'MyDatabase' -OwnerName 'sa' -PassThru Sets the owner and returns the updated database object. + .EXAMPLE + $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' + Set-SqlDscDatabaseOwner -ServerObject $serverObject -Name 'MyDatabase' -OwnerName 'sa' -Refresh -Force + + Refreshes the ServerObject.Databases collection before resolving the database, then sets the owner.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
source/Public/Set-SqlDscDatabaseOwner.ps1(1 hunks)tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1source/Public/Set-SqlDscDatabaseOwner.ps1
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
🧠 Learnings (4)
📚 Learning: 2025-10-11T08:18:26.062Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:18:26.062Z
Learning: In unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), when DscResource.Test module dependency is not found during BeforeDiscovery setup, the error message should instruct users to run ".\build.ps1 -Tasks noop" (not "build") because the noop task is designed for quick test environment setup. The build task is more extensive and unnecessary when tests run in a separate process, as the module should already be built before running tests.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : All public commands must include parameter set validation tests
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
📚 Learning: 2025-10-11T08:35:56.141Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:35:56.141Z
Learning: In DSC Community projects, when writing error messages for missing DscResource.Test module dependency in unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), the policy is: new code should instruct users to run ".\build.ps1 -Tasks noop" for quick test environment setup; existing code using ".\build.ps1 -Tasks build" is acceptable but slower since it also builds the project. The `noop` task is preferred as it assumes the module is already built before running tests, especially when tests run in a separate process.
Applied to files:
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
🔇 Additional comments (2)
tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1 (1)
362-395: Good: parameter set validation tests are present and follow the template.This locks the public surface for both ServerObjectSet and DatabaseObjectSet.
source/Public/Set-SqlDscDatabaseOwner.ps1 (1)
151-156: ShouldProcess, Force, and idempotence are implemented correctly.Pattern, confirm bypass, and skip-on-match logic look solid.
Also applies to: 157-178
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
source/Public/Set-SqlDscDatabaseOwner.ps1 (1)
157-164: Consider Write-Verbose for user-facing flow messages.Lines 160 and 164 use Write-Debug for idempotence and update messages. While acceptable, Write-Verbose would better align with the guideline to use it for "high-level execution flow" and "user-actionable information."
Apply this diff if you prefer more user-visible flow messages:
if ($sqlDatabaseObject.Owner -eq $OwnerName) { - Write-Debug -Message ($script:localizedData.DatabaseOwner_OwnerAlreadyCorrect -f $sqlDatabaseObject.Name, $OwnerName) + Write-Verbose -Message ($script:localizedData.DatabaseOwner_OwnerAlreadyCorrect -f $sqlDatabaseObject.Name, $OwnerName) } else { - Write-Debug -Message ($script:localizedData.DatabaseOwner_Updating -f $sqlDatabaseObject.Name, $OwnerName) + Write-Verbose -Message ($script:localizedData.DatabaseOwner_Updating -f $sqlDatabaseObject.Name, $OwnerName)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
source/Public/Set-SqlDscDatabaseOwner.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
source/Public/Set-SqlDscDatabaseOwner.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
🔇 Additional comments (4)
source/Public/Set-SqlDscDatabaseOwner.ps1 (4)
121-127: LGTM!The Force parameter pattern is correctly implemented per coding guidelines.
136-142: LGTM!The ErrorActionPreference pattern is correctly implemented—store, set, restore without try-catch-finally—per coding guidelines.
179-191: LGTM!The error handling is correct, and the ErrorId 'SSDDO0004' now matches the localized string identifier, resolving the past review concern.
196-211: LGTM!The Refresh and PassThru logic is well-designed: refresh occurs when the user wants the updated object back (PassThru) or when the user's own DatabaseObject reference should reflect changes (DatabaseObjectSet). The comment clearly explains the rationale.
…eaner code and improved readability
|
/azp run |
|
Azure Pipelines successfully started running 1 pipeline(s). |
johlju
left a comment
There was a problem hiding this comment.
@johlju reviewed 4 of 6 files at r8, 2 of 2 files at r10, all commit messages.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on @johlju)
Pull Request (PR) description
Set-SqlDscDatabaseOwnerName. Use the new commandSet-SqlDscDatabaseOwnerto change database ownership instead.
properties as parameters. The command now uses a generic property-setting loop
instead of hard-coded property handling. This allows setting any writable
property of the
Microsoft.SqlServer.Management.Smo.Databaseclass, including:AnsiNullDefault,AutoClose,AutoShrink,IsSystemObject,RecursiveTriggersEnabled)AutoCreateStatisticsIncremental,DataSpaceUsage,IndexSpaceUsage,TargetRecoveryTime)MaxSizeInBytes)Collation,DefaultFileGroup,DefaultSchema,PrimaryFilePath)CompatibilityLevel,PageVerify,RecoveryModel,UserAccess)Database_UpdatingPropertymessageunnecessary database operations
Set-SqlDscDatabaseOwnerto change the owner of a SQL Serverdatabase. This command uses the SMO
SetOwner()method and supports bothServerObjectandDatabaseObjectparameter sets. It replaces theOwnerNameparameter that was removed from
Set-SqlDscDatabase.This Pull Request (PR) fixes the following issues
Set-SqlDscDatabase: Add parameters to command #2177Task list
file CHANGELOG.md. Entry should say what was changed and how that
affects users (if applicable), and reference the issue being resolved
(if applicable).
This change is