MigrationsNpgsqlTest.cs 98.2 KB
Newer Older
S
Shay Rojansky 已提交
1
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure;
S
Shay Rojansky 已提交
2
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
S
Shay Rojansky 已提交
3 4
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal;
S
Shay Rojansky 已提交
5
using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities;
S
Shay Rojansky 已提交
6 7

#nullable enable
8

9 10 11
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Migrations;

public class MigrationsNpgsqlTest : MigrationsTestBase<MigrationsNpgsqlTest.MigrationsNpgsqlFixture>
12
{
13 14
    public MigrationsNpgsqlTest(MigrationsNpgsqlFixture fixture, ITestOutputHelper testOutputHelper)
        : base(fixture)
15
    {
16 17 18
        Fixture.TestSqlLoggerFactory.Clear();
        // Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
    }
S
Shay Rojansky 已提交
19

20
    #region Table
S
Shay Rojansky 已提交
21

22 23 24
    public override async Task Create_table()
    {
        await base.Create_table();
S
Shay Rojansky 已提交
25

26 27
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
28
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
S
Shay Rojansky 已提交
29 30 31
    ""Name"" text NULL,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
);");
32
    }
S
Shay Rojansky 已提交
33

34 35 36 37
    [Fact]
    public override async Task Create_table_all_settings()
    {
        await base.Create_table_all_settings();
S
Shay Rojansky 已提交
38

39
        AssertSql(
40 41 42 43 44 45
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'dbo2') THEN
        CREATE SCHEMA dbo2;
    END IF;
END $EF$;",
46 47
            //
            @"CREATE TABLE dbo2.""People"" (
S
Shay Rojansky 已提交
48
    ""CustomId"" integer GENERATED BY DEFAULT AS IDENTITY,
S
Shay Rojansky 已提交
49
    ""EmployerId"" integer NOT NULL,
50
    ""SSN"" character varying(11) COLLATE ""POSIX"" NOT NULL,
S
Shay Rojansky 已提交
51 52
    CONSTRAINT ""PK_People"" PRIMARY KEY (""CustomId""),
    CONSTRAINT ""AK_People_SSN"" UNIQUE (""SSN""),
S
Shay Rojansky 已提交
53
    CONSTRAINT ""CK_People_EmployerId"" CHECK (""EmployerId"" > 0),
S
Shay Rojansky 已提交
54
    CONSTRAINT ""FK_People_Employers_EmployerId"" FOREIGN KEY (""EmployerId"") REFERENCES ""Employers"" (""Id"") ON DELETE CASCADE
S
Shay Rojansky 已提交
55 56
);
COMMENT ON TABLE dbo2.""People"" IS 'Table comment';
S
Shay Rojansky 已提交
57 58 59
COMMENT ON COLUMN dbo2.""People"".""EmployerId"" IS 'Employer ID comment';",
            //
            @"CREATE INDEX ""IX_People_EmployerId"" ON dbo2.""People"" (""EmployerId"");");
60
    }
S
Shay Rojansky 已提交
61

62 63 64
    public override async Task Create_table_no_key()
    {
        await base.Create_table_no_key();
S
Shay Rojansky 已提交
65

66 67
        AssertSql(
            @"CREATE TABLE ""Anonymous"" (
S
Shay Rojansky 已提交
68 69
    ""SomeColumn"" integer NOT NULL
);");
70
    }
S
Shay Rojansky 已提交
71

72 73 74
    public override async Task Create_table_with_comments()
    {
        await base.Create_table_with_comments();
S
Shay Rojansky 已提交
75

76 77
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
78 79 80
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
    ""Name"" text NULL,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
81 82 83
);
COMMENT ON TABLE ""People"" IS 'Table comment';
COMMENT ON COLUMN ""People"".""Name"" IS 'Column comment';");
84
    }
S
Shay Rojansky 已提交
85

86 87 88
    public override async Task Create_table_with_multiline_comments()
    {
        await base.Create_table_with_multiline_comments();
S
Shay Rojansky 已提交
89

90 91
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
92 93 94
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
    ""Name"" text NULL,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
95 96 97 98 99 100 101 102 103
);
COMMENT ON TABLE ""People"" IS 'This is a multi-line
table comment.
More information can
be found in the docs.';
COMMENT ON COLUMN ""People"".""Name"" IS 'This is a multi-line
column comment.
More information can
be found in the docs.';");
104
    }
S
Shay Rojansky 已提交
105

106 107 108
    public override async Task Create_table_with_computed_column(bool? stored)
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
109
        {
110 111 112
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Create_table_with_computed_column(stored));
            return;
        }
113

114 115 116 117 118 119
        if (stored != true)
        {
            // Non-stored generated columns aren't yet supported (PG12)
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Create_table_with_computed_column(stored));
            return;
        }
120

121
        await base.Create_table_with_computed_column(stored: true);
122

123 124
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
125
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
126 127
    ""Sum"" text GENERATED ALWAYS AS (""X"" + ""Y"") STORED,
    ""X"" integer NOT NULL,
S
Shay Rojansky 已提交
128 129
    ""Y"" integer NOT NULL,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
130
);");
131
    }
132

133 134 135 136
    [Fact]
    public virtual async Task Create_table_with_identity_by_default()
    {
        await Test(
S
Shay Rojansky 已提交
137
            _ => { },
138 139 140 141 142 143 144 145 146 147 148 149
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityByDefaultColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
150 151
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
152
);");
153
    }
S
Shay Rojansky 已提交
154

155 156 157 158
    [Fact]
    public virtual async Task Create_table_with_identity_always()
    {
        await Test(
S
Shay Rojansky 已提交
159
            _ => { },
160 161 162 163 164 165 166 167 168 169 170 171
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
172 173
    ""Id"" integer GENERATED ALWAYS AS IDENTITY,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
174
);");
175
    }
176

177 178 179 180
    [Fact]
    public virtual async Task Create_table_with_identity_always_with_options()
    {
        await Test(
S
Shay Rojansky 已提交
181
            _ => { },
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityAlwaysColumn()
                .HasIdentityOptions(startValue: 10, incrementBy: 2, maxValue: 2000),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(10, options.StartValue);
                Assert.Equal(2, options.IncrementBy);
                Assert.Equal(2000, options.MaxValue);
                Assert.Null(options.MinValue);
                Assert.Equal(1, options.NumbersToCache);
                Assert.False(options.IsCyclic);
            });

        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
201 202
    ""Id"" integer GENERATED ALWAYS AS IDENTITY (START WITH 10 INCREMENT BY 2 MAXVALUE 2000),
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
203
);");
204
    }
205

206 207 208 209
    [Fact]
    public virtual async Task Create_table_with_serial()
    {
        await Test(
S
Shay Rojansky 已提交
210
            _ => { },
211 212 213 214 215 216 217
            builder => builder.Entity("People").Property<int>("Id")
                .UseSerialColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
S
Shay Rojansky 已提交
218

219 220
                Assert.Empty(model.Sequences);
            });
221

222 223
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
224 225
    ""Id"" serial NOT NULL,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
226
);");
227
    }
S
Shay Rojansky 已提交
228

229 230 231 232 233 234
    [Fact]
    public virtual async Task Create_table_with_system_column()
    {
        // System columns (e.g. xmin) are implicitly always present. If an xmin property is present,
        // nothing should happen.
        await Test(
S
Shay Rojansky 已提交
235
            _ => { },
236 237 238 239 240 241 242 243 244 245 246 247
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<uint>("xmin");
                    e.HasKey("Id");
                }),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal("Id", Assert.Single(table.Columns).Name);
            });
S
Shay Rojansky 已提交
248

249 250
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
251
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
S
Shay Rojansky 已提交
252 253
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
);");
254
    }
S
Shay Rojansky 已提交
255

256 257 258 259
    [Fact]
    public virtual async Task Create_table_with_storage_parameter()
    {
        await Test(
S
Shay Rojansky 已提交
260
            _ => { },
261 262 263 264 265 266 267 268 269
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                    e.HasStorageParameter("fillfactor", 70);
                    e.HasStorageParameter("user_catalog_table", true);
                }),
            asserter: null);  // We don't scaffold storage parameters
S
Shay Rojansky 已提交
270

271 272
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
273
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
S
Shay Rojansky 已提交
274 275 276
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
)
WITH (fillfactor=70, user_catalog_table=true);");
277
    }
S
Shay Rojansky 已提交
278

279 280 281 282
    [Fact]
    public virtual async Task Create_table_with_unlogged()
    {
        await Test(
S
Shay Rojansky 已提交
283
            _ => { },
284 285 286 287 288 289 290 291
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                    e.IsUnlogged();
                }),
            asserter: null);  // We don't scaffold unlogged
S
Shay Rojansky 已提交
292

293 294
        AssertSql(
            @"CREATE UNLOGGED TABLE ""People"" (
S
Shay Rojansky 已提交
295
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
S
Shay Rojansky 已提交
296 297
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
);");
298
    }
S
Shay Rojansky 已提交
299

300 301 302
    public override async Task Drop_table()
    {
        await base.Drop_table();
S
Shay Rojansky 已提交
303

304 305 306
        AssertSql(
            @"DROP TABLE ""People"";");
    }
S
Shay Rojansky 已提交
307

308 309 310
    public override async Task Alter_table_add_comment()
    {
        await base.Alter_table_add_comment();
S
Shay Rojansky 已提交
311

312 313 314
        AssertSql(
            @"COMMENT ON TABLE ""People"" IS 'Table comment';");
    }
S
Shay Rojansky 已提交
315

316 317 318
    public override async Task Alter_table_add_comment_non_default_schema()
    {
        await base.Alter_table_add_comment_non_default_schema();
S
Shay Rojansky 已提交
319

320 321 322
        AssertSql(
            @"COMMENT ON TABLE ""SomeOtherSchema"".""People"" IS 'Table comment';");
    }
S
Shay Rojansky 已提交
323

324 325 326
    public override async Task Alter_table_change_comment()
    {
        await base.Alter_table_change_comment();
S
Shay Rojansky 已提交
327

328 329 330
        AssertSql(
            @"COMMENT ON TABLE ""People"" IS 'Table comment2';");
    }
S
Shay Rojansky 已提交
331

332 333 334
    public override async Task Alter_table_remove_comment()
    {
        await base.Alter_table_remove_comment();
S
Shay Rojansky 已提交
335

336 337 338
        AssertSql(
            @"COMMENT ON TABLE ""People"" IS NULL;");
    }
S
Shay Rojansky 已提交
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
    [Fact]
    public virtual async Task Alter_table_change_storage_parameters()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
            builder => builder.Entity(
                "People", e =>
                {
                    e.HasStorageParameter("fillfactor", 70);
                    e.HasStorageParameter("user_catalog_table", true);
                    e.HasStorageParameter("parallel_workers", 8);
                }),
            builder => builder.Entity(
                "People", e =>
                {
                    // Add parameter
                    e.HasStorageParameter("autovacuum_enabled", true);
                    // Change parameter
                    e.HasStorageParameter("fillfactor", 80);
                    // Drop parameter user_catalog
                    // Leave parameter unchanged
                    e.HasStorageParameter("parallel_workers", 8);
                }),
            asserter: null);  // We don't scaffold storage parameters

        AssertSql(
            @"ALTER TABLE ""People"" SET (autovacuum_enabled=true, fillfactor=80);
S
Shay Rojansky 已提交
372
ALTER TABLE ""People"" RESET (user_catalog_table);");
373
    }
S
Shay Rojansky 已提交
374

375 376 377 378 379 380 381 382 383 384
    [Fact]
    public virtual async Task Alter_table_make_unlogged()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
385
            _ => { },
386 387
            builder => builder.Entity("People").IsUnlogged(),
            asserter: null);  // We don't scaffold unlogged
S
Shay Rojansky 已提交
388

389 390 391
        AssertSql(
            @"ALTER TABLE ""People"" SET UNLOGGED;");
    }
S
Shay Rojansky 已提交
392

