Skip to content

New-SqlDscDatabase: Add IsLedger parameter#2350

Merged
johlju merged 3 commits intomainfrom
copilot/move-isledger-parameter
Nov 27, 2025
Merged

New-SqlDscDatabase: Add IsLedger parameter#2350
johlju merged 3 commits intomainfrom
copilot/move-isledger-parameter

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Nov 26, 2025

Pull Request (PR) description

IsLedger is read-only after database creation per SQL Server behavior. This moves the parameter from Set-SqlDscDatabaseProperty to New-SqlDscDatabase where it can actually be set.

Changes:

  • Set-SqlDscDatabaseProperty: Removed IsLedger parameter; documented in .NOTES that ledger status is immutable post-creation
  • New-SqlDscDatabase: Added IsLedger parameter to Database parameter set with implementation to set property during creation. Added version validation that throws a clear error (NSD0007) when -IsLedger is used on SQL Server versions older than 2022 (version 16), following the same pattern as CatalogCollation validation.
  • Localization: Added Database_IsLedgerNotSupported error message string
  • Unit tests: Updated parameter validation tests for both commands; added tests for ledger database creation and version validation error

Usage:

# Create a ledger database (the only way to enable ledger)
$serverObject | New-SqlDscDatabase -Name 'AuditDb' -IsLedger $true -Force

# IsLedger can be tested on existing databases but not modified
Test-SqlDscDatabaseProperty -ServerObject $serverObject -Name 'AuditDb' -IsLedger $true

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.
Original prompt

This section details on the original issue you should resolve

<issue_title>Move IsLedger parameter to New-SqlDscDatabase (creation-time only)</issue_title>
<issue_description>## Description

The IsLedger parameter in Set-SqlDscDatabaseProperty is read-only after database creation and can only be set when creating a new database.

Proposed Solution

  • Remove IsLedger parameter from Set-SqlDscDatabaseProperty
  • Add IsLedger parameter to New-SqlDscDatabase to support ledger database creation
  • Update documentation to clarify that ledger status cannot be changed after creation

References

Technical Details

  • Property: Database.IsLedger
  • Type: Read-only after creation
  • Creation: Set via WITH LEDGER = ON in CREATE DATABASE statement</issue_description>

<agent_instructions>Follow instructions. Make sure to update changelog and unit tests</agent_instructions>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.


This change is Reviewable

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 26, 2025

Walkthrough

Adds an IsLedger parameter to New-SqlDscDatabase to allow creating ledger databases at creation time and removes IsLedger from Set-SqlDscDatabaseProperty, making ledger state creation-only. Tests and localized strings updated; creation path validates SQL Server version (16+/2022+).

Changes

Cohort / File(s) Summary
Changelog
CHANGELOG.md
Documented addition of IsLedger to New-SqlDscDatabase and removal from Set-SqlDscDatabaseProperty, noting ledger is creation-time only.
New-SqlDscDatabase implementation & help
source/Public/New-SqlDscDatabase.ps1
Added [bool] $IsLedger to the Database parameter set; validate server major version >= 16; propagate IsLedger to the SMO Database object during creation; updated help text.
Set-SqlDscDatabaseProperty implementation & help
source/Public/Set-SqlDscDatabaseProperty.ps1
Removed public IsLedger parameter from the function signature; updated documentation/comments to state ledger cannot be modified post-creation.
Unit tests
tests/Unit/Public/New-SqlDscDatabase.Tests.ps1, tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
Added/updated mocks to include IsLedger; added positive and negative tests for ledger creation and server-version validation; removed IsLedger expectations from Set-SqlDscDatabaseProperty tests.
Localization
source/en-US/SqlServerDsc.strings.psd1
Added Database_IsLedgerNotSupported localized string for version validation error.

Sequence Diagram(s)

mermaid
sequenceDiagram
autonumber
participant User as User/DSC
participant Cmdlet as New-SqlDscDatabase
participant SMOLib as SMO Database
participant SQL as SQL Server

Note over Cmdlet: Start creation flow
User->>Cmdlet: Invoke New-SqlDscDatabase (-Name, -IsLedger?)
Cmdlet->>SQL: Query Server MajorVersion
alt MajorVersion < 16 and IsLedger requested
    Cmdlet-->>User: Throw error (IsLedger not supported) 
