-
Notifications
You must be signed in to change notification settings - Fork 227
Add commands for SQL Server database management #2148
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
johlju
merged 18 commits into
main
from
copilot/fix-1fc19ae7-6072-474f-b527-f0328b3aaa64
Aug 29, 2025
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
1fabc48
Initial plan
Copilot cc00e28
Add complete SqlDsc database public commands with tests
Copilot ade4c3e
Fix file endings and trailing whitespace in database commands
Copilot 07097b3
Add integration tests for Set-SqlDscDatabase and Remove-SqlDscDatabas…
Copilot fbccf7c
Merge branch 'main' into copilot/fix-1fc19ae7-6072-474f-b527-f0328b3a…
johlju 07b1936
Merge branch 'main' into copilot/fix-1fc19ae7-6072-474f-b527-f0328b3a…
johlju 88b8388
Fix integration test
johlju 9ef342a
Fix integraiton tests
johlju a76a24c
FIx review commenrts
johlju 7fadb6d
DEBUG 1
johlju 4d458ef
DEBUG 2
johlju 1d4a1b5
DEBUG 3
johlju 4982d91
DEBUF 4
johlju bceea2f
Fix review comments
johlju 9dea35c
Merge branch 'main' into copilot/fix-1fc19ae7-6072-474f-b527-f0328b3a…
johlju fcffe42
Add unit test coverage for CompatibilityLevel, Collation, and OwnerNa…
Copilot dd5a18c
Remove Write-Verbose mocks and fix -Not -Throw patterns in database c…
Copilot d262457
Revert build.ps1 file mode change
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,103 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Get databases from a SQL Server Database Engine instance. | ||
|
|
||
| .DESCRIPTION | ||
| This command gets one or more databases from a SQL Server Database Engine instance. | ||
| If no name is specified, all databases are returned. | ||
|
|
||
| .PARAMETER ServerObject | ||
| Specifies current server connection object. | ||
|
|
||
| .PARAMETER Name | ||
| Specifies the name of the database to get. If not specified, all | ||
| databases are returned. | ||
|
|
||
| .PARAMETER Refresh | ||
| Specifies that the **ServerObject**'s databases should be refreshed before | ||
| trying to get the database object. This is helpful when databases could have been | ||
| modified outside of the **ServerObject**, for example through T-SQL. But | ||
| on instances with a large amount of databases it might be better to make | ||
| sure the **ServerObject** is recent enough. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' | ||
| $serverObject | Get-SqlDscDatabase | ||
|
|
||
| Get all databases from the instance. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' | ||
| $serverObject | Get-SqlDscDatabase -Name 'MyDatabase' | ||
|
|
||
| Get the database named **MyDatabase**. | ||
|
|
||
| .OUTPUTS | ||
| `[Microsoft.SqlServer.Management.Smo.Database[]]` | ||
| #> | ||
| function Get-SqlDscDatabase | ||
| { | ||
| [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([Microsoft.SqlServer.Management.Smo.Database[]])] | ||
| [CmdletBinding()] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | ||
| [Microsoft.SqlServer.Management.Smo.Server] | ||
| $ServerObject, | ||
|
|
||
| [Parameter()] | ||
| [System.String] | ||
| $Name, | ||
|
|
||
| [Parameter()] | ||
| [System.Management.Automation.SwitchParameter] | ||
| $Refresh | ||
| ) | ||
|
|
||
| process | ||
| { | ||
| if ($Refresh.IsPresent) | ||
| { | ||
| # Refresh the server object's databases collection | ||
| $ServerObject.Databases.Refresh() | ||
| } | ||
|
|
||
| Write-Verbose -Message ($script:localizedData.Database_Get -f $ServerObject.InstanceName) | ||
|
|
||
| $databaseObject = @() | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('Name')) | ||
| { | ||
| $databaseObject = $ServerObject.Databases[$Name] | ||
|
|
||
| if (-not $databaseObject) | ||
| { | ||
| Write-Verbose -Message ($script:localizedData.Database_NotFound -f $Name) | ||
|
|
||
| $missingDatabaseMessage = $script:localizedData.Database_NotFound -f $Name | ||
|
|
||
| $writeErrorParameters = @{ | ||
| Message = $missingDatabaseMessage | ||
| Category = 'ObjectNotFound' | ||
| ErrorId = 'GSDD0001' # cspell: disable-line | ||
| TargetObject = $Name | ||
| } | ||
|
|
||
| Write-Error @writeErrorParameters | ||
| } | ||
| else | ||
| { | ||
| Write-Verbose -Message ($script:localizedData.Database_Found -f $Name) | ||
| } | ||
| } | ||
| else | ||
| { | ||
| Write-Verbose -Message ($script:localizedData.Database_GetAll) | ||
|
|
||
| $databaseObject = $ServerObject.Databases | ||
| } | ||
|
|
||
| return [Microsoft.SqlServer.Management.Smo.Database[]] $databaseObject | ||
| } | ||
| } |
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,206 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Creates a new database in a SQL Server Database Engine instance. | ||
|
|
||
| .DESCRIPTION | ||
| This command creates a new database in a SQL Server Database Engine instance. | ||
|
|
||
| .PARAMETER ServerObject | ||
| Specifies current server connection object. | ||
|
|
||
| .PARAMETER Name | ||
| Specifies the name of the database to be created. | ||
|
|
||
| .PARAMETER Collation | ||
| The name of the SQL collation to use for the new database. | ||
| Default value is server collation. | ||
|
|
||
| .PARAMETER CompatibilityLevel | ||
| The version of the SQL compatibility level to use for the new database. | ||
| Default value is server version. | ||
|
|
||
| .PARAMETER RecoveryModel | ||
| The recovery model to be used for the new database. | ||
| Default value is Full. | ||
|
|
||
| .PARAMETER OwnerName | ||
| Specifies the name of the login that should be the owner of the database. | ||
|
|
||
| .PARAMETER Force | ||
| Specifies that the database should be created without any confirmation. | ||
|
|
||
| .PARAMETER Refresh | ||
| Specifies that the **ServerObject**'s databases should be refreshed before | ||
| creating the database object. This is helpful when databases could have been | ||
| modified outside of the **ServerObject**, for example through T-SQL. But | ||
| on instances with a large amount of databases it might be better to make | ||
| sure the **ServerObject** is recent enough. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' | ||
| $serverObject | New-SqlDscDatabase -Name 'MyDatabase' | ||
|
|
||
| Creates a new database named **MyDatabase**. | ||
|
|
||
| .EXAMPLE | ||
| $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance' | ||
| $serverObject | New-SqlDscDatabase -Name 'MyDatabase' -Collation 'SQL_Latin1_General_Pref_CP850_CI_AS' -RecoveryModel 'Simple' -Force | ||
|
|
||
| Creates a new database named **MyDatabase** with the specified collation and recovery model | ||
| without prompting for confirmation. | ||
|
|
||
| .OUTPUTS | ||
| `[Microsoft.SqlServer.Management.Smo.Database]` | ||
| #> | ||
| function New-SqlDscDatabase | ||
| { | ||
| [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([Microsoft.SqlServer.Management.Smo.Database])] | ||
| [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | ||
| [Microsoft.SqlServer.Management.Smo.Server] | ||
| $ServerObject, | ||
|
|
||
| [Parameter(Mandatory = $true)] | ||
| [ValidateNotNullOrEmpty()] | ||
| [System.String] | ||
| $Name, | ||
|
|
||
| [Parameter()] | ||
| [ValidateNotNullOrEmpty()] | ||
| [System.String] | ||
| $Collation, | ||
|
|
||
| [Parameter()] | ||
| [ValidateSet('Version80', 'Version90', 'Version100', 'Version110', 'Version120', 'Version130', 'Version140', 'Version150', 'Version160')] | ||
| [System.String] | ||
| $CompatibilityLevel, | ||
|
|
||
| [Parameter()] | ||
| [ValidateSet('Simple', 'Full', 'BulkLogged')] | ||
| [System.String] | ||
| $RecoveryModel, | ||
|
|
||
| [Parameter()] | ||
| [System.String] | ||
| $OwnerName, | ||
|
|
||
| [Parameter()] | ||
| [System.Management.Automation.SwitchParameter] | ||
| $Force, | ||
|
|
||
| [Parameter()] | ||
| [System.Management.Automation.SwitchParameter] | ||
| $Refresh | ||
| ) | ||
|
|
||
| begin | ||
| { | ||
| if ($Force.IsPresent -and -not $Confirm) | ||
| { | ||
| $ConfirmPreference = 'None' | ||
| } | ||
| } | ||
|
|
||
| process | ||
| { | ||
| if ($Refresh.IsPresent) | ||
| { | ||
| # Refresh the server object's databases collection | ||
| $ServerObject.Databases.Refresh() | ||
| } | ||
|
|
||
| Write-Verbose -Message ($script:localizedData.Database_Create -f $Name, $ServerObject.InstanceName) | ||
|
|
||
| # Check if the database already exists | ||
| if ($ServerObject.Databases[$Name]) | ||
| { | ||
| $errorMessage = $script:localizedData.Database_AlreadyExists -f $Name, $ServerObject.InstanceName | ||
| New-InvalidOperationException -Message $errorMessage | ||
| } | ||
|
|
||
| # Validate compatibility level if specified | ||
| if ($PSBoundParameters.ContainsKey('CompatibilityLevel')) | ||
| { | ||
| $supportedCompatibilityLevels = @{ | ||
| 8 = @('Version80') | ||
| 9 = @('Version80', 'Version90') | ||
| 10 = @('Version80', 'Version90', 'Version100') | ||
| 11 = @('Version90', 'Version100', 'Version110') | ||
| 12 = @('Version100', 'Version110', 'Version120') | ||
| 13 = @('Version100', 'Version110', 'Version120', 'Version130') | ||
| 14 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140') | ||
| 15 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140', 'Version150') | ||
| 16 = @('Version100', 'Version110', 'Version120', 'Version130', 'Version140', 'Version150', 'Version160') | ||
| } | ||
|
|
||
| if ($CompatibilityLevel -notin $supportedCompatibilityLevels.$($ServerObject.VersionMajor)) | ||
| { | ||
| $errorMessage = $script:localizedData.Database_InvalidCompatibilityLevel -f $CompatibilityLevel, $ServerObject.InstanceName | ||
| New-InvalidArgumentException -ArgumentName 'CompatibilityLevel' -Message $errorMessage | ||
| } | ||
| } | ||
|
|
||
| # Validate collation if specified | ||
| if ($PSBoundParameters.ContainsKey('Collation')) | ||
| { | ||
| if ($Collation -notin $ServerObject.EnumCollations().Name) | ||
| { | ||
| $errorMessage = $script:localizedData.Database_InvalidCollation -f $Collation, $ServerObject.InstanceName | ||
johlju marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| New-InvalidArgumentException -ArgumentName 'Collation' -Message $errorMessage | ||
| } | ||
| } | ||
|
|
||
| $verboseDescriptionMessage = $script:localizedData.Database_Create_ShouldProcessVerboseDescription -f $Name, $ServerObject.InstanceName | ||
| $verboseWarningMessage = $script:localizedData.Database_Create_ShouldProcessVerboseWarning -f $Name | ||
| $captionMessage = $script:localizedData.Database_Create_ShouldProcessCaption | ||
|
|
||
| if ($PSCmdlet.ShouldProcess($verboseDescriptionMessage, $verboseWarningMessage, $captionMessage)) | ||
| { | ||
| try | ||
| { | ||
| $sqlDatabaseObjectToCreate = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Database' -ArgumentList $ServerObject, $Name | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('RecoveryModel')) | ||
| { | ||
| $sqlDatabaseObjectToCreate.RecoveryModel = $RecoveryModel | ||
| } | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('Collation')) | ||
| { | ||
| $sqlDatabaseObjectToCreate.Collation = $Collation | ||
| } | ||
|
|
||
| if ($PSBoundParameters.ContainsKey('CompatibilityLevel')) | ||
| { | ||
| $sqlDatabaseObjectToCreate.CompatibilityLevel = $CompatibilityLevel | ||
| } | ||
|
|
||
| Write-Verbose -Message ($script:localizedData.Database_Creating -f $Name) | ||
|
|
||
| $sqlDatabaseObjectToCreate.Create() | ||
|
|
||
| <# | ||
| This must be run after the object is created because | ||
| the owner property is read-only and the method cannot | ||
| be call until the object has been created. | ||
| #> | ||
| if ($PSBoundParameters.ContainsKey('OwnerName')) | ||
| { | ||
| $sqlDatabaseObjectToCreate.SetOwner($OwnerName) | ||
| } | ||
|
|
||
| Write-Verbose -Message ($script:localizedData.Database_Created -f $Name) | ||
|
|
||
| return $sqlDatabaseObjectToCreate | ||
| } | ||
| catch | ||
| { | ||
| $errorMessage = $script:localizedData.Database_CreateFailed -f $Name, $ServerObject.InstanceName | ||
| New-InvalidOperationException -Message $errorMessage -ErrorRecord $_ | ||
| } | ||
| } | ||
| } | ||
| } | ||
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.