393 394 395 396 397 398 399 400 401 402 403
    [Fact]
    public virtual async Task Alter_table_make_logged()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").IsUnlogged(),
S
Shay Rojansky 已提交
404
            _ => { },
405
            asserter: null);  // We don't scaffold unlogged
S
Shay Rojansky 已提交
406

407 408 409
        AssertSql(
            @"ALTER TABLE ""People"" SET LOGGED;");
    }
S
Shay Rojansky 已提交
410

411 412 413
    public override async Task Rename_table()
    {
        await base.Rename_table();
S
Shay Rojansky 已提交
414

415
        AssertSql(
S
Shay Rojansky 已提交
416 417 418 419 420
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""PK_People"";",
            //
            @"ALTER TABLE ""People"" RENAME TO ""Persons"";",
            //
            @"ALTER TABLE ""Persons"" ADD CONSTRAINT ""PK_Persons"" PRIMARY KEY (""Id"");");
421
    }
S
Shay Rojansky 已提交
422

423 424 425 426 427 428 429 430 431 432 433
    public override async Task Rename_table_with_primary_key()
    {
        await base.Rename_table_with_primary_key();

        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""PK_People"";",
            //
            @"ALTER TABLE ""People"" RENAME TO ""Persons"";",
            //
            @"ALTER TABLE ""Persons"" ADD CONSTRAINT ""PK_Persons"" PRIMARY KEY (""Id"");");
    }
S
Shay Rojansky 已提交
434

435 436 437
    public override async Task Move_table()
    {
        await base.Move_table();
S
Shay Rojansky 已提交
438

439
        AssertSql(
440 441 442 443 444 445
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'TestTableSchema') THEN
        CREATE SCHEMA ""TestTableSchema"";
    END IF;
END $EF$;",
446 447 448
            //
            @"ALTER TABLE ""TestTable"" SET SCHEMA ""TestTableSchema"";");
    }
S
Shay Rojansky 已提交
449

450
    #endregion
S
Shay Rojansky 已提交
451

452
    #region Schema
S
Shay Rojansky 已提交
453

454 455 456
    public override async Task Create_schema()
    {
        await base.Create_schema();
S
Shay Rojansky 已提交
457

458
        AssertSql(
459 460 461 462 463 464
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'SomeOtherSchema') THEN
        CREATE SCHEMA ""SomeOtherSchema"";
    END IF;
END $EF$;",
465 466
            //
            @"CREATE TABLE ""SomeOtherSchema"".""People"" (
S
Shay Rojansky 已提交
467 468
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
469
);");
470
    }
S
Shay Rojansky 已提交
471

472 473 474 475
    [Fact]
    public virtual async Task Create_schema_public_is_ignored()
    {
        await Test(
S
Shay Rojansky 已提交
476
            _ => { },
477 478 479 480 481 482 483
            builder => builder.Entity("People")
                .ToTable("People", "public")
                .Property<int>("Id"),
            model => Assert.Equal("public", Assert.Single(model.Tables).Schema));

        AssertSql(
            @"CREATE TABLE public.""People"" (
S
Shay Rojansky 已提交
484 485
    ""Id"" integer GENERATED BY DEFAULT AS IDENTITY,
    CONSTRAINT ""PK_People"" PRIMARY KEY (""Id"")
S
Shay Rojansky 已提交
486
);");
487
    }
S
Shay Rojansky 已提交
488

489
    #endregion
S
Shay Rojansky 已提交
490

491
    #region Column
S
Shay Rojansky 已提交
492

493 494 495
    public override async Task Add_column_with_defaultValue_string()
    {
        await base.Add_column_with_defaultValue_string();
S
Shay Rojansky 已提交
496

497 498 499
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text NOT NULL DEFAULT 'John Doe';");
    }
S
Shay Rojansky 已提交
500

501 502 503 504 505
    public override async Task Add_column_with_defaultValue_datetime()
    {
        // We default to mapping DateTime to 'timestamp with time zone', so we need to explicitly specify UTC
        await Test(
            builder => builder.Entity("People").Property<int>("Id"),
S
Shay Rojansky 已提交
506
            _ => { },
507 508 509 510 511 512 513 514 515 516 517 518 519
            builder => builder.Entity("People").Property<DateTime>("Birthday")
                .HasDefaultValue(new DateTime(2015, 4, 12, 17, 5, 0, DateTimeKind.Utc)),
            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"" timestamp with time zone NOT NULL DEFAULT TIMESTAMPTZ '2015-04-12 17:05:00Z';");
    }
S
Shay Rojansky 已提交
520

521 522 523 524
    [Fact]
    public override async Task Add_column_with_defaultValueSql()
    {
        await base.Add_column_with_defaultValueSql();
S
Shay Rojansky 已提交
525

526 527 528
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Sum"" integer NOT NULL DEFAULT (1 + 2);");
    }
S
Shay Rojansky 已提交
529

530 531 532
    public override async Task Add_column_with_computedSql(bool? stored)
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
S
Shay Rojansky 已提交
533
        {
534 535 536
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Add_column_with_computedSql(stored));
            return;
        }
S
Shay Rojansky 已提交
537

538 539 540 541 542 543
        if (stored != true)
        {
            // Non-stored generated columns aren't yet supported (PG12)
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Add_column_with_computedSql(stored));
            return;
        }
544

545
        await base.Add_column_with_computedSql(stored: true);
S
Shay Rojansky 已提交
546

547 548 549
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Sum"" text GENERATED ALWAYS AS (""X"" + ""Y"") STORED;");
    }
S
Shay Rojansky 已提交
550

551 552 553
    public override async Task Add_column_with_required()
    {
        await base.Add_column_with_required();
S
Shay Rojansky 已提交
554

555 556 557
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text NOT NULL DEFAULT '';");
    }
S
Shay Rojansky 已提交
558

559 560 561
    public override async Task Add_column_with_ansi()
    {
        await base.Add_column_with_ansi();
S
Shay Rojansky 已提交
562

563 564 565
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text NULL;");
    }
S
Shay Rojansky 已提交
566

567 568 569
    public override async Task Add_column_with_max_length()
    {
        await base.Add_column_with_max_length();
S
Shay Rojansky 已提交
570

571 572 573
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" character varying(30) NULL;");
    }
S
Shay Rojansky 已提交
574

575 576 577
    public override async Task Add_column_with_max_length_on_derived()
    {
        await base.Add_column_with_max_length_on_derived();
S
Shay Rojansky 已提交
578

579 580
        AssertSql();
    }
S
Shay Rojansky 已提交
581

582 583 584
    public override async Task Add_column_with_fixed_length()
    {
        await base.Add_column_with_fixed_length();
S
Shay Rojansky 已提交
585

586 587 588
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" character(100) NULL;");
    }
S
Shay Rojansky 已提交
589

590 591 592
    public override async Task Add_column_with_comment()
    {
        await base.Add_column_with_comment();
S
Shay Rojansky 已提交
593

594 595
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""FullName"" text NULL;
S
Shay Rojansky 已提交
596
COMMENT ON COLUMN ""People"".""FullName"" IS 'My comment';");
597
    }
S
Shay Rojansky 已提交
598

599 600 601 602
    [ConditionalFact]
    public override async Task Add_column_with_collation()
    {
        await base.Add_column_with_collation();
603

604 605 606
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text COLLATE ""POSIX"" NULL;");
    }
607

608 609 610 611
    [ConditionalFact]
    public override async Task Add_column_computed_with_collation()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
612
        {
613 614
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Add_column_computed_with_collation());
            return;
615 616
        }

617 618 619
        // Non-stored generated columns aren't yet supported (PG12), so we override to used stored
        await Test(
            builder => builder.Entity("People").Property<int>("Id"),
S
Shay Rojansky 已提交
620
            _ => { },
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
            builder => builder.Entity("People").Property<string>("Name")
                .HasComputedColumnSql("'hello'", stored: true)
                .UseCollation(NonDefaultCollation),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal(2, table.Columns.Count);
                var nameColumn = Assert.Single(table.Columns, c => c.Name == "Name");
                Assert.Contains("hello", nameColumn.ComputedColumnSql);
                Assert.Equal(NonDefaultCollation, nameColumn.Collation);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text COLLATE ""POSIX"" GENERATED ALWAYS AS ('hello') STORED;");
    }
636

