functions/New-DbaDbTable.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
function New-DbaDbTable {
    <#
    .SYNOPSIS
        Creates a new table in a database
 
    .DESCRIPTION
        Creates a new table in a database
 
   .PARAMETER SqlInstance
       The target SQL Server instance or instances.
 
    .PARAMETER SqlCredential
       Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER Database
        The database or databases where the table will be created
 
    .PARAMETER Name
        The name of the table
 
    .PARAMETER Schema
        The schema for the table, defaults to dbo
 
    .PARAMETER ColumnMap
        Hashtable for easy column creation. Looks like this:
 
        # Create collection
        $cols = @()
 
        # Add columns to collection
        $cols += @{
            Name = 'test'
            Type = 'varchar'
            MaxLength = 20
            Nullable = $true
        }
        $cols += @{
            Name = 'test2'
            Type = 'int'
            Nullable = $false
        }
 
    .PARAMETER ColumnObject
        If you want to get fancy, you can build your own column objects and pass them in
 
    .PARAMETER InputObject
        Allows piped input from Get-DbaDatabase
 
    .PARAMETER AnsiNullsStatus
        No information provided by Microsoft
 
    .PARAMETER ChangeTrackingEnabled
        No information provided by Microsoft
 
    .PARAMETER DataSourceName
        No information provided by Microsoft
 
    .PARAMETER Durability
        No information provided by Microsoft
 
    .PARAMETER ExternalTableDistribution
        No information provided by Microsoft
 
    .PARAMETER FileFormatName
        No information provided by Microsoft
 
    .PARAMETER FileGroup
        No information provided by Microsoft
 
    .PARAMETER FileStreamFileGroup
        No information provided by Microsoft
 
    .PARAMETER FileStreamPartitionScheme
        No information provided by Microsoft
 
    .PARAMETER FileTableDirectoryName
        No information provided by Microsoft
 
    .PARAMETER FileTableNameColumnCollation
        No information provided by Microsoft
 
    .PARAMETER FileTableNamespaceEnabled
        No information provided by Microsoft
 
    .PARAMETER HistoryTableName
        No information provided by Microsoft
 
    .PARAMETER HistoryTableSchema
        No information provided by Microsoft
 
    .PARAMETER IsExternal
        No information provided by Microsoft
 
    .PARAMETER IsFileTable
        No information provided by Microsoft
 
    .PARAMETER IsMemoryOptimized
        No information provided by Microsoft
 
    .PARAMETER IsSystemVersioned
        No information provided by Microsoft
 
    .PARAMETER Location
        No information provided by Microsoft
 
    .PARAMETER LockEscalation
        No information provided by Microsoft
 
    .PARAMETER Owner
        No information provided by Microsoft
 
    .PARAMETER PartitionScheme
        No information provided by Microsoft
 
    .PARAMETER QuotedIdentifierStatus
        No information provided by Microsoft
 
    .PARAMETER RejectSampleValue
        No information provided by Microsoft
 
    .PARAMETER RejectType
        No information provided by Microsoft
 
    .PARAMETER RejectValue
        No information provided by Microsoft
 
    .PARAMETER RemoteDataArchiveDataMigrationState
        No information provided by Microsoft
 
    .PARAMETER RemoteDataArchiveEnabled
        No information provided by Microsoft
 
    .PARAMETER RemoteDataArchiveFilterPredicate
        No information provided by Microsoft
 
    .PARAMETER RemoteObjectName
        No information provided by Microsoft
 
    .PARAMETER RemoteSchemaName
        No information provided by Microsoft
 
    .PARAMETER RemoteTableName
        No information provided by Microsoft
 
    .PARAMETER RemoteTableProvisioned
        No information provided by Microsoft
 
    .PARAMETER ShardingColumnName
        No information provided by Microsoft
 
    .PARAMETER TextFileGroup
        No information provided by Microsoft
 
    .PARAMETER TrackColumnsUpdatedEnabled
        No information provided by Microsoft
 
    .PARAMETER HistoryRetentionPeriod
        No information provided by Microsoft
 
    .PARAMETER HistoryRetentionPeriodUnit
        No information provided by Microsoft
 
    .PARAMETER DwTableDistribution
        No information provided by Microsoft
 
    .PARAMETER RejectedRowLocation
        No information provided by Microsoft
 
    .PARAMETER OnlineHeapOperation
        No information provided by Microsoft
 
    .PARAMETER LowPriorityMaxDuration
        No information provided by Microsoft
 
    .PARAMETER DataConsistencyCheck
        No information provided by Microsoft
 
    .PARAMETER LowPriorityAbortAfterWait
        No information provided by Microsoft
 
    .PARAMETER MaximumDegreeOfParallelism
        No information provided by Microsoft
 
    .PARAMETER IsNode
        No information provided by Microsoft
 
    .PARAMETER IsEdge
        No information provided by Microsoft
 
    .PARAMETER IsVarDecimalStorageFormatEnabled
        No information provided by Microsoft
 
    .PARAMETER WhatIf
       Shows what would happen if the command were to run. No actions are actually performed.
 
    .PARAMETER Confirm
       Prompts you for confirmation before executing any changing operations within the command.
 
    .PARAMETER EnableException
       By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
       This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
       Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
    .NOTES
       Tags: table
       Author: Chrissy LeMaire (@cl)
       Website: https://dbatools.io
       Copyright: (c) 2019 by dbatools, licensed under MIT
       License: MIT https://opensource.org/licenses/MIT
 
    .LINK
       https://dbatools.io/Get-Table
 
    .EXAMPLE
       PS C:\> $col = @{
        >> Name = 'test'
        >> Type = 'varchar'
        >> MaxLength = 20
        >> Nullable = $true
        >> }
       PS C:\> New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $col
 
       Creates a new table on sql2017 in tempdb witht he name testtable and one column
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [String[]]$Database,
        [String]$Name,
        [String]$Schema = "dbo",
        [hashtable[]]$ColumnMap,
        [Microsoft.SqlServer.Management.Smo.Column[]]$ColumnObject,
        [Switch]$AnsiNullsStatus,
        [Switch]$ChangeTrackingEnabled,
        [String]$DataSourceName,
        [Microsoft.SqlServer.Management.Smo.DurabilityType]$Durability,
        [Microsoft.SqlServer.Management.Smo.ExternalTableDistributionType]$ExternalTableDistribution,
        [String]$FileFormatName,
        [String]$FileGroup,
        [String]$FileStreamFileGroup,
        [String]$FileStreamPartitionScheme,
        [String]$FileTableDirectoryName,
        [String]$FileTableNameColumnCollation,
        [Switch]$FileTableNamespaceEnabled,
        [String]$HistoryTableName,
        [String]$HistoryTableSchema,
        [Switch]$IsExternal,
        [Switch]$IsFileTable,
        [Switch]$IsMemoryOptimized,
        [Switch]$IsSystemVersioned,
        [String]$Location,
        [Microsoft.SqlServer.Management.Smo.LockEscalationType]$LockEscalation,
        [String]$Owner,
        [String]$PartitionScheme,
        [Switch]$QuotedIdentifierStatus,
        [Double]$RejectSampleValue,
        [Microsoft.SqlServer.Management.Smo.ExternalTableRejectType]$RejectType,
        [Double]$RejectValue,
        [Microsoft.SqlServer.Management.Smo.RemoteDataArchiveMigrationState]$RemoteDataArchiveDataMigrationState,
        [Switch]$RemoteDataArchiveEnabled,
        [String]$RemoteDataArchiveFilterPredicate,
        [String]$RemoteObjectName,
        [String]$RemoteSchemaName,
        [String]$RemoteTableName,
        [Switch]$RemoteTableProvisioned,
        [String]$ShardingColumnName,
        [String]$TextFileGroup,
        [Switch]$TrackColumnsUpdatedEnabled,
        [Int32]$HistoryRetentionPeriod,
        [Microsoft.SqlServer.Management.Smo.TemporalHistoryRetentionPeriodUnit]$HistoryRetentionPeriodUnit,
        [Microsoft.SqlServer.Management.Smo.DwTableDistributionType]$DwTableDistribution,
        [String]$RejectedRowLocation,
        [Switch]$OnlineHeapOperation,
        [Int32]$LowPriorityMaxDuration,
        [Switch]$DataConsistencyCheck,
        [Microsoft.SqlServer.Management.Smo.AbortAfterWait]$LowPriorityAbortAfterWait,
        [Int32]$MaximumDegreeOfParallelism,
        [Switch]$IsNode,
        [Switch]$IsEdge,
        [Switch]$IsVarDecimalStorageFormatEnabled,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        function Get-SqlType {
            param([string]$TypeName)
            switch ($TypeName) {
                'Boolean' { [Data.SqlDbType]::Bit }
                'Byte[]' { [Data.SqlDbType]::VarBinary }
                'Byte' { [Data.SQLDbType]::VarBinary }
                'Datetime' { [Data.SQLDbType]::DateTime }
                'Decimal' { [Data.SqlDbType]::Decimal }
                'Double' { [Data.SqlDbType]::Float }
                'Guid' { [Data.SqlDbType]::UniqueIdentifier }
                'Int16' { [Data.SQLDbType]::SmallInt }
                'Int32' { [Data.SQLDbType]::Int }
                'Int64' { [Data.SqlDbType]::BigInt }
                'UInt16' { [Data.SQLDbType]::SmallInt }
                'UInt32' { [Data.SQLDbType]::Int }
                'UInt64' { [Data.SqlDbType]::BigInt }
                'Single' { [Data.SqlDbType]::Decimal }
                default { [Data.SqlDbType]::VarChar }
            }
        }
    }
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Database) -or (Test-Bound -Not -ParameterName Name)) {
                Stop-Function -Message "You must specify one or more databases and one Name when using the SqlInstance parameter."
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent
            if ($Pscmdlet.ShouldProcess("Creating new object $name in $db on $server")) {
                try {
                    $object = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Table $db, $name, $schema
                    $properties = $PSBoundParameters | Where-Object Key -notin 'SqlInstance', 'SqlCredential', 'Name', 'Schema', 'ColumnMap', 'ColumnObject', 'InputObject', 'EnableException', 'Passthru'

                    foreach ($prop in $properties.Key) {
                        $object.$prop = $prop
                    }

                    foreach ($column in $ColumnObject) {
                        $object.Columns.Add($column)
                    }

                    foreach ($column in $ColumnMap) {
                        $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]$($column.Type)
                        if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') {
                            if ($column.MaxLength -gt 0) {
                                $dataType = New-Object Microsoft.SqlServer.Management.Smo.DataType $sqlDbType, $maxlength
                            } else {
                                $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max"
                                $dataType = New-Object Microsoft.SqlServer.Management.Smo.DataType $sqlDbType
                            }
                        } else {
                            $dataType = New-Object Microsoft.SqlServer.Management.Smo.DataType $sqlDbType
                        }
                        $sqlcolumn = New-Object Microsoft.SqlServer.Management.Smo.Column $object, $column.Name, $dataType
                        $sqlcolumn.Nullable = $column.Nullable
                        $object.Columns.Add($sqlcolumn)
                    }

                    if ($Passthru) {
                        $object.Script()
                    } else {
                        $null = Invoke-Create -Object $object
                    }
                    $db | Get-DbaDbTable -Table $Name
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}