-
Notifications
You must be signed in to change notification settings - Fork 227
Add Get-SqlDscDateTime and Invoke-SqlDscScalarQuery commands #2371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a39be07
Initial plan
Copilot ab1dc36
Add Invoke-SqlDscScalarQuery and Get-SqlDscDateTime commands with tests
Copilot a4834e9
Add integration tests to azure-pipelines.yml
Copilot 5ea5052
Add documentation to ExecuteScalar method stub
Copilot 18bd1b8
Address code review feedback
Copilot 72da0cb
Address additional code review feedback
Copilot 41ce9f0
Fix parameter property tests to use -BeTrue instead of -Contain
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Retrieves the current date and time from a SQL Server instance. | ||
|
|
||
| .DESCRIPTION | ||
| Retrieves the current date and time from a SQL Server instance using the | ||
| specified T-SQL date/time function. This command helps eliminate clock-skew | ||
| and timezone issues when coordinating time-sensitive operations between the | ||
| client and SQL Server. | ||
|
|
||
| The command queries SQL Server using the server connection context, which | ||
| does not require any database to be online. | ||
|
|
||
| .PARAMETER ServerObject | ||
| Specifies current server connection object. | ||
|
|
||
| .PARAMETER DateTimeFunction | ||
| Specifies which T-SQL date/time function to use for retrieving the date and time. | ||
| Valid values are: | ||
| - `SYSDATETIME` (default): Returns datetime2(7) with server local time | ||
| - `SYSDATETIMEOFFSET`: Returns datetimeoffset(7) with server local time and timezone offset | ||
| - `SYSUTCDATETIME`: Returns datetime2(7) with UTC time | ||
| - `GETDATE`: Returns datetime with server local time | ||
| - `GETUTCDATE`: Returns datetime with UTC time | ||
|
|
||
| .PARAMETER StatementTimeout | ||
| Specifies the query StatementTimeout in seconds. Default 600 seconds (10 minutes). | ||
|
|
||
| .INPUTS | ||
| `Microsoft.SqlServer.Management.Smo.Server` | ||
|
|
||
| Accepts input via the pipeline. | ||
|
|
||
| .OUTPUTS | ||
| `System.DateTime` | ||
|
|
||
| Returns the current date and time from the SQL Server instance. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| Get-SqlDscDateTime -ServerObject $serverObject | ||
|
|
||
| Connects to the default instance and retrieves the current date and time | ||
| using the default SYSDATETIME function. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| $serverObject | Get-SqlDscDateTime -DateTimeFunction 'SYSUTCDATETIME' | ||
|
|
||
| Connects to the default instance and retrieves the current UTC date and time | ||
| from the SQL Server instance. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| $serverTime = Get-SqlDscDateTime -ServerObject $serverObject | ||
| Restore-SqlDscDatabase -ServerObject $serverObject -Name 'MyDatabase' -StopAt $serverTime.AddHours(-1) | ||
|
|
||
| Demonstrates using the server's clock for a point-in-time restore operation, | ||
| avoiding clock skew issues between client and server. | ||
| #> | ||
| function Get-SqlDscDateTime | ||
| { | ||
| [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('UseSyntacticallyCorrectExamples', '', Justification = 'Because the rule does not yet support parsing the code when a parameter type is not available. The ScriptAnalyzer rule UseSyntacticallyCorrectExamples will always error in the editor due to https://github.com/indented-automation/Indented.ScriptAnalyzerRules/issues/8.')] | ||
| [OutputType([System.DateTime])] | ||
| [CmdletBinding()] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | ||
| [Microsoft.SqlServer.Management.Smo.Server] | ||
| $ServerObject, | ||
|
|
||
| [Parameter()] | ||
| [ValidateSet('SYSDATETIME', 'SYSDATETIMEOFFSET', 'SYSUTCDATETIME', 'GETDATE', 'GETUTCDATE')] | ||
| [System.String] | ||
| $DateTimeFunction = 'SYSDATETIME', | ||
|
|
||
| [Parameter()] | ||
| [ValidateNotNull()] | ||
| [System.Int32] | ||
| $StatementTimeout = 600 | ||
| ) | ||
|
|
||
| process | ||
| { | ||
| Write-Verbose -Message ( | ||
| $script:localizedData.Get_SqlDscDateTime_RetrievingDateTime -f $DateTimeFunction | ||
| ) | ||
|
|
||
| $query = "SELECT $DateTimeFunction()" | ||
|
|
||
| $invokeSqlDscScalarQueryParameters = @{ | ||
| ServerObject = $ServerObject | ||
| Query = $query | ||
| StatementTimeout = $StatementTimeout | ||
| ErrorAction = 'Stop' | ||
| Verbose = $VerbosePreference | ||
| } | ||
|
|
||
| try | ||
| { | ||
| $result = Invoke-SqlDscScalarQuery @invokeSqlDscScalarQueryParameters | ||
|
|
||
| # Convert the result to DateTime if it's a DateTimeOffset | ||
| if ($result -is [System.DateTimeOffset]) | ||
| { | ||
| $result = $result.DateTime | ||
| } | ||
|
|
||
| return $result | ||
| } | ||
| catch | ||
| { | ||
| $writeErrorParameters = @{ | ||
| Message = $script:localizedData.Get_SqlDscDateTime_FailedToRetrieve -f $DateTimeFunction, $_.Exception.Message | ||
| Category = 'InvalidOperation' | ||
| ErrorId = 'GSDD0001' # cSpell: disable-line | ||
| TargetObject = $DateTimeFunction | ||
| Exception = $_.Exception | ||
| } | ||
|
|
||
| Write-Error @writeErrorParameters | ||
|
|
||
| return | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Executes a scalar query on the specified server. | ||
|
|
||
| .DESCRIPTION | ||
| Executes a scalar query on the specified server using the server connection | ||
| context. This command is designed for queries that return a single value, | ||
| such as `SELECT @@VERSION` or `SELECT SYSDATETIME()`. | ||
|
|
||
| The command uses `Server.ConnectionContext.ExecuteScalar()` which is | ||
| server-level and does not require any database to be online. | ||
|
|
||
| .PARAMETER ServerObject | ||
| Specifies current server connection object. | ||
|
|
||
| .PARAMETER Query | ||
| Specifies the scalar query string to execute. | ||
|
|
||
| .PARAMETER StatementTimeout | ||
| Specifies the query StatementTimeout in seconds. Default 600 seconds (10 minutes). | ||
|
|
||
| .PARAMETER RedactText | ||
| Specifies one or more text strings to redact from the query when verbose messages | ||
| are written to the console. Strings will be escaped so they will not | ||
| be interpreted as regular expressions (RegEx). | ||
|
|
||
| .INPUTS | ||
| `Microsoft.SqlServer.Management.Smo.Server` | ||
|
|
||
| Accepts input via the pipeline. | ||
|
|
||
| .OUTPUTS | ||
| `System.Object` | ||
|
|
||
| Returns the scalar value returned by the query. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| Invoke-SqlDscScalarQuery -ServerObject $serverObject -Query 'SELECT @@VERSION' | ||
|
|
||
| Connects to the default instance and then runs a query to return the SQL Server version. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| $serverObject | Invoke-SqlDscScalarQuery -Query 'SELECT SYSDATETIME()' | ||
|
|
||
| Connects to the default instance and then runs the query to return the current | ||
| date and time from the SQL Server instance. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine | ||
| Invoke-SqlDscScalarQuery -ServerObject $serverObject -Query "SELECT name FROM sys.databases WHERE name = 'MyPassword123'" -RedactText @('MyPassword123') -Verbose | ||
|
|
||
| Shows how to redact sensitive information in the query when the query string | ||
| is output as verbose information when the parameter Verbose is used. | ||
| #> | ||
| function Invoke-SqlDscScalarQuery | ||
| { | ||
| [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('UseSyntacticallyCorrectExamples', '', Justification = 'Because the rule does not yet support parsing the code when a parameter type is not available. The ScriptAnalyzer rule UseSyntacticallyCorrectExamples will always error in the editor due to https://github.com/indented-automation/Indented.ScriptAnalyzerRules/issues/8.')] | ||
| [OutputType([System.Object])] | ||
| [CmdletBinding()] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | ||
| [Microsoft.SqlServer.Management.Smo.Server] | ||
| $ServerObject, | ||
|
|
||
| [Parameter(Mandatory = $true)] | ||
| [System.String] | ||
| $Query, | ||
|
|
||
| [Parameter()] | ||
| [ValidateNotNull()] | ||
| [System.Int32] | ||
| $StatementTimeout = 600, | ||
|
|
||
| [Parameter()] | ||
| [ValidateNotNullOrEmpty()] | ||
| [System.String[]] | ||
| $RedactText | ||
| ) | ||
|
|
||
| process | ||
| { | ||
| $redactedQuery = $Query | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('RedactText')) | ||
| { | ||
| $redactedQuery = ConvertTo-RedactedText -Text $Query -RedactPhrase $RedactText | ||
| } | ||
|
|
||
| Write-Verbose -Message ( | ||
| $script:localizedData.Invoke_SqlDscScalarQuery_ExecutingQuery -f $redactedQuery | ||
| ) | ||
|
|
||
| $previousStatementTimeout = $null | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('StatementTimeout')) | ||
| { | ||
| # Make sure we can return the StatementTimeout before exiting. | ||
| $previousStatementTimeout = $ServerObject.ConnectionContext.StatementTimeout | ||
|
|
||
| $ServerObject.ConnectionContext.StatementTimeout = $StatementTimeout | ||
| } | ||
|
|
||
| try | ||
| { | ||
| $result = $ServerObject.ConnectionContext.ExecuteScalar($Query) | ||
|
|
||
| return $result | ||
| } | ||
| catch | ||
| { | ||
| $writeErrorParameters = @{ | ||
| Message = $script:localizedData.Invoke_SqlDscScalarQuery_FailedToExecute -f $_.Exception.Message | ||
| Category = 'InvalidOperation' | ||
| ErrorId = 'ISDSQ0002' # cSpell: disable-line | ||
| TargetObject = $redactedQuery | ||
| Exception = $_.Exception | ||
| } | ||
|
|
||
| Write-Error @writeErrorParameters | ||
|
|
||
| return | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| finally | ||
| { | ||
| if ($null -ne $previousStatementTimeout) | ||
| { | ||
| $ServerObject.ConnectionContext.StatementTimeout = $previousStatementTimeout | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.