-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathDatabaseManagement.cs
More file actions
733 lines (639 loc) · 30.4 KB
/
DatabaseManagement.cs
File metadata and controls
733 lines (639 loc) · 30.4 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
namespace DurableTask.SqlServer.Tests.Integration
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using DurableTask.Core;
using DurableTask.SqlServer.Tests.Logging;
using DurableTask.SqlServer.Tests.Utils;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using SemVersion;
using Xunit;
using Xunit.Abstractions;
[Collection("Integration")]
public class DatabaseManagement
{
readonly TestLogProvider logProvider;
readonly ITestOutputHelper output;
public DatabaseManagement(ITestOutputHelper output)
{
this.logProvider = new TestLogProvider(output);
this.output = output;
}
/// <summary>
/// BOM check for all expected schema script files. This test should
/// fail if scripts are added or removed unintentionally.
/// </summary>
[Fact]
public void CanEnumerateEmbeddedSqlScripts()
{
// Starting in 1.0.0, elements can be added but must NEVER be removed!
var expectedScriptFiles = new HashSet<string>
{
"drop-schema.sql",
"schema-1.0.0.sql",
"schema-1.2.0.sql",
"schema-1.6.0.sql",
"logic.sql",
"permissions.sql",
};
// The actual prefix value may change if the project structure changes.
Assembly productAssembly = typeof(SqlOrchestrationService).Assembly;
string prefix = $"{productAssembly.GetName().Name}.Scripts.";
// Consider only the non-prefixed part of the file name (should match the source code name)
string[] actualScriptFiles = productAssembly
.GetManifestResourceNames()
.Where(name => name.EndsWith(".sql"))
.Select(path => path.Replace(prefix, string.Empty))
.ToArray();
Assert.Equal(expectedScriptFiles.Count, actualScriptFiles.Length);
foreach (string actual in actualScriptFiles)
{
Assert.Contains(actual, expectedScriptFiles);
}
}
/// <summary>
/// Verifies that the schema can be created the first time correctly,
/// that the CreateItNotExist API doesn't attempt to create it again,
/// and then that the schema can be subsequently deleted.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCreateAndDropSchema(bool isDatabaseMissing)
{
using TestDatabase testDb = this.CreateTestDb(!isDatabaseMissing);
IOrchestrationService service = this.CreateServiceWithTestDb(testDb);
// Create the DB schema for the first time
await service.CreateAsync(recreateInstanceStore: true);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert
.For(this.logProvider)
.Expect(
LogAssert.CheckedDatabase())
.ExpectIf(
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CreatedDatabase(testDb.Name))
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted("dt._UpdateVersion"))
.EndOfLog();
await this.ValidateDatabaseSchemaAsync(testDb);
// Create the DB schema again - should be a no-op since it already exists
this.logProvider.Clear();
await service.CreateIfNotExistsAsync();
await this.ValidateDatabaseSchemaAsync(testDb);
// The subsequent execution should run exactly one sproc and no scripts.
// It's important to verify this to ensure the overhead of CreateIfNotExistsAsync is very small.
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.CheckedDatabase(),
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"));
// Delete the database and validate
this.logProvider.Clear();
await service.DeleteAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"));
// The previous schema validation ensures all objects are in the "dt" schema.
// We know that all objects were successfully removed if the "dt" no longer exists.
Assert.DoesNotContain("dt", testDb.GetSchemas());
}
/// <summary>
/// Verifies that the schema can be created and dropped correctly when using
/// a case-sensitive database collation (SQL_Latin1_General_CP1_CS_AS).
/// This helps prevent case-sensitivity regressions (see issue #111).
/// </summary>
[Fact]
public async Task CanCreateAndDropSchemaWithCaseSensitiveCollation()
{
using TestDatabase testDb = this.CreateTestDb(
initializeDatabase: true,
collation: "SQL_Latin1_General_CP1_CS_AS");
IOrchestrationService service = this.CreateServiceWithTestDb(testDb);
// Create the DB schema for the first time
await service.CreateAsync(recreateInstanceStore: true);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert
.For(this.logProvider)
.Expect(
LogAssert.CheckedDatabase())
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted("dt._UpdateVersion"))
.EndOfLog();
await this.ValidateDatabaseSchemaAsync(testDb);
// Create the DB schema again - should be a no-op since it already exists
this.logProvider.Clear();
await service.CreateIfNotExistsAsync();
await this.ValidateDatabaseSchemaAsync(testDb);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.CheckedDatabase(),
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"));
// Delete the database and validate
this.logProvider.Clear();
await service.DeleteAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"));
Assert.DoesNotContain("dt", testDb.GetSchemas());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCreateAndDropSchemaWithCustomSchemaName(bool isDatabaseMissing)
{
using TestDatabase testDb = this.CreateTestDb(!isDatabaseMissing);
string schemaName = "testSchemaName";
IOrchestrationService service = this.CreateServiceWithTestDb(testDb,schemaName);
await service.CreateAsync(recreateInstanceStore: true);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert
.For(this.logProvider)
.Expect(
LogAssert.CheckedDatabase())
.ExpectIf(
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CreatedDatabase(testDb.Name))
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted($"{schemaName}._UpdateVersion"))
.EndOfLog();
await this.ValidateDatabaseSchemaAsync(testDb, schemaName);
this.logProvider.Clear();
await service.CreateIfNotExistsAsync();
await this.ValidateDatabaseSchemaAsync(testDb, schemaName);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.CheckedDatabase(),
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted($"{schemaName}._GetVersions"));
this.logProvider.Clear();
await service.DeleteAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"));
Assert.DoesNotContain($"{schemaName}", testDb.GetSchemas());
Assert.DoesNotContain("dt", testDb.GetSchemas());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCreateAndDropMultipleSchemas(bool isDatabaseMissing)
{
using TestDatabase testDb = this.CreateTestDb(!isDatabaseMissing);
const string firstTestSchemaName = "firstTestSchemaName";
const string secondTestSchemaName = "secondTestSchemaName";
IOrchestrationService firstService = this.CreateServiceWithTestDb(testDb, firstTestSchemaName);
IOrchestrationService secondService = this.CreateServiceWithTestDb(testDb, secondTestSchemaName);
await firstService.CreateAsync(recreateInstanceStore: true);
await this.ValidateDatabaseSchemaAsync(testDb, firstTestSchemaName);
await secondService.CreateAsync(recreateInstanceStore: true);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert
.For(this.logProvider)
.Expect(
LogAssert.CheckedDatabase())
.ExpectIf(
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CreatedDatabase(testDb.Name))
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted($"{firstTestSchemaName}._UpdateVersion"))
.Expect(
LogAssert.CheckedDatabase())
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted($"{secondTestSchemaName}._UpdateVersion"))
.EndOfLog();
await this.ValidateDatabaseSchemaAsync(testDb, secondTestSchemaName);
this.logProvider.Clear();
await firstService.CreateIfNotExistsAsync();
await this.ValidateDatabaseSchemaAsync(testDb, firstTestSchemaName);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.CheckedDatabase(),
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted($"{firstTestSchemaName}._GetVersions"));
this.logProvider.Clear();
await secondService.CreateIfNotExistsAsync();
await this.ValidateDatabaseSchemaAsync(testDb, secondTestSchemaName);
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.CheckedDatabase(),
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted($"{secondTestSchemaName}._GetVersions"));
Assert.Contains($"{firstTestSchemaName}", testDb.GetSchemas());
Assert.Contains($"{secondTestSchemaName}", testDb.GetSchemas());
this.logProvider.Clear();
await firstService.DeleteAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"));
Assert.DoesNotContain($"{firstTestSchemaName}",testDb.GetSchemas());
Assert.Contains($"{secondTestSchemaName}", testDb.GetSchemas());
this.logProvider.Clear();
await secondService.DeleteAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert.Sequence(
this.logProvider,
LogAssert.AcquiredAppLock(),
LogAssert.ExecutedSqlScript("drop-schema.sql"));
Assert.DoesNotContain($"{secondTestSchemaName}",testDb.GetSchemas());
}
/// <summary>
/// Verifies that the CreateIfNotExistsAsync API can correctly initialize the
/// DB schema. The previous test covered CreateAsync from scratch. This one covers
/// CreateIfNotExistsAsync from scratch.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCreateIfNotExists(bool isDatabaseMissing)
{
using TestDatabase testDb = this.CreateTestDb(!isDatabaseMissing);
IOrchestrationService service = this.CreateServiceWithTestDb(testDb);
await service.CreateIfNotExistsAsync();
LogAssert.NoWarningsOrErrors(this.logProvider);
LogAssert
.For(this.logProvider)
.Expect(
LogAssert.CheckedDatabase())
.ExpectIf(
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CreatedDatabase(testDb.Name))
.Expect(
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted("dt._UpdateVersion"))
.EndOfLog();
await this.ValidateDatabaseSchemaAsync(testDb);
}
/// <summary>
/// Verifies that CreateIfNotExistsAsync is thread-safe.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task SchemaCreationIsSerializedAndIdempotent(bool isDatabaseMissing)
{
using TestDatabase testDb = this.CreateTestDb(!isDatabaseMissing);
IOrchestrationService service = this.CreateServiceWithTestDb(testDb);
// Simulate 4 workers starting up concurrently and trying to initialize
// the same database schema. It should just work with predictable output.
await Enumerable.Range(0, 4).ParallelForEachAsync(4, i => service.CreateIfNotExistsAsync());
await this.ValidateDatabaseSchemaAsync(testDb);
// Operations are expected to be serialized, making the log output deterministic.
LogAssert
.For(this.logProvider)
.Expect(
// At least 1 worker will check the database first
LogAssert.CheckedDatabase())
.Contains(
// The other 3 workers will check in some non-deterministic order
LogAssert.CheckedDatabase(),
LogAssert.CheckedDatabase(),
LogAssert.CheckedDatabase())
.ContainsIf(
// One worker may obtain the lock after another worker created the database.
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CreatedDatabase(testDb.Name))
.OptionallyContainsIf(
// Anywhere from 0 to 3 of the workers may end up attempting to create the database.
isDatabaseMissing,
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"),
LogAssert.CommandCompleted($"CREATE DATABASE [{testDb.Name}]"))
.Expect(
// 1st
LogAssert.AcquiredAppLock(statusCode: 0),
LogAssert.SprocCompleted("dt._GetVersions"),
LogAssert.ExecutedSqlScript("schema-1.0.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.2.0.sql"),
LogAssert.ExecutedSqlScript("schema-1.6.0.sql"),
LogAssert.ExecutedSqlScript("logic.sql"),
LogAssert.ExecutedSqlScript("permissions.sql"),
LogAssert.SprocCompleted("dt._UpdateVersion"),
// 2nd
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"),
// 3rd
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"),
// 4th
LogAssert.AcquiredAppLock(),
LogAssert.SprocCompleted("dt._GetVersions"))
.EndOfLog();
}
/// <summary>
/// Verifies that the schema-1.6.0 migration correctly adds the Tags column
/// to the Instances and NewTasks tables. Without the correctly named schema file,
/// existing databases would not be upgraded and the @Tags parameter would be unrecognized.
/// </summary>
[Fact]
public async Task SchemaUpgradeAddsTagsColumn()
{
using TestDatabase testDb = this.CreateTestDb();
IOrchestrationService service = this.CreateServiceWithTestDb(testDb);
// Create the full schema from scratch
await service.CreateAsync(recreateInstanceStore: true);
// Verify the Tags column exists on the Instances table
IEnumerable<string> instanceColumns = testDb.GetColumns("Instances");
Assert.Contains("Tags", instanceColumns);
// Verify the Tags column exists on the NewTasks table
IEnumerable<string> taskColumns = testDb.GetColumns("NewTasks");
Assert.Contains("Tags", taskColumns);
}
TestDatabase CreateTestDb(bool initializeDatabase = true, string collation = "Latin1_General_100_BIN2_UTF8")
{
var testDb = new TestDatabase(this.output, collation);
if (initializeDatabase)
{
testDb.Create();
}
return testDb;
}
IOrchestrationService CreateServiceWithTestDb(TestDatabase testDb, string? schemaName = null)
{
var options = new SqlOrchestrationServiceSettings(testDb.ConnectionString, null, schemaName)
{
CreateDatabaseIfNotExists = true,
LoggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddProvider(this.logProvider);
}),
};
return new SqlOrchestrationService(options);
}
async Task ValidateDatabaseSchemaAsync(TestDatabase database, string schemaName = "dt")
{
var expectedTableNames = new HashSet<string>(StringComparer.Ordinal)
{
$"{schemaName}.NewEvents",
$"{schemaName}.NewTasks",
$"{schemaName}.GlobalSettings",
$"{schemaName}.History",
$"{schemaName}.Instances",
$"{schemaName}.Payloads",
$"{schemaName}.Versions",
};
var expectedSprocNames = new HashSet<string>(StringComparer.Ordinal)
{
$"{schemaName}.CreateInstance",
$"{schemaName}.GetInstanceHistory",
$"{schemaName}.QuerySingleOrchestration",
$"{schemaName}.RaiseEvent",
$"{schemaName}.SetGlobalSetting",
$"{schemaName}.TerminateInstance",
$"{schemaName}.PurgeInstanceStateByID",
$"{schemaName}.PurgeInstanceStateByTime",
$"{schemaName}._AddOrchestrationEvents",
$"{schemaName}._CheckpointOrchestration",
$"{schemaName}._CompleteTasks",
$"{schemaName}._DiscardEventsAndUnlockInstance",
$"{schemaName}._GetVersions",
$"{schemaName}._LockNextOrchestration",
$"{schemaName}._LockNextTask",
$"{schemaName}._QueryManyOrchestrations",
$"{schemaName}._RenewOrchestrationLocks",
$"{schemaName}._RenewTaskLocks",
$"{schemaName}._UpdateVersion",
$"{schemaName}._RewindInstance",
$"{schemaName}._RewindInstanceRecursive",
};
var expectedViewNames = new HashSet<string>(StringComparer.Ordinal)
{
$"{schemaName}.vHistory",
$"{schemaName}.vInstances",
};
var expectedFunctionNames = new HashSet<string>(StringComparer.Ordinal)
{
$"{schemaName}.CurrentTaskHub",
$"{schemaName}.GetScaleMetric",
$"{schemaName}.GetScaleRecommendation",
};
// Ensure the schema exists
Assert.Contains(schemaName, database.GetSchemas());
// Make sure we've accounted for all expected tables
foreach (string tableName in database.GetTables(schemaName))
{
Assert.Contains(tableName, expectedTableNames);
expectedTableNames.Remove(tableName);
}
Assert.Empty(expectedTableNames);
// Make sure we've accounted for all expected sprocs
foreach (string sprocName in database.GetSprocs(schemaName))
{
Assert.Contains(sprocName, expectedSprocNames);
expectedSprocNames.Remove(sprocName);
}
Assert.Empty(expectedSprocNames);
// Make sure we've accounted for all expected views
foreach (string viewName in database.GetViews(schemaName))
{
Assert.Contains(viewName, expectedViewNames);
expectedViewNames.Remove(viewName);
}
Assert.Empty(expectedViewNames);
// Make sure we've accounted for all expected functions
foreach (string functionName in database.GetFunctions(schemaName))
{
Assert.Contains(functionName, expectedFunctionNames);
expectedFunctionNames.Remove(functionName);
}
Assert.Empty(expectedFunctionNames);
// Verify that the schema version in the database matches the expected version
// Note that we'll need to change the expected version here whenever we introduce new schema.
SemanticVersion currentSchemaVersion = await SharedTestHelpers.GetCurrentSchemaVersionAsync(
this.output,
database.ConnectionString,
schemaName);
Assert.Equal(1, currentSchemaVersion.Major);
Assert.Equal(6, currentSchemaVersion.Minor);
Assert.Equal(0, currentSchemaVersion.Patch);
}
sealed class TestDatabase : IDisposable
{
readonly Server server;
readonly Database testDb;
readonly ITestOutputHelper output;
bool created = false;
public TestDatabase(ITestOutputHelper output, string collation = "Latin1_General_100_BIN2_UTF8")
{
string defaultConnectionString = SharedTestHelpers.GetDefaultConnectionString("master");
this.server = new Server(new ServerConnection(new SqlConnection(defaultConnectionString)));
this.testDb = new Database(this.server, $"TestDB_{DateTime.UtcNow:yyyyMMddhhmmssfffffff}")
{
Collation = collation
};
this.ConnectionString =
new SqlConnectionStringBuilder(this.server.ConnectionContext.ConnectionString)
{
InitialCatalog = this.testDb.Name,
}
.ConnectionString;
this.output = output;
}
public string ConnectionString { get; }
public string Name => this.testDb.Name;
public void Create()
{
this.output.WriteLine($"Creating database: {this.server.Name}/{this.Name}");
this.testDb.Create();
this.created = true;
}
public IEnumerable<string> GetSchemas()
{
this.testDb.Schemas.Refresh();
foreach (Schema schema in this.testDb.Schemas)
{
yield return schema.Name;
}
}
public IEnumerable<string> GetTables(string schemaName = "dt")
{
this.testDb.Tables.Refresh();
foreach (Table table in this.testDb.Tables)
{
// e.g. "dt.History"
if (table.Schema == schemaName)
{
yield return $"{table.Schema}.{table.Name}";
}
}
}
public IEnumerable<string> GetColumns(string tableName, string schemaName = "dt")
{
this.testDb.Tables.Refresh();
Table? table = this.testDb.Tables[tableName, schemaName];
if (table != null)
{
foreach (Column column in table.Columns)
{
yield return column.Name;
}
}
}
public IEnumerable<string> GetSprocs(string schemaName = "dt")
{
this.testDb.StoredProcedures.Refresh();
foreach (StoredProcedure sproc in this.testDb.StoredProcedures)
{
if (sproc.Schema == "sys")
{
continue;
}
// e.g. "dt.LockNextOrchestration"
if (sproc.Schema == schemaName)
{
yield return $"{sproc.Schema}.{sproc.Name}";
}
}
}
public IEnumerable<string> GetViews(string schemaName = "dt")
{
this.testDb.Views.Refresh();
foreach (View view in this.testDb.Views)
{
if (view.Schema == "sys" || view.Schema == "INFORMATION_SCHEMA")
{
continue;
}
if (view.Schema == schemaName)
{
yield return $"{view.Schema}.{view.Name}";
}
}
}
public IEnumerable<string> GetFunctions(string schemaName = "dt")
{
this.testDb.UserDefinedFunctions.Refresh();
foreach (UserDefinedFunction function in this.testDb.UserDefinedFunctions)
{
if (function.Schema == "sys" || function.Schema == "INFORMATION_SCHEMA")
{
continue;
}
if (function.Schema == schemaName)
{
yield return $"{function.Schema}.{function.Name}";
}
}
}
public void Dispose()
{
if (this.created)
{
this.output.WriteLine($"Dropping database: {this.server.Name}/{this.Name}");
this.server.KillDatabase(this.Name);
}
}
}
}
}