-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathNpgsqlMigrationsSqlGenerator.cs
More file actions
1878 lines (1579 loc) · 77 KB
/
NpgsqlMigrationsSqlGenerator.cs
File metadata and controls
1878 lines (1579 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Operations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Migrations
{
public class NpgsqlMigrationsSqlGenerator : MigrationsSqlGenerator
{
private readonly RelationalTypeMapping _stringTypeMapping;
/// <summary>
/// The backend version to target.
/// </summary>
private readonly Version _postgresVersion;
public NpgsqlMigrationsSqlGenerator(
MigrationsSqlGeneratorDependencies dependencies,
INpgsqlOptions npgsqlOptions)
: base(dependencies)
{
_postgresVersion = npgsqlOptions.PostgresVersion;
_stringTypeMapping = dependencies.TypeMappingSource.GetMapping(typeof(string))
?? throw new InvalidOperationException("No string type mapping found");
}
public override IReadOnlyList<MigrationCommand> Generate(
IReadOnlyList<MigrationOperation> operations,
IModel? model = null,
MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default)
{
var results = base.Generate(operations, model, options);
// For all tables where we had data seeding insertions, get any identity/serial columns for those tables.
var seededGeneratedColumns = operations
.OfType<InsertDataOperation>()
.Select(o => new { o.Schema, o.Table })
.Distinct()
.Select(t => new
{
t.Schema,
t.Table,
Columns = (model?.GetRelationalModel().FindTable(t.Table, t.Schema)
?.EntityTypeMappings.Select(m => m.EntityType) ?? Enumerable.Empty<IEntityType>())
.SelectMany(e => e.GetDeclaredProperties()
.Where(p => p.GetValueGenerationStrategy() switch
{
NpgsqlValueGenerationStrategy.IdentityByDefaultColumn => true,
NpgsqlValueGenerationStrategy.IdentityAlwaysColumn => true,
NpgsqlValueGenerationStrategy.SerialColumn => true,
_ => false
})
.Select(p => p.GetColumnName(StoreObjectIdentifier.Table(t.Table, t.Schema))))
})
.SelectMany(t => t.Columns.Select(p => new
{
t.Schema,
t.Table,
Column = p!,
}))
.ToArray();
if (seededGeneratedColumns.Any())
{
var builder = new MigrationCommandListBuilder(Dependencies);
foreach (var c in seededGeneratedColumns)
{
// Weirdly, pg_get_serial_sequence accepts a standard quoted "schema"."table" inside its first
// parameter string literal, but the second one is a column name that shouldn't be double-quoted...
var table = Dependencies.SqlGenerationHelper.DelimitIdentifier(c.Table, c.Schema);
var column = Dependencies.SqlGenerationHelper.DelimitIdentifier(c.Column!);
var unquotedColumn = c.Column.Replace("'", "''");
// When generating idempotent scripts, migration DDL is enclosed in anonymous DO blocks,
// where PERFORM must be used instead of SELECT
var selectOrPerform = options.HasFlag(MigrationsSqlGenerationOptions.Idempotent)
? "PERFORM"
: "SELECT";
// Set the sequence's value to the greater of:
// 1. Maximum value currently present in the column (i.e. just seeded)
// 2. Current value of the sequence (the max value above could be out of range of the sequence,
// e.g. negative values seeded)
builder
.AppendLine(
@$"{selectOrPerform} setval(
pg_get_serial_sequence('{table}', '{unquotedColumn}'),
GREATEST(
(SELECT MAX({column}) FROM {table}) + 1,
nextval(pg_get_serial_sequence('{table}', '{unquotedColumn}'))),
false);");
}
builder.EndCommand();
return results.Concat(builder.GetCommandList()).ToArray();
}
return results;
}
protected override void Generate(MigrationOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
if (operation is NpgsqlCreateDatabaseOperation createDatabaseOperation)
{
Generate(createDatabaseOperation, model, builder);
return;
}
if (operation is NpgsqlDropDatabaseOperation dropDatabaseOperation)
{
Generate(dropDatabaseOperation, model, builder);
return;
}
base.Generate(operation, model, builder);
}
#region Standard migrations
protected override void Generate(
CreateTableOperation operation,
IModel? model,
MigrationCommandListBuilder builder,
bool terminate = true)
{
if (!terminate && operation.Comment != null)
throw new ArgumentException($"When generating migrations SQL for {nameof(CreateTableOperation)}, can't produce unterminated SQL with comments");
operation.Columns.RemoveAll(c => IsSystemColumn(c.Name));
builder.Append("CREATE ");
if (operation[NpgsqlAnnotationNames.UnloggedTable] is bool unlogged && unlogged)
builder.Append("UNLOGGED ");
builder
.Append("TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema))
.AppendLine(" (");
using (builder.Indent())
{
base.CreateTableColumns(operation, model, builder);
base.CreateTableConstraints(operation, model, builder);
builder.AppendLine();
}
builder.Append(")");
// Table Partitioning (https://www.postgresql.org/docs/current/ddl-partitioning.html)
if (operation[NpgsqlAnnotationNames.TablePartitioning] is TablePartitioning tablePartitioning)
{
var columnNames = tablePartitioning.PartitionKeyProperties
.Select(property =>
property.GetColumnName(StoreObjectIdentifier.Table(operation.Name, operation.Schema)))
.ToArray();
builder.AppendLine()
.Append("PARTITION BY ")
.Append(GetPartitionTypeString(tablePartitioning.Type))
.Append(" (")
.Append(ColumnList(columnNames!))
.Append(") ");
}
// CockroachDB "interleave in parent" (https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html)
if (operation[CockroachDbAnnotationNames.InterleaveInParent] is string)
{
var interleaveInParent = new CockroachDbInterleaveInParent(operation);
var parentTableSchema = interleaveInParent.ParentTableSchema;
var parentTableName = interleaveInParent.ParentTableName;
var interleavePrefix = interleaveInParent.InterleavePrefix;
builder
.AppendLine()
.Append("INTERLEAVE IN PARENT ")
.Append(DelimitIdentifier(parentTableName, parentTableSchema))
.Append(" (")
.Append(string.Join(", ", interleavePrefix.Select(c => DelimitIdentifier(c))))
.Append(")");
}
var storageParameters = GetStorageParameters(operation);
if (storageParameters.Count > 0)
{
builder
.AppendLine()
.Append("WITH (")
.Append(string.Join(", ", storageParameters.Select(p => $"{p.Key}={p.Value}")))
.Append(")");
}
// Comment on the table
if (operation.Comment != null)
{
builder.AppendLine(";");
builder
.Append("COMMENT ON TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema))
.Append(" IS ")
.Append(_stringTypeMapping.GenerateSqlLiteral(operation.Comment));
}
// Comments on the columns
foreach (var columnOp in operation.Columns.Where(c => c.Comment != null))
{
var columnComment = columnOp.Comment;
builder.AppendLine(";");
builder
.Append("COMMENT ON COLUMN ")
.Append(DelimitIdentifier(operation.Name, operation.Schema))
.Append(".")
.Append(DelimitIdentifier(columnOp.Name))
.Append(" IS ")
.Append(_stringTypeMapping.GenerateSqlLiteral(columnComment));
}
if (terminate)
{
builder.AppendLine(";");
EndStatement(builder);
}
}
protected override void Generate(AlterTableOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
var madeChanges = false;
// Table Partitioning may not be added after table creation
if (HasTablePartioningChanges(operation))
{
throw new ArgumentException($"When generating migrations SQL for {nameof(AlterTableOperation)}, can't alter a table's partitioning after it was created.");
}
// Storage parameters
var oldStorageParameters = GetStorageParameters(operation.OldTable);
var newStorageParameters = GetStorageParameters(operation);
var newOrChanged = newStorageParameters.Where(p =>
!oldStorageParameters.ContainsKey(p.Key) ||
oldStorageParameters[p.Key] != p.Value
).ToList();
if (newOrChanged.Count > 0)
{
builder
.Append("ALTER TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema));
builder
.Append(" SET (")
.Append(string.Join(", ", newOrChanged.Select(p => $"{p.Key}={p.Value}")))
.Append(")");
builder.AppendLine(";");
madeChanges = true;
}
var removed = oldStorageParameters
.Select(p => p.Key)
.Where(pn => !newStorageParameters.ContainsKey(pn))
.ToList();
if (removed.Count > 0)
{
builder
.Append("ALTER TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema));
builder
.Append(" RESET (")
.Append(string.Join(", ", removed))
.Append(")");
builder.AppendLine(";");
madeChanges = true;
}
// Comment
if (operation.Comment != operation.OldTable.Comment)
{
builder
.Append("COMMENT ON TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema))
.Append(" IS ")
.Append(_stringTypeMapping.GenerateSqlLiteral(operation.Comment));
builder.AppendLine(";");
madeChanges = true;
}
// Unlogged table (null is equivalent to false)
var oldUnlogged = operation.OldTable[NpgsqlAnnotationNames.UnloggedTable] is bool ou && ou;
var newUnlogged = operation[NpgsqlAnnotationNames.UnloggedTable] is bool nu && nu;
if (oldUnlogged != newUnlogged)
{
builder
.Append("ALTER TABLE ")
.Append(DelimitIdentifier(operation.Name, operation.Schema))
.Append(" SET ")
.Append(newUnlogged ? "UNLOGGED" : "LOGGED")
.AppendLine(";");
madeChanges = true;
}
if (madeChanges)
EndStatement(builder);
}
protected override void Generate(
DropColumnOperation operation,
IModel? model,
MigrationCommandListBuilder builder,
bool terminate = true)
{
// Never touch system columns
if (IsSystemColumn(operation.Name))
return;
base.Generate(operation, model, builder, terminate);
}
protected override void Generate(
AddColumnOperation operation,
IModel? model,
MigrationCommandListBuilder builder,
bool terminate = true)
{
if (!terminate && operation.Comment != null)
throw new ArgumentException($"When generating migrations SQL for {nameof(AddColumnOperation)}, can't produce unterminated SQL with comments");
// Never touch system columns
if (IsSystemColumn(operation.Name))
return;
if (operation[NpgsqlAnnotationNames.ValueGenerationStrategy] is NpgsqlValueGenerationStrategy strategy)
{
switch (strategy)
{
case NpgsqlValueGenerationStrategy.SerialColumn:
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
// NB: This gets added to all added non-nullable columns by MigrationsModelDiffer. We need to suppress
// it, here because PG can't have both IDENTITY/SERIAL and a DEFAULT constraint on the same column.
operation.DefaultValue = null;
break;
}
}
base.Generate(operation, model, builder, terminate: false);
if (operation.Comment != null)
{
builder.AppendLine(";");
builder
.Append("COMMENT ON COLUMN ")
.Append(DelimitIdentifier(operation.Table, operation.Schema))
.Append(".")
.Append(DelimitIdentifier(operation.Name))
.Append(" IS ")
.Append(_stringTypeMapping.GenerateSqlLiteral(operation.Comment));
}
if (terminate)
{
builder.AppendLine(";");
EndStatement(builder);
}
}
protected override void Generate(AlterColumnOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
// Never touch system columns
if (IsSystemColumn(operation.Name))
return;
var column = model?.GetRelationalModel().FindTable(operation.Table, operation.Schema)
?.Columns.FirstOrDefault(c => c.Name == operation.Name);
if (operation.ComputedColumnSql != null)
{
// TODO: The following will fail if the column being altered is part of an index.
// SqlServer recreates indexes, but wait to see if PostgreSQL will introduce a proper ALTER TABLE ALTER COLUMN
// that allows us to do this cleanly.
var dropColumnOperation = new DropColumnOperation
{
Schema = operation.Schema,
Table = operation.Table,
Name = operation.Name
};
if (column != null)
dropColumnOperation.AddAnnotations(column.GetAnnotations());
Generate(dropColumnOperation, model, builder);
var addColumnOperation = new AddColumnOperation
{
Schema = operation.Schema,
Table = operation.Table,
Name = operation.Name,
ClrType = operation.ClrType,
ColumnType = operation.ColumnType,
IsUnicode = operation.IsUnicode,
MaxLength = operation.MaxLength,
IsRowVersion = operation.IsRowVersion,
IsNullable = operation.IsNullable,
DefaultValue = operation.DefaultValue,
DefaultValueSql = operation.DefaultValueSql,
ComputedColumnSql = operation.ComputedColumnSql,
IsFixedLength = operation.IsFixedLength,
IsStored = operation.IsStored
};
addColumnOperation.AddAnnotations(operation.GetAnnotations());
Generate(addColumnOperation, model, builder);
return;
}
string? newSequenceName = null;
var alterBase = $"ALTER TABLE {DelimitIdentifier(operation.Table, operation.Schema)} " +
$"ALTER COLUMN {DelimitIdentifier(operation.Name)} ";
// TYPE + COLLATION
var type = operation.ColumnType ??
GetColumnType(operation.Schema, operation.Table, operation.Name, operation, model)!;
var oldType = IsOldColumnSupported(model)
? operation.OldColumn.ColumnType ??
GetColumnType(operation.Schema, operation.Table, operation.Name, operation.OldColumn, model)
: null;
// If a collation was defined on the column specifically, via the standard EF mechanism, it will be
// available in operation.Collation (as usual). If not, there may be a model-wide default column collation,
// which gets transmitted via the Npgsql-specific annotation.
var oldCollation = (string?)(operation.OldColumn.Collation ?? operation.OldColumn[NpgsqlAnnotationNames.DefaultColumnCollation]);
var newCollation = (string?)(operation.Collation ?? operation[NpgsqlAnnotationNames.DefaultColumnCollation]);
if (type != oldType || newCollation != oldCollation)
{
builder.Append(alterBase)
.Append("TYPE ")
.Append(type);
if (newCollation != oldCollation)
builder.Append(" COLLATE ").Append(DelimitIdentifier(newCollation ?? "default"));
builder.AppendLine(";");
}
if (operation.IsNullable != operation.OldColumn.IsNullable)
{
builder.Append(alterBase)
.Append(operation.IsNullable ? "DROP NOT NULL" : "SET NOT NULL")
.AppendLine(";");
}
CheckForOldValueGenerationAnnotation(operation);
var oldStrategy = operation.OldColumn[NpgsqlAnnotationNames.ValueGenerationStrategy] as NpgsqlValueGenerationStrategy?;
var newStrategy = operation[NpgsqlAnnotationNames.ValueGenerationStrategy] as NpgsqlValueGenerationStrategy?;
if (oldStrategy != newStrategy)
{
// We have a value generation strategy change
if (oldStrategy == NpgsqlValueGenerationStrategy.SerialColumn)
{
// TODO: It would be better to actually select for the owned sequence.
// This would require plpgsql.
var sequence = DelimitIdentifier($"{operation.Table}_{operation.Name}_seq", operation.Schema);
switch (newStrategy)
{
case null:
// Drop the serial, converting the column to a regular int
builder.AppendLine($"DROP SEQUENCE {sequence} CASCADE;");
break;
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
// Convert serial column to identity, maintaining the current sequence value
var identityTypeClause = newStrategy == NpgsqlValueGenerationStrategy.IdentityAlwaysColumn
? "ALWAYS"
: "BY DEFAULT";
var oldSequence = DelimitIdentifier($"{operation.Table}_{operation.Name}_old_seq", operation.Schema);
var oldSequenceWithoutSchema = DelimitIdentifier($"{operation.Table}_{operation.Name}_old_seq");
builder
.AppendLine($"ALTER SEQUENCE {sequence} RENAME TO {oldSequenceWithoutSchema};")
.AppendLine($"{alterBase}DROP DEFAULT;")
.AppendLine($"{alterBase}ADD GENERATED {identityTypeClause} AS IDENTITY;")
// When generating idempotent scripts, migration DDL is enclosed in anonymous DO blocks,
// where PERFORM must be used instead of SELECT
.Append(Options.HasFlag(MigrationsSqlGenerationOptions.Idempotent) ? "PERFORM" : "SELECT")
.AppendLine($" * FROM setval('{sequence}', nextval('{oldSequence}'), false);")
.AppendLine($"DROP SEQUENCE {oldSequence};");
break;
default:
throw new NotSupportedException($"Don't know how to migrate serial column to {newStrategy}");
}
}
else if (oldStrategy.IsIdentity())
{
switch (newStrategy)
{
case null:
// Drop the identity, converting the column to a regular int
builder.AppendLine(alterBase).AppendLine("DROP IDENTITY;");
break;
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
builder.Append(alterBase).AppendLine("SET GENERATED ALWAYS;");
break;
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
builder.Append(alterBase).AppendLine("SET GENERATED BY DEFAULT;");
break;
case NpgsqlValueGenerationStrategy.SerialColumn:
throw new NotSupportedException("Migrating from identity to serial isn't currently supported (and is a bad idea)");
default:
throw new NotSupportedException($"Don't know how to migrate identity column to {newStrategy}");
}
}
else if (oldStrategy == null)
{
switch (newStrategy)
{
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
builder.Append(alterBase).AppendLine("DROP DEFAULT;");
builder.Append(alterBase).Append("ADD");
IdentityDefinition(operation, builder);
builder.AppendLine(";");
break;
case NpgsqlValueGenerationStrategy.SerialColumn:
switch (type)
{
case "integer":
case "int":
case "int4":
case "bigint":
case "int8":
case "smallint":
case "int2":
newSequenceName = $"{operation.Table}_{operation.Name}_seq";
Generate(new CreateSequenceOperation
{
Schema = operation.Schema,
Name = newSequenceName,
ClrType = operation.ClrType
}, model, builder);
builder.Append(alterBase).Append("SET");
DefaultValue(null, $@"nextval('{DelimitIdentifier(newSequenceName, operation.Schema)}')", type, builder);
builder.AppendLine(";");
// Note: we also need to set the sequence ownership, this is done below after the ALTER COLUMN
break;
}
break;
default:
throw new NotSupportedException($"Don't know how to apply value generation strategy {newStrategy}");
}
}
}
// Identity sequence options may have changed
if (oldStrategy.IsIdentity() && newStrategy.IsIdentity())
{
var newSequenceOptions = IdentitySequenceOptionsData.Get(operation);
var oldSequenceOptions = IdentitySequenceOptionsData.Get(operation.OldColumn);
if (newSequenceOptions.StartValue != oldSequenceOptions.StartValue)
{
var startValue = newSequenceOptions.StartValue ?? 1;
builder
.Append(alterBase)
.Append("RESTART WITH ")
.Append(startValue.ToString(CultureInfo.InvariantCulture))
.AppendLine(";");
}
if (newSequenceOptions.IncrementBy != oldSequenceOptions.IncrementBy)
{
builder
.Append(alterBase)
.Append("SET INCREMENT BY ")
.Append(newSequenceOptions.IncrementBy.ToString(CultureInfo.InvariantCulture))
.AppendLine(";");
}
if (newSequenceOptions.MinValue != oldSequenceOptions.MinValue)
{
builder
.Append(alterBase)
.Append(newSequenceOptions.MinValue == null
? "SET NO MINVALUE"
: "SET MINVALUE " + newSequenceOptions.MinValue)
.AppendLine(";");
}
if (newSequenceOptions.MaxValue != oldSequenceOptions.MaxValue)
{
builder
.Append(alterBase)
.Append(newSequenceOptions.MaxValue == null
? "SET NO MAXVALUE"
: "SET MAXVALUE " + newSequenceOptions.MaxValue)
.AppendLine(";");
}
if (newSequenceOptions.IsCyclic != oldSequenceOptions.IsCyclic)
{
builder
.Append(alterBase)
.Append(newSequenceOptions.IsCyclic
? "SET CYCLE"
: "SET NO CYCLE")
.AppendLine(";");
}
if (newSequenceOptions.NumbersToCache != oldSequenceOptions.NumbersToCache)
{
builder
.Append(alterBase)
.Append("SET CACHE ")
.Append(newSequenceOptions.NumbersToCache.ToString(CultureInfo.InvariantCulture))
.AppendLine(";");
}
}
// DEFAULT.
// Note that defaults values for value-generated columns (identity, serial) are managed above. This is
// only for regular columns with user-specified default settings.
if (newStrategy == null &&
(operation.DefaultValueSql != operation.OldColumn.DefaultValueSql ||
!Equals(operation.DefaultValue, operation.OldColumn.DefaultValue)))
{
builder.Append(alterBase);
if (operation.DefaultValue != null || operation.DefaultValueSql != null)
{
builder.Append("SET");
DefaultValue(operation.DefaultValue, operation.DefaultValueSql, type, builder);
}
else
builder.Append("DROP DEFAULT");
builder.AppendLine(";");
}
// A sequence has been created because this column was altered to be a serial.
// Change the sequence's ownership.
if (newSequenceName != null)
{
builder
.Append("ALTER SEQUENCE ")
.Append(DelimitIdentifier(newSequenceName, operation.Schema))
.Append(" OWNED BY ")
.Append(DelimitIdentifier(operation.Table, operation.Schema))
.Append(".")
.Append(DelimitIdentifier(operation.Name))
.AppendLine(";");
}
// Comment
if (operation.Comment != operation.OldColumn.Comment)
{
builder
.Append("COMMENT ON COLUMN ")
.Append(DelimitIdentifier(operation.Table, operation.Schema))
.Append(".")
.Append(DelimitIdentifier(operation.Name))
.Append(" IS ")
.Append(_stringTypeMapping.GenerateSqlLiteral(operation.Comment))
.AppendLine(";");
}
EndStatement(builder);
}
protected override void Generate(RenameIndexOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
if (operation.NewName != null &&
operation.NewName != operation.Name)
{
Rename(operation.Schema, operation.Name, operation.NewName, "INDEX", builder);
}
// N.B. indexes are always stored in the same schema as the table.
EndStatement(builder);
}
protected override void Generate(RenameSequenceOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
var name = operation.Name;
if (operation.NewName != null &&
operation.NewName != operation.Name)
{
Rename(operation.Schema, operation.Name, operation.NewName, "SEQUENCE", builder);
name = operation.NewName;
}
if (operation.NewSchema != null &&
operation.NewSchema != operation.Schema)
{
Transfer(operation.NewSchema, operation.Schema, name, "SEQUENCE", builder);
}
EndStatement(builder);
}
protected override void Generate(RenameTableOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
var name = operation.Name;
if (operation.NewName != null &&
operation.NewName != operation.Name)
{
Rename(operation.Schema, operation.Name, operation.NewName, "TABLE", builder);
name = operation.NewName;
}
if (operation.NewSchema != null &&
operation.NewSchema != operation.Schema)
{
Transfer(operation.NewSchema, operation.Schema, name, "TABLE", builder);
}
EndStatement(builder);
}
protected override void Generate(
CreateIndexOperation operation,
IModel? model,
MigrationCommandListBuilder builder,
bool terminate = true)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder.Append("CREATE ");
if (operation.IsUnique)
builder.Append("UNIQUE ");
builder.Append("INDEX ");
var concurrently = operation[NpgsqlAnnotationNames.CreatedConcurrently] as bool? == true;
if (concurrently)
builder.Append("CONCURRENTLY ");
builder
.Append(DelimitIdentifier(operation.Name))
.Append(" ON ")
.Append(DelimitIdentifier(operation.Table, operation.Schema));
var method = operation[NpgsqlAnnotationNames.IndexMethod] as string;
if (method?.Length > 0)
builder.Append(" USING ").Append(method);
var indexColumns = GetIndexColumns(operation);
var columnsExpression = operation[NpgsqlAnnotationNames.TsVectorConfig] is string tsVectorConfig
? ColumnsToTsVector(indexColumns.Select(i => i.Name), tsVectorConfig, model, operation.Schema, operation.Table)
: IndexColumnList(indexColumns, method);
builder
.Append(" (")
.Append(columnsExpression)
.Append(")");
IndexOptions(operation, model, builder);
if (terminate)
{
builder.AppendLine(";");
// Concurrent indexes cannot be created within a transaction
EndStatement(builder, suppressTransaction: concurrently);
}
}
protected override void IndexOptions(CreateIndexOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
if (_postgresVersion.AtLeast(11) &&
operation[NpgsqlAnnotationNames.IndexInclude] is string[] includeColumns &&
includeColumns.Length > 0)
{
builder
.Append(" INCLUDE (")
.Append(ColumnList(includeColumns))
.Append(")");
}
base.IndexOptions(operation, model, builder);
}
protected override void Generate(EnsureSchemaOperation operation, IModel? model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
// PostgreSQL 9.2 and below unfortunately doesn't have CREATE SCHEMA IF NOT EXISTS.
// An attempted workaround by creating a function which checks and creates the schema, and then invoking it, failed because
// of #641 (pg_temp doesn't exist yet).
// So the only workaround for pre-9.3 PostgreSQL, at least for now, is to define all tables in the public schema.
// TODO: Since Npgsql 3.1 we can now ensure schema with a function in pg_temp
// NOTE: Technically the public schema can be dropped so we should also be ensuring it, but this is a rare case and
// we want to allow pre-9.3
if (operation.Name == "public")
return;
builder
.Append("CREATE SCHEMA IF NOT EXISTS ")
.Append(DelimitIdentifier(operation.Name))
.AppendLine(";");
EndStatement(builder);
}
protected virtual void Generate(
NpgsqlCreateDatabaseOperation operation,
IModel? model,
MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder
.Append("CREATE DATABASE ")
.Append(DelimitIdentifier(operation.Name));
if (!string.IsNullOrEmpty(operation.Template))
{
builder
.AppendLine()
.Append("TEMPLATE ")
.Append(DelimitIdentifier(operation.Template));
}
if (!string.IsNullOrEmpty(operation.Tablespace))
{
builder
.AppendLine()
.Append("TABLESPACE ")
.Append(DelimitIdentifier(operation.Tablespace));
}
if (!string.IsNullOrEmpty(operation.Collation))
{
builder
.AppendLine()
.Append("LC_COLLATE ")
.Append(DelimitIdentifier(operation.Collation));
}
builder.AppendLine(";");
EndStatement(builder, suppressTransaction: true);
}
public virtual void Generate(
NpgsqlDropDatabaseOperation operation,
IModel? model,
MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
var dbName = DelimitIdentifier(operation.Name);
if (_postgresVersion.AtLeast(13))
{
builder.AppendLine($"DROP DATABASE {dbName} WITH (FORCE);");
}
else
{
builder
.AppendLine($"REVOKE CONNECT ON DATABASE {dbName} FROM PUBLIC;")
.AppendLine($"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = '{operation.Name}';")
.EndCommand(suppressTransaction: true)
.AppendLine($"DROP DATABASE {dbName};");
}
EndStatement(builder, suppressTransaction: true);
}
protected override void Generate(
AlterDatabaseOperation operation,
IModel? model,
MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
if (operation.Collation != operation.OldDatabase.Collation)
throw new NotSupportedException("PostgreSQL does not support altering the collation on an existing database.");
GenerateCollationStatements(operation, model, builder);
GenerateEnumStatements(operation, model, builder);
GenerateRangeStatements(operation, model, builder);
foreach (var extension in operation.GetPostgresExtensions())
GenerateCreateExtension(extension, model, builder);
builder.EndCommand();
}
protected virtual void GenerateCreateExtension(
PostgresExtension extension,
IModel? model,
MigrationCommandListBuilder builder)
{
var schema = extension.Schema ?? model?.GetDefaultSchema();
// Schemas are normally created (or rather ensured) by the model differ, which scans all tables, sequences
// and other database objects. However, it isn't aware of extensions, so we always ensure schema on enum creation.
if (schema is not null)
Generate(new EnsureSchemaOperation { Name = schema }, model, builder);
builder
.Append("CREATE EXTENSION IF NOT EXISTS ")
.Append(DelimitIdentifier(extension.Name));
if (extension.Schema is not null)
{
builder
.Append(" SCHEMA ")
.Append(DelimitIdentifier(extension.Schema));
}
if (extension.Version is not null)
{
builder
.Append(" VERSION ")
.Append(DelimitIdentifier(extension.Version));
}
builder.AppendLine(";");
}
#region Collation management
protected virtual void GenerateCollationStatements(
AlterDatabaseOperation operation,
IModel? model,
MigrationCommandListBuilder builder)
{
foreach (var collationToCreate in operation.GetPostgresCollations()
.Where(ne => operation.GetOldPostgresCollations().All(oe => oe.Name != ne.Name || oe.Schema != ne.Schema)))
{
GenerateCreateCollation(collationToCreate, model, builder);
}
foreach (var collationToDrop in operation.GetOldPostgresCollations()
.Where(oe => operation.GetPostgresCollations().All(ne => ne.Name != oe.Name || oe.Schema != ne.Schema)))
{
GenerateDropCollation(collationToDrop, model, builder);
}
foreach (var (newCollation, oldCollation) in operation.GetPostgresCollations()
.Join(operation.GetOldPostgresCollations(),
e => new { e.Name, e.Schema },
e => new { e.Name, e.Schema },
(ne, oe) => (New: ne, Old: oe)))
{