continue and break without a local target - 41 sites, Invoke-DbaXEReplay replays nothing

Aperta
#10,806 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
powershell

Direzione di ricerca

Start with the listed command sites in public/ and private/, especially Invoke-DbaXEReplay and the other public command defects; the issue provides their function names and line numbers. Read CLAUDE.md rule 1 and Get-DbaCommandStructureFinding in tests/dbatools.CommandStructure.ps1, then inspect the analyzer Describe and its exception mechanism. Done means the command defects and analyzer changes are handled in the stated order, fixtures cover local and nonlocal jump targets, and the rule text includes plain continue and break.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

The problem

Rule 1 of the command invariants in CLAUDE.md demands a local target for Stop-Function -Continue, and the "command structure" Describe enforces it. A plain continue or break has the same problem, and nothing checks it. In a function or scriptblock without a loop, switch or trap of its own, PowerShell looks for the target up the call stack, across function boundaries, and a try/catch in between does not stop it.

A probe of a command with continue in its process block gave the same result on Windows PowerShell 5.1 and PowerShell 7.6:

Caller What happens
A plain call or a pipeline in a script, no loop The whole script ends silently, with exit code 0. Neither the end block of the command nor the next statement of the caller runs.
Inside a foreach of the caller The rest of that iteration of the loop of the caller is skipped, then the loop goes on.

Found while working on #10801: Update-SqlPermission ended its database mapping part for a destination older than SQL Server 2005 with continue, so Sync-DbaLoginPermission lost its result rows. That one is fixed in #10801 (34a8ddc78).

How the list was made

An AST scan of public/ and private/ on development 900ba0347 (v2.9.1) for continue and break statements without a loop, switch or trap in the same function or scriptblock. It found 41 sites. The script is at the end. Lab checks ran on SQL03\SQL2019 under Windows PowerShell 5.1.

Defects in public commands (8 sites in 7 commands)

  • Invoke-DbaXEReplay:113, process: if ($InputObject.Name -notin $Event) { continue }. Piped from Read-DbaXEFile, as all three examples do, the first event that is not in -Event ends the pipeline. The end block, which runs sqlcmd, never runs, so nothing is replayed, and the calling script ends. The default of -Event is 'sql_batch_completed', 'rcp_completed', and rcp_completed is a typo of rpc_completed, so every RPC event of a capture hits this. Lab: one rpc_completed event followed by one sql_batch_completed event gave no output, nothing was replayed, the line after the call never ran, exit code 0. The batch event alone is replayed. The test uses a sql_batch_completed event only. Fix: return, and the name of the event.
  • Invoke-DbaDbccFreeCache:137, begin: -Operation has the default FreeProcCache, but without an explicit -Operation the command warns "You must specify an operation" and runs continue. The default is never used, the command does nothing, and the calling script ends (lab: the warning, exit code 0, the next line did not run). Every example passes -Operation. Fix: use the default, or Stop-Function and return with the guard in process (rule 3).
  • Find-DbaDbUnusedIndex:236, process: a -Database that matches nothing warns "Database [...] was not found on [...]" and runs continue (lab: the script ended after the warning). Fix: return.
  • Get-DbaDbCompatibility:88, Set-DbaDbCompatibility:99, Invoke-DbaDbUpgrade:155 and :160, process: the parameter checks "You must specify either a SQL instance or pipe a database collection" and "You must explicitly specify a database ..." warn and run continue. Fix: return, or Stop-Function and return.
  • Get-DbaManagementObject:216, in the scriptblock that runs locally with Invoke-Command and remotely with Invoke-Command2: "No SMO versions found in GAC" runs continue, which skips the output of the SNI modules after it ("always run this regardless of other conditions"). Locally the scriptblock runs in the same runspace, so the continue also lands in foreach ($computer in $ComputerName.ComputerName) of process. No SMO in the GAC is the normal case when SMO comes from dbatools.library. Lab, with Microsoft.Data.SqlClient.SNI.x64.dll loaded: the command returned 4 rows and no SNI row; the same function without the continue returned the SNI row as the fifth. Fix: delete the continue. A return would skip the SNI output as well.

