-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathMigrationsSqlServerTest.cs
More file actions
4445 lines (3986 loc) · 155 KB
/
Copy pathMigrationsSqlServerTest.cs
File metadata and controls
4445 lines (3986 loc) · 155 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.Data.SqlTypes;
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities.Xunit;
// ReSharper disable StringLiteralTypo
// ReSharper disable UnusedParameter.Local
// ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local
namespace Microsoft.EntityFrameworkCore.Migrations;
public partial class MigrationsSqlServerTest : MigrationsTestBase<MigrationsSqlServerTest.MigrationsSqlServerFixture>
{
public MigrationsSqlServerTest(MigrationsSqlServerFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
Fixture.TestSqlLoggerFactory.Clear();
Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
public override async Task Create_table()
{
await base.Create_table();
AssertSql(
"""
CREATE TABLE [People] (
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
""");
}
public override async Task Create_table_all_settings()
{
await base.Create_table_all_settings();
AssertSql(
"""
IF SCHEMA_ID(N'dbo2') IS NULL EXEC(N'CREATE SCHEMA [dbo2];');
""",
//
"""
CREATE TABLE [dbo2].[People] (
[CustomId] int NOT NULL IDENTITY,
[EmployerId] int NOT NULL,
[SSN] nvarchar(11) COLLATE German_PhoneBook_CI_AS NOT NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([CustomId]),
CONSTRAINT [AK_People_SSN] UNIQUE ([SSN]),
CONSTRAINT [CK_People_EmployerId] CHECK ([EmployerId] > 0),
CONSTRAINT [FK_People_Employers_EmployerId] FOREIGN KEY ([EmployerId]) REFERENCES [Employers] ([Id]) ON DELETE CASCADE
);
DECLARE @description AS sql_variant;
SET @description = N'Table comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', N'dbo2', 'TABLE', N'People';
SET @description = N'Employer ID comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', N'dbo2', 'TABLE', N'People', 'COLUMN', N'EmployerId';
""",
//
"""
CREATE INDEX [IX_People_EmployerId] ON [dbo2].[People] ([EmployerId]);
""");
}
public override async Task Create_table_no_key()
{
await base.Create_table_no_key();
AssertSql(
"""
CREATE TABLE [Anonymous] (
[SomeColumn] int NOT NULL
);
""");
}
public override async Task Create_table_with_comments()
{
await base.Create_table_with_comments();
AssertSql(
"""
CREATE TABLE [People] (
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
DECLARE @defaultSchema AS sysname;
SET @defaultSchema = SCHEMA_NAME();
DECLARE @description AS sql_variant;
SET @description = N'Table comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People';
SET @description = N'Column comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People', 'COLUMN', N'Name';
""");
}
public override async Task Create_table_with_multiline_comments()
{
await base.Create_table_with_multiline_comments();
AssertSql(
"""
CREATE TABLE [People] (
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
DECLARE @defaultSchema AS sysname;
SET @defaultSchema = SCHEMA_NAME();
DECLARE @description AS sql_variant;
SET @description = CONCAT(N'This is a multi-line', NCHAR(13), NCHAR(10), N'table comment.', NCHAR(13), NCHAR(10), N'More information can', NCHAR(13), NCHAR(10), N'be found in the docs.');
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People';
SET @description = CONCAT(N'This is a multi-line', NCHAR(10), N'column comment.', NCHAR(10), N'More information can', NCHAR(10), N'be found in the docs.');
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People', 'COLUMN', N'Name';
""");
}
public override async Task Create_table_with_computed_column(bool? stored)
{
await base.Create_table_with_computed_column(stored);
var storedSql = stored == true ? " PERSISTED" : "";
AssertSql(
$"""
CREATE TABLE [People] (
[Id] int NOT NULL IDENTITY,
[Sum] AS [X] + [Y]{storedSql},
[X] int NOT NULL,
[Y] int NOT NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
""");
}
public override async Task Create_table_with_json_column()
{
await base.Create_table_with_json_column();
AssertSql(
"""
CREATE TABLE [Entity] (
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max) NULL,
[OwnedCollection] nvarchar(max) NULL,
[OwnedReference] nvarchar(max) NULL,
[OwnedRequiredReference] nvarchar(max) NOT NULL,
CONSTRAINT [PK_Entity] PRIMARY KEY ([Id])
);
""");
}
public override async Task Create_table_with_json_column_explicit_json_column_names()
{
await base.Create_table_with_json_column_explicit_json_column_names();
AssertSql(
"""
CREATE TABLE [Entity] (
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max) NULL,
[json_collection] nvarchar(max) NULL,
[json_reference] nvarchar(max) NULL,
CONSTRAINT [PK_Entity] PRIMARY KEY ([Id])
);
""");
}
[ConditionalFact]
public virtual async Task Create_table_with_sparse_column()
{
await Test(
_ => { },
builder => builder.Entity("People", e => e.Property<string>("SomeProperty").IsSparse()),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "SomeProperty");
Assert.True((bool?)column[SqlServerAnnotationNames.Sparse]);
});
AssertSql(
"""
CREATE TABLE [People] (
[SomeProperty] nvarchar(max) SPARSE NULL
);
""");
}
[ConditionalFact]
public virtual async Task Create_table_with_identity_column_value_converter()
{
await Test(
_ => { },
builder => builder.UseIdentityColumns()
.Entity("People").Property<int>("IdentityColumn").HasConversion<short>().ValueGeneratedOnAdd(),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "IdentityColumn");
Assert.Equal(ValueGenerated.OnAdd, column.ValueGenerated);
});
AssertSql(
"""
CREATE TABLE [People] (
[IdentityColumn] smallint NOT NULL IDENTITY
);
""");
}
[ConditionalFact, SqlServerCondition(SqlServerCondition.SupportsMemoryOptimized)]
public virtual async Task Create_memory_optimized_table()
{
await Test(
_ => { },
builder => builder.UseIdentityColumns().Entity(
"People", b =>
{
b.ToTable(tb => tb.IsMemoryOptimized());
b.Property<int>("Id");
}),
model =>
{
var table = Assert.Single(model.Tables);
Assert.True((bool)table[SqlServerAnnotationNames.MemoryOptimized]!);
});
AssertSql(
"""
IF SERVERPROPERTY('IsXTPSupported') = 1 AND SERVERPROPERTY('EngineEdition') <> 5
BEGIN
IF NOT EXISTS (
SELECT 1 FROM [sys].[filegroups] [FG] JOIN [sys].[database_files] [F] ON [FG].[data_space_id] = [F].[data_space_id] WHERE [FG].[type] = N'FX' AND [F].[type] = 2)
BEGIN
ALTER DATABASE CURRENT SET AUTO_CLOSE OFF;
DECLARE @db_name nvarchar(max) = DB_NAME();
DECLARE @fg_name nvarchar(max);
SELECT TOP(1) @fg_name = [name] FROM [sys].[filegroups] WHERE [type] = N'FX';
IF @fg_name IS NULL
BEGIN
SET @fg_name = QUOTENAME(@db_name + N'_MODFG');
EXEC(N'ALTER DATABASE CURRENT ADD FILEGROUP ' + @fg_name + ' CONTAINS MEMORY_OPTIMIZED_DATA;');
END
DECLARE @path1 nvarchar(max);
SELECT TOP(1) @path1 = [physical_name] FROM [sys].[database_files] WHERE charindex('\', [physical_name]) > 0 ORDER BY [file_id];
IF (@path1 IS NULL)
SET @path1 = '\' + @db_name;
DECLARE @filename nvarchar(max) = right(@path1, charindex('\', reverse(@path1)) - 1);
SET @filename = REPLACE(left(@filename, len(@filename) - charindex('.', reverse(@filename))), '''', '''''') + N'_MOD';
DECLARE @new_path nvarchar(max) = REPLACE(CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(max)), '''', '''''') + @filename;
EXEC(N'
ALTER DATABASE CURRENT
ADD FILE (NAME=''' + @filename + ''', filename=''' + @new_path + ''')
TO FILEGROUP ' + @fg_name + ';')
END
END
IF SERVERPROPERTY('IsXTPSupported') = 1
EXEC(N'
ALTER DATABASE CURRENT
SET MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT ON;')
""",
//
"""
CREATE TABLE [People] (
[Id] int NOT NULL IDENTITY,
CONSTRAINT [PK_People] PRIMARY KEY NONCLUSTERED ([Id])
) WITH (MEMORY_OPTIMIZED = ON);
""");
}
[ConditionalFact, SqlServerCondition(SqlServerCondition.SupportsMemoryOptimized)]
[PlatformSkipCondition(
TestUtilities.Xunit.TestPlatform.Mac,
SkipReason = "SQL Server crashes under Rosetta on macOS; see #37647")]
public virtual async Task Create_memory_optimized_temporal_table()
{
await Test(
_ => { },
builder => builder.UseIdentityColumns().Entity(
"People", b =>
{
b.ToTable("Customers", tb => tb.IsMemoryOptimized().IsTemporal());
b.Property<int>("Id");
}),
model =>
{
var table = Assert.Single(model.Tables);
Assert.True((bool)table[SqlServerAnnotationNames.MemoryOptimized]!);
});
AssertSql(
"""
IF SERVERPROPERTY('IsXTPSupported') = 1 AND SERVERPROPERTY('EngineEdition') <> 5
BEGIN
IF NOT EXISTS (
SELECT 1 FROM [sys].[filegroups] [FG] JOIN [sys].[database_files] [F] ON [FG].[data_space_id] = [F].[data_space_id] WHERE [FG].[type] = N'FX' AND [F].[type] = 2)
BEGIN
ALTER DATABASE CURRENT SET AUTO_CLOSE OFF;
DECLARE @db_name nvarchar(max) = DB_NAME();
DECLARE @fg_name nvarchar(max);
SELECT TOP(1) @fg_name = [name] FROM [sys].[filegroups] WHERE [type] = N'FX';
IF @fg_name IS NULL
BEGIN
SET @fg_name = QUOTENAME(@db_name + N'_MODFG');
EXEC(N'ALTER DATABASE CURRENT ADD FILEGROUP ' + @fg_name + ' CONTAINS MEMORY_OPTIMIZED_DATA;');
END
DECLARE @path1 nvarchar(max);
SELECT TOP(1) @path1 = [physical_name] FROM [sys].[database_files] WHERE charindex('\', [physical_name]) > 0 ORDER BY [file_id];
IF (@path1 IS NULL)
SET @path1 = '\' + @db_name;
DECLARE @filename nvarchar(max) = right(@path1, charindex('\', reverse(@path1)) - 1);
SET @filename = REPLACE(left(@filename, len(@filename) - charindex('.', reverse(@filename))), '''', '''''') + N'_MOD';
DECLARE @new_path nvarchar(max) = REPLACE(CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(max)), '''', '''''') + @filename;
EXEC(N'
ALTER DATABASE CURRENT
ADD FILE (NAME=''' + @filename + ''', filename=''' + @new_path + ''')
TO FILEGROUP ' + @fg_name + ';')
END
END
IF SERVERPROPERTY('IsXTPSupported') = 1
EXEC(N'
ALTER DATABASE CURRENT
SET MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT ON;')
""",
//
"""
DECLARE @historyTableSchema2 nvarchar(max) = QUOTENAME(SCHEMA_NAME())
EXEC(N'CREATE TABLE [Customers] (
[Id] int NOT NULL IDENTITY,
[PeriodEnd] datetime2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
[PeriodStart] datetime2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY NONCLUSTERED ([Id]),
PERIOD FOR SYSTEM_TIME([PeriodStart], [PeriodEnd])
) WITH (
SYSTEM_VERSIONING = ON (HISTORY_TABLE = ' + @historyTableSchema2 + N'.[CustomersHistory]),
MEMORY_OPTIMIZED = ON
)');
""");
}
[ConditionalFact]
public virtual async Task Create_table_with_fill_factor()
{
await Test(
_ => { },
builder =>
{
builder.Entity("People").Property<int>("TheKey");
builder.Entity("People").Property<Guid>("TheAlternateKey");
builder.Entity("People").HasKey("TheKey").HasFillFactor(81);
builder.Entity("People").HasAlternateKey("TheAlternateKey").HasFillFactor(82);
},
model =>
{
var table = Assert.Single(model.Tables);
var primaryKey = table.PrimaryKey;
Assert.NotNull(primaryKey);
Assert.Equal(81, primaryKey[SqlServerAnnotationNames.FillFactor]);
var uniqueConstraint = table.UniqueConstraints.FirstOrDefault();
Assert.NotNull(uniqueConstraint);
Assert.Equal(82, uniqueConstraint[SqlServerAnnotationNames.FillFactor]);
});
AssertSql(
"""
CREATE TABLE [People] (
[TheKey] int NOT NULL IDENTITY,
[TheAlternateKey] uniqueidentifier NOT NULL,
CONSTRAINT [PK_People] PRIMARY KEY ([TheKey]) WITH (FILLFACTOR = 81),
CONSTRAINT [AK_People_TheAlternateKey] UNIQUE ([TheAlternateKey]) WITH (FILLFACTOR = 82)
);
""");
}
public override async Task Drop_table()
{
await base.Drop_table();
AssertSql(
"""
DROP TABLE [People];
""");
}
public override async Task Alter_table_add_comment()
{
await base.Alter_table_add_comment();
AssertSql(
"""
DECLARE @defaultSchema AS sysname;
SET @defaultSchema = SCHEMA_NAME();
DECLARE @description AS sql_variant;
SET @description = N'Table comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People';
""");
}
public override async Task Alter_table_add_comment_non_default_schema()
{
await base.Alter_table_add_comment_non_default_schema();
AssertSql(
"""
DECLARE @description AS sql_variant;
SET @description = N'Table comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', N'SomeOtherSchema', 'TABLE', N'People';
""");
}
public override async Task Alter_table_change_comment()
{
await base.Alter_table_change_comment();
AssertSql(
"""
DECLARE @defaultSchema1 AS sysname;
SET @defaultSchema1 = SCHEMA_NAME();
DECLARE @description1 AS sql_variant;
EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', @defaultSchema1, 'TABLE', N'People';
SET @description1 = N'Table comment2';
EXEC sp_addextendedproperty 'MS_Description', @description1, 'SCHEMA', @defaultSchema1, 'TABLE', N'People';
""");
}
public override async Task Alter_table_remove_comment()
{
await base.Alter_table_remove_comment();
AssertSql(
"""
DECLARE @defaultSchema1 AS sysname;
SET @defaultSchema1 = SCHEMA_NAME();
DECLARE @description1 AS sql_variant;
EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', @defaultSchema1, 'TABLE', N'People';
""");
}
public override async Task Rename_table()
{
await base.Rename_table();
AssertSql(
"""
ALTER TABLE [People] DROP CONSTRAINT [PK_People];
""",
//
"""
EXEC sp_rename N'[People]', N'Persons', 'OBJECT';
""",
//
"""
ALTER TABLE [Persons] ADD CONSTRAINT [PK_Persons] PRIMARY KEY ([Id]);
""");
}
public override async Task Rename_table_with_primary_key()
{
await base.Rename_table_with_primary_key();
AssertSql(
"""
ALTER TABLE [People] DROP CONSTRAINT [PK_People];
""",
//
"""
EXEC sp_rename N'[People]', N'Persons', 'OBJECT';
""",
//
"""
ALTER TABLE [Persons] ADD CONSTRAINT [PK_Persons] PRIMARY KEY ([Id]);
""");
}
public override async Task Rename_table_with_json_column()
{
await base.Rename_table_with_json_column();
AssertSql(
"""
ALTER TABLE [Entities] DROP CONSTRAINT [PK_Entities];
""",
//
"""
EXEC sp_rename N'[Entities]', N'NewEntities', 'OBJECT';
""",
//
"""
ALTER TABLE [NewEntities] ADD CONSTRAINT [PK_NewEntities] PRIMARY KEY ([Id]);
""");
}
public override async Task Move_table()
{
await base.Move_table();
AssertSql(
"""
IF SCHEMA_ID(N'TestTableSchema') IS NULL EXEC(N'CREATE SCHEMA [TestTableSchema];');
""",
//
"""
ALTER SCHEMA [TestTableSchema] TRANSFER [TestTable];
""");
}
[ConditionalFact]
public virtual async Task Move_table_into_default_schema()
{
await Test(
builder => builder.Entity("TestTable")
.ToTable("TestTable", "TestTableSchema")
.Property<int>("Id"),
builder => builder.Entity("TestTable")
.Property<int>("Id"),
model =>
{
var table = Assert.Single(model.Tables);
Assert.Equal("dbo", table.Schema);
Assert.Equal("TestTable", table.Name);
});
AssertSql(
"""
DECLARE @defaultSchema nvarchar(max) = QUOTENAME(SCHEMA_NAME());
EXEC(N'ALTER SCHEMA ' + @defaultSchema + N' TRANSFER [TestTableSchema].[TestTable];');
""");
}
public override async Task Create_schema()
{
await base.Create_schema();
AssertSql(
"""
IF SCHEMA_ID(N'SomeOtherSchema') IS NULL EXEC(N'CREATE SCHEMA [SomeOtherSchema];');
""",
//
"""
CREATE TABLE [SomeOtherSchema].[People] (
[Id] int NOT NULL IDENTITY,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
""");
}
[ConditionalFact]
public virtual async Task Create_schema_dbo_is_ignored()
{
await Test(
builder => { },
builder => builder.Entity("People")
.ToTable("People", "dbo")
.Property<int>("Id"),
model => Assert.Equal("dbo", Assert.Single(model.Tables).Schema));
AssertSql(
"""
CREATE TABLE [dbo].[People] (
[Id] int NOT NULL IDENTITY,
CONSTRAINT [PK_People] PRIMARY KEY ([Id])
);
""");
}
public override async Task Add_column_with_defaultValue_string()
{
await base.Add_column_with_defaultValue_string();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] nvarchar(max) NOT NULL DEFAULT N'John Doe';
""");
}
public override async Task Add_column_with_defaultValue_datetime()
{
await base.Add_column_with_defaultValue_datetime();
AssertSql(
"""
ALTER TABLE [People] ADD [Birthday] datetime2 NOT NULL DEFAULT '2015-04-12T17:05:00.0000000';
""");
}
[ConditionalTheory, InlineData(0, "", 1234567), InlineData(1, ".1", 1234567), InlineData(2, ".12", 1234567),
InlineData(3, ".123", 1234567), InlineData(4, ".1234", 1234567), InlineData(5, ".12345", 1234567), InlineData(6, ".123456", 1234567),
InlineData(7, ".1234567", 1234567), InlineData(7, ".1200000", 1200000)]
//should this really output trailing zeros?
public async Task Add_column_with_defaultValue_datetime_with_explicit_precision(int precision, string fractionalSeconds, int ticksToAdd)
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<DateTime>("Birthday").HasPrecision(precision)
.HasDefaultValue(new DateTime(2015, 4, 12, 17, 5, 0).AddTicks(ticksToAdd)),
model =>
{
var table = Assert.Single(model.Tables);
Assert.Equal(2, table.Columns.Count);
var birthdayColumn = Assert.Single(table.Columns, c => c.Name == "Birthday");
Assert.False(birthdayColumn.IsNullable);
});
AssertSql(
$"""
ALTER TABLE [People] ADD [Birthday] datetime2({precision}) NOT NULL DEFAULT '2015-04-12T17:05:00{fractionalSeconds}';
""");
}
[ConditionalTheory, InlineData(0, "", 1234567), InlineData(1, ".1", 1234567), InlineData(2, ".12", 1234567),
InlineData(3, ".123", 1234567), InlineData(4, ".1234", 1234567), InlineData(5, ".12345", 1234567), InlineData(6, ".123456", 1234567),
InlineData(7, ".1234567", 1234567), InlineData(7, ".1200000", 1200000)]
//should this really output trailing zeros?
public async Task Add_column_with_defaultValue_datetimeoffset_with_explicit_precision(
int precision,
string fractionalSeconds,
int ticksToAdd)
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<DateTimeOffset>("Birthday").HasPrecision(precision)
.HasDefaultValue(new DateTimeOffset(new DateTime(2015, 4, 12, 17, 5, 0).AddTicks(ticksToAdd), TimeSpan.FromHours(10))),
model =>
{
var table = Assert.Single(model.Tables);
Assert.Equal(2, table.Columns.Count);
var birthdayColumn = Assert.Single(table.Columns, c => c.Name == "Birthday");
Assert.False(birthdayColumn.IsNullable);
});
AssertSql(
$"""
ALTER TABLE [People] ADD [Birthday] datetimeoffset({precision}) NOT NULL DEFAULT '2015-04-12T17:05:00{fractionalSeconds}+10:00';
""");
}
[ConditionalTheory, InlineData(0, "", 1234567), InlineData(1, ".1", 1234567), InlineData(2, ".12", 1234567),
InlineData(3, ".123", 1234567), InlineData(4, ".1234", 1234567), InlineData(5, ".12345", 1234567), InlineData(6, ".123456", 1234567),
InlineData(7, ".1234567", 1234567), InlineData(7, ".12", 1200000)]
public async Task Add_column_with_defaultValue_time_with_explicit_precision(int precision, string fractionalSeconds, int ticksToAdd)
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<TimeSpan>("Age").HasPrecision(precision)
.HasDefaultValue(
TimeSpan.Parse("12:34:56", CultureInfo.InvariantCulture).Add(TimeSpan.FromTicks(ticksToAdd))),
model =>
{
var table = Assert.Single(model.Tables);
Assert.Equal(2, table.Columns.Count);
var birthdayColumn = Assert.Single(table.Columns, c => c.Name == "Age");
Assert.False(birthdayColumn.IsNullable);
});
AssertSql(
$"""
ALTER TABLE [People] ADD [Age] time({precision}) NOT NULL DEFAULT '12:34:56{fractionalSeconds}';
""");
}
[ConditionalFact]
public virtual async Task Add_column_with_defaultValue_datetime_store_type()
{
await Test(
builder => builder.Entity("People").Property<string>("Id"),
builder => { },
builder => builder.Entity("People").Property<DateTime>("Birthday")
.HasColumnType("datetime")
.HasDefaultValue(new DateTime(2019, 1, 1)),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "Birthday");
Assert.Contains("2019", column.DefaultValueSql);
});
AssertSql(
"""
ALTER TABLE [People] ADD [Birthday] datetime NOT NULL DEFAULT '2019-01-01T00:00:00.000';
""");
}
[ConditionalFact]
public virtual async Task Add_column_with_defaultValue_smalldatetime_store_type()
{
await Test(
builder => builder.Entity("People").Property<string>("Id"),
builder => { },
builder => builder.Entity("People").Property<DateTime>("Birthday")
.HasColumnType("smalldatetime")
.HasDefaultValue(new DateTime(2019, 1, 1)),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "Birthday");
Assert.Contains("2019", column.DefaultValueSql);
});
AssertSql(
"""
ALTER TABLE [People] ADD [Birthday] smalldatetime NOT NULL DEFAULT '2019-01-01T00:00:00';
""");
}
[ConditionalFact]
public virtual async Task Add_column_with_rowversion()
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<byte[]>("RowVersion").IsRowVersion(),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "RowVersion");
Assert.Equal("rowversion", column.StoreType);
Assert.True(column.IsRowVersion());
});
AssertSql(
"""
ALTER TABLE [People] ADD [RowVersion] rowversion NULL;
""");
}
[ConditionalFact]
public virtual async Task Add_column_with_rowversion_and_value_conversion()
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<ulong>("RowVersion")
.IsRowVersion()
.HasConversion<byte[]>(),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "RowVersion");
Assert.Equal("rowversion", column.StoreType);
Assert.True(column.IsRowVersion());
});
AssertSql(
"""
ALTER TABLE [People] ADD [RowVersion] rowversion NOT NULL;
""");
}
public override async Task Add_column_with_defaultValueSql()
{
await base.Add_column_with_defaultValueSql();
AssertSql(
"""
ALTER TABLE [People] ADD [Sum] int NOT NULL DEFAULT (1 + 2);
""");
}
public override async Task Add_json_columns_to_existing_table()
{
await base.Add_json_columns_to_existing_table();
AssertSql(
"""
ALTER TABLE [Entity] ADD [OwnedCollection] nvarchar(max) NULL;
""",
//
"""
ALTER TABLE [Entity] ADD [OwnedReference] nvarchar(max) NULL;
""",
//
"""
ALTER TABLE [Entity] ADD [OwnedRequiredReference] nvarchar(max) NOT NULL DEFAULT N'{}';
""");
}
public override async Task Add_column_with_computedSql(bool? stored)
{
await base.Add_column_with_computedSql(stored);
var computedColumnTypeSql = stored == true ? " PERSISTED" : "";
AssertSql(
$"""
ALTER TABLE [People] ADD [Sum] AS [X] + [Y]{computedColumnTypeSql};
""");
}
[ConditionalFact]
public virtual async Task Add_column_generates_exec_when_computed_and_idempotent()
{
await Test(
builder => builder.Entity("People").Property<int>("Id"),
builder => { },
builder => builder.Entity("People").Property<int>("IdPlusOne").HasComputedColumnSql("[Id] + 1"),
model =>
{
var table = Assert.Single(model.Tables);
Assert.Equal(2, table.Columns.Count);
var column = Assert.Single(table.Columns, c => c.Name == "IdPlusOne");
Assert.Equal("([Id]+(1))", column.ComputedColumnSql);
},
migrationsSqlGenerationOptions: MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
"""
EXEC(N'ALTER TABLE [People] ADD [IdPlusOne] AS [Id] + 1');
""");
}
[ConditionalFact]
public virtual async Task Alter_computed_column_clr_type_only_change_is_noop()
{
// Regression test for #33425: when only the CLR type of a property mapped to a computed
// column changes (the expression and IsStored are unchanged), SQL Server has nothing to
// alter — the column's type is derived from the expression. The migration must complete
// without emitting `ALTER TABLE ... ALTER COLUMN`, which would fail with
// "Cannot alter column ... because it is 'COMPUTED'".
await Test(
builder => builder.Entity(
"People", x =>
{
x.Property<int>("Id");
x.Property<int>("Calc").HasComputedColumnSql("[Id] * 2");
}),
builder => builder.Entity(
"People", x =>
{
x.Property<int>("Id");
x.Property<long>("Calc").HasComputedColumnSql("[Id] * 2");
}),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "Calc");
Assert.Equal("([Id]*(2))", column.ComputedColumnSql);
});
AssertSql();
}
public override async Task Add_column_with_required()
{
await base.Add_column_with_required();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] nvarchar(max) NOT NULL DEFAULT N'';
""");
}
public override async Task Add_column_with_ansi()
{
await base.Add_column_with_ansi();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] varchar(max) NULL;
""");
}
public override async Task Add_column_with_max_length()
{
await base.Add_column_with_max_length();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] nvarchar(30) NULL;
""");
}
public override async Task Add_column_with_max_length_on_derived()
{
await base.Add_column_with_max_length_on_derived();
Assert.Empty(Fixture.TestSqlLoggerFactory.SqlStatements);
}
public override async Task Add_column_with_fixed_length()
{
await base.Add_column_with_fixed_length();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] nchar(100) NULL;
""");
}
public override async Task Add_column_with_comment()
{
await base.Add_column_with_comment();
AssertSql(
"""
ALTER TABLE [People] ADD [FullName] nvarchar(max) NULL;
DECLARE @defaultSchema AS sysname;
SET @defaultSchema = SCHEMA_NAME();
DECLARE @description AS sql_variant;
SET @description = N'My comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People', 'COLUMN', N'FullName';
""");
}
public override async Task Add_column_with_collation()
{
await base.Add_column_with_collation();
AssertSql(
"""
ALTER TABLE [People] ADD [Name] nvarchar(max) COLLATE German_PhoneBook_CI_AS NULL;
""");
}
public override async Task Add_column_computed_with_collation(bool stored)
{
await base.Add_column_computed_with_collation(stored);
AssertSql(
stored
? """ALTER TABLE [People] ADD [Name] AS 'hello' COLLATE German_PhoneBook_CI_AS PERSISTED;"""
: """ALTER TABLE [People] ADD [Name] AS 'hello' COLLATE German_PhoneBook_CI_AS;""");
}
public override async Task Add_column_shared()
{
await base.Add_column_shared();
AssertSql();
}
public override async Task Add_column_with_check_constraint()
{
await base.Add_column_with_check_constraint();
AssertSql(
"""
ALTER TABLE [People] ADD [DriverLicense] int NOT NULL DEFAULT 0;
""",
//
"""
ALTER TABLE [People] ADD CONSTRAINT [CK_People_Foo] CHECK ([DriverLicense] > 0);
""");
}
[ConditionalFact]
public virtual async Task Add_column_identity()
{
await Test(
builder => builder.Entity("People").Property<string>("Id"),
builder => { },
builder => builder.Entity("People").Property<int>("IdentityColumn").UseIdentityColumn(),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "IdentityColumn");
Assert.Equal(ValueGenerated.OnAdd, column.ValueGenerated);
});
AssertSql(
"""
ALTER TABLE [People] ADD [IdentityColumn] int NOT NULL IDENTITY;
""");
}
[ConditionalFact]
public virtual async Task Add_column_identity_seed_increment()
{
await Test(
builder => builder.Entity("People").Property<string>("Id"),
builder => { },
builder => builder.Entity("People").Property<int>("IdentityColumn").UseIdentityColumn(100, 5),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "IdentityColumn");