Skip to content

Comments

Set-SqlDscDatabaseProperty: Refactor command#2327

Merged
johlju merged 70 commits intodsccommunity:mainfrom
johlju:fix/issue-#2177
Oct 31, 2025
Merged

Set-SqlDscDatabaseProperty: Refactor command#2327
johlju merged 70 commits intodsccommunity:mainfrom
johlju:fix/issue-#2177

Conversation

@johlju
Copy link
Member

@johlju johlju commented Oct 26, 2025

Pull Request (PR) description

  • Set-SqlDscDatabase
    • BREAKING CHANGE: Removed parameter OwnerName. Use the new command Set-SqlDscDatabaseOwner
      to change database ownership instead.
    • BREAKING CHANGE: Completely refactored to support all 85+ settable SMO Database
      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.Database class, including:
      • 46 Boolean properties (e.g., AnsiNullDefault, AutoClose, AutoShrink,
        IsSystemObject, RecursiveTriggersEnabled)
      • 8 Int32 properties (e.g., AutoCreateStatisticsIncremental, DataSpaceUsage,
        IndexSpaceUsage, TargetRecoveryTime)
      • 1 Int64 property (MaxSizeInBytes)
      • 19 String properties (e.g., Collation, DefaultFileGroup, DefaultSchema,
        PrimaryFilePath)
      • 11 Enum properties (e.g., CompatibilityLevel, PageVerify, RecoveryModel,
        UserAccess)
    • Removed all property-specific validation logic - SMO now handles validation
    • Removed individual property update messages - now uses generic
      Database_UpdatingProperty message
    • Added check to skip updating properties that are already set to the desired value
    • Properties are only modified if they differ from the current value, reducing
      unnecessary database operations
  • Added public command Set-SqlDscDatabaseOwner to change the owner of a SQL Server
    database. This command uses the SMO SetOwner() method and supports both
    ServerObject and DatabaseObject parameter sets. It replaces the OwnerName
    parameter that was removed from Set-SqlDscDatabase.

This Pull Request (PR) fixes the following issues

Task list

  • Added an entry to the change log under the Unreleased section of the
    file CHANGELOG.md. Entry should say what was changed and how that
    affects users (if applicable), and reference the issue being resolved
    (if applicable).
  • Resource documentation updated in the resource's README.md.
  • Resource parameter descriptions updated in schema.mof.
  • Comment-based help updated, including parameter descriptions.
  • Localization strings updated.
  • Examples updated.
  • Unit tests updated. See DSC Community Testing Guidelines.
  • Integration tests updated (where possible). See DSC Community Testing Guidelines.
  • Code changes adheres to DSC Community Style Guidelines.

This change is Reviewable

@johlju johlju requested a review from a team as a code owner October 26, 2025 19:30
@coderabbitai
Copy link

coderabbitai bot commented Oct 26, 2025

Walkthrough

Split 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