637 638 639 640 641 642 643 644 645
    [ConditionalFact]
    public async Task Add_column_with_default_column_collation()
    {
        await Test(
            builder =>
            {
                builder.UseDefaultColumnCollation("POSIX");
                builder.Entity("People").Property<int>("Id");
            },
S
Shay Rojansky 已提交
646
            _ => { },
647 648 649 650 651 652 653 654 655 656 657 658
            builder => builder.Entity("People").Property<string>("Name"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal(2, table.Columns.Count);
                var nameColumn = Assert.Single(table.Columns, c => c.Name == "Name");
                Assert.Equal("POSIX", nameColumn.Collation);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text COLLATE ""POSIX"" NULL;");
    }
659

660 661 662 663 664 665 666 667 668
    [ConditionalFact]
    public async Task Add_column_with_collation_overriding_default()
    {
        await Test(
            builder =>
            {
                builder.UseDefaultColumnCollation("POSIX");
                builder.Entity("People").Property<int>("Id");
            },
S
Shay Rojansky 已提交
669
            _ => { },
670 671 672 673 674 675 676 677 678 679 680 681 682
            builder => builder.Entity("People").Property<string>("Name")
                .UseCollation("C"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal(2, table.Columns.Count);
                var nameColumn = Assert.Single(table.Columns, c => c.Name == "Name");
                Assert.Equal("C", nameColumn.Collation);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text COLLATE ""C"" NULL;");
    }
S
Shay Rojansky 已提交
683

684 685 686
    public override async Task Add_column_shared()
    {
        await base.Add_column_shared();
S
Shay Rojansky 已提交
687

688 689 690 691 692 693 694 695 696
        AssertSql();
    }

    [Fact]
    public virtual async Task Add_column_with_upper_case_store_type()
    {
        // At least for now, it's the user's responsibility to quote store type name when needed,
        // because it seems standard for people to specify either text or TEXT, and both should work.
        await Test(
S
Shay Rojansky 已提交
697
            _ => { },
698 699 700 701 702 703 704
            builder => builder.Entity("People").Property<string>("Name").HasColumnType("TEXT"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "Name");
                Assert.Equal("text", column.StoreType);
            });
S
Shay Rojansky 已提交
705

706 707
        AssertSql(
            @"CREATE TABLE ""People"" (
S
Shay Rojansky 已提交
708 709
    ""Name"" TEXT NULL
);");
710
    }
S
Shay Rojansky 已提交
711

712 713 714 715 716 717
    [Fact]
    public virtual async Task Add_column_with_identity_by_default()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
718
                {
719 720 721
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
722
            _ => { },
723 724 725 726 727 728 729 730 731 732 733 734 735
            builder => builder.Entity("People").Property<int?>("SomeColumn")
                .UseIdentityByDefaultColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""SomeColumn"" integer GENERATED BY DEFAULT AS IDENTITY;");
    }
S
Shay Rojansky 已提交
736

737 738 739 740 741 742
    [Fact]
    public virtual async Task Add_column_with_identity_always()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
743
                {
744 745 746
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
747
            _ => { },
748 749 750 751 752 753 754 755 756 757 758 759 760
            builder => builder.Entity("People").Property<int?>("SomeColumn")
                .UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""SomeColumn"" integer GENERATED ALWAYS AS IDENTITY;");
    }
S
Shay Rojansky 已提交
761

762 763 764 765 766 767
    [Fact]
    public virtual async Task Add_column_with_identity_by_default_with_all_options()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
768
                {
769 770 771
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
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
            builder => builder.Entity("People").Property<int?>("SomeColumn")
                .UseIdentityByDefaultColumn()
                .HasIdentityOptions(
                    startValue: 5,
                    incrementBy: 2,
                    minValue: 3,
                    maxValue: 2000,
                    cyclic: true,
                    numbersToCache: 10),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(5, options.StartValue);
                Assert.Equal(2, options.IncrementBy);
                Assert.Equal(3, options.MinValue);
                Assert.Equal(2000, options.MaxValue);
                Assert.True(options.IsCyclic);
                Assert.Equal(10, options.NumbersToCache);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""SomeColumn"" integer GENERATED BY DEFAULT AS IDENTITY (START WITH 5 INCREMENT BY 2 MINVALUE 3 MAXVALUE 2000 CYCLE CACHE 10);");
    }
S
Shay Rojansky 已提交
799

800 801 802 803 804
    [Fact]
    public virtual Task Add_column_optional_with_serial_not_supported()
        => TestThrows<NotSupportedException>(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
805
                {
806 807 808
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
809
            _ => { },
810 811
            builder => builder.Entity("People").Property<int?>("SomeColumn")
                .UseSerialColumn());
S
Shay Rojansky 已提交
812

813 814 815 816 817 818
    [Fact]
    public virtual async Task Add_column_required_with_serial()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
819
                {
820 821 822
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
823
            _ => { },
824 825 826 827 828 829 830 831 832 833 834 835 836
            builder => builder.Entity("People").Property<int>("SomeColumn")
                .UseSerialColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""SomeColumn"" serial NOT NULL;");
    }
S
Shay Rojansky 已提交
837

838 839 840 841 842 843
    [Fact]
    public virtual async Task Add_column_required_with_identity_by_default()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
844
                {
845 846 847
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
848
            _ => { },
849 850 851 852 853 854 855 856 857 858 859 860 861
            builder => builder.Entity("People").Property<int>("SomeColumn")
                .UseIdentityByDefaultColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ADD ""SomeColumn"" integer GENERATED BY DEFAULT AS IDENTITY;");
    }
S
Shay Rojansky 已提交
862

863 864 865 866 867 868 869 870 871 872 873 874
    [Fact]
    public virtual async Task Add_column_system()
    {
        // System columns (e.g. xmin) are implicitly always present. If an xmin property is added,
        // nothing should happen.
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
875
            _ => { },
876 877 878 879 880 881
            builder => builder.Entity("People").Property<uint>("xmin"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal("Id", Assert.Single(table.Columns).Name);
            });
S
Shay Rojansky 已提交
882

883 884
        AssertSql();
    }
S
Shay Rojansky 已提交
885

886 887 888 889 890 891 892 893 894 895 896 897
    [Fact]
    public virtual async Task Add_column_with_huge_varchar()
    {
        // PostgreSQL doesn't allow varchar(x) with x > 10485760, so we map this to text.
        // See #342 and https://www.postgresql.org/message-id/15790.1291824247%40sss.pgh.pa.us
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
898
            _ => { },
899 900
            builder => builder.Entity("People").Property<string>("Name").HasMaxLength(10485761),
            model =>
901
            {
902 903 904 905
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "Name");
                Assert.Equal("text", column.StoreType);
            });
906

907 908 909
        AssertSql(
            @"ALTER TABLE ""People"" ADD ""Name"" text NULL;");
    }
910

911 912 913 914
    [Fact]
    public virtual async Task Add_column_generated_tsvector()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
915
        {
916 917
            return;
        }
918

919 920 921
        await Test(
            builder => builder.Entity(
                "Blogs", e =>
922
                {
923 924 925
                    e.Property<string>("Title").IsRequired();
                    e.Property<string>("Description");
                }),
S
Shay Rojansky 已提交
926
            _ => { },
927 928 929 930 931 932 933 934 935 936 937 938 939
            builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
                .IsGeneratedTsVectorColumn("english", "Title", "Description"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "TsVector");
                Assert.Equal("tsvector", column.StoreType);
                Assert.Equal(@"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", column.ComputedColumnSql);
            });

        AssertSql(
            @"ALTER TABLE ""Blogs"" ADD ""TsVector"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""Title"" || ' ' || coalesce(""Description"", ''))) STORED;");
    }
940

941 942 943 944 945 946
    [Fact]
    public virtual async Task Add_column_with_compression_method()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(14))
        {
            return;
947 948
        }

949 950
        await Test(
            builder => builder.Entity("Blogs", e => e.Property<int>("Id")),
S
Shay Rojansky 已提交
951
            _ => { },
952 953 954 955 956 957 958
            builder => builder.Entity("Blogs").Property<string>("Title").UseCompressionMethod("pglz"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "Title");
                Assert.Equal("pglz", column[NpgsqlAnnotationNames.CompressionMethod]);
            });
S
Shay Rojansky 已提交
959

960 961 962
        AssertSql(
            @"ALTER TABLE ""Blogs"" ADD ""Title"" text COMPRESSION pglz NULL;");
    }
S
Shay Rojansky 已提交
963

964 965 966 967 968 969 970 971 972 973 974
    public override async Task Alter_column_change_type()
    {
        await base.Alter_column_change_type();

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeColumn"" TYPE bigint;");
    }

    public override async Task Alter_column_make_required()
    {
        await base.Alter_column_make_required();
S
Shay Rojansky 已提交
975

976 977
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeColumn"" SET NOT NULL;
978
ALTER TABLE ""People"" ALTER COLUMN ""SomeColumn"" SET DEFAULT '';");
979
    }
S
Shay Rojansky 已提交
980

981 982 983
    public override async Task Alter_column_make_required_with_index()
    {
        await base.Alter_column_make_required_with_index();
S
Shay Rojansky 已提交
984

985 986
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeColumn"" SET NOT NULL;
987
ALTER TABLE ""People"" ALTER COLUMN ""SomeColumn"" SET DEFAULT '';");
988
    }
S
Shay Rojansky 已提交
989

990 991 992
    public override async Task Alter_column_make_required_with_composite_index()
    {
        await base.Alter_column_make_required_with_composite_index();
S
Shay Rojansky 已提交
993

994 995
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""FirstName"" SET NOT NULL;
996
ALTER TABLE ""People"" ALTER COLUMN ""FirstName"" SET DEFAULT '';");
997 998 999 1000 1001 1002 1003 1004
    }

    public override async Task Alter_column_make_computed(bool? stored)
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
        {
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Add_column_with_computedSql(stored));
            return;
S
Shay Rojansky 已提交
1005 1006
        }

1007
        if (stored != true)
S
Shay Rojansky 已提交
1008
        {
1009 1010 1011 1012
            // Non-stored generated columns aren't yet supported (PG12)
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Add_column_with_computedSql(stored));
            return;
        }
S
Shay Rojansky 已提交
1013

1014
        await base.Alter_column_make_computed(stored);
1015

1016 1017 1018 1019 1020
        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""Sum"";",
            //
            @"ALTER TABLE ""People"" ADD ""Sum"" integer GENERATED ALWAYS AS (""X"" + ""Y"") STORED;");
    }
S
Shay Rojansky 已提交
1021

1022 1023 1024 1025 1026 1027
    public override async Task Alter_column_change_computed()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
        {
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Alter_column_change_computed());
            return;
S
Shay Rojansky 已提交
1028
        }
S
Shay Rojansky 已提交
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        // Non-stored generated columns aren't yet supported (PG12), so we override to used stored
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<int>("X");
                    e.Property<int>("Y");
                    e.Property<int>("Sum");
                }),
            builder => builder.Entity("People").Property<int>("Sum")
                .HasComputedColumnSql($"{DelimitIdentifier("X")} + {DelimitIdentifier("Y")}", stored: true),
            builder => builder.Entity("People").Property<int>("Sum")
                .HasComputedColumnSql($"{DelimitIdentifier("X")} - {DelimitIdentifier("Y")}", stored: true),
            model =>
S
Shay Rojansky 已提交
1045
            {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
                var table = Assert.Single(model.Tables);
                var sumColumn = Assert.Single(table.Columns, c => c.Name == "Sum");
                Assert.Contains("X", sumColumn.ComputedColumnSql);
                Assert.Contains("Y", sumColumn.ComputedColumnSql);
                Assert.Contains("-", sumColumn.ComputedColumnSql);
            });

        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""Sum"";",
            //
            @"ALTER TABLE ""People"" ADD ""Sum"" integer GENERATED ALWAYS AS (""X"" - ""Y"") STORED;");
    }
S
Shay Rojansky 已提交
1058

1059
    [ConditionalFact]
S
Shay Rojansky 已提交
1060
    public override async Task Alter_column_change_computed_recreates_indexes()
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
        {
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Alter_column_change_computed());
            return;
        }

        // Non-stored generated columns aren't yet supported (PG12), so we override to used stored
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<int>("X");
                    e.Property<int>("Y");
                    e.Property<int>("Sum");

                    e.HasIndex("Sum");
                }),
            builder => builder.Entity("People").Property<int>("Sum")
                .HasComputedColumnSql($"{DelimitIdentifier("X")} + {DelimitIdentifier("Y")}", stored: true),
            builder => builder.Entity("People").Property<int>("Sum")
                .HasComputedColumnSql($"{DelimitIdentifier("X")} - {DelimitIdentifier("Y")}", stored: true),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var sumColumn = Assert.Single(table.Columns, c => c.Name == "Sum");
                if (AssertComputedColumns)
1089 1090 1091 1092
                {
                    Assert.Contains("X", sumColumn.ComputedColumnSql);
                    Assert.Contains("Y", sumColumn.ComputedColumnSql);
                    Assert.Contains("-", sumColumn.ComputedColumnSql);
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
                }

                var sumIndex = Assert.Single(table.Indexes);
                Assert.Collection(sumIndex.Columns, c => Assert.Equal("Sum", c.Name));
            });

        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""Sum"";",
            //
            @"ALTER TABLE ""People"" ADD ""Sum"" integer GENERATED ALWAYS AS (""X"" - ""Y"") STORED;",
            //
            @"CREATE INDEX ""IX_People_Sum"" ON ""People"" (""Sum"");");
    }
S
Shay Rojansky 已提交
1106

1107 1108
    public override Task Alter_column_change_computed_type()
        => Assert.ThrowsAsync<NotSupportedException>(() => base.Alter_column_change_computed());
S
Shay Rojansky 已提交
1109

1110 1111 1112
    public override async Task Alter_column_make_non_computed()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
1113
        {
1114 1115
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Alter_column_make_non_computed());
            return;
1116 1117
        }

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<int>("X");
                    e.Property<int>("Y");
                }),
            builder => builder.Entity("People").Property<int>("Sum")
                .HasComputedColumnSql(@"""X"" + ""Y""", stored: true),
            builder => builder.Entity("People").Property<int>("Sum"),
            model =>
1130
            {
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
                var table = Assert.Single(model.Tables);
                var sumColumn = Assert.Single(table.Columns, c => c.Name == "Sum");
                Assert.Null(sumColumn.ComputedColumnSql);
                Assert.NotEqual(true, sumColumn.IsStored);
            });

        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""Sum"";",
            //
            @"ALTER TABLE ""People"" ADD ""Sum"" integer NOT NULL;");
    }
1142

1143 1144 1145
    public override async Task Alter_column_add_comment()
    {
        await base.Alter_column_add_comment();
1146

1147 1148 1149
        AssertSql(
            @"COMMENT ON COLUMN ""People"".""Id"" IS 'Some comment';");
    }
S
Shay Rojansky 已提交
1150

1151 1152 1153 1154 1155 1156
    public override async Task Alter_computed_column_add_comment()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
        {
            await Assert.ThrowsAsync<NotSupportedException>(() => base.Alter_computed_column_add_comment());
            return;
S
Shay Rojansky 已提交
1157
        }
S
Shay Rojansky 已提交
1158

1159 1160 1161 1162 1163 1164 1165
        await Test(
            builder => builder.Entity(
                "People", x =>
                {
                    x.Property<int>("Id");
                    x.Property<int>("SomeColumn").HasComputedColumnSql("42", stored: true);
                }),
S
Shay Rojansky 已提交
1166
            _ => { },
1167 1168
            builder => builder.Entity("People").Property<int>("SomeColumn").HasComment("Some comment"),
            model =>
S
Shay Rojansky 已提交
1169
            {
1170 1171 1172
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns.Where(c => c.Name == "SomeColumn"));
                if (AssertComments)
S
Shay Rojansky 已提交
1173
                {
1174 1175 1176
                    Assert.Equal("Some comment", column.Comment);
                }
            });
