-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTests.cs
More file actions
857 lines (732 loc) · 25.9 KB
/
Tests.cs
File metadata and controls
857 lines (732 loc) · 25.9 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
[TestFixture]
public class Tests
{
static SqlInstance sqlInstance;
static Tests() =>
sqlInstance = new(
"VerifySqlServer",
connection =>
{
var serverConnection = new ServerConnection
{
ConnectionString = connection.ConnectionString,
};
var server = new Server(serverConnection);
server.ConnectionContext.ExecuteNonQuery(
"""
CREATE TABLE
MyTable(Value int);
GO
CREATE INDEX MyIndex
ON MyTable (Value);
GO
INSERT INTO MyTable (Value)
VALUES (42);
GO
CREATE TRIGGER MyTrigger
ON MyTable
AFTER UPDATE
AS RAISERROR ('Notify Customer Relations', 16, 10);
GO
CREATE TABLE
MyOtherTable(Value int);
GO
CREATE VIEW MyView
AS
SELECT Value
FROM MyTable
WHERE (Value > 10);
GO
create synonym synonym1
for MyTable;
GO
CREATE PROCEDURE MyProcedure
AS
BEGIN
SET NOCOUNT ON;
SELECT Value
FROM MyTable
WHERE (Value > 10);
END;
GO
CREATE FUNCTION MyFunction(
@quantity INT,
@list_price DEC(10,2),
@discount DEC(4,2)
)
RETURNS DEC(10,2)
AS
BEGIN
RETURN @quantity * @list_price * (1 - @discount);
END;
GO
CREATE TABLE ColumnTypes(
Id int NOT NULL IDENTITY(1,1),
Name nvarchar(100) NOT NULL,
Description nvarchar(max) NULL,
Code varchar(20) NULL,
Amount decimal(18,4) NOT NULL,
IsActive bit NOT NULL,
Created datetime2 NOT NULL,
RowVersion rowversion NOT NULL,
Price money NULL,
Ratio float NULL,
SmallNum smallint NULL,
TinyNum tinyint NULL,
BigNum bigint NULL,
UniqueCode uniqueidentifier NULL,
Notes text NULL,
BinaryData varbinary(500) NULL,
MaxBinary varbinary(max) NULL,
FixedChar char(10) NULL,
FixedBinary binary(16) NULL,
TimeOnly time NULL,
DateOnly date NULL,
NText ntext NULL,
Xml xml NULL,
CONSTRAINT PK_ColumnTypes PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE TABLE WithDefaults(
Id int NOT NULL IDENTITY(1,1),
Status varchar(20) NOT NULL CONSTRAINT DF_WithDefaults_Status DEFAULT ('active'),
Created datetime2 NOT NULL CONSTRAINT DF_WithDefaults_Created DEFAULT (GETUTCDATE()),
Score int NOT NULL CONSTRAINT DF_WithDefaults_Score DEFAULT (0),
CONSTRAINT PK_WithDefaults PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE TABLE WithComputed(
Id int NOT NULL IDENTITY(1,1),
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
FullName AS (FirstName + ' ' + LastName),
Quantity int NOT NULL,
UnitPrice decimal(10,2) NOT NULL,
TotalPrice AS (Quantity * UnitPrice) PERSISTED,
CONSTRAINT PK_WithComputed PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE TABLE ParentTable(
Id int NOT NULL IDENTITY(1,1),
Name nvarchar(100) NOT NULL,
CONSTRAINT PK_ParentTable PRIMARY KEY CLUSTERED (Id),
CONSTRAINT UQ_ParentTable_Name UNIQUE NONCLUSTERED (Name)
);
GO
CREATE TABLE ChildTable(
Id int NOT NULL IDENTITY(1,1),
ParentId int NOT NULL,
Value int NOT NULL,
CONSTRAINT PK_ChildTable PRIMARY KEY CLUSTERED (Id),
CONSTRAINT FK_ChildTable_ParentTable FOREIGN KEY (ParentId)
REFERENCES ParentTable(Id),
CONSTRAINT CK_ChildTable_Value CHECK (Value >= 0)
);
GO
CREATE TABLE CompositeKeyTable(
Key1 int NOT NULL,
Key2 int NOT NULL,
Data nvarchar(200) NULL,
CONSTRAINT PK_CompositeKeyTable PRIMARY KEY CLUSTERED (Key1, Key2)
);
GO
CREATE TABLE MultiIndexTable(
Id int NOT NULL IDENTITY(1,1),
Name nvarchar(100) NOT NULL,
Category nvarchar(50) NOT NULL,
Status int NOT NULL,
CONSTRAINT PK_MultiIndexTable PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE INDEX IX_MultiIndexTable_Name
ON MultiIndexTable (Name);
GO
CREATE UNIQUE INDEX IX_MultiIndexTable_Category_Name
ON MultiIndexTable (Category, Name);
GO
CREATE INDEX IX_MultiIndexTable_Status_Desc
ON MultiIndexTable (Status DESC, Name ASC);
GO
CREATE TABLE MultiTriggerTable(
Id int NOT NULL IDENTITY(1,1),
Name nvarchar(100) NULL,
CONSTRAINT PK_MultiTriggerTable PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE TRIGGER TR_MultiTrigger_Insert
ON MultiTriggerTable
AFTER INSERT
AS RAISERROR ('Insert detected', 16, 10);
GO
CREATE TRIGGER TR_MultiTrigger_Update
ON MultiTriggerTable
AFTER UPDATE
AS RAISERROR ('Update detected', 16, 10);
GO
CREATE TRIGGER TR_MultiTrigger_Delete
ON MultiTriggerTable
AFTER DELETE
AS RAISERROR ('Delete detected', 16, 10);
GO
CREATE VIEW MyViewWithJoin
AS
SELECT c.Id, c.Value, p.Name AS ParentName
FROM ChildTable c
INNER JOIN ParentTable p ON c.ParentId = p.Id;
GO
CREATE VIEW MyViewWithSchemabinding
WITH SCHEMABINDING
AS
SELECT Id, Name
FROM dbo.ParentTable;
GO
CREATE PROCEDURE ProcWithParams
@Id int,
@Name nvarchar(100),
@Count int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT @Count = COUNT(*)
FROM ParentTable
WHERE Id = @Id AND Name = @Name;
END;
GO
CREATE FUNCTION InlineTableFunction(@MinValue int)
RETURNS TABLE
AS
RETURN
SELECT Value
FROM MyTable
WHERE Value >= @MinValue;
GO
CREATE FUNCTION MultiStatementTableFunction(@MinValue int)
RETURNS @Result TABLE (Value int, Category nvarchar(20))
AS
BEGIN
INSERT INTO @Result
SELECT Value,
CASE
WHEN Value < 10 THEN 'Low'
WHEN Value < 100 THEN 'Medium'
ELSE 'High'
END
FROM MyTable
WHERE Value >= @MinValue;
RETURN;
END;
GO
create synonym synonym2
for ParentTable;
GO
CREATE SCHEMA TestSchema;
GO
CREATE TABLE TestSchema.SchemaTable(
Id int NOT NULL IDENTITY(1,1),
Name nvarchar(50) NOT NULL,
CONSTRAINT PK_SchemaTable PRIMARY KEY CLUSTERED (Id)
);
GO
CREATE VIEW TestSchema.SchemaView
AS
SELECT Id, Name
FROM TestSchema.SchemaTable;
GO
CREATE PROCEDURE TestSchema.SchemaProc
AS
BEGIN
SELECT Id, Name
FROM TestSchema.SchemaTable;
END;
GO
CREATE FUNCTION TestSchema.SchemaFunction(@Id int)
RETURNS nvarchar(50)
AS
BEGIN
DECLARE @Name nvarchar(50);
SELECT @Name = Name
FROM TestSchema.SchemaTable
WHERE Id = @Id;
RETURN @Name;
END;
GO
create synonym TestSchema.SchemaSynonym
for TestSchema.SchemaTable;
GO
SET ANSI_NULLS OFF;
GO
SET QUOTED_IDENTIFIER OFF;
GO
CREATE PROCEDURE ProcWithAnsiNullsOff
AS
BEGIN
SELECT Value FROM MyTable;
END;
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
""");
return Task.CompletedTask;
});
[Test]
public async Task Schema()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
#region SqlServerSchema
await Verify(connection);
#endregion
}
[Test]
public async Task SchemaAsSql()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
#region SqlServerSchemaAsSql
await Verify(connection)
.SchemaAsSql();
#endregion
}
[Test]
public async Task SchemaInDynamic()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(new
{
connection
});
}
[Test]
public async Task RecordingError()
{
await using var database = await sqlInstance.Build();
await using var connection = new SqlConnection(database.ConnectionString);
await connection.OpenAsync();
Recording.Start();
await using var command = connection.CreateCommand();
command.CommandText = "select * from MyTabl2e";
try
{
await using var dataReader = await command.ExecuteReaderAsync();
}
catch
{
}
await Verify()
.ScrubLinesContaining("HelpLink.ProdVer");
}
[Test]
public async Task CommandEscaped()
{
var command = new SqlCommand
{
CommandText = "select * from [MyTable]"
};
await Verify(command);
}
[Test]
public async Task CommandEmpty()
{
var command = new SqlCommand
{
CommandText = "select * from MyTable"
};
await Verify(command);
}
[Test]
public async Task CommandFull()
{
var command = new SqlCommand
{
CommandText = "select * from MyTable",
CommandTimeout = 10,
CommandType = CommandType.StoredProcedure,
DesignTimeVisible = true,
UpdatedRowSource = UpdateRowSource.FirstReturnedRecord,
EnableOptimizedParameterBinding = true,
Notification = new("user data", "options", 10)
};
command.Parameters.AddWithValue("name", 10);
await Verify(command);
}
[Test]
public async Task CommandOrderBySingleColumn()
{
var command = new SqlCommand
{
CommandText = "select Value from MyTable order by Value"
};
await Verify(command);
}
[Test]
public async Task CommandOrderByMultipleColumns()
{
var command = new SqlCommand
{
CommandText = "select Id, Name from MyTable order by Name, Id"
};
await Verify(command);
}
[Test]
public async Task CommandOrderByMultipleColumnsDesc()
{
var command = new SqlCommand
{
CommandText = "select Id, Name from MyTable order by Name desc, Id asc"
};
await Verify(command);
}
[Test]
public async Task CommandInClause()
{
var command = new SqlCommand
{
CommandText = "select Id, Name from MyTable where Id in (1, 2, 4, 6)"
};
await Verify(command);
}
[Test]
public async Task CommandNotInClause()
{
var command = new SqlCommand
{
CommandText = "select Id, Name from MyTable where Id not in (1, 2, 4)"
};
await Verify(command);
}
[Test]
public async Task Exception()
{
await using var database = await sqlInstance.Build();
await using var connection = new SqlConnection(database.ConnectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "select * from MyTabl2e";
await ThrowsTask(() => command.ExecuteReaderAsync());
}
[Test]
public async Task Error()
{
await using var database = await sqlInstance.Build();
await using var connection = new SqlConnection(database.ConnectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "select * from MyTabl2e";
try
{
await command.ExecuteReaderAsync();
}
catch (SqlException exception)
{
await Verify(exception.Errors[0]);
}
}
[Test]
public async Task RecordingUsage()
{
await using var database = await sqlInstance.Build();
var connectionString = database.ConnectionString;
#region Recording
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
Recording.Start();
await using var command = connection.CreateCommand();
command.CommandText = "select Value from MyTable";
var value = await command.ExecuteScalarAsync();
await Verify(value!);
#endregion
}
[Test]
public async Task RecordingWithParameter()
{
await using var database = await sqlInstance.Build();
var connectionString = database.ConnectionString;
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
Recording.Start();
await using var command = connection.CreateCommand();
command.Parameters.AddWithValue("param", 10);
command.CommandText = "select Value from MyTable where Value = @param";
var value = await command.ExecuteScalarAsync();
await Verify(value!);
}
[Test]
public Task ParameterEmpty()
{
var parameter = new SqlParameter("name", SqlDbType.Date);
return Verify(parameter);
}
[Test]
public Task ParameterFull()
{
var parameter = BuildFullParameter();
return Verify(parameter);
}
[Test]
public Task ParameterCollectionFull()
{
var parameter = BuildFullParameter();
var parameters = new SqlCommand().Parameters;
parameters.Add(parameter);
return Verify(parameters);
}
static SqlParameter BuildFullParameter() =>
new("name", SqlDbType.DateTime)
{
Direction = ParameterDirection.InputOutput,
Offset = 5,
Precision = 2,
Scale = 3,
Value = DateTime.Now,
CompareInfo = SqlCompareOptions.BinarySort2,
LocaleId = 10,
Size = 4,
IsNullable = false,
SourceVersion = DataRowVersion.Proposed,
ForceColumnEncryption = true,
SourceColumn = "sourceColumn"
};
[Test]
public async Task RecordingSpecific()
{
await using var database = await sqlInstance.Build();
var connectionString = database.ConnectionString;
#region RecordingSpecific
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
Recording.Start();
await using var command = connection.CreateCommand();
command.CommandText = "select Value from MyTable";
var value = await command.ExecuteScalarAsync();
await using var errorCommand = connection.CreateCommand();
errorCommand.CommandText = "select Value from BadTable";
try
{
await errorCommand.ExecuteScalarAsync();
}
catch
{
}
var entries = Recording
.Stop()
.Select(_ => _.Data);
//Optionally filter results
await Verify(
new
{
value,
sqlEntries = entries
});
#endregion
}
[Test]
public async Task RecordingReadingResults()
{
await using var database = await sqlInstance.Build();
var connectionString = database.ConnectionString;
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
Recording.Start();
await using var command = connection.CreateCommand();
command.CommandText = "select Value from MyTable";
await command.ExecuteScalarAsync();
await using var errorCommand = connection.CreateCommand();
errorCommand.CommandText = "select Value from BadTable";
try
{
await errorCommand.ExecuteScalarAsync();
}
catch
{
}
#region RecordingReadingResults
var entries = Recording.Stop();
// all sql entries via key
var sqlEntries = entries
.Where(_ => _.Name == "sql")
.Select(_ => _.Data);
// successful Commands via Type
var sqlCommandsViaType = entries
.Select(_ => _.Data)
.OfType<SqlCommand>();
// failed Commands via Type
var sqlErrorsViaType = entries
.Select(_ => _.Data)
.OfType<ErrorEntry>();
#endregion
await Verify(
new
{
sqlEntries,
sqlCommandsViaType,
sqlErrorsViaType,
});
}
[Test]
public async Task RecordingTest()
{
static async Task Execute(SqlConnection sqlConnection)
{
await using var command = sqlConnection.CreateCommand();
command.CommandText = "select * from MyTable";
await using var dataReader = await command.ExecuteReaderAsync();
}
await using var database = await sqlInstance.Build();
await using var connection = new SqlConnection(database.ConnectionString);
await connection.OpenAsync();
await Execute(connection);
Recording.Start();
await Execute(connection);
await Execute(connection);
await Execute(connection);
await Verify();
}
[Test]
public async Task SchemaInclude()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
#region SchemaInclude
await Verify(connection)
// include only tables and views
.SchemaIncludes(DbObjects.Tables | DbObjects.Views);
#endregion
}
[Test]
public async Task SchemaIncludeAll()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.All);
}
[Test]
public async Task SchemaFilter()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
#region SchemaFilter
await Verify(connection)
// include tables & views, or named MyTrigger
.SchemaFilter(
_ => _ is TableViewBase ||
_.Name == "MyTrigger");
#endregion
}
[Test]
public async Task SchemaFilterByName()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaFilter(_ => _.Name is "MyTable" or "MyView" or "MyProcedure");
}
[Test]
public async Task SchemaFilterExcludesAll()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaFilter(_ => false);
}
[Test]
public async Task SchemaFilterExcludesAllSql()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaFilter(_ => false)
.SchemaAsSql();
}
[Test]
public async Task SchemaIncludeTablesOnly()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.Tables);
}
[Test]
public async Task SchemaIncludeViewsOnly()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.Views);
}
[Test]
public async Task SchemaIncludeStoredProceduresOnly()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.StoredProcedures);
}
[Test]
public async Task SchemaIncludeUserDefinedFunctionsOnly()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.UserDefinedFunctions);
}
[Test]
public async Task SchemaIncludeSynonymsOnly()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaIncludes(DbObjects.Synonyms);
}
[Test]
public async Task SchemaAsMarkdown()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
await Verify(connection)
.SchemaAsMarkdown();
}
[Test]
public async Task SchemaAnsiNullsOff()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
// ProcWithAnsiNullsOff was created with SET ANSI_NULLS OFF and SET QUOTED_IDENTIFIER OFF.
// Verify the SET statements are stripped from the output.
await Verify(connection)
.SchemaFilter(_ => _.Name == "ProcWithAnsiNullsOff")
.SchemaIncludes(DbObjects.StoredProcedures);
}
[Test]
public async Task SchemaAnsiPaddingStripped()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
// MultiIndexTable has nvarchar indexes which cause SMO to emit SET ANSI_PADDING ON.
// Verify the SET ANSI_PADDING statements are stripped from the output.
await Verify(connection)
.SchemaFilter(_ => _.Name == "MultiIndexTable")
.SchemaIncludes(DbObjects.Tables);
}
[Test]
public async Task SchemaMissingInitialCatalog()
{
var connection = new SqlConnection("Server=localhost");
var exception = Assert.ThrowsAsync<Exception>(
async () => await Verify(connection));
Assert.That(exception!.Message, Does.Contain("Initial Catalog"));
}
[Test]
public async Task SchemaIncludesAndFilter()
{
await using var database = await sqlInstance.Build();
var connection = database.Connection;
// SchemaIncludes restricts to tables and views,
// SchemaFilter further restricts by name.
await Verify(connection)
.SchemaIncludes(DbObjects.Tables | DbObjects.Views)
.SchemaFilter(_ => _.Name is "MyTable" or "MyView" or "MyProcedure");
}
}