Cohort / File(s) Summary
Set-SqlDscDatabaseProperty (new)
source/Public/Set-SqlDscDatabaseProperty.ps1
New cmdlet exposing many SMO.Database settable properties as parameters; two parameter sets (ServerObjectSet, DatabaseObjectSet); validates CompatibilityLevel/Collation; applies only bound properties and calls Alter() when changes occur; supports ShouldProcess/Force/PassThru.
Set-SqlDscDatabaseOwner (new)
source/Public/Set-SqlDscDatabaseOwner.ps1
New cmdlet to change database owner via SMO.SetOwner(); supports ServerObjectSet and DatabaseObjectSet, Refresh, DropExistingUser, ShouldProcess/Force/PassThru; resolves target via Get-SqlDscDatabase or pipeline and handles idempotence and errors.
Get-SqlDscCompatibilityLevel (new)
source/Public/Get-SqlDscCompatibilityLevel.ps1
New helper enumerating SMO.CompatibilityLevel names and filtering by server major version or supplied Version; returns string[] and warns when SMO lacks expected max level.
Set-SqlDscDatabase (removed / renamed)
source/Public/Set-SqlDscDatabase.ps1
Replaced by Set-SqlDscDatabaseProperty and Set-SqlDscDatabaseOwner; original owner parameter removed and property-driven API inserted.
New-SqlDscDatabase (updated)
source/Public/New-SqlDscDatabase.ps1
Adds CatalogCollation parameter (CatalogCollationType), enforces server major version >= 15 for it, and applies it during database creation.
Get-SqlDscDatabase (minor)
source/Public/Get-SqlDscDatabase.ps1
When resolving a named database with -Refresh, refreshes the individual SMO.Database object before returning.
Localization / resources
source/en-US/SqlServerDsc.strings.psd1
Add/rename string keys for property-driven updates, owner operations, and compatibility helpers; remove legacy per-property update strings; add codes for new messages.
SMO stubs (tests)
tests/Unit/Stubs/SMO.cs
Add VersionMajor, CatalogCollationType, DelayedDurability, Refresh() and related enum/property updates to support new behaviors in unit tests.
Unit tests (new/updated)
tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1, tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1, tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1, tests/Unit/Public/New-SqlDscDatabase.Tests.ps1, tests/Unit/Private/ConvertTo-AuditNewParameterSet.Tests.ps1, tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
Add/adjust Pester tests for property updates, owner changes, compatibility discovery, CatalogCollation, PassThru/Force/ShouldProcess, error paths and SMO-mocked behaviors; small test harness redirection change.
Integration tests & docs (new/updated)
tests/Integration/Commands/Set-SqlDscDatabaseProperty.Integration.Tests.ps1, tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1, tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1, tests/Integration/Commands/README.md
Add integration tests for multi-property updates, idempotency, owner changes, compatibility-level discovery; update README to replace old Set-SqlDscDatabase with new commands.
CI config
azure-pipelines.yml
Replace Set-SqlDscDatabase integration entry with Set-SqlDscDatabaseProperty and add Set-SqlDscDatabaseOwner in the SQL Server test matrix.
Changelog
CHANGELOG.md
Document breaking rename/split (Set-SqlDscDatabaseSet-SqlDscDatabaseProperty + Set-SqlDscDatabaseOwner), new commands, and refactor summary.

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
Loading
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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Areas to focus review on:

  • Correct mapping of exposed parameters to SMO properties and ensuring creation-only or method-only behaviors are not improperly exposed (Set vs New).
  • CompatibilityLevel and Collation validation logic against server/SMO capabilities (Get-SqlDscCompatibilityLevel usage and error messages).
  • Alter()/SetOwner() execution paths: ShouldProcess/Force/PassThru semantics, error handling, and construction of terminating ErrorRecords.
  • SMO test stub changes (VersionMajor, CatalogCollationType, DelayedDurability, Refresh) and their interaction with unit tests.
  • Integration and unit test updates replacing the old Set-SqlDscDatabase usage and verifying idempotence and Refresh behavior.

Possibly related issues

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Set-SqlDscDatabaseProperty: Refactor command" refers to the primary refactoring work in this changeset—the transformation of the property-setting command to support extensive SMO Database properties through a generic binding loop. The title accurately identifies the command and indicates that a refactor occurred, which allows a teammate scanning commit history to recognize this as a significant restructuring effort. However, the title could be more descriptive by indicating the scope of changes (e.g., adding 85+ properties, breaking changes, or the new Set-SqlDscDatabaseOwner command), though the instructions acknowledge that titles don't need to capture every detail.
Linked Issues Check ✅ Passed
Out of Scope Changes Check ✅ Passed All code changes in the PR are directly aligned with the scope of issue #2177 and the PR objectives. The refactoring of Set-SqlDscDatabase/Set-SqlDscDatabaseProperty, addition of Set-SqlDscDatabaseOwner, and creation of Get-SqlDscCompatibilityLevel are all in-scope. The update to New-SqlDscDatabase to add the CatalogCollation parameter is in-scope. Test files and localization strings are updated to support the new functionality. SMO stub updates (adding CatalogCollationType, DelayedDurability enums, VersionMajor property, and Database.Refresh() method) are in-scope because they provide the mocking infrastructure required for the new properties and validation logic. No out-of-scope changes were detected.
Description Check ✅ Passed The pull request description clearly explains the changes made: the refactoring of Set-SqlDscDatabase with the removal of the OwnerName parameter (breaking change), the expansion to support 85+ settable SMO Database properties grouped by type (boolean, integer, long, string, and enum), and the addition of a new Set-SqlDscDatabaseOwner command to handle ownership changes separately. The description also references issue #2177 that this PR fixes and includes a comprehensive task checklist. The description is directly related to the changeset and provides meaningful context about the work performed.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a7a5d3 and 9a86402.

📒 Files selected for processing (2)
  • azure-pipelines.yml (1 hunks)
  • tests/Integration/Commands/README.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.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.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 MD013 rule 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.md
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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/Integration/Commands/README.md
  • azure-pipelines.yml
azure-pipelines.yml

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

azure-pipelines.yml: Integration test script files must be added to a group within the test stage in ./azure-pipelines.yml
Choose an appropriate test group number based on required dependencies in the pipeline configuration

Files:

  • azure-pipelines.yml