else MajorVersion >= 16 or IsLedger not requested
    Cmdlet->>SMOLib: Build Database object (+IsLedger if bound)
    Cmdlet->>SQL: CREATE DATABASE ... WITH LEDGER = ON (if IsLedger)
    SQL-->>Cmdlet: Creation result
    Cmdlet-->>User: Return created Database object (IsLedger property set)
end

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review focus areas:
    • source/Public/New-SqlDscDatabase.ps1: creation-time propagation and server-version validation (edge cases, error messages, localization key usage).
    • source/Public/Set-SqlDscDatabaseProperty.ps1: ensure removal doesn't break callers/tests or public contract expectations.
    • Unit tests: verify mocks correctly reflect SMO property and negative-version tests are robust.

Possibly related PRs

Pre-merge checks

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding the IsLedger parameter to New-SqlDscDatabase.
Description check ✅ Passed The description clearly explains why the change was made, details all modifications, provides usage examples, and references the fixed issue.
Linked Issues check ✅ Passed The PR successfully implements all requirements from issue #2331: removes IsLedger from Set-SqlDscDatabaseProperty, adds it to New-SqlDscDatabase with version validation for SQL Server 2022+, updates documentation and unit tests, and includes changelog entry.
Out of Scope Changes check ✅ Passed All changes are directly related to moving the IsLedger parameter as specified in issue #2331. No out-of-scope modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 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 4b7708d and 793b8c4.

📒 Files selected for processing (3)
  • source/Public/New-SqlDscDatabase.ps1 (4 hunks)
  • source/en-US/SqlServerDsc.strings.psd1 (1 hunks)
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1 (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • source/en-US/SqlServerDsc.strings.psd1
🧰 Additional context used
📓 Path-based instructions (5)
**

⚙️ 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
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.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/New-SqlDscDatabase.Tests.ps1
  • source/Public/New-SqlDscDatabase.ps1
tests/[Uu]nit/**/*.[Tt]ests.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/New-SqlDscDatabase.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/New-SqlDscDatabase.Tests.ps1
  • source/Public/New-SqlDscDatabase.ps1
**/*.[Tt]ests.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 or creating an object using an internal class)
  • 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 ...

Files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
source/**/*.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/New-SqlDscDatabase.ps1
🧠 Learnings (17)
📚 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/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 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 : Omit -MockWith when the mock should return $null

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 not mock real SMO types; use SMO stub types from SMO.cs

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Prefix variables used for mocks with 'mock'

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Never add an empty -MockWith block

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Avoid using -ExpectedMessage with Should -Throw assertions

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 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 : Never use Assert-MockCalled; use Should -Invoke instead

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 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/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 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 : Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.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). (5)
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (9)
tests/Unit/Public/New-SqlDscDatabase.Tests.ps1 (5)

76-76: LGTM!

The mock database object correctly includes the IsLedger property with a default value of $false, which aligns with the SMO Database object structure and supports the new ledger database tests.


106-122: Good test coverage for ledger database creation.

The test correctly validates creating a ledger database on SQL Server 2022. The mock server object is properly set up with VersionMajor = 16. However, consider whether the mock should include the EnumCollations method for consistency, even if not exercised by this specific test path.


173-182: LGTM!

The test correctly validates that using -IsLedger $true on SQL Server versions older than 2022 throws the expected error with proper error ID (NSD0007), category (InvalidOperation), and target object validation.


186-201: LGTM!

The parameter set validation test correctly includes [-IsLedger <bool>] in the expected parameter string for the Database parameter set, matching the implementation.


235-240: LGTM!

The test correctly validates that the IsLedger parameter exists within the Database parameter set using the appropriate parameter introspection approach.

source/Public/New-SqlDscDatabase.ps1 (4)

36-41: LGTM!

The parameter documentation clearly explains the purpose, immutability constraint, and version requirements for the IsLedger parameter.


148-150: LGTM!

The parameter definition correctly uses [System.Boolean] type and restricts to the Database parameter set. The parameter follows PowerShell naming conventions and style guidelines.


269-285: LGTM!

The version validation follows the established pattern used for CatalogCollation validation. The implementation correctly throws a terminating error with appropriate error ID (NSD0007), category (InvalidOperation), and uses the localized error message.


344-348: LGTM!

The IsLedger property assignment correctly follows the established pattern for optional parameters and is properly placed within the Database creation path (not Snapshot) before the Create() call.


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.

…Database

