-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathAzureSQLDataSyncHealthChecker.ps1
More file actions
2836 lines (2533 loc) · 138 KB
/
AzureSQLDataSyncHealthChecker.ps1
File metadata and controls
2836 lines (2533 loc) · 138 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Copyright (c) Microsoft Corporation.
#Licensed under the MIT license.
#Azure SQL Data Sync Health Checker
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Databases and credentials
# Sync metadata database credentials (Only SQL Authentication is supported)
$SyncDbServer = '.database.windows.net'
$SyncDbDatabase = ''
$SyncDbUser = ''
$SyncDbPassword = ''
# Hub credentials (Only SQL Authentication is supported)
$HubServer = '.database.windows.net'
$HubDatabase = ''
$HubUser = ''
$HubPassword = ''
# Member credentials (Azure SQL DB or SQL Server)
$MemberServer = ''
$MemberDatabase = ''
$MemberUser = ''
$MemberPassword = ''
# set MemberUseWindowsAuthentication to $true in case you wish to use integrated Windows authentication (MemberUser and MemberPassword will be ignored)
$MemberUseWindowsAuthentication = $false
## Optional parameters (default values will be used if ommited)
## Health checks
$HealthChecksEnabled = $true #Set as $true (default) or $false
## Monitoring
$MonitoringMode = 'AUTO' #Set as AUTO (default), ENABLED or DISABLED
$MonitoringIntervalInSeconds = 20
$MonitoringDurationInMinutes = 1
## Tracking Record Validations
$ExtendedValidationsTableFilter = @('All') #Set as "All" or the tables you need using '[dbo].[TableName1]','[dbo].[TableName2]'
$ExtendedValidationsEnabledForHub = $true #Set as $true (default) or $false
$ExtendedValidationsEnabledForMember = $true #Set as $true (default) or $false
$ExtendedValidationsCommandTimeout = 900 #seconds (default)
## Other
$SendAnonymousUsageData = $true #Set as $true (default) or $false
$DumpMetadataSchemasForSyncGroup = '' #leave empty for automatic detection
$DumpMetadataObjectsForTable = '' #needs to be formatted like [SchemaName].[TableName]
#####################################################################################################
# Parameter region when Invoke-Command -ScriptBlock is used
$parameters = $args[0]
if ($null -ne $parameters) {
## Databases and credentials
# Sync metadata database credentials (Only SQL Authentication is supported)
$SyncDbServer = $parameters['SyncDbServer']
$SyncDbDatabase = $parameters['SyncDbDatabase']
$SyncDbUser = $parameters['SyncDbUser']
$SyncDbPassword = $parameters['SyncDbPassword']
# Hub credentials (Only SQL Authentication is supported)
$HubServer = $parameters['HubServer']
$HubDatabase = $parameters['HubDatabase']
$HubUser = $parameters['HubUser']
$HubPassword = $parameters['HubPassword']
# Member credentials (Azure SQL DB or SQL Server)
$MemberServer = $parameters['MemberServer']
$MemberDatabase = $parameters['MemberDatabase']
$MemberUser = $parameters['MemberUser']
$MemberPassword = $parameters['MemberPassword']
# set MemberUseWindowsAuthentication to $true in case you wish to use integrated Windows authentication (MemberUser and MemberPassword will be ignored)
$MemberUseWindowsAuthentication = $false
if ($parameters['MemberUseWindowsAuthentication']) {
$MemberUseWindowsAuthentication = $parameters['MemberUseWindowsAuthentication']
}
## Health checks
$HealthChecksEnabled = $true #Set as $true or $false
if ($null -ne $parameters['HealthChecksEnabled']) {
$HealthChecksEnabled = $parameters['HealthChecksEnabled']
}
## Monitoring
if ($null -ne $parameters['MonitoringMode']) {
$MonitoringMode = $parameters['MonitoringMode']
}
if ($null -ne $parameters['MonitoringIntervalInSeconds']) {
$MonitoringIntervalInSeconds = $parameters['MonitoringIntervalInSeconds']
}
if ($null -ne $parameters['MonitoringDurationInMinutes']) {
$MonitoringDurationInMinutes = $parameters['MonitoringDurationInMinutes']
}
## Tracking Record Validations
# Set as "All" to validate all tables
# or pick the tables you need using '[dbo].[TableName1]','[dbo].[TableName2]'
$ExtendedValidationsTableFilter = @('All')
if ($null -ne $parameters['ExtendedValidationsTableFilter']) {
$ExtendedValidationsTableFilter = $parameters['ExtendedValidationsTableFilter']
}
if ($null -ne $parameters['ExtendedValidationsEnabledForHub']) {
$ExtendedValidationsEnabledForHub = $parameters['ExtendedValidationsEnabledForHub']
}
if ($null -ne $parameters['ExtendedValidationsEnabledForMember']) {
$ExtendedValidationsEnabledForMember = $parameters['ExtendedValidationsEnabledForMember']
}
if ($null -ne $parameters['ExtendedValidationsCommandTimeout']) {
$ExtendedValidationsCommandTimeout = $parameters['ExtendedValidationsCommandTimeout']
}
## Other
if ($null -ne $parameters['SendAnonymousUsageData']) {
$SendAnonymousUsageData = $parameters['SendAnonymousUsageData']
}
if ($null -ne $parameters['DumpMetadataSchemasForSyncGroup']) {
$DumpMetadataSchemasForSyncGroup = $parameters['DumpMetadataSchemasForSyncGroup']
}
if ($null -ne $parameters['DumpMetadataObjectsForTable']) {
$DumpMetadataObjectsForTable = $parameters['DumpMetadataObjectsForTable']
}
}
#####################################################################################################
$cmdTimeout = 300
function ValidateTablesVSLocalSchema([Array] $userTables) {
Try {
if ($userTables.Count -eq 0) {
$msg = "WARNING: member schema with 0 tables was detected, maybe related to provisioning issues."
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine()
[void]$errorSummary.AppendLine($msg)
}
else {
Write-Host Schema has $userTables.Count tables
}
foreach ($userTable in $userTables) {
$TablePKList = New-Object System.Collections.ArrayList
$query = "SELECT
c.name 'ColumnName',
t.Name 'Datatype',
c.max_length 'MaxLength',
c.is_nullable 'IsNullable',
c.is_computed 'IsComputed',
c.default_object_id 'DefaultObjectId'
FROM sys.columns c
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID('" + $userTable + "')"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
foreach ($userColumn in $datatable) {
$sbCol = New-Object -TypeName "System.Text.StringBuilder"
$schemaObj = $global:scope_config_data.SqlSyncProviderScopeConfiguration.Adapter | Where-Object GlobalName -eq $userTable
$schemaColumn = $schemaObj.Col | Where-Object Name -eq $userColumn.ColumnName
if (!$schemaColumn) {
if (($userColumn.IsNullable -eq $false) -and ($userColumn.IsComputed -eq $false) -and ($userColumn.DefaultObjectId -eq 0) ) {
$msg = "WARNING: " + $userTable + ".[" + $userColumn.ColumnName + "] is not included in the sync group but is NOT NULLABLE, not a computed column or has a default value!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
continue
}
[void]$sbCol.Append($userTable + ".[" + $userColumn.ColumnName + "] " + $schemaColumn.param)
if ($schemaColumn.pk) {
[void]$sbCol.Append(" PrimaryKey ")
[void]$TablePKList.Add($schemaColumn.name)
}
if ($schemaColumn.type -ne $userColumn.Datatype) {
[void]$sbCol.Append(' Type(' + $schemaColumn.type + '):NOK ')
$msg = "WARNING: " + $userTable + ".[" + $userColumn.ColumnName + "] has a different datatype! (table:" + $userColumn.Datatype + " VS scope:" + $schemaColumn.type + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
[void]$sbCol.Append(' Type(' + $schemaColumn.type + '):OK ')
}
$colMaxLen = $userColumn.MaxLength
if ($schemaColumn.type -eq 'nvarchar' -or $schemaColumn.type -eq 'nchar') { $colMaxLen = $colMaxLen / 2 }
if ($userColumn.MaxLength -eq -1 -and ($schemaColumn.type -eq 'nvarchar' -or $schemaColumn.type -eq 'nchar' -or $schemaColumn.type -eq 'varbinary' -or $schemaColumn.type -eq 'varchar' -or $schemaColumn.type -eq 'nvarchar')) { $colMaxLen = 'max' }
if ($schemaColumn.size -ne $colMaxLen) {
[void]$sbCol.Append(' Size(' + $schemaColumn.size + '):NOK ')
$msg = "WARNING: " + $userTable + ".[" + $userColumn.ColumnName + "] has a different data size!(table:" + $colMaxLen + " VS scope:" + $schemaColumn.size + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
[void]$sbCol.Append(' Size(' + $schemaColumn.size + '):OK ')
}
if ($schemaColumn.null) {
if ($schemaColumn.null -ne $userColumn.IsNullable) {
[void]$sbCol.Append(' Nullable(' + $schemaColumn.null + '):NOK ')
$msg = "WARNING: " + $userTable + ".[" + $userColumn.ColumnName + "] has a different IsNullable! (table:" + $userColumn.IsNullable + " VS scope:" + $schemaColumn.null + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
[void]$sbCol.Append(' Nullable(' + $schemaColumn.null + '):OK ')
}
}
$sbColString = $sbCol.ToString()
if ($sbColString -match 'NOK') { Write-Host $sbColString -ForegroundColor Red } else { Write-Host $sbColString -ForegroundColor Green }
}
if ($ExtendedValidationsEnabled -and (($ExtendedValidationsTableFilter -contains 'All') -or ($ExtendedValidationsTableFilter -contains $userTable))) {
ValidateTrackingRecords $userTable $TablePKList
}
}
}
Catch {
Write-Host ValidateTablesVSLocalSchema exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ShowRowCountAndFragmentation([Array] $userTables) {
Try {
$tablesList = New-Object System.Collections.ArrayList
foreach ($item in $userTables) {
$tablesList.Add($item) > $null
$tablesList.Add('[DataSync].[' + ($item.Replace("[", "").Replace("]", "").Split('.')[1]) + '_dss_tracking]') > $null
}
$tablesListStr = "'$($tablesList -join "','")'"
Write-Host "Row Counts:"
$query = "SELECT
'['+s.name+'].['+ t.name+']' as TableName,
p.rows AS RowCounts,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE '['+s.name+'].['+ t.name+']' IN (" + $tablesListStr + ")
GROUP BY t.Name, s.Name, p.Rows
ORDER BY '['+s.name+'].['+ t.name+']'"
$MemberCommand.CommandTimeout = $cmdTimeout
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows.Count -gt 0) {
$datatable | Format-Table -Wrap -AutoSize | Out-String -Width 4096
}
Write-Host "Fragmentation:"
$query = "SELECT '['+s.[name]+'].['+ t.[name]+']' as TableName, i.[name] as [IndexName],
CONVERT(DECIMAL(10,2),idxstats.avg_fragmentation_in_percent) as FragmentationPercent,
idxstats.page_count AS [PageCount]
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS idxstats
INNER JOIN sys.tables t on t.[object_id] = idxstats.[object_id]
INNER JOIN sys.schemas s on t.[schema_id] = s.[schema_id]
INNER JOIN sys.indexes AS i ON i.[object_id] = idxstats.[object_id] AND idxstats.index_id = i.index_id
WHERE '['+s.name+'].['+ t.name+']' IN (" + $tablesListStr + ")
AND idxstats.database_id = DB_ID() AND idxstats.avg_fragmentation_in_percent >= 5
ORDER BY idxstats.avg_fragmentation_in_percent desc"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows.Count -gt 0) {
$datatable | Format-Table -Wrap -AutoSize | Out-String -Width 4096
}
else {
Write-Host "- No relevant fragmentation (>5%) detected" -ForegroundColor Green
Write-Host
}
}
Catch {
Write-Host ShowRowCountAndFragmentation exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateTablesVSSyncDbSchema($SyncDbScopes) {
Try {
foreach ($SyncDbScope in $SyncDbScopes) {
Write-Host 'Validating Table(s) VS SyncDB for' $SyncDbScope.SyncGroupName':' -Foreground White
$ValidateTablesVSSyncDbSchemaIssuesFound = $false
$syncdbscopeobj = ([xml]$SyncDbScope.SchemaDescription).DssSyncScopeDescription.TableDescriptionCollection.DssTableDescription
$syncGroupSchemaTables = $syncdbscopeobj | Select-Object -ExpandProperty QuotedTableName
foreach ($syncGroupSchemaTable in $syncGroupSchemaTables) {
$syncGroupSchemaColumns = $syncdbscopeobj | Where-Object { $_.QuotedTableName -eq $syncGroupSchemaTable } | Select-Object -ExpandProperty ColumnsToSync
$query = "SELECT
c.name 'ColumnName',
t.Name 'Datatype',
c.max_length 'MaxLength',
c.is_nullable 'IsNullable'
FROM sys.columns c
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID('" + $syncGroupSchemaTable + "')"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows.Count -eq 0) {
$ValidateTablesVSSyncDbSchemaIssuesFound = $true
$msg = "WARNING: " + $syncGroupSchemaTable + " does not exist in the database but exist in the sync group schema."
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
foreach ($syncGroupSchemaColumn in $syncGroupSchemaColumns.DssColumnDescription) {
$scopeCol = $datatable | Where-Object ColumnName -eq $syncGroupSchemaColumn.Name
if (!$scopeCol) {
$ValidateTablesVSSyncDbSchemaIssuesFound = $true
$msg = "WARNING: " + $syncGroupSchemaTable + ".[" + $syncGroupSchemaColumn.Name + "] is missing in this database but exist in sync group schema, maybe preventing provisioning/re-provisioning!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
if ($syncGroupSchemaColumn.DataType -ne $scopeCol.Datatype) {
$ValidateTablesVSSyncDbSchemaIssuesFound = $true
$msg = "WARNING: " + $syncGroupSchemaTable + ".[" + $syncGroupSchemaColumn.Name + "] has a different datatype! (" + $syncGroupSchemaColumn.DataType + " VS " + $scopeCol.Datatype + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
$colMaxLen = $scopeCol.MaxLength
if ($syncGroupSchemaColumn.DataType -eq 'nvarchar' -or $syncGroupSchemaColumn.DataType -eq 'nchar') { $colMaxLen = $colMaxLen / 2 }
if ($scopeCol.MaxLength -eq -1 -and ($syncGroupSchemaColumn.DataType -eq 'nvarchar' -or $syncGroupSchemaColumn.DataType -eq 'nchar' -or $syncGroupSchemaColumn.DataType -eq 'varbinary' -or $syncGroupSchemaColumn.DataType -eq 'varchar' -or $syncGroupSchemaColumn.DataType -eq 'nvarchar')) { $colMaxLen = 'max' }
if ($syncGroupSchemaColumn.DataSize -ne $colMaxLen) {
$ValidateTablesVSSyncDbSchemaIssuesFound = $true
$msg = "WARNING: " + $syncGroupSchemaTable + ".[" + $syncGroupSchemaColumn.Name + "] has a different data size! (" + $syncGroupSchemaColumn.DataSize + " VS " + $scopeCol.MaxLength + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
}
}
}
}
if (!$ValidateTablesVSSyncDbSchemaIssuesFound) {
Write-Host '- No issues detected for' $SyncDbScope.SyncGroupName -Foreground Green
}
}
}
Catch {
Write-Host ValidateTablesVSSyncDbSchema exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateTrackingRecords([String] $table, [Array] $tablePKList) {
Try {
Write-Host "Running ValidateTrackingRecords for" $table "..." -Foreground Green
$tableNameWithoutSchema = ($table.Replace("[", "").Replace("]", "").Split('.'))[1]
$sbQuery = New-Object -TypeName "System.Text.StringBuilder"
$sbDeleteQuery = New-Object -TypeName "System.Text.StringBuilder"
[void]$sbQuery.Append("SELECT COUNT(*) AS C FROM DataSync.[")
[void]$sbQuery.Append($tableNameWithoutSchema)
[void]$sbQuery.Append("_dss_tracking] t WITH (NOLOCK) WHERE sync_row_is_tombstone=0 AND NOT EXISTS (SELECT * FROM ")
[void]$sbQuery.Append($table)
[void]$sbQuery.Append(" s WITH (NOLOCK) WHERE ")
[void]$sbDeleteQuery.Append("DELETE DataSync.[")
[void]$sbDeleteQuery.Append($tableNameWithoutSchema)
[void]$sbDeleteQuery.Append("_dss_tracking] FROM DataSync.[")
[void]$sbDeleteQuery.Append($tableNameWithoutSchema)
[void]$sbDeleteQuery.Append("_dss_tracking] t WHERE sync_row_is_tombstone=0 AND NOT EXISTS (SELECT * FROM ")
[void]$sbDeleteQuery.Append($table)
[void]$sbDeleteQuery.Append(" s WHERE ")
for ($i = 0; $i -lt $tablePKList.Length; $i++) {
if ($i -gt 0) {
[void]$sbQuery.Append(" AND ")
[void]$sbDeleteQuery.Append(" AND ")
}
[void]$sbQuery.Append("t." + $tablePKList[$i] + " = s." + $tablePKList[$i] )
[void]$sbDeleteQuery.Append("t." + $tablePKList[$i] + " = s." + $tablePKList[$i] )
}
[void]$sbQuery.Append(")")
[void]$sbDeleteQuery.Append(")")
$previousMemberCommandTimeout = $MemberCommand.CommandTimeout
$MemberCommand.CommandTimeout = $ExtendedValidationsCommandTimeout
$MemberCommand.CommandText = $sbQuery.ToString()
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
$count = $datatable | Select-Object C -ExpandProperty C
$MemberCommand.CommandTimeout = $previousMemberCommandTimeout
if ($count -ne 0) {
$msg = "WARNING: Tracking Records for Table " + $table + " may have " + $count + " invalid records!"
Write-Host $msg -Foreground Red
Write-Host $sbDeleteQuery.ToString() -Foreground Yellow
[void]$errorSummary.AppendLine()
[void]$errorSummary.AppendLine($msg)
[void]$errorSummary.AppendLine($sbDeleteQuery.ToString())
}
else {
$msg = "No issues detected in Tracking Records for Table " + $table
Write-Host $msg -Foreground Green
}
}
Catch {
Write-Host "Error at ValidateTrackingRecords" $table -Foreground Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateTrackingTable($table) {
Try {
if (![string]::IsNullOrEmpty($table)) {
[void]$allTrackingTableList.Add($table)
}
$query = "SELECT COUNT(*) AS C FROM INFORMATION_SCHEMA.TABLES WHERE '['+TABLE_SCHEMA+'].['+ TABLE_NAME + ']' = '" + $table + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
$count = $datatable | Select-Object C -ExpandProperty C
if ($count -eq 1) {
Write-Host "Tracking Table " $table "exists" -Foreground Green
}
if ($count -eq 0) {
$msg = "WARNING: Tracking Table " + $table + " IS MISSING!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
Catch {
Write-Host "Error at ValidateTrackingTable" $table -Foreground Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateTrigger([String] $trigger) {
Try {
if (![string]::IsNullOrEmpty($trigger)) {
[void]$allTriggersList.Add($trigger)
}
$query = "SELECT tr.name, tr.is_disabled AS 'Disabled'
FROM sys.triggers tr
INNER JOIN sys.tables t ON tr.parent_id = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE '['+s.name+'].['+ tr.name+']' = '" + $trigger + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$table = new-object 'System.Data.DataTable'
$table.Load($result)
$count = $table.Rows.Count
if ($count -eq 1) {
if ($table.Rows[0].Disabled -eq 1) {
$msg = "WARNING (DSS035): Trigger " + $trigger + " exists but is DISABLED!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
Write-Host "Trigger" $trigger "exists and is enabled." -Foreground Green
}
$query = "sp_helptext '" + $trigger + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$sphelptextDataTable = new-object 'System.Data.DataTable'
$sphelptextDataTable.Load($result)
#DumpObject
$tableNameWithoutSchema = ($DumpMetadataObjectsForTable.Replace("[", "").Replace("]", "").Split('.'))[1] + '_dss'
if ($DumpMetadataObjectsForTable -and ($SP.IndexOf($tableNameWithoutSchema) -ne -1)) {
$xmlResult = $sphelptextDataTable.Text
if ($xmlResult -and $canWriteFiles) {
$xmlResult | Out-File -filepath ('.\' + (SanitizeString $Server) + '_' + (SanitizeString $Database) + '_' + (SanitizeString $trigger) + '.txt')
}
}
#orphan trigger validations
$objectId = ([string[]] $sphelptextDataTable.Text) | Where-Object { $_ -match 'object_id' } | Select-Object -First 1
if ($objectId) {
$objectId = $objectId.Replace('WHERE [object_id] =', '').Trim()
$query = "select COUNT(object_id) as C from sys.tables where object_id = " + $objectId
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows[0].C -eq 0) {
$msg = "WARNING: Table with object_id " + $objectId + " was not found, " + $trigger + " was provisoned using this object_id!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
$msg = " - Found table with object_id " + $objectId
Write-Host $msg -Foreground Green
}
$query = "SELECT [owner_scope_local_id] FROM [DataSync].[provision_marker_dss] WHERE object_id = " + $objectId
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows | Where-Object { $_.owner_scope_local_id -eq 0 }) {
$msg = " - Found owner_scope_local_id 0 for object_id " + $objectId
Write-Host $msg -Foreground Green
}
else {
$msg = "WARNING: owner_scope_local_id 0 was not found for object_id " + $objectId
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
$owner_scope_local_id = ([string[]] $sphelptextDataTable.Text) | Where-Object { $_ -match 'owner_scope_local_id' -and $_ -notmatch '0' }
if ($owner_scope_local_id) {
$owner_scope_local_id = $owner_scope_local_id.Replace('AND [owner_scope_local_id] =', '').Trim()
if ($datatable.Rows | Where-Object { $_.owner_scope_local_id -eq $owner_scope_local_id }) {
$msg = " - Found owner_scope_local_id " + $owner_scope_local_id + " for object_id " + $objectId
Write-Host $msg -Foreground Green
}
else {
$msg = "WARNING: owner_scope_local_id " + $owner_scope_local_id + " was not found for object_id " + $objectId
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
}
}
if ($count -eq 0) {
$msg = "WARNING (DSS035): Trigger " + $trigger + " IS MISSING!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
Catch {
Write-Host "Error at ValidateTrigger" $trigger -Foreground Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateSP([String] $SP) {
Try {
if (![string]::IsNullOrEmpty($SP)) {
[void]$allSPsList.Add($SP)
}
$query = "SELECT COUNT(*) AS C FROM sys.procedures p INNER JOIN sys.schemas s ON p.schema_id = s.schema_id WHERE '['+s.name+'].['+ p.name+']' = N'" + $SP + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$table = new-object 'System.Data.DataTable'
$table.Load($result)
$count = $table | Select-Object C -ExpandProperty C
if ($count -eq 1) {
Write-Host "Procedure" $SP "exists" -Foreground Green
$query = "sp_helptext '" + $SP + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$sphelptextDataTable = new-object 'System.Data.DataTable'
$sphelptextDataTable.Load($result)
#DumpObject
$tableNameWithoutSchema = ($DumpMetadataObjectsForTable.Replace("[", "").Replace("]", "").Split('.'))[1] + '_dss'
if ($DumpMetadataObjectsForTable -and ($SP.IndexOf($tableNameWithoutSchema) -ne -1)) {
$xmlResult = $sphelptextDataTable.Text
if ($xmlResult -and $canWriteFiles) {
$xmlResult | Out-File -filepath ('.\' + (SanitizeString $Server) + '_' + (SanitizeString $Database) + '_' + (SanitizeString $SP) + '.txt')
}
}
#provision marker validations
$objectId = ([string[]] $sphelptextDataTable.Text) | Where-Object { $_ -match 'object_id' } | Select-Object -First 1
if ($objectId) {
$objectId = $objectId.Replace('WHERE [object_id] =', '').Trim()
$query = "select COUNT(object_id) as C from sys.tables where object_id = " + $objectId
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows[0].C -eq 0) {
$msg = "WARNING: Table with object_id " + $objectId + " was not found, " + $SP.Replace('[', '').Replace(']', '') + " was provisoned using this object_id!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
$msg = " - Found table with object_id " + $objectId
Write-Host $msg -Foreground Green
}
$query = "SELECT [owner_scope_local_id] FROM [DataSync].[provision_marker_dss] WHERE object_id = " + $objectId
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows | Where-Object { $_.owner_scope_local_id -eq 0 }) {
$msg = " - Found owner_scope_local_id 0 for object_id " + $objectId
Write-Host $msg -Foreground Green
}
else {
$msg = "WARNING: owner_scope_local_id 0 was not found for object_id " + $objectId
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
$owner_scope_local_id = ([string[]] $sphelptextDataTable.Text) | Where-Object { $_ -match 'owner_scope_local_id' -and $_ -notmatch '0' }
if ($owner_scope_local_id) {
$owner_scope_local_id = $owner_scope_local_id.Replace('AND [owner_scope_local_id] =', '').Trim()
if ($datatable.Rows | Where-Object { $_.owner_scope_local_id -eq $owner_scope_local_id }) {
$msg = " - Found owner_scope_local_id " + $owner_scope_local_id + " for object_id " + $objectId
Write-Host $msg -Foreground Green
}
else {
$msg = "WARNING: owner_scope_local_id " + $owner_scope_local_id + " was not found for object_id " + $objectId
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
}
}
if ($count -eq 0) {
$msg = "WARNING: Procedure " + $SP + " IS MISSING!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
Catch {
Write-Host "Error at ValidateSP" $SP -Foreground Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateBulkType([String] $bulkType, $columns) {
Try {
if (![string]::IsNullOrEmpty($bulkType)) {
[void]$allBulkTypeList.Add($bulkType)
}
$query = "select tt.name 'Type',
c.name 'ColumnName',
t.Name 'Datatype',
c.max_length 'MaxLength',
c.is_nullable 'IsNullable',
c.column_id 'ColumnId'
from sys.table_types tt
inner join sys.columns c on c.object_id = tt.type_table_object_id
inner join sys.types t ON c.user_type_id = t.user_type_id
where '['+ SCHEMA_NAME(tt.schema_id) +'].['+ tt.name+']' ='" + $bulkType + "'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$table = new-object 'System.Data.DataTable'
$table.Load($result)
$count = $table.Rows.Count
if ($count -gt 0) {
Write-Host "Type" $bulkType "exists" -Foreground Green
foreach ($column in $columns) {
$sbCol = New-Object -TypeName "System.Text.StringBuilder"
$typeColumn = $table.Rows | Where-Object ColumnName -eq $column.name
if (!$typeColumn) {
$msg = "WARNING: " + $bulkType + ".[" + $column.name + "] does not exit!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
continue
}
[void]$sbCol.Append("- [" + $column.name + "] " + $column.param)
if ($column.type -ne $typeColumn.Datatype) {
if ($column.type -eq 'geography' -or $column.type -eq 'geometry') {
[void]$sbCol.Append(' Type(' + $column.type + '):Expected diff ')
}
else {
[void]$sbCol.Append(' Type(' + $column.type + '):NOK ')
$msg = "WARNING: " + $bulkType + ".[" + $column.name + "] has a different datatype! (type:" + $typeColumn.Datatype + " VS scope:" + $column.type + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
}
else {
[void]$sbCol.Append(' Type(' + $column.type + '):OK ')
}
$colMaxLen = $typeColumn.MaxLength
if ($column.type -eq 'nvarchar' -or $column.type -eq 'nchar') { $colMaxLen = $colMaxLen / 2 }
if ($typeColumn.MaxLength -eq -1 -and ($column.type -eq 'nvarchar' -or $column.type -eq 'nchar' -or $column.type -eq 'varbinary' -or $column.type -eq 'varchar' -or $column.type -eq 'nvarchar')) { $colMaxLen = 'max' }
if ($column.size -ne $colMaxLen) {
[void]$sbCol.Append(' Size(' + $column.size + '):NOK ')
$msg = "WARNING: " + $bulkType + ".[" + $column.name + "] has a different data size!(type:" + $colMaxLen + " VS scope:" + $column.size + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
[void]$sbCol.Append(' Size(' + $column.size + '):OK ')
}
if ($column.null) {
if ($column.null -ne $typeColumn.IsNullable) {
[void]$sbCol.Append(' Nullable(' + $column.null + '):NOK ')
$msg = "WARNING: " + $bulkType + ".[" + $column.name + "] has a different IsNullable! (type:" + $typeColumn.IsNullable + " VS scope:" + $column.null + ")"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
else {
[void]$sbCol.Append(' Nullable(' + $column.null + '):OK ')
}
}
$sbColString = $sbCol.ToString()
if ($sbColString -match 'NOK') {
Write-Host $sbColString -ForegroundColor Red
}
else {
Write-Host $sbColString -ForegroundColor Green
}
}
}
if ($count -eq 0) {
$msg = "WARNING: Type " + $bulkType + " IS MISSING!"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine($msg)
}
#DumpObject
$tableNameWithoutSchema = ($DumpMetadataObjectsForTable.Replace("[", "").Replace("]", "").Split('.'))[1] + '_dss_BulkType_'
if ($DumpMetadataObjectsForTable -and $bulkType -match $tableNameWithoutSchema -and $canWriteFiles) {
$table | Out-File -filepath ('.\' + (SanitizeString $Server) + '_' + (SanitizeString $Database) + '_' + (SanitizeString $bulkType) + '.txt')
}
}
Catch {
Write-Host "Error at ValidateBulkType" $bulkType -Foreground Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function DetectTrackingTableLeftovers() {
Try {
$allTrackingTableString = "'$($allTrackingTableList -join "','")'"
$query = "SELECT '['+TABLE_SCHEMA+'].['+ TABLE_NAME + ']' as FullTableName, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%_dss_tracking' AND '['+TABLE_SCHEMA+'].['+ TABLE_NAME + ']' NOT IN (" + $allTrackingTableString + ")"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if (($datatable.FullTableName).Count -eq 0) {
Write-Host "There are no Tracking Table leftovers" -Foreground Green
}
else {
foreach ($leftover in $datatable) {
Write-Host "WARNING: Tracking Table" $leftover.FullTableName "should be a leftover." -Foreground Yellow
$deleteStatement = "Drop Table " + $leftover.FullTableName + ";"
[void]$runnableScript.AppendLine($deleteStatement)
[void]$runnableScript.AppendLine("GO")
$leftover.TABLE_NAME = ($leftover.TABLE_NAME -replace "_dss_tracking", "")
$query = "SELECT [object_id] FROM [DataSync].[provision_marker_dss] WHERE [owner_scope_local_id] = 0 and object_name([object_id]) = '" + $leftover.TABLE_NAME + "'"
$MemberCommand.CommandText = $query
$provision_marker_result2 = $MemberCommand.ExecuteReader()
$provision_marker_leftovers2 = new-object 'System.Data.DataTable'
$provision_marker_leftovers2.Load($provision_marker_result2)
foreach ($provision_marker_leftover2 in $provision_marker_leftovers2) {
$deleteStatement = "DELETE FROM [DataSync].[provision_marker_dss] WHERE [owner_scope_local_id] = 0 and [object_id] = " + $provision_marker_leftover2.object_id + " --" + $leftover.TABLE_NAME
Write-Host "WARNING: [DataSync].[provision_marker_dss] WHERE [owner_scope_local_id] = 0 and [object_id] = " $provision_marker_leftover2.object_id "(" $leftover.TABLE_NAME ") should be a leftover." -Foreground Yellow
[void]$runnableScript.AppendLine($deleteStatement)
[void]$runnableScript.AppendLine("GO")
}
}
}
}
Catch {
Write-Host DetectTrackingTableLeftovers exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function DetectTriggerLeftovers() {
Try {
$allTriggersString = "'$($allTriggersList -join "','")'"
$query = "SELECT '['+s.name+'].['+ trig.name+']'
FROM sys.triggers trig
INNER JOIN sys.tables t ON trig.parent_id = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE trig.name like '&_dss_&' AND '['+s.name+'].['+ trig.name+']' NOT IN (" + $allTriggersString + ")"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if (($datatable.Column1).Count -eq 0) {
Write-Host "There are no Trigger leftovers" -Foreground Green
}
else {
foreach ($leftover in $datatable.Column1) {
Write-Host "WARNING: Trigger" $leftover "should be a leftover." -Foreground Yellow
$deleteStatement = "Drop Trigger " + $leftover + ";"
[void]$runnableScript.AppendLine($deleteStatement)
[void]$runnableScript.AppendLine("GO")
}
}
}
Catch {
Write-Host DetectTriggerLeftovers exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function DetectProcedureLeftovers() {
Try {
$allSPsString = "'$($allSPsList -join "','")'"
$query = "SELECT '['+s.name+'].['+ p.name+']'
FROM sys.procedures p
INNER JOIN sys.schemas s ON p.schema_id = s.schema_id
WHERE p.name like '%_dss_%' AND '['+s.name+'].['+ p.name+']' NOT IN (" + $allSPsString + ")"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if (($datatable.Column1).Count -eq 0) {
Write-Host "There are no Procedure leftovers" -Foreground Green
}
else {
foreach ($leftover in $datatable.Column1) {
Write-Host "WARNING: Procedure" $leftover "should be a leftover." -Foreground Yellow
$deleteStatement = "Drop Procedure " + $leftover + ";"
[void]$runnableScript.AppendLine($deleteStatement)
[void]$runnableScript.AppendLine("GO")
}
}
}
Catch {
Write-Host DetectProcedureLeftovers exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function DetectBulkTypeLeftovers() {
Try {
$allBulkTypeString = "'$($allBulkTypeList -join "','")'"
$query = "select distinct '['+ SCHEMA_NAME(tt.schema_id) +'].['+ tt.name+']' 'Type'
from sys.table_types tt
inner join sys.columns c on c.object_id = tt.type_table_object_id
inner join sys.types t ON c.user_type_id = t.user_type_id
where SCHEMA_NAME(tt.schema_id) = 'DataSync' and '['+ SCHEMA_NAME(tt.schema_id) +'].['+ tt.name+']' NOT IN (" + $allBulkTypeString + ")"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if (($datatable.Type).Count -eq 0) {
Write-Host "There are no Bulk Type leftovers" -Foreground Green
}
else {
foreach ($leftover in $datatable.Type) {
Write-Host "WARNING: Bulk Type" $leftover "should be a leftover." -Foreground Yellow
$deleteStatement = "Drop Type " + $leftover + ";"
[void]$runnableScript.AppendLine($deleteStatement)
[void]$runnableScript.AppendLine("GO")
}
}
}
Catch {
Write-Host DetectBulkTypeLeftovers exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateFKDependencies([Array] $userTables) {
Try {
$allTablesFKString = "'$($userTables -join "','")'"
$query = "SELECT
OBJECT_NAME(fk.parent_object_id) TableName
,OBJECT_NAME(fk.constraint_object_id) FKName
,OBJECT_NAME(fk.referenced_object_id) ParentTableName
,t.name TrackingTableName
FROM sys.foreign_key_columns fk
INNER JOIN sys.tables t2 ON t2.name = OBJECT_NAME(fk.parent_object_id)
INNER JOIN sys.schemas s ON s.schema_id = t2.schema_id
LEFT OUTER JOIN sys.tables t ON t.name like OBJECT_NAME(fk.referenced_object_id)+'_dss_tracking'
WHERE t.name IS NULL AND '['+s.name +'].['+OBJECT_NAME(fk.parent_object_id)+']' IN (" + $allTablesFKString + ")"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows.Count -gt 0) {
$msg = "WARNING: Missing tables in the sync group due to FK references:"
Write-Host $msg -Foreground Red
[void]$errorSummary.AppendLine()
[void]$errorSummary.AppendLine($msg)
foreach ($fkrow in $datatable) {
$msg = "- The " + $fkrow.FKName + " in " + $fkrow.TableName + " needs " + $fkrow.ParentTableName
Write-Host $msg -Foreground Yellow
[void]$errorSummary.AppendLine($msg)
}
}
else {
Write-Host "No FKs referencing tables not used in sync group detected" -ForegroundColor Green
}
}
Catch {
Write-Host ValidateFKDependencies exception:
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
function ValidateProvisionMarker {
Try {
$query = "SELECT COUNT(*) AS C FROM sys.tables WHERE schema_name(schema_id) = 'DataSync' and [name] = 'provision_marker_dss'"
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
$provisionMarkerDSSExists = ($datatable.Rows[0].C -eq 1);
if (!$provisionMarkerDSSExists) {
$query = "WITH TrackingTablesObjId_CTE (object_id) AS (
SELECT OBJECT_ID(REPLACE([name], '_dss_tracking', ''))
FROM sys.tables WHERE schema_name(schema_id) = 'DataSync' and [name] like ('%_dss_tracking'))
SELECT '['+OBJECT_SCHEMA_NAME(cte.object_id)+'].['+ OBJECT_NAME(cte.object_id) +']' AS TableName, cte.object_id
FROM TrackingTablesObjId_CTE AS cte WHERE cte.object_id IS NOT NULL"
}
else {
$query = "WITH TrackingTablesObjId_CTE (object_id) AS (
SELECT OBJECT_ID(REPLACE([name], '_dss_tracking', ''))
FROM sys.tables WHERE schema_name(schema_id) = 'DataSync' and [name] like ('%_dss_tracking'))
SELECT '['+OBJECT_SCHEMA_NAME(cte.object_id)+'].['+ OBJECT_NAME(cte.object_id) +']' AS TableName, cte.object_id
FROM TrackingTablesObjId_CTE AS cte
LEFT OUTER JOIN [DataSync].[provision_marker_dss] marker on marker.owner_scope_local_id = 0 and marker.object_id = cte.object_id
WHERE marker.object_id IS NULL AND cte.object_id IS NOT NULL"
}
$MemberCommand.CommandText = $query
$result = $MemberCommand.ExecuteReader()
$datatable = new-object 'System.Data.DataTable'
$datatable.Load($result)
if ($datatable.Rows.Count -gt 0) {
$msg = "WARNING (DSS034): ValidateProvisionMarker found some possible issues"
Write-Host $msg -Foreground Yellow
[void]$errorSummary.AppendLine()