S
Shay Rojansky 已提交
1177

1178 1179 1180
        AssertSql(
            @"COMMENT ON COLUMN ""People"".""SomeColumn"" IS 'Some comment';");
    }
S
Shay Rojansky 已提交
1181

1182 1183 1184
    public override async Task Alter_column_change_comment()
    {
        await base.Alter_column_change_comment();
S
Shay Rojansky 已提交
1185

1186 1187 1188
        AssertSql(
            @"COMMENT ON COLUMN ""People"".""Id"" IS 'Some comment2';");
    }
S
Shay Rojansky 已提交
1189

1190 1191 1192
    public override async Task Alter_column_remove_comment()
    {
        await base.Alter_column_remove_comment();
S
Shay Rojansky 已提交
1193

1194 1195 1196
        AssertSql(
            @"COMMENT ON COLUMN ""People"".""Id"" IS NULL;");
    }
S
Shay Rojansky 已提交
1197

1198 1199 1200 1201
    [Fact]
    public virtual async Task Alter_column_make_identity_by_default()
    {
        await Test(
S
Shay Rojansky 已提交
1202 1203
            builder => builder.Entity("People").Property<int>("Id")
                .ValueGeneratedNever(),
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityByDefaultColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" DROP DEFAULT;
S
Shay Rojansky 已提交
1216
ALTER TABLE ""People"" ALTER COLUMN ""Id"" ADD GENERATED BY DEFAULT AS IDENTITY;");
1217
    }
S
Shay Rojansky 已提交
1218

1219 1220 1221 1222 1223 1224
    [Fact]
    public virtual async Task Alter_column_make_identity_always()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1225
                {
1226 1227 1228
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
1229
            _ => { },
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
S
Shay Rojansky 已提交
1241
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET GENERATED ALWAYS;");
1242
    }
1243

1244 1245 1246 1247 1248 1249
    [Fact]
    public virtual async Task Alter_column_make_default_into_identity()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
1250
                {
1251 1252 1253
                    e.Property<int>("Id").HasDefaultValue(8);
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
1254
            _ => { },
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" DROP DEFAULT;
S
Shay Rojansky 已提交
1267
ALTER TABLE ""People"" ALTER COLUMN ""Id"" ADD GENERATED ALWAYS AS IDENTITY;");
1268
    }
S
Shay Rojansky 已提交
1269

1270 1271 1272 1273
    [Fact]
    public virtual async Task Alter_column_make_identity_by_default_with_options()
    {
        await Test(
S
Shay Rojansky 已提交
1274 1275
            builder => builder.Entity("People").Property<int>("Id")
                .ValueGeneratedNever(),
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityByDefaultColumn()
                .HasIdentityOptions(startValue: 10, incrementBy: 2, maxValue: 2000),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(10, options.StartValue);
                Assert.Equal(2, options.IncrementBy);
                Assert.Equal(2000, options.MaxValue);
                Assert.Null(options.MinValue);
                Assert.Equal(1, options.NumbersToCache);
                Assert.False(options.IsCyclic);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" DROP DEFAULT;
S
Shay Rojansky 已提交
1295
ALTER TABLE ""People"" ALTER COLUMN ""Id"" ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 10 INCREMENT BY 2 MAXVALUE 2000);");
1296
    }
S
Shay Rojansky 已提交
1297

1298 1299 1300 1301 1302 1303
    [Fact]
    public virtual async Task Alter_column_make_identity_with_default_options()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
1304
                {
1305 1306 1307
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
1308
            _ => { },
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
            builder => builder.Entity("People").Property<int>("Id")
                .UseIdentityByDefaultColumn()
                .HasIdentityOptions(startValue: 1, incrementBy: 1, minValue: 1, maxValue: null),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Null(options.StartValue);
                Assert.Equal(1, options.IncrementBy);
                Assert.Null(options.MaxValue);
                Assert.Null(options.MinValue);
                Assert.Equal(1, options.NumbersToCache);
                Assert.False(options.IsCyclic);
            });

        AssertSql(
S
Shay Rojansky 已提交
1327 1328
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" RESTART WITH 1;
ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET MINVALUE 1;");
1329
    }
1330

1331 1332 1333 1334 1335 1336
    [Fact]
    public virtual async Task Alter_column_change_identity_options()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1337
                {
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
                    e.Property<int>("Id").UseIdentityByDefaultColumn();
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").Property<int>("Id")
                .HasIdentityOptions(incrementBy: 1, maxValue: 1000, cyclic: false),
            builder => builder.Entity("People").Property<int>("Id")
                .HasIdentityOptions(incrementBy: 2, maxValue: 1000, cyclic: true),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(2, options.IncrementBy);
                Assert.Equal(1000, options.MaxValue);
                Assert.True(options.IsCyclic);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET INCREMENT BY 2;
S
Shay Rojansky 已提交
1358
ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET CYCLE;");
1359
    }
S
Shay Rojansky 已提交
1360

1361 1362 1363 1364 1365 1366
    [Fact]
    public virtual async Task Alter_column_remove_identity_options()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1367
                {
1368 1369 1370 1371 1372
                    e.Property<int>("Id").UseIdentityByDefaultColumn();
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").Property<int>("Id")
                .HasIdentityOptions(startValue: 5, incrementBy: 2, cyclic: true, numbersToCache: 5),
S
Shay Rojansky 已提交
1373
            _ => { },
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(5, options.StartValue);  // Restarting doesn't change the scaffolded start value
                Assert.Equal(1, options.IncrementBy);
                Assert.False(options.IsCyclic);
                Assert.Equal(1, options.NumbersToCache);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" RESTART WITH 1;
S
Shay Rojansky 已提交
1388 1389 1390
ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET INCREMENT BY 1;
ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET NO CYCLE;
ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET CACHE 1;");
1391
    }
S
Shay Rojansky 已提交
1392

1393 1394 1395 1396
    [Fact]
    public virtual async Task Alter_column_make_serial()
    {
        await Test(
S
Shay Rojansky 已提交
1397 1398
            builder => builder.Entity("People").Property<int>("Id")
                .ValueGeneratedNever(),
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
            builder => builder.Entity("People").Property<int>("Id")
                .UseSerialColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);

                Assert.Empty(model.Sequences);
            });

        AssertSql(
            @"CREATE SEQUENCE ""People_Id_seq"" AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE;",
            //
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET DEFAULT (nextval('""People_Id_seq""'));
S
Shay Rojansky 已提交
1415
ALTER SEQUENCE ""People_Id_seq"" OWNED BY ""People"".""Id"";");
1416
    }
S
Shay Rojansky 已提交
1417

1418 1419 1420 1421
    [Fact]
    public virtual async Task Alter_column_make_serial_in_non_default_schema()
    {
        await Test(
S
Shay Rojansky 已提交
1422 1423 1424
            builder => builder.Entity("People", e => e.ToTable("People", "some_schema")),
            builder => builder.Entity("People").Property<int>("Id")
                .ValueGeneratedNever(),
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
            builder => builder.Entity("People").Property<int>("Id")
                .UseSerialColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);

                Assert.Empty(model.Sequences);
            });

        AssertSql(
            @"CREATE SEQUENCE some_schema.""People_Id_seq"" AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE;",
            //
            @"ALTER TABLE some_schema.""People"" ALTER COLUMN ""Id"" SET DEFAULT (nextval('some_schema.""People_Id_seq""'));
S
Shay Rojansky 已提交
1441
ALTER SEQUENCE some_schema.""People_Id_seq"" OWNED BY some_schema.""People"".""Id"";");
1442
    }
S
Shay Rojansky 已提交
1443

1444 1445 1446 1447
    [Fact]
    public virtual async Task Alter_column_long_make_bigserial()
    {
        await Test(
S
Shay Rojansky 已提交
1448 1449
            builder => builder.Entity("People").Property<long>("Id")
                .ValueGeneratedNever(),
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            builder => builder.Entity("People").Property<long>("Id")
                .UseSerialColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Equal("bigint", column.StoreType);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);

                Assert.Empty(model.Sequences);
            });

        AssertSql(
            @"CREATE SEQUENCE ""People_Id_seq"" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE;",
            //
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET DEFAULT (nextval('""People_Id_seq""'));
S
Shay Rojansky 已提交
1467
ALTER SEQUENCE ""People_Id_seq"" OWNED BY ""People"".""Id"";");
1468
    }
S
Shay Rojansky 已提交
1469

1470 1471 1472 1473 1474 1475
    [Fact]
    public virtual async Task Alter_column_change_identity_type()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1476
                {
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").Property<int>("Id").UseIdentityByDefaultColumn(),
            builder => builder.Entity("People").Property<int>("Id").UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" SET GENERATED ALWAYS;");
    }
S
Shay Rojansky 已提交
1493

1494 1495 1496 1497 1498 1499
    [Fact]
    public virtual async Task Alter_column_change_serial_to_identity()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1500
                {
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").Property<int>("Id").UseSerialColumn(),
            builder => builder.Entity("People").Property<int>("Id").UseIdentityAlwaysColumn(),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER SEQUENCE ""People_Id_seq"" RENAME TO ""People_Id_old_seq"";
S
Shay Rojansky 已提交
1516 1517 1518 1519
ALTER TABLE ""People"" ALTER COLUMN ""Id"" DROP DEFAULT;
ALTER TABLE ""People"" ALTER COLUMN ""Id"" ADD GENERATED ALWAYS AS IDENTITY;
SELECT * FROM setval('""People_Id_seq""', nextval('""People_Id_old_seq""'), false);
DROP SEQUENCE ""People_Id_old_seq"";");
1520
    }
S
Shay Rojansky 已提交
1521

1522 1523 1524 1525 1526 1527
    [Fact]
    public virtual async Task Alter_column_serial_change_type()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1528
                {
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
                    e.Property<int>("Id").UseSerialColumn();
                    e.HasKey("Id");
                }),
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<long>("Id").UseSerialColumn();
                    e.HasKey("Id");
                }),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.SerialColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                Assert.Equal("bigint", column.StoreType);
                Assert.Null(column[NpgsqlAnnotationNames.IdentityOptions]);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" TYPE bigint;");
    }
S
Shay Rojansky 已提交
1550

1551 1552 1553 1554 1555 1556
    [Fact]
    public virtual async Task Alter_column_restart_identity()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1557
                {
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
                    e.Property<int>("Id").UseIdentityByDefaultColumn();
                    e.HasKey("Id");
                }),
            builder => builder.Entity("People").Property<int>("Id").HasIdentityOptions(startValue: 10),
            builder => builder.Entity("People").Property<int>("Id").HasIdentityOptions(startValue: 20),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns);
                Assert.Equal(NpgsqlValueGenerationStrategy.IdentityByDefaultColumn, column[NpgsqlAnnotationNames.ValueGenerationStrategy]);
                var options = IdentitySequenceOptionsData.Get(column);
                Assert.Equal(10, options.StartValue);  // Restarting doesn't change the scaffolded start value
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Id"" RESTART WITH 20;");
    }
S
Shay Rojansky 已提交
1575

1576 1577 1578 1579
    [Fact]
    public override async Task Alter_column_set_collation()
    {
        await base.Alter_column_set_collation();
1580

1581 1582 1583
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Name"" TYPE text COLLATE ""POSIX"";");
    }
1584

1585 1586 1587 1588
    [Fact]
    public override async Task Alter_column_reset_collation()
    {
        await base.Alter_column_reset_collation();
1589

1590 1591 1592
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Name"" TYPE text COLLATE ""default"";");
    }