Co-authored-by: johlju <7189721+johlju@users.noreply.github.com>
Copilot AI changed the title [WIP] Move IsLedger parameter to New-SqlDscDatabase Move IsLedger parameter to New-SqlDscDatabase (creation-time only) Nov 26, 2025
Copilot AI requested a review from johlju November 26, 2025 16:56
@johlju johlju marked this pull request as ready for review November 26, 2025 16:59
@johlju johlju requested a review from a team as a code owner November 26, 2025 16:59
@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 26, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (2)
tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1 (1)

365-381: Parameter set expectations correctly updated to drop IsLedger

The updated ExpectedParameters strings for ServerObjectSet and DatabaseObjectSet correctly remove -IsLedger <bool>, matching the new signature for Set-SqlDscDatabaseProperty. This keeps the parameter set validation aligned with the breaking change that moves ledger handling to creation time.

If you want extra protection against regressions, you could also assert that IsLedger is not present in $command.Parameters.Keys in the “settable SMO properties” test, but that’s optional. Based on learnings, this follows the existing parameter validation template.

-        It 'Should have many settable SMO properties available as parameters' {
+        It 'Should have many settable SMO properties available as parameters' {
             $command = Get-Command -Name 'Set-SqlDscDatabaseProperty'
@@
             $command.Parameters.Keys | Should -Contain 'TargetRecoveryTime'
+
+            # Ledger status is immutable post-creation and must not be exposed here
+            $command.Parameters.Keys | Should -Not -Contain 'IsLedger'
         }

Also applies to: 383-398

source/Public/New-SqlDscDatabase.ps1 (1)

36-42: IsLedger parameter is correctly scoped and applied during creation

The IsLedger parameter is:

  • Documented clearly as creation-time only and immutable afterward.
  • Scoped only to the Database parameter set (not snapshots).
  • Applied to the SMO database object only when bound ($PSBoundParameters.ContainsKey('IsLedger')), before Create() is called.

This cleanly implements creation-time ledger support without affecting existing paths.

One improvement to consider: the help text states this requires SQL Server 2022 (version 16) or Azure SQL Database, but the implementation doesn’t currently enforce that. For a clearer failure mode (instead of a generic “create failed”), you could add an explicit capability check similar to CatalogCollation and throw a targeted error when -IsLedger is used against unsupported versions/editions. As per coding guidelines, this would better surface version compatibility constraints.

Also applies to: 148-150, 327-330

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ababf9 and 4b7708d.

📒 Files selected for processing (5)
  • CHANGELOG.md (2 hunks)
  • source/Public/New-SqlDscDatabase.ps1 (3 hunks)
  • source/Public/Set-SqlDscDatabaseProperty.ps1 (1 hunks)
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1 (4 hunks)
  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1 (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**

⚙️ 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
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.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-SqlDscDatabaseProperty.ps1
  • source/Public/New-SqlDscDatabase.ps1
  • CHANGELOG.md
  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.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:

  • source/Public/Set-SqlDscDatabaseProperty.ps1
  • source/Public/New-SqlDscDatabase.ps1
  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
source/**/*.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-SqlDscDatabaseProperty.ps1
  • source/Public/New-SqlDscDatabase.ps1
**/*.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 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
tests/[Uu]nit/**/*.[Tt]ests.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-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
**/*.[Tt]ests.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 or creating an object using an internal class)
  • 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 ...

Files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
🧠 Learnings (24)
📚 Learning: 2025-09-14T19:17:05.477Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-changelog.instructions.md:0-0
Timestamp: 2025-09-14T19:17:05.477Z
Learning: Applies to CHANGELOG.md : Describe notable changes briefly, with no more than 2 items per change type

Applied to files:

  • CHANGELOG.md
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
📚 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
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 : Set-TargetResource and Test-TargetResource must have identical parameters

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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} : ValueFromPipeline must be consistent across all parameter set declarations for the same parameter

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
📚 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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} : Parameters should use full .NET type names

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
📚 Learning: 2025-08-16T13:35:08.323Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:0-0
Timestamp: 2025-08-16T13:35:08.323Z
Learning: In PowerShell, users expect to receive $null when no objects are found or when a non-terminating error occurs, rather than empty arrays. This is normal PowerShell behavior and should be maintained in DSC commands.

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 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/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Do not add param() inside Pester blocks when using -ForEach

Applied to files:

  • tests/Unit/Public/Set-SqlDscDatabaseProperty.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 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 not mock real SMO types; use SMO stub types from SMO.cs

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/New-SqlDscDatabase.Tests.ps1
📚 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 : Omit -MockWith when the mock should return $null

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Prefix variables used for mocks with 'mock'

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Never add an empty -MockWith block

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Pass all mandatory parameters in tests to avoid prompts

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.Tests.ps1
📚 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 : Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabase.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). (6)
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test HQRM)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Unit)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Determine DSC Resource Test Requirements)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (4)
CHANGELOG.md (2)

25-27: IsLedger removal entry is clear and consistent with existing BREAKING CHANGE block

The new sub-bullet under the existing Set-SqlDscDatabaseProperty BREAKING CHANGE correctly documents the removal of IsLedger and points users to the proper creation-time command. Wording, nesting, and issue link format all match the established changelog style.


64-66: New-SqlDscDatabase IsLedger addition is well-described

The added IsLedger entry under New-SqlDscDatabase cleanly explains the new creation-time capability and the read-only nature of ledger status, with a correctly formatted issue reference. This pairs well with the corresponding removal note above.

source/Public/Set-SqlDscDatabaseProperty.ps1 (1)

312-315: IsLedger .NOTES entry accurately documents read-only behavior

Documenting IsLedger alongside other read-only-after-creation properties and explicitly pointing users to New-SqlDscDatabase -IsLedger aligns the help text with the updated behavior and avoids implying that this command can toggle ledger status.

tests/Unit/Public/New-SqlDscDatabase.Tests.ps1 (1)

76-76: Ledger-related tests thoroughly cover behavior and signature

  • The SMO stub now includes an IsLedger note property, so the unit tests can observe the flag set by New-SqlDscDatabase.
  • The new test “Should create a ledger database with IsLedger set to true” verifies that passing -IsLedger $true results in a created object whose IsLedger is True, which confirms the wiring from parameter to SMO property.
  • The updated ExpectedParameters string for the Database parameter set correctly adds [-IsLedger <bool>] in the expected position.
  • The dedicated assertion that IsLedger has a ParameterSetName of Database ensures the parameter is only available where intended.

This is a solid, guideline-compliant extension of the existing test suite. Based on learnings, the parameter set validation and parameter-attribute checks follow the recommended unit test patterns.

Also applies to: 106-112, 169-169, 216-220

@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 26, 2025

@copilot the help text states this requires SQL Server 2022 (version 16) or Azure SQL Database, but the implementation doesn’t currently enforce that. For a clearer failure mode (instead of a generic “create failed”), you could add an explicit capability check similar to CatalogCollation and throw a targeted error when -IsLedger is used against unsupported versions/editions. As per coding guidelines, this would better surface version compatibility constraints.

…22+)

Co-authored-by: johlju <7189721+johlju@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Nov 26, 2025

@copilot the help text states this requires SQL Server 2022 (version 16) or Azure SQL Database, but the implementation doesn’t currently enforce that. For a clearer failure mode (instead of a generi...

Added version validation for IsLedger in commit 793b8c4. The check follows the same pattern as CatalogCollation and throws a clear error with error ID NSD0007 when -IsLedger is used on SQL Server versions older than 2022 (version 16).

@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 26, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copilot AI changed the title Move IsLedger parameter to New-SqlDscDatabase (creation-time only) BREAKING CHANGE: Move IsLedger parameter to New-SqlDscDatabase (creation-time only) Nov 26, 2025
@johlju johlju changed the title BREAKING CHANGE: Move IsLedger parameter to New-SqlDscDatabase (creation-time only) New-SqlDscDatabase: Add IsLedger parameter Nov 26, 2025
@codecov
Copy link
Copy Markdown

codecov Bot commented Nov 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (f49e80a) to head (793b8c4).
⚠️ Report is 40 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2350   +/-   ##
====================================
  Coverage    94%     94%           
====================================
  Files       162     162           
  Lines      9492    9498    +6     
====================================
+ Hits       8999    9005    +6     
  Misses      493     493           
Flag Coverage Δ
unit 94% <100%> (+<1%) ⬆️
Files with missing lines Coverage Δ
source/Public/New-SqlDscDatabase.ps1 89% <100%> (+<1%) ⬆️
source/Public/Set-SqlDscDatabaseProperty.ps1 98% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Member

@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 6 of 6 files at r1, all commit messages.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on @copilot)

@johlju johlju merged commit 6c4fbd1 into main Nov 27, 2025
51 of 52 checks passed
@johlju johlju deleted the copilot/move-isledger-parameter branch November 27, 2025 12:15
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.

Move IsLedger parameter to New-SqlDscDatabase (creation-time only)

2 participants