Skip to content

Fix/graceful sqlscript file missing#2449

Merged
johlju merged 15 commits intodsccommunity:mainfrom
manuelgr0:fix/graceful-sqlscript-file-missing
Feb 7, 2026
Merged

Fix/graceful sqlscript file missing#2449
johlju merged 15 commits intodsccommunity:mainfrom
manuelgr0:fix/graceful-sqlscript-file-missing

Conversation

@manuelgr0
Copy link
Contributor

@manuelgr0 manuelgr0 commented Feb 6, 2026

Pull Request (PR) description

This PR improves the logic for handling missing SQL script files across the Get, Test, and Set methods in the SqlScript resource. It addresses issues where errors were previously swallowed or logic prevented bootstrapping scenarios.

Crucially, this fix is necessary for Azure Arc Guest Configuration (Machine Configuration). In Guest Configuration, if Test-TargetResource throws an exception due to a missing file, the entire configuration agent halts the consistency check. This prevents the remediation (Set) phase from ever running. Consequently, any dependent resources (via DependsOn) that are responsible for creating the SQL file are never executed, leading to a permanent failure loop.

Changes:

  • Get-TargetResource: Changed behavior to throw a terminating error if $GetFilePath is missing. Previously, it returned an empty result object, which masked configuration errors (such as typos in the file path) and falsely reported success.
  • Test-TargetResource: Updated to return $false (and write a Verbose message) if $TestFilePath is missing. This fixes scenarios where the SQL file is generated by a dependent resource (using DependsOn). Returning $false allows the DSC engine to proceed to the Set phase where the file can be created.
  • Set-TargetResource:
    • Fixed a bug where the validation logic checked a non-existent variable ($FilePath) instead of the correct parameter ($SetFilePath).
    • Ensures a terminating error is thrown if the file is still missing during the Set phase, as this indicates a failure in the dependency chain or configuration.

This Pull Request (PR) fixes the following issues

None

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

@manuelgr0 manuelgr0 requested review from a team and johlju as code owners February 6, 2026 16:25
@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2026

Walkthrough

Adds pre-validation file-existence checks to the SqlScript DSC resource: Get-TargetResource and Set-TargetResource now throw localized file-not-found errors when their script paths are missing; Test-TargetResource logs verbose and returns false when its file is missing. CHANGELOG, localization strings, unit and integration tests updated.

Changes

Cohort / File(s) Summary
Changelog
CHANGELOG.md
Updated Unreleased Fixed entries documenting new file-not-found behavior for Get-TargetResource, Set-TargetResource, and Test-TargetResource.
Module Implementation
source/DSCResources/DSC_SqlScript/DSC_SqlScript.psm1
Added Test-Path -PathType Leaf pre-checks for GetFilePath / SetFilePath / TestFilePath. Get-/Set-TargetResource now construct and throw localized ObjectNotFound exceptions when the file is missing; Test-TargetResource logs verbose and returns false when its file is missing.
Localization
source/DSCResources/DSC_SqlScript/en-US/DSC_SqlScript.strings.psd1
Added localization keys: GetFilePath_FileNotFound, SetFilePath_FileNotFound, and TestFilePath_FileNotFound.
Unit Tests
tests/Unit/DSC_SqlScript.Tests.ps1
Added tests mocking Test-Path = $false for Get/Set/Test contexts to verify missing-file behavior: expect localized exceptions for Get/Set and false for Test-TargetResource; preserved existing positive-path mocks.
Integration Tests / Examples
tests/Integration/Resources/DSC_SqlScript.config.ps1
Adjusted GetScript blocks to assign return hashtable to a local variable before returning; changed GetScript logic to return false when the script result is null/empty (explicitly differentiating empty result vs. success).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main focus of the PR—fixing graceful handling of missing SQL script files in the SqlScript resource.
Description check ✅ Passed The description provides clear context on what was changed, why it matters (Azure Arc Guest Configuration support), and specific details about Get, Test, and Set methods.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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: 2