1593

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    [Fact]
    public async Task Alter_column_change_default_column_collation()
    {
        await Test(
            builder => builder.Entity("People", b =>
            {
                b.Property<int>("Id");
                b.Property<string>("Name");
            }),
            builder => builder.UseDefaultColumnCollation("POSIX"),
            builder => builder.UseDefaultColumnCollation("C"),
S
Shay Rojansky 已提交
1605
            _ =>
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
            {
                // var table = Assert.Single(model.Tables);
                // Assert.Equal(2, table.Columns.Count);
                // var nameColumn = Assert.Single(table.Columns, c => c.Name == "Name");
                // Assert.Equal("C", nameColumn.Collation);
            });

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Name"" TYPE text COLLATE ""C"";");
    }

    [Fact]
    public virtual async Task Alter_column_generated_tsvector_change_config()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
1621
        {
1622
            return;
1623 1624
        }

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
        await Test(
            builder => builder.Entity(
                "Blogs", e =>
                {
                    e.Property<string>("Title").IsRequired();
                    e.Property<string>("Description");
                }),
            builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
                .IsGeneratedTsVectorColumn("german", "Title", "Description"),
            builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
                .IsGeneratedTsVectorColumn("english", "Title", "Description"),
            model =>
1637
            {
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "TsVector");
                Assert.Equal("tsvector", column.StoreType);
                Assert.Equal(@"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", column.ComputedColumnSql);
            });

        AssertSql(
            @"ALTER TABLE ""Blogs"" DROP COLUMN ""TsVector"";",
            //
            @"ALTER TABLE ""Blogs"" ADD ""TsVector"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""Title"" || ' ' || coalesce(""Description"", ''))) STORED;");
    }
1649

1650 1651 1652 1653 1654 1655
    [Fact]
    public virtual async Task Alter_column_computed_set_collation()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
        {
            return;
1656 1657
        }

1658 1659
        await Test(
            builder => builder.Entity("People", b =>
1660
            {
1661 1662 1663
                b.Property<string>("Name");
                b.Property<string>("Name2").HasComputedColumnSql(@"""Name""", stored: true);
            }),
S
Shay Rojansky 已提交
1664
            _ => { },
1665 1666 1667 1668 1669 1670 1671 1672
            builder => builder.Entity("People").Property<string>("Name2")
                .UseCollation(NonDefaultCollation),
            model =>
            {
                var computedColumn = Assert.Single(Assert.Single(model.Tables).Columns, c => c.Name == "Name2");
                Assert.Equal(@"""Name""", computedColumn.ComputedColumnSql);
                Assert.Equal(NonDefaultCollation, computedColumn.Collation);
            });
1673

1674 1675 1676
        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""Name2"" TYPE text COLLATE ""POSIX"";");
    }
1677

1678 1679 1680 1681 1682 1683
    [Fact]
    public virtual async Task Alter_column_set_compression_method()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(14))
        {
            return;
1684 1685
        }

1686 1687
        await Test(
            builder => builder.Entity("Blogs", e => e.Property<string>("Title")),
S
Shay Rojansky 已提交
1688
            _ => { },
1689 1690
            builder => builder.Entity("Blogs").Property<string>("Title").UseCompressionMethod("pglz"),
            model =>
1691
            {
1692 1693 1694 1695
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "Title");
                Assert.Equal("pglz", column[NpgsqlAnnotationNames.CompressionMethod]);
            });
1696

1697 1698 1699
        AssertSql(
            @"ALTER TABLE ""Blogs"" ALTER COLUMN ""Title"" SET COMPRESSION pglz");
    }
1700

1701 1702 1703 1704 1705 1706
    [Fact]
    public virtual async Task Alter_column_set_compression_method_to_default()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(14))
        {
            return;
1707 1708
        }

1709
        await Test(
S
Shay Rojansky 已提交
1710
            _ => { },
1711 1712 1713
            builder => builder.Entity("Blogs", e => e.Property<string>("Title").UseCompressionMethod("lz4")),
            builder => builder.Entity("Blogs").Property<string>("Title"),
            model =>
1714
            {
1715 1716 1717 1718
                var table = Assert.Single(model.Tables);
                var column = Assert.Single(table.Columns, c => c.Name == "Title");
                Assert.Null(column[NpgsqlAnnotationNames.CompressionMethod]);
            });
1719

1720 1721 1722
        AssertSql(
            @"ALTER TABLE ""Blogs"" ALTER COLUMN ""Title"" SET COMPRESSION default");
    }
1723

1724 1725 1726
    public override async Task Drop_column()
    {
        await base.Drop_column();
S
Shay Rojansky 已提交
1727

1728 1729 1730
        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""SomeColumn"";");
    }
S
Shay Rojansky 已提交
1731

1732 1733 1734
    public override async Task Drop_column_primary_key()
    {
        await base.Drop_column_primary_key();
S
Shay Rojansky 已提交
1735

1736 1737 1738 1739 1740
        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""PK_People"";",
            //
            @"ALTER TABLE ""People"" DROP COLUMN ""Id"";");
    }
S
Shay Rojansky 已提交
1741

1742 1743 1744 1745
    [ConditionalFact]
    public override async Task Drop_column_computed_and_non_computed_with_dependency()
    {
        if (TestEnvironment.PostgresVersion.IsUnder(12))
S
Shay Rojansky 已提交
1746
        {
1747
            return;
S
Shay Rojansky 已提交
1748 1749
        }

1750 1751 1752 1753
        await Test(
            builder => builder.Entity("People").Property<int>("Id"),
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
1754
                {
1755 1756 1757
                    e.Property<int>("X");
                    e.Property<int>("Y").HasComputedColumnSql($"{DelimitIdentifier("X")} + 1", stored: true);
                }),
S
Shay Rojansky 已提交
1758
            _ => { },
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal("Id", Assert.Single(table.Columns).Name);
            });

        AssertSql(
            @"ALTER TABLE ""People"" DROP COLUMN ""Y"";",
            //
            @"ALTER TABLE ""People"" DROP COLUMN ""X"";");
    }
S
Shay Rojansky 已提交
1770

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
    [Fact]
    public virtual async Task Drop_column_system()
    {
        // System columns (e.g. xmin) are implicitly always present. If an xmin property is removed,
        // nothing should happen.
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<uint>("xmin");
                    e.HasKey("Id");
                }),
S
Shay Rojansky 已提交
1784
            _ => { },
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.HasKey("Id");
                }),
            model =>
            {
                var table = Assert.Single(model.Tables);
                Assert.Equal("Id", Assert.Single(table.Columns).Name);
            });
S
Shay Rojansky 已提交
1796

1797 1798
        AssertSql();
    }
S
Shay Rojansky 已提交
1799

1800 1801 1802
    public override async Task Rename_column()
    {
        await base.Rename_column();
S
Shay Rojansky 已提交
1803

1804 1805 1806
        AssertSql(
            @"ALTER TABLE ""People"" RENAME COLUMN ""SomeColumn"" TO ""SomeOtherColumn"";");
    }
S
Shay Rojansky 已提交
1807

1808
    #endregion
S
Shay Rojansky 已提交
1809

1810
    #region Index
S
Shay Rojansky 已提交
1811

1812 1813 1814
    public override async Task Create_index_unique()
    {
        await base.Create_index_unique();
S
Shay Rojansky 已提交
1815

1816 1817 1818
        AssertSql(
            @"CREATE UNIQUE INDEX ""IX_People_FirstName_LastName"" ON ""People"" (""FirstName"", ""LastName"");");
    }
S
Shay Rojansky 已提交
1819

1820 1821 1822
    public override async Task Create_index_with_filter()
    {
        await base.Create_index_with_filter();
S
Shay Rojansky 已提交
1823

1824 1825 1826
        AssertSql(
            @"CREATE INDEX ""IX_People_Name"" ON ""People"" (""Name"") WHERE ""Name"" IS NOT NULL;");
    }
S
Shay Rojansky 已提交
1827

1828 1829 1830
    public override async Task Create_unique_index_with_filter()
    {
        await base.Create_unique_index_with_filter();
S
Shay Rojansky 已提交
1831

1832 1833 1834
        AssertSql(
            @"CREATE UNIQUE INDEX ""IX_People_Name"" ON ""People"" (""Name"") WHERE ""Name"" IS NOT NULL AND ""Name"" <> '';");
    }
S
Shay Rojansky 已提交
1835

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
    [Fact]
    public virtual async Task Create_index_with_include()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName").HasColumnName("last_name");
                    e.Property<string>("Name");
                }),
S
Shay Rojansky 已提交
1848
            _ => { },
1849 1850 1851 1852 1853 1854 1855 1856
            builder => builder.Entity("People").HasIndex("Name")
                .IncludeProperties("FirstName", "LastName"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal(1, index.Columns.Count);
                Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns);
1857 1858

                // Scaffolding included/covered properties is currently blocked, see #2194
1859
                var includedColumns = (string[])index[NpgsqlAnnotationNames.IndexInclude]!;
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
                Assert.Null(includedColumns);

                // if (TestEnvironment.PostgresVersion.AtLeast(11))
                // {
                //     Assert.Contains("FirstName", includedColumns);
                //     Assert.Contains("last_name", includedColumns);
                // }
                // else
                // {
                //     Assert.Null(includedColumns);
                // }
1871 1872 1873 1874 1875 1876
            });

        AssertSql(TestEnvironment.PostgresVersion.AtLeast(11)
            ? @"CREATE INDEX ""IX_People_Name"" ON ""People"" (""Name"") INCLUDE (""FirstName"", last_name);"
            : @"CREATE INDEX ""IX_People_Name"" ON ""People"" (""Name"");");
    }
S
Shay Rojansky 已提交
1877

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
    [Fact]
    public virtual async Task Create_index_with_include_and_filter()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName");
                    e.Property<string>("Name");
                }),
S
Shay Rojansky 已提交
1890
            _ => { },
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
            builder => builder.Entity("People").HasIndex("Name")
                .IncludeProperties("FirstName", "LastName")
                .HasFilter(@"""Name"" IS NOT NULL"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal(@"(""Name"" IS NOT NULL)", index.Filter);
                Assert.Equal(1, index.Columns.Count);
                Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns);
1901 1902

                // Scaffolding included/covered properties is currently blocked, see #2194
1903
                var includedColumns = (string[])index[NpgsqlAnnotationNames.IndexInclude]!;
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
                Assert.Null(includedColumns);

                // if (TestEnvironment.PostgresVersion.AtLeast(11))
                // {
                //     Assert.Contains("FirstName", includedColumns);
                //     Assert.Contains("LastName", includedColumns);
                // }
                // else
                // {
                //     Assert.Null(includedColumns);
                // }
1915 1916 1917 1918 1919 1920
            });

        AssertSql(TestEnvironment.PostgresVersion.AtLeast(11)
            ? @"CREATE INDEX ""IX_People_Name"" ON ""People"" (""Name"") INCLUDE (""FirstName"", ""LastName"") WHERE ""Name"" IS NOT NULL;"
            : @"CREATE INDEX ""IX_People_Name"" ON ""People"" (""Name"") WHERE ""Name"" IS NOT NULL;");
    }
S
Shay Rojansky 已提交
1921

1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
    [Fact]
    public virtual async Task Create_index_unique_with_include()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName");
                    e.Property<string>("Name").IsRequired();
                }),
S
Shay Rojansky 已提交
1934
            _ => { },
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
            builder => builder.Entity("People").HasIndex("Name")
                .IsUnique()
                .IncludeProperties("FirstName", "LastName"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.True(index.IsUnique);
                Assert.Equal(1, index.Columns.Count);
                Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns);
1945 1946

                // Scaffolding included/covered properties is currently blocked, see #2194
1947
                var includedColumns = (string[])index[NpgsqlAnnotationNames.IndexInclude]!;
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
                Assert.Null(includedColumns);

                // if (TestEnvironment.PostgresVersion.AtLeast(11))
                // {
                //     Assert.Contains("FirstName", includedColumns);
                //     Assert.Contains("LastName", includedColumns);
                // }
                // else
                // {
                //     Assert.Null(includedColumns);
                // }
1959 1960 1961 1962 1963 1964
            });

        AssertSql(TestEnvironment.PostgresVersion.AtLeast(11)
            ? @"CREATE UNIQUE INDEX ""IX_People_Name"" ON ""People"" (""Name"") INCLUDE (""FirstName"", ""LastName"");"
            : @"CREATE UNIQUE INDEX ""IX_People_Name"" ON ""People"" (""Name"");");
    }
S
Shay Rojansky 已提交
1965

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    [Fact]
    public virtual async Task Create_index_unique_with_include_and_filter()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName");
                    e.Property<string>("Name").IsRequired();
                }),
S
Shay Rojansky 已提交
1978
            _ => { },
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
            builder => builder.Entity("People").HasIndex("Name")
                .IsUnique()
                .IncludeProperties("FirstName", "LastName")
                .HasFilter(@"""Name"" IS NOT NULL"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.True(index.IsUnique);
                Assert.Equal(@"(""Name"" IS NOT NULL)", index.Filter);
                Assert.Equal(1, index.Columns.Count);
                Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns);