Defects in helpers, where the jump lands in the loop of the caller (17 sites)

  • Update-SqlPermission:204: fixed in #10801 (34a8ddc78), see above.
  • Copy-DbaDbMail:165, in Copy-DbaDbMailConfig: after a failed copy of the configuration values, the continue in the catch lands in foreach ($destinstance in $Destination) and skips the accounts, profiles, mail servers and Database Mail XPs of that destination, without a row for them (the failed row of the configuration is written). With -Type it lands in switch ($type) and only skips the refresh of the configuration values.
  • Copy-DbaLogin:255, 257, 261, 271, 281, 296, 313, 322, 335, 346, 356, 414, 424, 479, 506, in Copy-Login: the exits for a login that is skipped or fails, each after its result row. They land in foreach ($destinstance in $Destination) of process and skip the -SyncSaName block of that iteration. When every login of a run is skipped, for example because all of them exist and -Force is not used, -SyncSaName never runs (from the code, not reproduced in the lab). The new -UpdateExisting path of #10801 leaves with return for that reason. To decide: return in all 15, or an exception for a deliberate pattern.

Harmless, but they depend on the shape of the caller (3 sites)

  • Copy-DbaRegServer:141, 152, 169, in Invoke-ParseServerGroup: reachable only from the top-level call with -Group, which is the last statement of foreach ($store in $stores), so the effect is that of a return. A return keeps it that way when the caller changes.

Dead code (8 sites)

  • Test-DbaLsnChain:70, 85, 93 and Test-DbaRestoreVersion:53, 72, 78, 84: break after return $false. Invoke-Parallel:417: Break after Throw. Never reached, they can go.

Deliberate (5 sites)

  • Stop-Function:248, 250, 270, 272: the continue of -Continue, -ContinueLabel and -SilentlyContinue, the mechanism rule 1 is about.
  • private/scripts/updateTeppAsync.ps1:30, Update-TeppCache: the stop flag of the tab completion updater ends the while ($true) loop of its caller, like the explicit check at line 70.

Proposal: extend rule 1 to plain continue and break

Get-DbaCommandStructureFinding in tests/dbatools.CommandStructure.ps1 already walks from a Stop-Function -Continue to its loop or switch in the same function or scriptblock and checks the label. The same walk for every ContinueStatementAst and BreakStatementAst, with trap as a target as well, would report a plain jump without a local target as a rule 1 finding. The exceptions use the existing mechanism ($dynamicContinueExceptions: file, function, exact number of sites, reason): at first Stop-Function (4) and Update-TeppCache (1), and Copy-Login (15) if those stay. Fixtures go into the analyzer Describe, and the text of rule 1 in CLAUDE.md names plain continue and break as well.

Order, as for #10794: first the fixes, one PR per command, then the check, which stays red until they are merged.

Scan script
# Lists continue and break statements without a loop, switch or trap in the same function or scriptblock.
$files = Get-ChildItem -Path .\public, .\private -Filter *.ps1 -Recurse
foreach ($file in $files) {
    $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$null, [ref]$null)
    $jumps = $ast.FindAll({
            param($node)
            $node -is [System.Management.Automation.Language.ContinueStatementAst] -or
            $node -is [System.Management.Automation.Language.BreakStatementAst]
        }, $true)
    foreach ($jump in $jumps) {
        $parent = $jump.Parent
        $hasTarget = $false
        while ($parent) {
            if ($parent -is [System.Management.Automation.Language.LoopStatementAst] -or
                $parent -is [System.Management.Automation.Language.SwitchStatementAst] -or
                $parent -is [System.Management.Automation.Language.TrapStatementAst]) {
                $hasTarget = $true
                break
            }
            if ($parent -is [System.Management.Automation.Language.FunctionDefinitionAst] -or
                $parent -is [System.Management.Automation.Language.ScriptBlockExpressionAst]) {
                break
            }
            $parent = $parent.Parent
        }
        if (-not $hasTarget) {
            $function = $jump.Parent
            while ($function -and $function -isnot [System.Management.Automation.Language.FunctionDefinitionAst]) {
                $function = $function.Parent
            }
            [PSCustomObject]@{
                File      = $file.Name
                Line      = $jump.Extent.StartLineNumber
                Function  = $function.Name
                Statement = $jump.Extent.Text
            }
        }
    }
}

This text was created by Claude and reviewed by Andreas Jordan.

Lingua principale
PowerShell
Stelle
2.9k
Fork
869
Merge medio
2g 4h
PR unite (30g)
38

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dataplat/dbatools

Tutte le issue di dataplat/dbatools

Issue simili

Altre issue su Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.