🤖 Fix all issues with AI agents
In `@source/DSCResources/DSC_SqlScript/DSC_SqlScript.psm1`:
- Around line 287-291: Replace the bare Throw inside the Test-Path check for
$SetFilePath with creation and throwing of an ItemNotFoundException that uses a
localized string; add a new resource key SetFilePath_FileNotFound to
en-US/DSC_SqlScript.strings.psd1 (value like "The file specified in SetFilePath
('{0}') does not exist or is not accessible. Cannot apply desired state."), then
in the Test-Path block build the message from the localized key (e.g. $msg =
$LocalizedData['SetFilePath_FileNotFound'] -f $SetFilePath) and throw
(New-Object System.Management.Automation.ItemNotFoundException($msg)) instead of
the current Throw, ensuring you reference $SetFilePath in the message.
- Around line 124-128: Replace the bare Throw when the file at $GetFilePath is
missing with a call to New-ObjectNotFoundException using a localized message
from $script:localizedData; add a new key (e.g., "GetFilePath_FileNotFound") to
en-US/DSC_SqlScript.strings.psd1 with the message template and then change the
check in DSC_SqlScript.psm1 to construct the message via -f $GetFilePath (or the
helper used elsewhere) and pass it to New-ObjectNotFoundException so the
exception follows MOF DSC guidelines and uses localization.
🧹 Nitpick comments (1)
CHANGELOG.md (1)

26-34: Add issue reference and wrap long lines in Fixed entry.

The new Fixed items lack an issue reference in the required format, and multiple lines exceed 80 characters. Please add an issue link and wrap lines at word boundaries. As per coding guidelines: “Reference issues using format issue #<issue_number> in CHANGELOG.md” and “Wrap lines at word boundaries when over 80 characters.”

Proposed update (placeholder issue number)
 - SqlScript
-  - Fixed logic in `Get-TargetResource` and `Set-TargetResource` to throw an error
-    when the SQL script file is missing, instead of incorrectly reporting success
-    or using a null variable.
-  - Fixed `Test-TargetResource` to return `$false` (instead of throwing) when
-    the SQL script file is missing, enabling `DependsOn` scenarios where the file
-    is created at runtime.
+  - Fixed logic in `Get-TargetResource` and `Set-TargetResource` to throw an
+    error when the SQL script file is missing, instead of incorrectly reporting
+    success or using a null variable
+    ([issue `#2449`](https://github.com/dsccommunity/SqlServerDsc/issues/2449)).
+  - Fixed `Test-TargetResource` to return `$false` (instead of throwing) when
+    the SQL script file is missing, enabling `DependsOn` scenarios where the
+    file is created at runtime
+    ([issue `#2449`](https://github.com/dsccommunity/SqlServerDsc/issues/2449)).

@manuelgr0
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2026

✅ 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

@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

🤖 Fix all issues with AI agents
In `@source/DSCResources/DSC_SqlScript/en-US/DSC_SqlScript.strings.psd1`:
- Around line 8-9: Add a new localized string key TestFilePath_FileNotFound in
the same .strings.psd1 block (matching the pattern of GetFilePath_FileNotFound
and SetFilePath_FileNotFound) and update the Test-TargetResource implementation
to use this key instead of the hardcoded English message; specifically, add the
TestFilePath_FileNotFound entry with the appropriate localized message text and
replace the hardcoded Write-Verbose/Write-Error call in Test-TargetResource to
retrieve and use the localized string (e.g., via the existing
Get-LocalizedString helper or the module's localization lookup used for the
other keys).

@johlju johlju added the needs review The pull request needs a code review. label Feb 6, 2026
@manuelgr0
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2026

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

@codecov
Copy link

codecov bot commented Feb 6, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (78a2c04) to head (b7fe2c0).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@          Coverage Diff          @@
##            main   #2449   +/-   ##
=====================================
  Coverage     94%     94%           
=====================================
  Files        227     227           
  Lines      10778   10788   +10     
=====================================
+ Hits       10149   10159   +10     
  Misses       629     629           
Flag Coverage Δ
unit 94% <100%> (+<1%) ⬆️
Files with missing lines Coverage Δ
...urce/DSCResources/DSC_SqlScript/DSC_SqlScript.psm1 100% <100%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/Unit/DSC_SqlScript.Tests.ps1 (2)

263-377: ⚠️ Potential issue | 🟠 Major

Missing Test-Path mocks and file-missing test scenario for Test-TargetResource.

Same pattern as Set-TargetResource — the PR objectives state Test-TargetResource now returns $false when TestFilePath is missing, but:

  1. Existing "desired state" contexts (lines 286–318) don't mock Test-Path. The tests at lines 297 and 315 assert Should -BeTrue, but with the new pre-check, Test-Path 'test.sql' will return $false on the runner, causing the function to return $false before Invoke-SqlScript runs — failing these assertions.

  2. Missing a Context 'When the TestFilePath file is missing' under "not in desired state" to verify the function returns $false (and optionally that the verbose message is written, though per guidelines verbose messages aren't tested).

Suggested additions

Add Mock -CommandName Test-Path -MockWith { return $true } to the BeforeAll blocks at lines 287 and 303, and to the "not in desired state" contexts at lines 323, 343, and 361.

Add a new Context:

        Context 'When the TestFilePath file is missing' {
            BeforeAll {
                Mock -CommandName Test-Path -MockWith { return $false }
            }

            It 'Should return false' {
                InModuleScope -ScriptBlock {
                    Set-StrictMode -Version 1.0

                    $result = Test-TargetResource `@mockTestTargetResourceParameters`

                    $result | Should -BeFalse
                }
            }
        }

209-260: ⚠️ Potential issue | 🟠 Major

Add Test-Path mocks to Set-TargetResource test contexts and add missing file-validation test scenario.

Per the PR, Set-TargetResource now validates that SetFilePath exists before calling Invoke-SqlScript (line 288). Two gaps:

  1. Existing test contexts need Mock -CommandName Test-Path -MockWith { return $true } — Without this, Test-Path will return $false for the mock path 'set.sql', causing the file validation to throw SetFilePath_FileNotFound before Invoke-SqlScript is ever called, breaking these tests.

  2. Missing a new Context 'When the SetFilePath file is missing' to verify the localized terminating error is thrown (analogous to lines 170–184 for Get-TargetResource).

Suggested additions

Add to each existing BeforeAll in Set-TargetResource contexts (lines 211 and 227):

  BeforeAll {
+     Mock -CommandName Test-Path -MockWith { return $true }
+
      Mock -CommandName Invoke-SqlScript -MockWith {

Add a new Context after line 260:

    Context 'When the SetFilePath file is missing' {
        BeforeAll {
            Mock -CommandName Test-Path -MockWith { return $false }
        }

        It 'Should throw the localized file not found exception' {
            InModuleScope -ScriptBlock {
                Set-StrictMode -Version 1.0

                $expectedError = $script:localizedData.SetFilePath_FileNotFound -f $script:mockSetTargetResourceParameters.SetFilePath

                { Set-TargetResource `@mockSetTargetResourceParameters` } | Should -Throw -ExpectedMessage $expectedError
            }
        }
    }
🤖 Fix all issues with AI agents
In `@CHANGELOG.md`:
- Around line 30-36: Change the plain "SqlScript" heading to use Markdown
italics: wrap the resource name (SqlScript) with underscores (or asterisks) so
it appears as _SqlScript_ in the changelog; update the line containing the
resource name and any other occurrences in the same block referencing the
resource (e.g., Get-TargetResource, Set-TargetResource, Test-TargetResource
entries) to keep formatting consistent.
- Around line 28-36: The CHANGELOG.md Unreleased "Fixed" entry for SqlScript is
missing the required issue reference; update the SqlScript bullets under "Fixed"
to append the issue link in the required format (e.g. [issue
#<n>](https://github.com/<owner>/<repo>/issues/<n>)) so each notable change (the
fixes to Get-TargetResource, Set-TargetResource and Test-TargetResource) cites
the correct issue; locate the SqlScript section and add the appropriate [issue
#...] link(s) after the sentence(s) for Get-TargetResource, Set-TargetResource
and Test-TargetResource using the real owner/repo and issue number.

@manuelgr0
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2026

✅ 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

@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: 2

🤖 Fix all issues with AI agents
In `@tests/Unit/DSC_SqlScript.Tests.ps1`:
- Around line 415-425: Remove the entire "It 'Should write the verbose message'"
test block: delete the It { ... } that calls Test-TargetResource and uses Should
-WriteVerbose, including the local variables $expectedMessage,
$verbosePreference and the invocation { Test-TargetResource
`@mockTestTargetResourceParameters` }, because testing verbose output (and using
the non-standard Should -WriteVerbose assertion) violates the coding guideline;
leave other tests intact.
- Around line 167-181: The test uses wrong localized string keys causing
$script:localizedData lookups to return $null; update the key names used where
$expectedError is built to match the strings file pattern
"{FunctionName}_FileNotFound" — replace GetScriptFileNotFound with
GetFilePath_FileNotFound for the Get-TargetResource test, and likewise update
the other tests to use SetFilePath_FileNotFound and TestFilePath_FileNotFound so
that $script:localizedData.GetFilePath_FileNotFound (and the Set/Test
equivalents) return the expected message for the Should -Throw assertion.
🧹 Nitpick comments (1)
tests/Unit/DSC_SqlScript.Tests.ps1 (1)

249-251: Minor: extra blank line before It block.

There are two consecutive blank lines (Lines 249-250) before the It block. The coding guidelines state "Maximum two consecutive newlines," so this just barely passes, but the surrounding code consistently uses single blank lines between blocks.

Copy link
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 4 files and all commit messages, and made 1 comment.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on @manuelgr0).

@johlju
Copy link
Member

johlju commented Feb 7, 2026

I will merge once tests passes, I will keep an eye on them.

@johlju johlju added ready for merge The pull request was approved by the community and is ready to be merged by a maintainer. and removed needs review The pull request needs a code review. labels Feb 7, 2026
@johlju
Copy link
Member

johlju commented Feb 7, 2026

So there seems to be a bug in the integration tests with the xScript resource that hasn't surface until now. Unrelated to this PR I believe.

Copy link
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.

@johlju reviewed 1 file and all commit messages.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on @manuelgr0).

@johlju johlju merged commit a4cc440 into dsccommunity:main Feb 7, 2026
59 of 60 checks passed
@johlju johlju removed the ready for merge The pull request was approved by the community and is ready to be merged by a maintainer. label Feb 7, 2026
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.

2 participants