1991 1992

                // Scaffolding included/covered properties is currently blocked, see #2194
1993
                var includedColumns = (string[])index[NpgsqlAnnotationNames.IndexInclude]!;
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
                Assert.Null(includedColumns);

                // if (TestEnvironment.PostgresVersion.AtLeast(11))
                // {
                //     Assert.Contains("FirstName", includedColumns);
                //     Assert.Contains("LastName", includedColumns);
                // }
                // else
                // {
                //     Assert.Null(includedColumns);
                // }
2005 2006 2007 2008 2009 2010
            });

        AssertSql(TestEnvironment.PostgresVersion.AtLeast(11)
            ? @"CREATE UNIQUE INDEX ""IX_People_Name"" ON ""People"" (""Name"") INCLUDE (""FirstName"", ""LastName"") WHERE ""Name"" IS NOT NULL;"
            : @"CREATE UNIQUE INDEX ""IX_People_Name"" ON ""People"" (""Name"") WHERE ""Name"" IS NOT NULL;");
    }
S
Shay Rojansky 已提交
2011

2012 2013 2014 2015 2016 2017
    [Fact]
    public virtual async Task Create_index_concurrently()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
2018
                {
2019 2020 2021
                    e.Property<int>("Id");
                    e.Property<int>("Age");
                }),
S
Shay Rojansky 已提交
2022
            _ => { },
2023 2024 2025
            builder => builder.Entity("People").HasIndex("Age")
                .IsCreatedConcurrently(),
            asserter: null); // No scaffolding for IsCreatedConcurrently
S
Shay Rojansky 已提交
2026

2027 2028 2029
        AssertSql(
            @"CREATE INDEX CONCURRENTLY ""IX_People_Age"" ON ""People"" (""Age"");");
    }
S
Shay Rojansky 已提交
2030

2031 2032 2033 2034 2035 2036
    [Fact]
    public virtual async Task Create_index_with_method()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
2037
                {
2038 2039 2040
                    e.Property<int>("Id");
                    e.Property<int>("Age");
                }),
S
Shay Rojansky 已提交
2041
            _ => { },
2042 2043 2044 2045 2046 2047 2048 2049
            builder => builder.Entity("People").HasIndex("Age")
                .HasMethod("hash"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal("hash", index[NpgsqlAnnotationNames.IndexMethod]);
            });
S
Shay Rojansky 已提交
2050

2051 2052 2053
        AssertSql(
            @"CREATE INDEX ""IX_People_Age"" ON ""People"" USING hash (""Age"");");
    }
S
Shay Rojansky 已提交
2054

2055 2056 2057 2058 2059 2060
    [Fact]
    public virtual async Task Create_index_with_operators()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
2061
                {
2062 2063 2064 2065
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName");
                }),
S
Shay Rojansky 已提交
2066
            _ => { },
2067 2068 2069 2070 2071 2072 2073 2074
            builder => builder.Entity("People").HasIndex("FirstName", "LastName")
                .HasOperators("text_pattern_ops"),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal(new[] { "text_pattern_ops", null }, index[NpgsqlAnnotationNames.IndexOperators]);
            });
S
Shay Rojansky 已提交
2075

2076 2077 2078
        AssertSql(
            @"CREATE INDEX ""IX_People_FirstName_LastName"" ON ""People"" (""FirstName"" text_pattern_ops, ""LastName"");");
    }
S
Shay Rojansky 已提交
2079

2080 2081 2082
    // Index collation: which collations are available on a given PostgreSQL varies (e.g. Linux vs. Windows),
    // so we test support for this on the generated SQL only, in NpgsqlMigrationSqlGeneratorTest, and not against
    // the database here.
S
Shay Rojansky 已提交
2083

2084 2085 2086 2087 2088 2089
    [Fact]
    public virtual async Task Create_index_with_sort_order()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
S
Shay Rojansky 已提交
2090
                {
2091 2092 2093 2094
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("LastName");
                }),
S
Shay Rojansky 已提交
2095
            _ => { },
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
            builder => builder.Entity("People").HasIndex("FirstName", "LastName")
                .HasSortOrder(SortOrder.Descending, SortOrder.Ascending),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal(new[] { SortOrder.Descending, SortOrder.Ascending },
                    index[NpgsqlAnnotationNames.IndexSortOrder]);
            });

        AssertSql(
            @"CREATE INDEX ""IX_People_FirstName_LastName"" ON ""People"" (""FirstName"" DESC, ""LastName"");");
    }
S
Shay Rojansky 已提交
2109

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
    [Fact]
    public virtual async Task Create_index_with_null_sort_order()
    {
        await Test(
            builder => builder.Entity(
                "People", e =>
                {
                    e.Property<int>("Id");
                    e.Property<string>("FirstName");
                    e.Property<string>("MiddleName");
                    e.Property<string>("LastName");
                }),
S
Shay Rojansky 已提交
2122
            _ => { },
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
            builder => builder.Entity("People").HasIndex("FirstName", "MiddleName", "LastName")
                .HasNullSortOrder(NullSortOrder.NullsFirst, NullSortOrder.Unspecified, NullSortOrder.NullsLast),
            model =>
            {
                var table = Assert.Single(model.Tables);
                var index = Assert.Single(table.Indexes);
                Assert.Equal(new[] { NullSortOrder.NullsFirst, NullSortOrder.NullsLast, NullSortOrder.NullsLast },
                    index[NpgsqlAnnotationNames.IndexNullSortOrder]);
            });

        AssertSql(
            @"CREATE INDEX ""IX_People_FirstName_MiddleName_LastName"" ON ""People"" (""FirstName"" NULLS FIRST, ""MiddleName"", ""LastName"" NULLS LAST);");
    }
S
Shay Rojansky 已提交
2136

2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
    [Fact]
    public virtual async Task Create_index_tsvector()
    {
        await Test(
            builder => builder.Entity(
                "Blogs", e =>
                {
                    e.Property<string>("Title").IsRequired();
                    e.Property<string>("Description");
                }),
S
Shay Rojansky 已提交
2147
            _ => { },
2148 2149 2150
            builder => builder.Entity("Blogs")
                .HasIndex("Title", "Description")
                .IsTsVectorExpressionIndex("simple"),
S
Shay Rojansky 已提交
2151
            _ => { });
2152 2153 2154 2155

        AssertSql(
            @"CREATE INDEX ""IX_Blogs_Title_Description"" ON ""Blogs"" (to_tsvector('simple', ""Title"" || ' ' || coalesce(""Description"", '')));");
    }
2156

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
    [Fact]
    public virtual async Task Create_index_tsvector_using_gin()
    {
        await Test(
            builder => builder.Entity(
                "Blogs", e =>
                {
                    e.Property<string>("Title").IsRequired();
                    e.Property<string>("Description");
                }),
S
Shay Rojansky 已提交
2167
            _ => { },
2168 2169 2170 2171
            builder => builder.Entity("Blogs")
                .HasIndex("Title", "Description")
                .HasMethod("GIN")
                .IsTsVectorExpressionIndex("simple"),
S
Shay Rojansky 已提交
2172
            _ => { });
2173 2174 2175 2176

        AssertSql(
            @"CREATE INDEX ""IX_Blogs_Title_Description"" ON ""Blogs"" USING GIN (to_tsvector('simple', ""Title"" || ' ' || coalesce(""Description"", '')));");
    }
2177

2178 2179 2180
    public override async Task Drop_index()
    {
        await base.Drop_index();
S
Shay Rojansky 已提交
2181

2182 2183 2184
        AssertSql(
            @"DROP INDEX ""IX_People_SomeField"";");
    }
S
Shay Rojansky 已提交
2185

2186 2187 2188
    public override async Task Rename_index()
    {
        await base.Rename_index();
S
Shay Rojansky 已提交
2189

2190 2191 2192
        AssertSql(
            @"ALTER INDEX ""Foo"" RENAME TO foo;");
    }
S
Shay Rojansky 已提交
2193

2194
    #endregion
S
Shay Rojansky 已提交
2195

2196
    #region Key and constraint
S
Shay Rojansky 已提交
2197