🧠 Learnings (19)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.cs : In Database Engine resources, add InstanceName, ServerName, and Credential to $this.ExcludeDscProperties
Learnt from: dan-hughes
Repo: dsccommunity/UpdateServicesDsc PR: 85
File: source/en-US/UpdateServicesDsc.strings.psd1:1-2
Timestamp: 2025-10-04T21:33:23.022Z
Learning: In UpdateServicesDsc (and similar DSC modules), the module-level localization file (source/en-US/<ModuleName>.strings.psd1) can be empty when DSC resources have their own localization files in source/DSCResources/<ResourceName>/en-US/DSC_<ResourceName>.strings.psd1. Automated tests verify localization completeness for resources. Don't flag empty module-level localization files as issues when resources have separate localization.
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.{ps1,psm1,cs} : Prefer SMO over T-SQL for SQL Server interactions
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use localized strings for all messages (e.g., Write-Verbose, Write-Error)
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/README.md
  • azure-pipelines.yml
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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.md
  • azure-pipelines.yml
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Call commands with -Force where applicable to avoid prompting

Applied to files:

  • tests/Integration/Commands/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.{ps1,psm1} : Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format

Applied to files:

  • tests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to azure-pipelines.yml : Integration test script files must be added to a group within the test stage in ./azure-pipelines.yml

Applied to files:

  • tests/Integration/Commands/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Cover all scenarios and code paths in integration tests

