Skip to content

Commit 118aed5

Browse files
New-DbaDbTable - Handle bracket-quoted names and two-part names (#10279)
1 parent f73e441 commit 118aed5

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

public/New-DbaDbTable.ps1

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,20 @@ function New-DbaDbTable {
468468
}
469469
}
470470

471+
# Parse the Name parameter to handle bracket-quoted names and two-part names like [schema].[table]
472+
if (Test-Bound -ParameterName Name) {
473+
$parsedName = Get-ObjectNameParts -ObjectName $Name
474+
if ($parsedName.Parsed) {
475+
if ($parsedName.Schema -and -not (Test-Bound -ParameterName Schema)) {
476+
$Schema = $parsedName.Schema
477+
}
478+
$Name = $parsedName.Name
479+
} else {
480+
Stop-Function -Message "Could not parse -Name '$Name' as a valid object name."
481+
return
482+
}
483+
}
484+
471485
foreach ($instance in $SqlInstance) {
472486
$InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
473487
}

tests/New-DbaDbTable.Tests.ps1

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,37 @@ Describe $CommandName -Tag IntegrationTests {
224224
$tableWithSchema[2] | Should -Match "$tableName"
225225
}
226226
}
227+
Context "Should handle bracket-quoted names and two-part names" {
228+
BeforeAll {
229+
$map = @{
230+
Name = "testId"
231+
Type = "int"
232+
}
233+
}
234+
It "Strips brackets from a bracket-quoted table name" {
235+
$random = Get-Random
236+
$tableName = "table_bracket_$random"
237+
$result = New-DbaDbTable -SqlInstance $TestConfig.InstanceMulti1 -Database $dbname -Name "[$tableName]" -ColumnMap $map
238+
$result.Name | Should -Be $tableName
239+
$result.Schema | Should -Be "dbo"
240+
}
241+
It "Parses schema and table from a two-part bracket-quoted name" {
242+
$random = Get-Random
243+
$tableName = "table_twopart_$random"
244+
$schemaName = "schema_twopart_$random"
245+
$result = New-DbaDbTable -SqlInstance $TestConfig.InstanceMulti1 -Database $dbname -Name "[$schemaName].[$tableName]" -ColumnMap $map
246+
$result.Name | Should -Be $tableName
247+
$result.Schema | Should -Be $schemaName
248+
}
249+
It "Parses schema and table from a two-part unquoted name" {
250+
$random = Get-Random
251+
$tableName = "table_unquoted_$random"
252+
$schemaName = "schema_unquoted_$random"
253+
$result = New-DbaDbTable -SqlInstance $TestConfig.InstanceMulti1 -Database $dbname -Name "$schemaName.$tableName" -ColumnMap $map
254+
$result.Name | Should -Be $tableName
255+
$result.Schema | Should -Be $schemaName
256+
}
257+
}
227258
Context "Should create graph tables with IsNode and IsEdge switches" {
228259
BeforeAll {
229260
$server = Connect-DbaInstance -SqlInstance $TestConfig.InstanceMulti2

0 commit comments

Comments
 (0)