S
Shay Rojansky 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
    public override async Task Add_primary_key_int()
    {
        await base.Add_primary_key_int();

        AssertSql(
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeField"" DROP DEFAULT;
ALTER TABLE ""People"" ALTER COLUMN ""SomeField"" ADD GENERATED BY DEFAULT AS IDENTITY;",
            //
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""PK_People"" PRIMARY KEY (""SomeField"");");
    }

    public override async Task Add_primary_key_string()
2210
    {
S
Shay Rojansky 已提交
2211
        await base.Add_primary_key_string();
S
Shay Rojansky 已提交
2212

2213 2214 2215
        AssertSql(
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""PK_People"" PRIMARY KEY (""SomeField"");");
    }
S
Shay Rojansky 已提交
2216

2217 2218 2219
    public override async Task Add_primary_key_with_name()
    {
        await base.Add_primary_key_with_name();
S
Shay Rojansky 已提交
2220

2221
        AssertSql(
S
Shay Rojansky 已提交
2222 2223 2224
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeField"" SET NOT NULL;
ALTER TABLE ""People"" ALTER COLUMN ""SomeField"" SET DEFAULT '';",
            //
2225 2226
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""PK_Foo"" PRIMARY KEY (""SomeField"");");
    }
S
Shay Rojansky 已提交
2227

2228 2229 2230
    public override async Task Add_primary_key_composite_with_name()
    {
        await base.Add_primary_key_composite_with_name();
S
Shay Rojansky 已提交
2231

2232 2233 2234
        AssertSql(
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""PK_Foo"" PRIMARY KEY (""SomeField1"", ""SomeField2"");");
    }
S
Shay Rojansky 已提交
2235

S
Shay Rojansky 已提交
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
    public override async Task Drop_primary_key_int()
    {
        await base.Drop_primary_key_int();

        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""PK_People"";",
            //
            @"ALTER TABLE ""People"" ALTER COLUMN ""SomeField"" DROP IDENTITY;");
    }

    public override async Task Drop_primary_key_string()
2247
    {
S
Shay Rojansky 已提交
2248
        await base.Drop_primary_key_string();
S
Shay Rojansky 已提交
2249

2250 2251 2252
        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""PK_People"";");
    }
S
Shay Rojansky 已提交
2253

2254 2255
    public override Task Add_foreign_key()
        => Task.CompletedTask; // https://github.com/npgsql/efcore.pg/issues/1217
S
Shay Rojansky 已提交
2256

2257 2258 2259
    public override async Task Add_foreign_key_with_name()
    {
        await base.Add_foreign_key_with_name();
S
Shay Rojansky 已提交
2260

2261
        AssertSql(
S
Shay Rojansky 已提交
2262 2263 2264
            @"CREATE INDEX ""IX_Orders_CustomerId"" ON ""Orders"" (""CustomerId"");",
            //
            @"ALTER TABLE ""Orders"" ADD CONSTRAINT ""FK_Foo"" FOREIGN KEY (""CustomerId"") REFERENCES ""Customers"" (""Id"") ON DELETE CASCADE;");
2265
    }
S
Shay Rojansky 已提交
2266

2267 2268 2269
    public override async Task Drop_foreign_key()
    {
        await base.Drop_foreign_key();
S
Shay Rojansky 已提交
2270

2271
        AssertSql(
S
Shay Rojansky 已提交
2272 2273 2274
            @"ALTER TABLE ""Orders"" DROP CONSTRAINT ""FK_Orders_Customers_CustomerId"";",
            //
            @"DROP INDEX ""IX_Orders_CustomerId"";");
2275
    }
S
Shay Rojansky 已提交
2276

2277 2278 2279
    public override async Task Add_unique_constraint()
    {
        await base.Add_unique_constraint();
S
Shay Rojansky 已提交
2280

2281 2282 2283
        AssertSql(
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""AK_People_AlternateKeyColumn"" UNIQUE (""AlternateKeyColumn"");");
    }
S
Shay Rojansky 已提交
2284

2285 2286 2287
    public override async Task Add_unique_constraint_composite_with_name()
    {
        await base.Add_unique_constraint_composite_with_name();
S
Shay Rojansky 已提交
2288

2289 2290 2291
        AssertSql(
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""AK_Foo"" UNIQUE (""AlternateKeyColumn1"", ""AlternateKeyColumn2"");");
    }
S
Shay Rojansky 已提交
2292

2293 2294 2295
    public override async Task Drop_unique_constraint()
    {
        await base.Drop_unique_constraint();
S
Shay Rojansky 已提交
2296

2297 2298 2299
        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""AK_People_AlternateKeyColumn"";");
    }
S
Shay Rojansky 已提交
2300

2301 2302 2303
    public override async Task Add_check_constraint_with_name()
    {
        await base.Add_check_constraint_with_name();
S
Shay Rojansky 已提交
2304

2305 2306 2307
        AssertSql(
            @"ALTER TABLE ""People"" ADD CONSTRAINT ""CK_People_Foo"" CHECK (""DriverLicense"" > 0);");
    }
S
Shay Rojansky 已提交
2308

2309 2310 2311
    public override async Task Drop_check_constraint()
    {
        await base.Drop_check_constraint();
S
Shay Rojansky 已提交
2312

2313 2314 2315
        AssertSql(
            @"ALTER TABLE ""People"" DROP CONSTRAINT ""CK_People_Foo"";");
    }
S
Shay Rojansky 已提交
2316

2317
    #endregion
S
Shay Rojansky 已提交
2318

2319
    #region Sequence
S
Shay Rojansky 已提交
2320

2321 2322 2323
    public override async Task Create_sequence()
    {
        await base.Create_sequence();
S
Shay Rojansky 已提交
2324

2325 2326 2327
        AssertSql(
            @"CREATE SEQUENCE ""TestSequence"" AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE;");
    }
S
Shay Rojansky 已提交
2328

2329 2330 2331
    public override async Task Create_sequence_all_settings()
    {
        await base.Create_sequence_all_settings();
S
Shay Rojansky 已提交
2332

2333
        AssertSql(
2334 2335 2336 2337 2338 2339
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'dbo2') THEN
        CREATE SCHEMA dbo2;
    END IF;
END $EF$;",
2340 2341 2342
            //
            @"CREATE SEQUENCE dbo2.""TestSequence"" START WITH 3 INCREMENT BY 2 MINVALUE 2 MAXVALUE 916 CYCLE;");
    }
S
Shay Rojansky 已提交
2343

2344 2345 2346 2347
    [Fact]
    public virtual async Task Create_sequence_smallint()
    {
        await Test(
S
Shay Rojansky 已提交
2348
            _ => { },
2349 2350 2351 2352 2353 2354 2355
            builder => builder.HasSequence<short>("TestSequence"),
            model =>
            {
                var sequence = Assert.Single(model.Sequences);
                Assert.Equal("TestSequence", sequence.Name);
                Assert.Equal("smallint", sequence.StoreType);
            });
S
Shay Rojansky 已提交
2356

2357 2358 2359
        AssertSql(
            @"CREATE SEQUENCE ""TestSequence"" AS smallint START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE;");
    }
S
Shay Rojansky 已提交
2360

2361 2362 2363 2364 2365
    [Fact]
    public override async Task Alter_sequence_all_settings()
    {
        await Test(
            builder => builder.HasSequence<int>("foo"),
S
Shay Rojansky 已提交
2366
            _ => { },
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
            builder => builder.HasSequence<int>("foo")
                .StartsAt(-3)
                .IncrementsBy(2)
                .HasMin(-5)
                .HasMax(10)
                .IsCyclic(),
            model =>
            {
                var sequence = Assert.Single(model.Sequences);
                Assert.Equal(1, sequence.StartValue); // Restarting doesn't change the scaffolded start value
                Assert.Equal(2, sequence.IncrementBy);
                Assert.Equal(-5, sequence.MinValue);
                Assert.Equal(10, sequence.MaxValue);
                Assert.True(sequence.IsCyclic);
            });

        AssertSql(
            @"ALTER SEQUENCE foo INCREMENT BY 2 MINVALUE -5 MAXVALUE 10 CYCLE;",
            //
            @"ALTER SEQUENCE foo RESTART WITH -3;");
    }
S
Shay Rojansky 已提交
2388

2389 2390 2391
    public override async Task Alter_sequence_increment_by()
    {
        await base.Alter_sequence_increment_by();
S
Shay Rojansky 已提交
2392

2393 2394 2395
        AssertSql(
            @"ALTER SEQUENCE foo INCREMENT BY 2 NO MINVALUE NO MAXVALUE NO CYCLE;");
    }
S
Shay Rojansky 已提交
2396

2397 2398 2399
    public override async Task Drop_sequence()
    {
        await base.Drop_sequence();
S
Shay Rojansky 已提交
2400

2401 2402 2403
        AssertSql(
            @"DROP SEQUENCE ""TestSequence"";");
    }
S
Shay Rojansky 已提交
2404

2405 2406 2407
    public override async Task Rename_sequence()
    {
        await base.Rename_sequence();
S
Shay Rojansky 已提交
2408

2409 2410 2411
        AssertSql(
            @"ALTER SEQUENCE ""TestSequence"" RENAME TO testsequence;");
    }
S
Shay Rojansky 已提交
2412

2413 2414 2415
    public override async Task Move_sequence()
    {
        await base.Move_sequence();
S
Shay Rojansky 已提交
2416

2417
        AssertSql(
2418 2419 2420 2421 2422 2423
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'TestSequenceSchema') THEN
        CREATE SCHEMA ""TestSequenceSchema"";
    END IF;
END $EF$;",
2424 2425 2426
            //
            @"ALTER SEQUENCE ""TestSequence"" SET SCHEMA ""TestSequenceSchema"";");
    }
S
Shay Rojansky 已提交
2427

2428
    #endregion
S
Shay Rojansky 已提交
2429

2430
    #region Data seeding
S
Shay Rojansky 已提交
2431

2432 2433 2434
    public override async Task InsertDataOperation()
    {
        await base.InsertDataOperation();
S
Shay Rojansky 已提交
2435

2436 2437
        AssertSql(
            @"INSERT INTO ""Person"" (""Id"", ""Name"")
S
Shay Rojansky 已提交
2438 2439 2440 2441 2442 2443 2444 2445
VALUES (1, 'Daenerys Targaryen');
INSERT INTO ""Person"" (""Id"", ""Name"")
VALUES (2, 'John Snow');
INSERT INTO ""Person"" (""Id"", ""Name"")
VALUES (3, 'Arya Stark');
INSERT INTO ""Person"" (""Id"", ""Name"")
VALUES (4, 'Harry Strickland');
INSERT INTO ""Person"" (""Id"", ""Name"")
S
Shay Rojansky 已提交
2446 2447 2448 2449 2450 2451 2452 2453
VALUES (5, NULL);",
            //
            @"SELECT setval(
    pg_get_serial_sequence('""Person""', 'Id'),
    GREATEST(
        (SELECT MAX(""Id"") FROM ""Person"") + 1,
        nextval(pg_get_serial_sequence('""Person""', 'Id'))),
    false);");
2454
    }
S
Shay Rojansky 已提交
2455

2456 2457 2458
    public override async Task DeleteDataOperation_simple_key()
    {
        await base.DeleteDataOperation_simple_key();
S
Shay Rojansky 已提交
2459

2460 2461
        AssertSql(
            @"DELETE FROM ""Person""
S
Shay Rojansky 已提交
2462
WHERE ""Id"" = 2;");
2463
    }
S
Shay Rojansky 已提交
2464

2465 2466 2467
    public override async Task DeleteDataOperation_composite_key()
    {
        await base.DeleteDataOperation_composite_key();
S
Shay Rojansky 已提交
2468

2469 2470
        AssertSql(
            @"DELETE FROM ""Person""
S
Shay Rojansky 已提交
2471
WHERE ""AnotherId"" = 12 AND ""Id"" = 2;");
2472
    }
S
Shay Rojansky 已提交
2473

2474 2475 2476
    public override async Task UpdateDataOperation_simple_key()
    {
        await base.UpdateDataOperation_simple_key();
S
Shay Rojansky 已提交
2477

2478 2479
        AssertSql(
            @"UPDATE ""Person"" SET ""Name"" = 'Another John Snow'
S
Shay Rojansky 已提交
2480
WHERE ""Id"" = 2;");
2481
    }
S
Shay Rojansky 已提交
2482

2483 2484 2485
    public override async Task UpdateDataOperation_composite_key()
    {
        await base.UpdateDataOperation_composite_key();
S
Shay Rojansky 已提交
2486

2487 2488
        AssertSql(
            @"UPDATE ""Person"" SET ""Name"" = 'Another John Snow'
S
Shay Rojansky 已提交
2489
WHERE ""AnotherId"" = 11 AND ""Id"" = 2;");
2490
    }
S
Shay Rojansky 已提交
2491

2492 2493 2494
    public override async Task UpdateDataOperation_multiple_columns()
    {
        await base.UpdateDataOperation_multiple_columns();
S
Shay Rojansky 已提交
2495

2496 2497
        AssertSql(
            @"UPDATE ""Person"" SET ""Age"" = 21, ""Name"" = 'Another John Snow'
S
Shay Rojansky 已提交
2498
WHERE ""Id"" = 2;");
2499
    }
S
Shay Rojansky 已提交
2500

2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
    [ConditionalFact]
    public virtual async Task InsertDataOperation_restarts_identity()
    {
        await Test(
            builder =>
            {
                builder.Entity(
                    "Person", e =>
                    {
                        e.Property<int>("Id").UseIdentityByDefaultColumn();
                        e.Property<string>("Name");
                        e.HasKey("Id");
                    });
                builder.Entity(
                    "Person2", e =>
                    {
                        e.Property<int>("Id").UseIdentityByDefaultColumn();
                        e.Property<string>("Name");
                        e.HasKey("Id");
                    });
            },
S
Shay Rojansky 已提交
2522
            _ => { },
2523 2524 2525 2526 2527 2528 2529 2530 2531
            builder =>
            {
                builder.Entity("Person").HasData(
                    new { Id = 1, Name = "Daenerys Targaryen" },
                    new { Id = 2, Name = "John Snow"});
                builder.Entity("Person2").HasData(
                    new { Id = -10, Name = "Daenerys Targaryen" },
                    new { Id = -20, Name = "John Snow"});
            },
S
Shay Rojansky 已提交
2532
            _ => { });
2533 2534 2535

        AssertSql(
            @"INSERT INTO ""Person"" (""Id"", ""Name"")
2536 2537 2538
VALUES (1, 'Daenerys Targaryen');
INSERT INTO ""Person"" (""Id"", ""Name"")
VALUES (2, 'John Snow');",
2539 2540
            //
            @"INSERT INTO ""Person2"" (""Id"", ""Name"")
S
Shay Rojansky 已提交
2541
VALUES (-20, 'John Snow');
2542
INSERT INTO ""Person2"" (""Id"", ""Name"")
S
Shay Rojansky 已提交
2543
VALUES (-10, 'Daenerys Targaryen');",
2544 2545
            //
            @"SELECT setval(
2546 2547 2548 2549 2550 2551
    pg_get_serial_sequence('""Person""', 'Id'),
    GREATEST(
        (SELECT MAX(""Id"") FROM ""Person"") + 1,
        nextval(pg_get_serial_sequence('""Person""', 'Id'))),
    false);
SELECT setval(
2552
    pg_get_serial_sequence('""Person2""', 'Id'),
2553
    GREATEST(
2554 2555
        (SELECT MAX(""Id"") FROM ""Person2"") + 1,
        nextval(pg_get_serial_sequence('""Person2""', 'Id'))),
2556
    false);");
2557
    }
2558

2559
    #endregion
S
Shay Rojansky 已提交
2560

2561
    #region PostgreSQL extensions
S
Shay Rojansky 已提交
2562

2563 2564 2565 2566
    [Fact]
    public virtual async Task Ensure_postgres_extension()
    {
        await Test(
S
Shay Rojansky 已提交
2567
            _ => { },
2568 2569 2570 2571 2572 2573 2574
            builder => builder.HasPostgresExtension("citext"),
            model =>
            {
                var citext = Assert.Single(model.GetPostgresExtensions());
                Assert.Equal("citext", citext.Name);
                Assert.Equal("public", citext.Schema);
            });
S
Shay Rojansky 已提交
2575

2576 2577 2578
        AssertSql(
            @"CREATE EXTENSION IF NOT EXISTS citext;");
    }
S
Shay Rojansky 已提交
2579

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
    [Fact]
    public virtual async Task Ensure_postgres_extension_with_schema()
    {
        await Test(
            _ => { },
            builder => builder.HasPostgresExtension("some_schema", "citext"),
            model =>
            {
                var citext = Assert.Single(model.GetPostgresExtensions());
                Assert.Equal("citext", citext.Name);
                Assert.Equal("some_schema", citext.Schema);
            });

        AssertSql(
2594 2595 2596 2597 2598 2599
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'some_schema') THEN
        CREATE SCHEMA some_schema;
    END IF;
END $EF$;",
2600 2601 2602
            //
            @"CREATE EXTENSION IF NOT EXISTS citext SCHEMA some_schema;");
    }
S
Shay Rojansky 已提交
2603

2604
    #endregion
S
Shay Rojansky 已提交
2605

2606
    #region PostgreSQL enums
S
Shay Rojansky 已提交
2607

2608 2609 2610 2611
    [Fact]
    public virtual async Task Create_enum()
    {
        await Test(
S
Shay Rojansky 已提交
2612
            _ => { },
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
            model =>
            {
                var moodEnum = Assert.Single(model.GetPostgresEnums());
                Assert.Equal("Mood", moodEnum.Name);
                Assert.Null(moodEnum.Schema);
                Assert.Collection(moodEnum.Labels,
                    l => Assert.Equal("Happy", l),
                    l => Assert.Equal("Sad", l));
            });

        AssertSql(
            @"CREATE TYPE ""Mood"" AS ENUM ('Happy', 'Sad');");
    }
S
Shay Rojansky 已提交
2627

2628 2629 2630 2631
    [Fact]
    public virtual async Task Create_enum_with_schema()
    {
        await Test(
S
Shay Rojansky 已提交
2632
            _ => { },
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
            builder => builder.HasPostgresEnum("some_schema", "Mood", new[] { "Happy", "Sad" }),
            model =>
            {
                var moodEnum = Assert.Single(model.GetPostgresEnums());
                Assert.Equal("Mood", moodEnum.Name);
                Assert.Equal("some_schema", moodEnum.Schema);
                Assert.Collection(moodEnum.Labels,
                    l => Assert.Equal("Happy", l),
                    l => Assert.Equal("Sad", l));
            });

        AssertSql(
2645 2646 2647 2648 2649 2650
            @"DO $EF$
BEGIN
    IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'some_schema') THEN
        CREATE SCHEMA some_schema;
    END IF;
END $EF$;",
2651 2652 2653
            //
            @"CREATE TYPE some_schema.""Mood"" AS ENUM ('Happy', 'Sad');");
    }
S
Shay Rojansky 已提交
2654

2655 2656 2657 2658 2659
    [Fact]
    public virtual async Task Drop_enum()
    {
        await Test(
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
S
Shay Rojansky 已提交
2660
            _ => { },
2661
            model => Assert.Empty(model.GetPostgresEnums()));
S
Shay Rojansky 已提交
2662

2663 2664 2665
        AssertSql(
            @"DROP TYPE ""Mood"";");
    }
S
Shay Rojansky 已提交
2666

2667 2668 2669 2670 2671
    [Fact] // #979
    public virtual async Task Do_not_alter_existing_enum_when_creating_new_one()
    {
        await Test(
            builder => builder.HasPostgresEnum("Enum1", new[] { "A", "B" }),
S
Shay Rojansky 已提交
2672
            _ => { },
2673 2674 2675 2676 2677 2678
            builder => builder.HasPostgresEnum("Enum2", new[] { "X", "Y" }),
            model => Assert.Equal(2, model.GetPostgresEnums().Count()));

        AssertSql(
            @"CREATE TYPE ""Enum2"" AS ENUM ('X', 'Y');");
    }
S
Shay Rojansky 已提交
2679

2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
    [Fact]
    public virtual async Task Alter_enum_add_label_at_end()
    {
        await Test(
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad", "Angry" }),
            model =>
            {
                var moodEnum = Assert.Single(model.GetPostgresEnums());
                Assert.Collection(moodEnum.Labels,
                    l => Assert.Equal("Happy", l),
                    l => Assert.Equal("Sad", l),
                    l => Assert.Equal("Angry", l));
            });

        AssertSql(
            @"ALTER TYPE ""Mood"" ADD VALUE 'Angry';");
    }
S
Shay Rojansky 已提交
2698

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
    [Fact]
    public virtual async Task Alter_enum_add_label_in_middle()
    {
        await Test(
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Angry", "Sad" }),
            model =>
            {
                var moodEnum = Assert.Single(model.GetPostgresEnums());
                Assert.Collection(moodEnum.Labels,
                    l => Assert.Equal("Happy", l),
                    l => Assert.Equal("Angry", l),
                    l => Assert.Equal("Sad", l));
            });

        AssertSql(
            @"ALTER TYPE ""Mood"" ADD VALUE 'Angry' BEFORE 'Sad';");
    }
S
Shay Rojansky 已提交
2717

2718 2719 2720 2721 2722
    [Fact]
    public virtual Task Alter_enum_drop_label_not_supported()
        => TestThrows<NotSupportedException>(
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy" }));
S
Shay Rojansky 已提交
2723

2724 2725 2726 2727 2728
    [Fact]
    public virtual Task Alter_enum_change_label_not_supported()
        => TestThrows<NotSupportedException>(
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Sad" }),
            builder => builder.HasPostgresEnum("Mood", new[] { "Happy", "Angry" }));
S
Shay Rojansky 已提交
2729

2730
    #endregion
S
Shay Rojansky 已提交
2731

2732
    #region PostgreSQL collation management
2733

2734 2735 2736 2737
    [Fact]
    public virtual async Task Create_collation()
    {
        await Test(
S
Shay Rojansky 已提交
2738
            _ => { },
2739 2740 2741 2742
            builder => builder.HasCollation("dummy", locale: "POSIX", provider: "libc"),
            model =>
            {
                var collation = Assert.Single(PostgresCollation.GetCollations(model));
2743

2744 2745 2746 2747 2748 2749
                Assert.Equal("dummy", collation.Name);
                Assert.Equal("libc", collation.Provider);
                Assert.Equal("POSIX", collation.LcCollate);
                Assert.Equal("POSIX", collation.LcCtype);
                Assert.True(collation.IsDeterministic);
            });
2750

2751 2752
        AssertSql(
            @"CREATE COLLATION dummy (LC_COLLATE = 'POSIX',
2753 2754 2755
    LC_CTYPE = 'POSIX',
    PROVIDER = libc
);");
2756
    }
2757

2758 2759 2760 2761 2762
    [ConditionalFact]
    [MinimumPostgresVersion(12, 0)]
    public virtual async Task Create_collation_non_deterministic()
    {
        await Test(
S
Shay Rojansky 已提交
2763
            _ => { },
2764 2765 2766 2767
            builder => builder.HasCollation("some_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false),
            model =>
            {
                var collation = Assert.Single(PostgresCollation.GetCollations(model));
2768

2769 2770 2771 2772 2773 2774
                Assert.Equal("some_collation", collation.Name);
                Assert.Equal("icu", collation.Provider);
                Assert.Equal("en-u-ks-primary", collation.LcCollate);
                Assert.Equal("en-u-ks-primary", collation.LcCtype);
                Assert.False(collation.IsDeterministic);
            });
2775

2776 2777
        AssertSql(
            @"CREATE COLLATION some_collation (LC_COLLATE = 'en-u-ks-primary',
2778 2779 2780 2781
    LC_CTYPE = 'en-u-ks-primary',
    PROVIDER = icu,
    DETERMINISTIC = False
);");
2782
    }
2783

2784 2785 2786 2787 2788
    [Fact]
    public virtual async Task Drop_collation()
    {
        await Test(
            builder => builder.HasCollation("dummy", locale: "POSIX", provider: "libc"),
S
Shay Rojansky 已提交
2789
            _ => { },
2790
            model => Assert.Empty(PostgresCollation.GetCollations(model)));
2791

2792 2793 2794
        AssertSql(
            @"DROP COLLATION dummy;");
    }
2795

2796 2797 2798 2799 2800
    [Fact]
    public virtual Task Alter_collation_throws()
        => TestThrows<NotSupportedException>(
            builder => builder.HasCollation("dummy", locale: "POSIX", provider: "libc"),
            builder => builder.HasCollation("dummy", locale: "C", provider: "libc"));
2801

2802
    #endregion PostgreSQL collation management
2803

2804
    protected override string NonDefaultCollation => "POSIX";
2805

2806 2807
    public class MigrationsNpgsqlFixture : MigrationsFixtureBase
    {
S
Shay Rojansky 已提交
2808
        protected override string StoreName => nameof(MigrationsNpgsqlTest);
2809 2810 2811 2812 2813 2814 2815 2816
        protected override ITestStoreFactory TestStoreFactory => NpgsqlTestStoreFactory.Instance;
        public override TestHelpers TestHelpers => NpgsqlTestHelpers.Instance;

        protected override IServiceCollection AddServices(IServiceCollection serviceCollection)
            => base.AddServices(serviceCollection)
                .AddScoped<IDatabaseModelFactory, NpgsqlDatabaseModelFactory>();

        public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
S
Shay Rojansky 已提交
2817
        {
2818 2819 2820
            new NpgsqlDbContextOptionsBuilder(base.AddOptions(builder)
                    // Some tests create expression indexes, but these cannot be reverse-engineered.
                    .ConfigureWarnings(
S
Shay Rojansky 已提交
2821
                        w => { w.Ignore(NpgsqlEfEventId.ExpressionIndexSkippedWarning); }))
2822 2823 2824 2825 2826
                // Various migration operations PG-version sensitive, configure the context with the actual version
                // we're connecting to.
                .SetPostgresVersion(TestEnvironment.PostgresVersion);

            return builder;
S
Shay Rojansky 已提交
2827
        }
2828
    }
S
Shay Rojansky 已提交
2829 2830 2831 2832 2833

    protected override ICollection<BuildReference> GetAdditionalReferences()
        => AdditionalReferences;

    private static readonly BuildReference[] AdditionalReferences = { BuildReference.ByName("Npgsql") };
S
Shay Rojansky 已提交
2834
}