Applied to files:

  • tests/Integration/Commands/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/README.md
  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Use DSCSQLTEST (DB Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instances in CI environment

Applied to files:

  • tests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.cs : In Database Engine resources, add InstanceName, ServerName, and Credential to $this.ExcludeDscProperties

Applied to files:

  • tests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.{ps1,psm1,cs} : Prefer SMO over T-SQL for SQL Server interactions

Applied to files:

  • tests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to azure-pipelines.yml : Choose an appropriate test group number based on required dependencies in the pipeline configuration

Applied to files:

  • azure-pipelines.yml
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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, private functions and classes must have unit tests

Applied to files:

  • azure-pipelines.yml
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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:

  • azure-pipelines.yml
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources

Applied to files:

  • azure-pipelines.yml
⏰ 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 (2)
tests/Integration/Commands/README.md (1)

94-96: Documentation for new commands is correctly added.

The three new command entries follow the established table pattern with appropriate run order (4), dependencies on prerequisite installation steps, and DSCSQLTEST instance assignment. The formatting and placement are consistent with existing database-related commands.

Note: Per a previous review comment, the corresponding test invocations still need to be added to azure-pipelines.yml to actually execute these integration tests in the pipeline, as the test files are documented here but not yet invoked in CI.

azure-pipelines.yml (1)

338-340: Let me verify that these test files don't have duplicate references elsewhere in the pipeline and confirm the group placement is correct:

Let me check if there are any duplicate references to these test files in the pipeline and verify the test file structure aligns with SqlServerDsc guidelines:

Let me verify there are no duplicate references and check the test file implementation for database connection patterns:

✅ Integration test files successfully added to pipeline.

The three new integration test files are correctly configured in azure-pipelines.yml:

  • Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • Set-SqlDscDatabaseProperty.Integration.Tests.ps1
  • Set-SqlDscDatabaseOwner.Integration.Tests.ps1

All files exist at the correct repository paths following the standard convention: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1. Group 4 placement is appropriate as these commands require an existing database, positioning them after New-SqlDscDatabase in the test dependency chain. This addresses the earlier flagged issue and aligns with the PR's refactoring objectives.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 $ServerObject is only available in the ServerObjectSet parameter set. When using DatabaseObjectSet, 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 $ServerObject is only available in the ServerObjectSet parameter 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 DatabaseObjectSet parameter 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 instance

This 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 .OUTPUTS keyword 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-Error with continue for 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

📥 Commits

Reviewing files that changed from the base of the PR and between d6111a3 and 913e672.

📒 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.ps1
  • tests/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 $TestDrive variable (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/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.ps1
  • tests/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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/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.ps1
  • tests/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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/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.ps1
  • tests/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.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `InModuleSc...

Files:

  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/README.md
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • CHANGELOG.md
  • source/en-US/SqlServerDsc.strings.psd1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • source/Public/Set-SqlDscDatabase.ps1
  • tests/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.ps1
  • source/Public/Set-SqlDscDatabase.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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/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.ps1
  • source/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.md
  • 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 MD013 rule 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.md
  • CHANGELOG.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.ps1
  • 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-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests Guidelines

Requirements

  • 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-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required 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.ps1
  • 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-SqlDscDatabase.Integration.Tests.ps1
  • tests/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 section

Always 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 like KeyName = 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.ps1
  • tests/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.ps1
  • 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-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.md
  • tests/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.

CatalogCollation is 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.

@codecov
Copy link

codecov bot commented Oct 26, 2025

Codecov Report

❌ Patch coverage is 94.49541% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 94%. Comparing base (d6111a3) to head (9a86402).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
source/Public/New-SqlDscDatabase.ps1 33% 4 Missing ⚠️
source/Public/Get-SqlDscCompatibilityLevel.ps1 96% 1 Missing ⚠️
source/Public/Set-SqlDscDatabaseProperty.ps1 98% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2327   +/-   ##
====================================
- Coverage    94%     94%   -1%     
====================================
  Files       152     154    +2     
  Lines      9277    9326   +49     
====================================
+ Hits       8790    8834   +44     
- Misses      487     492    +5     
Flag Coverage Δ
unit 94% <94%> (-1%) ⬇️
Files with missing lines Coverage Δ
source/Public/Get-SqlDscDatabase.ps1 100% <100%> (ø)
source/Public/Set-SqlDscDatabaseOwner.ps1 100% <100%> (ø)
source/Public/Get-SqlDscCompatibilityLevel.ps1 96% <96%> (ø)
source/Public/Set-SqlDscDatabaseProperty.ps1 98% <98%> (ø)
source/Public/New-SqlDscDatabase.ps1 86% <33%> (-8%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

johlju added 14 commits October 27, 2025 12:36
…ling; update localized strings for new messages
…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
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 call

Ensure 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 Disconnect

Keep 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 Connect

Surface 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 Disconnect

Consistent 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 Connect

Follow 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

📥 Commits

Reviewing files that changed from the base of the PR and between 913e672 and baea0a7.

📒 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.ps1
  • tests/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 $TestDrive variable (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.ps1
  • tests/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.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • source/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.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • 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:

  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • tests/Unit/Stubs/SMO.cs
  • source/Public/Set-SqlDscDatabase.ps1
  • source/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.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `InModuleSc...

Files:

  • tests/Unit/Public/Set-SqlDscDatabase.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • tests/Unit/Stubs/SMO.cs
  • source/Public/Set-SqlDscDatabase.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
  • CHANGELOG.md
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • tests/Unit/Public/Get-SqlDscCompatibilityLevel.Tests.ps1
  • source/Public/Get-SqlDscCompatibilityLevel.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • source/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.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • 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-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests Guidelines

Requirements

  • 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-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required 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.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • 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-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/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 like KeyName = 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.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • 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/Get-SqlDscCompatibilityLevel.ps1
  • source/Public/Set-SqlDscDatabase.ps1
  • source/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 MD013 rule 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 section

Always 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.ps1
  • tests/Integration/Commands/Get-SqlDscCompatibilityLevel.Integration.Tests.ps1
  • tests/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.ps1
  • tests/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 ServerObjectSet and DatabaseObjectSet, 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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1878d66 and 689fdfe.

📒 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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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.ps1
  • 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/Get-SqlDscDatabase.ps1
  • 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/Get-SqlDscDatabase.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • 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/Get-SqlDscDatabase.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • 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/Get-SqlDscDatabase.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • 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/Get-SqlDscDatabase.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1
  • source/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 $TestDrive variable (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.ps1
  • tests/Integration/Commands/Set-SqlDscDatabaseOwner.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `InModuleSc...

Files:

  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • tests/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 Guidelines

Requirements

  • 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-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required 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 ServerObject and Name as mandatory parameters, with Refresh as an optional, set-specific parameter, and all other optional parameters.
  • DatabaseObjectSet: Correctly omits ServerObject and Refresh (set-specific to ServerObjectSet), including only the parameters that apply to this set.

All parameter types, mandatory/optional designations, and common parameters from SupportsShouldProcess are 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
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4959ec0 and a7ba2b8.

📒 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 $TestDrive variable (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.ps1
  • source/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.ps1
  • 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:

  • tests/Unit/Public/Set-SqlDscDatabaseOwner.Tests.ps1
  • source/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 Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.ps1
  • source/Public/Set-SqlDscDatabaseOwner.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • source/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 Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a7ba2b8 and 480db6b.

📒 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 Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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 Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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 Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.

@johlju
Copy link
Member Author

johlju commented Oct 30, 2025

/azp run

@azure-pipelines
Copy link

Azure Pipelines successfully started running 1 pipeline(s).

Copy link
Member Author

@johlju johlju left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:lgtm:

@johlju reviewed 4 of 6 files at r8, 2 of 2 files at r10, all commit messages.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on @johlju)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Set-SqlDscDatabase: Add parameters to command

1 participant