-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathNpgsqlDatabaseModelFactory.cs
More file actions
1505 lines (1309 loc) · 59.8 KB
/
NpgsqlDatabaseModelFactory.cs
File metadata and controls
1505 lines (1309 loc) · 59.8 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.Data;
using System.Data.Common;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Npgsql.EntityFrameworkCore.PostgreSQL.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Utilities;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal;
// ReSharper disable StringLiteralTypo
/// <summary>
/// The default database model factory for Npgsql.
/// </summary>
public class NpgsqlDatabaseModelFactory : DatabaseModelFactory
{
#region Fields
private const string NamePartRegex = """(?:(?:"(?<part{0}>(?:(?:"")|[^"])+)")|(?<part{0}>[^\.\["]+))""";
private static readonly Regex SchemaTableNameExtractor =
new(
string.Format(
CultureInfo.InvariantCulture,
@"^{0}(?:\.{1})?$",
string.Format(CultureInfo.InvariantCulture, NamePartRegex, 1),
string.Format(CultureInfo.InvariantCulture, NamePartRegex, 2)),
RegexOptions.Compiled,
TimeSpan.FromMilliseconds(1000.0));
private static readonly string[] SerialTypes = ["int2", "int4", "int8"];
private readonly IDiagnosticsLogger<DbLoggerCategory.Scaffolding> _logger;
#endregion
#region Public surface
/// <summary>
/// Constructs an instance of the <see cref="NpgsqlDatabaseModelFactory" /> class.
/// </summary>
public NpgsqlDatabaseModelFactory(IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
_logger = Check.NotNull(logger, nameof(logger));
}
/// <inheritdoc />
public override DatabaseModel Create(string connectionString, DatabaseModelFactoryOptions options)
{
Check.NotEmpty(connectionString, nameof(connectionString));
Check.NotNull(options, nameof(options));
using var connection = new NpgsqlConnection(connectionString);
return Create(connection, options);
}
/// <inheritdoc />
public override DatabaseModel Create(DbConnection dbConnection, DatabaseModelFactoryOptions options)
{
Check.NotNull(dbConnection, nameof(dbConnection));
Check.NotNull(options, nameof(options));
var databaseModel = new DatabaseModel();
var connection = (NpgsqlConnection)dbConnection;
var connectionStartedOpen = connection.State == ConnectionState.Open;
if (!connectionStartedOpen)
{
connection.Open();
}
try
{
var internalSchemas = "'pg_catalog', 'information_schema'";
using (var command = new NpgsqlCommand("SELECT version()", connection))
{
var longVersion = (string)command.ExecuteScalar()!;
if (longVersion.Contains("CockroachDB"))
{
internalSchemas += ", 'crdb_internal'";
}
}
databaseModel.DatabaseName = connection.Database;
databaseModel.DefaultSchema = "public";
PopulateGlobalDatabaseInfo(connection, databaseModel);
var schemaList = options.Schemas.ToList();
var schemaFilter = GenerateSchemaFilter(schemaList);
var tableList = options.Tables.ToList();
var tableFilter = GenerateTableFilter(tableList.Select(Parse).ToList(), schemaFilter);
var enums = GetEnums(connection, databaseModel);
foreach (var table in GetTables(connection, databaseModel, tableFilter, internalSchemas, enums, _logger))
{
table.Database = databaseModel;
databaseModel.Tables.Add(table);
}
foreach (var table in databaseModel.Tables)
{
while (table.Columns.Remove(null!)) { }
}
foreach (var sequence in GetSequences(connection, databaseModel, schemaFilter, _logger))
{
sequence.Database = databaseModel;
databaseModel.Sequences.Add(sequence);
}
if (connection.PostgreSqlVersion >= new Version(9, 1))
{
GetExtensions(connection, databaseModel);
GetCollations(connection, databaseModel, internalSchemas, _logger);
}
for (var i = 0; i < databaseModel.Tables.Count; i++)
{
var table = databaseModel.Tables[i];
// We may have dropped or skipped columns. We load these because constraints take them into
// account when referencing columns, but must now get rid of them before returning
// the database model.
while (table.Columns.Remove(null!)) { }
}
foreach (var schema in schemaList
.Except(databaseModel.Sequences.Select(s => s.Schema).Concat(databaseModel.Tables.Select(t => t.Schema))))
{
_logger.MissingSchemaWarning(schema);
}
foreach (var table in tableList)
{
var (schema, name) = Parse(table);
if (!databaseModel.Tables.Any(t => !string.IsNullOrEmpty(schema) && t.Schema == schema || t.Name == name))
{
_logger.MissingTableWarning(table);
}
}
return databaseModel;
}
finally
{
if (!connectionStartedOpen)
{
connection.Close();
}
}
}
#endregion
#region Type information queries
private static void PopulateGlobalDatabaseInfo(NpgsqlConnection connection, DatabaseModel databaseModel)
{
if (connection.PostgreSqlVersion < new Version(8, 4))
{
return;
}
var commandText = """
SELECT datcollate
FROM pg_database
WHERE datname=current_database() AND datcollate <> (SELECT datcollate FROM pg_database WHERE datname='template1')
""";
using var command = new NpgsqlCommand(commandText, connection);
using var reader = command.ExecuteReader();
if (reader.Read())
{
databaseModel.Collation = reader.GetString(0);
}
}
/// <summary>
/// Queries the database for defined tables and registers them with the model.
/// </summary>
private static IEnumerable<DatabaseTable> GetTables(
NpgsqlConnection connection,
DatabaseModel databaseModel,
Func<string, string, string>? tableFilter,
string internalSchemas,
HashSet<string> enums,
IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
var filter = tableFilter is not null ? $"AND {tableFilter("ns.nspname", "cls.relname")}" : null;
var commandText = $"""
SELECT
nspname, relname, relkind, description,
{(connection.PostgreSqlVersion >= new Version(8, 2) ? "reloptions" : "'{}'::text[] AS reloptions")}
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
LEFT OUTER JOIN pg_description AS des ON des.objoid = cls.oid AND des.objsubid=0
WHERE
cls.relkind IN ('r', 'v', 'm', 'f', 'p') AND
ns.nspname NOT IN ({internalSchemas}) AND
cls.relname <> '{HistoryRepository.DefaultTableName}' AND
-- Exclude child partitions
cls.relispartition <> true AND
-- Exclude tables which are members of PG extensions
NOT EXISTS (
SELECT 1 FROM pg_depend WHERE
classid=(
SELECT cls.oid
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE relname='pg_class' AND ns.nspname='pg_catalog'
) AND
objid=cls.oid AND
deptype IN ('e', 'x')
)
{filter}
""";
var tables = new List<DatabaseTable>();
using (var command = new NpgsqlCommand(commandText, connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetValueOrDefault<string>("nspname");
var name = reader.GetString("relname");
var type = reader.GetChar("relkind");
var comment = reader.GetValueOrDefault<string>("description");
var storageParameters = reader.GetValueOrDefault<string[]>("reloptions") ?? [];
var table = type switch
{
'r' => new DatabaseTable(),
'f' => new DatabaseTable(),
'p' => new DatabaseTable(),
'v' => new DatabaseView(),
'm' => new DatabaseView(),
_ => throw new ArgumentOutOfRangeException($"Unknown relkind '{type}' when scaffolding {DisplayName(schema, name)}")
};
table.Database = databaseModel;
table.Name = name;
table.Schema = schema;
table.Comment = comment;
foreach (var storageParameter in storageParameters)
{
if (storageParameter.Split("=") is [var paramName, var paramValue])
{
table[NpgsqlAnnotationNames.StorageParameterPrefix + paramName] = paramValue;
}
}
tables.Add(table);
}
}
GetColumns(connection, tables, filter, internalSchemas, enums, logger);
GetConstraints(connection, tables, filter, internalSchemas, out var constraintIndexes, logger);
GetIndexes(connection, tables, filter, internalSchemas, constraintIndexes, logger);
return tables;
}
/// <summary>
/// Queries the database for defined columns and registers them with the model.
/// </summary>
private static void GetColumns(
NpgsqlConnection connection,
IReadOnlyList<DatabaseTable> tables,
string? tableFilter,
string internalSchemas,
HashSet<string> enums,
IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
var commandText = $"""
SELECT
nspname,
cls.relname,
typ.typname,
basetyp.typname AS basetypname,
attname,
description,
{(connection.PostgreSqlVersion >= new Version(9, 1) ? "collname" : "NULL::text as collname")},
attisdropped,
{(connection.PostgreSqlVersion >= new Version(10, 0) ? "attidentity::text" : "' '::text as attidentity")},
{(connection.PostgreSqlVersion >= new Version(12, 0) ? "attgenerated::text" : "' '::text as attgenerated")},
{(connection.PostgreSqlVersion >= new Version(14, 0) ? "attcompression::text" : "''::text as attcompression")},
format_type(typ.oid, atttypmod) AS formatted_typname,
format_type(basetyp.oid, typ.typtypmod) AS formatted_basetypname,
CASE
WHEN pg_proc.proname = 'array_recv' THEN 'a'
ELSE typ.typtype
END AS typtype,
CASE WHEN pg_proc.proname='array_recv' THEN elemtyp.typname END AS elemtypname,
NOT (attnotnull OR typ.typnotnull) AS nullable,
CASE
WHEN atthasdef THEN (SELECT pg_get_expr(adbin, cls.oid) FROM pg_attrdef WHERE adrelid = cls.oid AND adnum = attr.attnum)
END AS default,
-- Sequence options for identity columns
{(connection.PostgreSqlVersion >= new Version(10, 0) ?
"format_type(seqtypid, 0) AS seqtype, seqstart, seqmin, seqmax, seqincrement, seqcycle, seqcache" :
"NULL AS seqtype, NULL AS seqstart, NULL AS seqmin, NULL AS seqmax, NULL AS seqincrement, NULL AS seqcycle, NULL AS seqcache")}
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
LEFT JOIN pg_attribute AS attr ON attrelid = cls.oid
LEFT JOIN pg_type AS typ ON attr.atttypid = typ.oid
LEFT JOIN pg_proc ON pg_proc.oid = typ.typreceive
LEFT JOIN pg_type AS elemtyp ON (elemtyp.oid = typ.typelem)
LEFT JOIN pg_type AS basetyp ON (basetyp.oid = typ.typbasetype)
LEFT JOIN pg_description AS des ON des.objoid = cls.oid AND des.objsubid = attnum
{(connection.PostgreSqlVersion >= new Version(9, 1) ? "LEFT JOIN pg_collation as coll ON coll.oid = attr.attcollation" : "")}
-- Bring in identity sequences the depend on this column
LEFT JOIN pg_depend AS dep ON dep.refobjid = cls.oid AND dep.refobjsubid = attr.attnum AND dep.deptype = 'i'
{(connection.PostgreSqlVersion >= new Version(10, 0) ? "LEFT JOIN pg_sequence AS seq ON seq.seqrelid = dep.objid" : "")}
WHERE
cls.relkind IN ('r', 'v', 'm', 'f', 'p') AND
nspname NOT IN ({internalSchemas}) AND
attnum > 0 AND
cls.relname <> '{HistoryRepository.DefaultTableName}' AND
-- Exclude child partitions
cls.relispartition <> true AND
-- Exclude tables which are members of PG extensions
NOT EXISTS (
SELECT 1 FROM pg_depend WHERE
classid=(
SELECT cls.oid
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE relname='pg_class' AND ns.nspname='pg_catalog'
) AND
objid=cls.oid AND
deptype IN ('e', 'x')
)
{tableFilter}
ORDER BY attnum
""";
using var command = new NpgsqlCommand(commandText, connection);
using var reader = command.ExecuteReader();
var tableGroups = reader.Cast<DbDataRecord>().GroupBy(
ddr => (
tableSchema: ddr.GetFieldValue<string>("nspname"),
tableName: ddr.GetFieldValue<string>("relname")));
foreach (var tableGroup in tableGroups)
{
var tableSchema = tableGroup.Key.tableSchema;
var tableName = tableGroup.Key.tableName;
var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName);
foreach (var record in tableGroup)
{
var columnName = record.GetFieldValue<string>("attname");
// We need to know about dropped columns because constraints take them into
// account when referencing columns. We'll get rid of them before returning the model.
if (record.GetValueOrDefault<bool>("attisdropped"))
{
table.Columns.Add(null!);
continue;
}
var formattedTypeName = AdjustFormattedTypeName(record.GetFieldValue<string>("formatted_typname"));
var formattedBaseTypeName = record.GetValueOrDefault<string>("formatted_basetypname");
var (storeType, systemTypeName) = formattedBaseTypeName is null
? (formattedTypeName, record.GetFieldValue<string>("typname"))
: (formattedBaseTypeName, record.GetFieldValue<string>("basetypname")); // domain type
var column = new DatabaseColumn
{
Table = table,
Name = columnName,
StoreType = storeType,
IsNullable = record.GetValueOrDefault<bool>("nullable"),
};
// Enum types cannot be scaffolded for now (nor can domains of enum types),
// skip with an informative message
if (enums.Contains(formattedTypeName) || formattedBaseTypeName is not null && enums.Contains(formattedBaseTypeName))
{
logger.EnumColumnSkippedWarning($"{DisplayName(tableSchema, tableName)}.{column.Name}");
// We need to know about skipped columns because constraints take them into
// account when referencing columns. We'll get rid of them before returning the model.
table.Columns.Add(null!);
continue;
}
// Default values and generated columns
var defaultValueSql = record.GetValueOrDefault<string>("default");
switch (record.GetFieldValue<string>("attgenerated"))
{
case "v":
column.ComputedColumnSql = defaultValueSql;
column.IsStored = false;
break;
case "s":
column.ComputedColumnSql = defaultValueSql;
column.IsStored = true;
break;
default:
column.DefaultValueSql = defaultValueSql;
column.DefaultValue = ParseDefaultValueSql(systemTypeName, defaultValueSql);
break;
}
// Identify IDENTITY columns, as well as SERIAL ones.
var isIdentity = false;
switch (record.GetFieldValue<string>("attidentity"))
{
case "a":
column[NpgsqlAnnotationNames.ValueGenerationStrategy] = NpgsqlValueGenerationStrategy.IdentityAlwaysColumn;
isIdentity = true;
break;
case "d":
column[NpgsqlAnnotationNames.ValueGenerationStrategy] = NpgsqlValueGenerationStrategy.IdentityByDefaultColumn;
isIdentity = true;
break;
default:
// Hacky but necessary...
// We identify serial columns by examining their default expression, and reverse-engineer these as ValueGenerated.OnAdd.
// We can't actually parse this since the table and column names are concatenated and may contain arbitrary underscores,
// so we construct various possibilities and compare against them.
// TODO: Think about composite keys? Do serial magic only for non-composite.
if (SerialTypes.Contains(systemTypeName))
{
var seqName = $"{column.Table.Name}_{column.Name}_seq";
if (column.Table.Schema == "public"
&& (column.DefaultValueSql == $"nextval('{seqName}'::regclass)"
|| column.DefaultValueSql == $"nextval('\"{seqName}\"'::regclass)")
|| // non-public schema
column.DefaultValueSql == $"nextval('{column.Table.Schema}.{seqName}'::regclass)"
|| column.DefaultValueSql == $"nextval('{column.Table.Schema}.\"{seqName}\"'::regclass)"
|| column.DefaultValueSql == $"nextval('\"{column.Table.Schema}\".{seqName}'::regclass)"
|| column.DefaultValueSql == $"nextval('\"{column.Table.Schema}\".\"{seqName}\"'::regclass)")
{
column.DefaultValueSql = null;
// Serial is the default value generation strategy, so NpgsqlAnnotationCodeGenerator
// makes sure it isn't actually rendered
column[NpgsqlAnnotationNames.ValueGenerationStrategy] = NpgsqlValueGenerationStrategy.SerialColumn;
}
}
break;
}
if (column[NpgsqlAnnotationNames.ValueGenerationStrategy] is not null)
{
column.ValueGenerated = ValueGenerated.OnAdd;
}
if (isIdentity)
{
// Get the options for the associated sequence
var seqInfo = ReadSequenceInfo(record, connection.PostgreSqlVersion);
var sequenceData = new IdentitySequenceOptionsData
{
StartValue = seqInfo.StartValue,
MinValue = seqInfo.MinValue,
MaxValue = seqInfo.MaxValue,
IncrementBy = (int)(seqInfo.IncrementBy ?? 1),
IsCyclic = seqInfo.IsCyclic ?? false,
NumbersToCache = seqInfo.CacheSize ?? 1
};
if (!sequenceData.Equals(IdentitySequenceOptionsData.Empty))
{
column[NpgsqlAnnotationNames.IdentityOptions] = sequenceData.Serialize();
}
}
if (record.GetValueOrDefault<string>("description") is { } comment)
{
column.Comment = comment;
}
if (record.GetValueOrDefault<string>("collname") is { } collation && collation != "default")
{
column.Collation = collation;
}
if (record.GetValueOrDefault<string>("attcompression") is { } compressionMethodChar)
{
column[NpgsqlAnnotationNames.CompressionMethod] = compressionMethodChar switch
{
"p" => "pglz",
"l" => "lz4",
_ => null
};
}
logger.ColumnFound(
DisplayName(tableSchema, tableName),
column.Name,
formattedTypeName,
column.IsNullable,
isIdentity,
column.DefaultValueSql,
column.ComputedColumnSql);
table.Columns.Add(column);
}
}
}
private static object? ParseDefaultValueSql(string systemTypeName, string? defaultValueSql)
{
defaultValueSql = defaultValueSql?.Trim();
if (string.IsNullOrEmpty(defaultValueSql))
{
return null;
}
while (defaultValueSql.StartsWith('(') && defaultValueSql.EndsWith(')'))
{
defaultValueSql = defaultValueSql[1..^1].Trim();
}
return systemTypeName switch
{
"bool" or "boolean" => defaultValueSql switch
{
"true" or "yes" or "on" or "1" => true,
"false" or "no" or "off" or "0" => false,
_ => null
},
"smallint" or "int2" => short.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @short) ? @short : null,
"integer" or "int" or "int4" => int.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @int) ? @int : null,
"bigint" or "int8" => long.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @long) ? @long : null,
"real" or "float4" => float.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @float) ? @float : null,
"double precision" or "float8" => double.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @double) ? @double : null,
"numeric" or "decimal" => decimal.TryParse(defaultValueSql, CultureInfo.InvariantCulture, out var @decimal) ? @decimal : null,
_ => null
};
}
/// <summary>
/// Queries the database for defined indexes and registers them with the model.
/// </summary>
private static void GetIndexes(
NpgsqlConnection connection,
IReadOnlyList<DatabaseTable> tables,
string? tableFilter,
string internalSchemas,
List<uint> constraintIndexes,
IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
// Load the pg_opclass table (https://www.postgresql.org/docs/current/catalog-pg-opclass.html),
// which is referenced by the indices we'll load below
var opClasses = new Dictionary<uint, (string Name, bool IsDefault)>();
try
{
using var command = new NpgsqlCommand("SELECT oid, opcname, opcdefault FROM pg_opclass", connection);
using var reader = command.ExecuteReader();
foreach (var opClass in reader.Cast<DbDataRecord>())
{
opClasses[opClass.GetFieldValue<uint>("oid")] = (
opClass.GetFieldValue<string>("opcname"),
opClass.GetFieldValue<bool>("opcdefault"));
}
}
catch (PostgresException e)
{
logger.Logger.LogWarning(
e,
"Could not load index operator classes from pg_opclass. Operator classes will not be scaffolded");
}
var collations = new Dictionary<uint, string>();
if (connection.PostgreSqlVersion >= new Version(9, 1))
{
using (var command = new NpgsqlCommand("SELECT oid, collname FROM pg_collation", connection))
using (var reader = command.ExecuteReader())
{
foreach (var collation in reader.Cast<DbDataRecord>())
{
collations[collation.GetFieldValue<uint>("oid")] = collation.GetFieldValue<string>("collname");
}
}
}
var commandText = $"""
SELECT
idxcls.oid AS idx_oid,
nspname,
cls.relname AS cls_relname,
idxcls.relname AS idx_relname,
indisunique,
{(connection.PostgreSqlVersion >= new Version(15, 0) ? "indnullsnotdistinct" : "false AS indnullsnotdistinct")},
{(connection.PostgreSqlVersion >= new Version(11, 0) ? "indnkeyatts" : "indnatts AS indnkeyatts")},
{(connection.PostgreSqlVersion >= new Version(9, 6) ? "pg_indexam_has_property(am.oid, 'can_order') as amcanorder" : "amcanorder")},
indkey,
amname,
indclass,
indoption,
{(connection.PostgreSqlVersion >= new Version(9, 1) ? "indcollation" : "''::oidvector AS indcollation")},
{(connection.PostgreSqlVersion >= new Version(8, 2) ? "idxcls.reloptions AS idx_reloptions" : "'{}'::text[] AS idx_reloptions")},
CASE
WHEN indexprs IS NULL THEN NULL
ELSE pg_get_expr(indexprs, cls.oid)
END AS exprs,
CASE
WHEN indpred IS NULL THEN NULL
ELSE pg_get_expr(indpred, cls.oid)
END AS pred
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
JOIN pg_index AS idx ON indrelid = cls.oid
JOIN pg_class AS idxcls ON idxcls.oid = indexrelid
JOIN pg_am AS am ON am.oid = idxcls.relam
WHERE
cls.relkind IN ('r','p') AND
nspname NOT IN ({internalSchemas}) AND
NOT indisprimary AND
cls.relname <> '{HistoryRepository.DefaultTableName}' AND
-- Exclude child partitions
cls.relispartition <> true AND
-- Exclude tables which are members of PG extensions
NOT EXISTS (
SELECT 1 FROM pg_depend WHERE
classid=(
SELECT cls.oid
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE relname='pg_class' AND ns.nspname='pg_catalog'
) AND
objid=cls.oid AND
deptype IN ('e', 'x')
)
{tableFilter}
""";
using (var command = new NpgsqlCommand(commandText, connection))
using (var reader = command.ExecuteReader())
{
var tableGroups = reader.Cast<DbDataRecord>().GroupBy(
ddr => (
tableSchema: ddr.GetFieldValue<string>("nspname"),
tableName: ddr.GetFieldValue<string>("cls_relname")));
foreach (var tableGroup in tableGroups)
{
var tableSchema = tableGroup.Key.tableSchema;
var tableName = tableGroup.Key.tableName;
var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName);
foreach (var record in tableGroup)
{
// Constraints are detected separately (see GetConstraints), and we don't want their
// supporting indexes to appear independently.
if (constraintIndexes.Contains(record.GetFieldValue<uint>("idx_oid")))
{
continue;
}
var indexName = record.GetFieldValue<string>("idx_relname");
var index = new DatabaseIndex
{
Table = table,
Name = indexName,
IsUnique = record.GetFieldValue<bool>("indisunique")
};
var numKeyColumns = record.GetFieldValue<short>("indnkeyatts");
var columnIndices = record.GetFieldValue<short[]>("indkey");
var tableColumns = (List<DatabaseColumn>)table.Columns;
if (columnIndices.Any(i => i == 0))
{
// Expression index, not supported
logger.ExpressionIndexSkippedWarning(index.Name, DisplayName(tableSchema, tableName));
continue;
/*
var expressions = record.GetValueOrDefault<string>("exprs");
if (expressions is null)
throw new Exception($"Seen 0 in indkey for index {index.Name} but indexprs is null");
index[NpgsqlAnnotationNames.IndexExpression] = expressions;
*/
}
// Key columns come before non-key (included) columns, process them first
foreach (var i in columnIndices.Take(numKeyColumns))
{
if (tableColumns[i - 1] is { } indexKeyColumn)
{
index.Columns.Add(indexKeyColumn);
}
else
{
logger.UnsupportedColumnIndexSkippedWarning(index.Name, DisplayName(tableSchema, tableName));
goto IndexEnd;
}
}
// Now go over non-key (included columns) if any are present
if (columnIndices.Length > numKeyColumns)
{
var nonKeyColumns = new List<string>();
foreach (var i in columnIndices.Skip(numKeyColumns))
{
if (tableColumns[i - 1] is { } indexKeyColumn)
{
nonKeyColumns.Add(indexKeyColumn.Name);
}
else
{
logger.UnsupportedColumnIndexSkippedWarning(index.Name, DisplayName(tableSchema, tableName));
goto IndexEnd;
}
}
// Scaffolding included/covered properties is currently blocked, see #2194
// index[NpgsqlAnnotationNames.IndexInclude] = nonKeyColumns.ToArray();
}
if (record.GetValueOrDefault<string>("pred") is { } predicate)
{
index.Filter = predicate;
}
// It's cleaner to always output the index method on the database model,
// even when it's btree (the default);
// NpgsqlAnnotationCodeGenerator can then omit it as by-convention.
// However, because of https://github.com/aspnet/EntityFrameworkCore/issues/11846 we omit
// the annotation from the model entirely.
if (record.GetValueOrDefault<string>("amname") is { } indexMethod && indexMethod != "btree")
{
index[NpgsqlAnnotationNames.IndexMethod] = indexMethod;
}
// Handle index operator classes, which we pre-loaded
var opClassNames = record
.GetFieldValue<uint[]>("indclass")
.Select(oid => opClasses.TryGetValue(oid, out var opc) && !opc.IsDefault ? opc.Name : null)
.ToArray();
if (opClassNames.Any(op => op is not null))
{
index[NpgsqlAnnotationNames.IndexOperators] = opClassNames;
}
var columnCollations = record
.GetFieldValue<uint[]>("indcollation")
.Select(oid => collations.TryGetValue(oid, out var collation) && collation != "default" ? collation : null)
.ToArray();
if (columnCollations.Any(coll => coll is not null))
{
index[RelationalAnnotationNames.Collation] = columnCollations;
}
if (record.GetValueOrDefault<bool>("amcanorder"))
{
var options = record.GetFieldValue<ushort[]>("indoption");
// The first bit in indoption specifies whether values are sorted in descending order, the second whether
// NULLs are sorted first instead of last.
var isDescending = options.Select(val => (val & 0x0001) != 0).ToList();
var nullSortOrders = options
.Select(val => (val & 0x0002) != 0 ? NullSortOrder.NullsFirst : NullSortOrder.NullsLast)
.ToArray();
index.IsDescending = isDescending;
if (!SortOrderHelper.IsDefaultNullSortOrder(nullSortOrders, isDescending))
{
index[NpgsqlAnnotationNames.IndexNullSortOrder] = nullSortOrders;
}
}
if (record.GetValueOrDefault<bool>("indnullsnotdistinct"))
{
index[NpgsqlAnnotationNames.NullsDistinct] = false;
}
foreach (var storageParameter in record.GetValueOrDefault<string[]>("idx_reloptions") ?? [])
{
if (storageParameter.Split("=") is [var paramName, var paramValue])
{
index[NpgsqlAnnotationNames.StorageParameterPrefix + paramName] = paramValue;
}
}
table.Indexes.Add(index);
IndexEnd: ;
}
}
}
}
/// <summary>
/// Queries the database for defined constraints and registers them with the model.
/// </summary>
private static void GetConstraints(
NpgsqlConnection connection,
IReadOnlyList<DatabaseTable> tables,
string? tableFilter,
string internalSchemas,
out List<uint> constraintIndexes,
IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
var commandText = $"""
SELECT
ns.nspname,
cls.relname,
conname,
contype::text,
conkey,
conindid,
frnns.nspname AS fr_nspname,
frncls.relname AS fr_relname,
confkey,
confdeltype::text
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
JOIN pg_constraint as con ON con.conrelid = cls.oid
LEFT OUTER JOIN pg_class AS frncls ON frncls.oid = con.confrelid
LEFT OUTER JOIN pg_namespace as frnns ON frnns.oid = frncls.relnamespace
WHERE
cls.relkind IN ('r','p') AND
ns.nspname NOT IN ({internalSchemas}) AND
con.contype IN ('p', 'f', 'u') AND
cls.relname <> '{HistoryRepository.DefaultTableName}' AND
-- Exclude child partitions
cls.relispartition <> true AND
-- Exclude tables which are members of PG extensions
NOT EXISTS (
SELECT 1 FROM pg_depend WHERE
classid=(
SELECT cls.oid
FROM pg_class AS cls
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE relname='pg_class' AND ns.nspname='pg_catalog'
) AND
objid=cls.oid AND
deptype IN ('e', 'x')
)
{tableFilter}
""";
using var command = new NpgsqlCommand(commandText, connection);
using var reader = command.ExecuteReader();
constraintIndexes = [];
var tableGroups = reader.Cast<DbDataRecord>().GroupBy(
ddr => (
tableSchema: ddr.GetFieldValue<string>("nspname"),
tableName: ddr.GetFieldValue<string>("relname")));
foreach (var tableGroup in tableGroups)
{
var tableSchema = tableGroup.Key.tableSchema;
var tableName = tableGroup.Key.tableName;
var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName);
// Primary keys
foreach (var primaryKeyRecord in tableGroup.Where(ddr => ddr.GetFieldValue<string>("contype") == "p"))
{
var pkName = primaryKeyRecord.GetValueOrDefault<string>("conname");
var primaryKey = new DatabasePrimaryKey { Table = table, Name = pkName };
foreach (var pkColumnIndex in primaryKeyRecord.GetFieldValue<short[]>("conkey"))
{
if (table.Columns[pkColumnIndex - 1] is { } pkColumn)
{
primaryKey.Columns.Add(pkColumn);
}
else
{
logger.UnsupportedColumnConstraintSkippedWarning(primaryKey.Name, DisplayName(tableSchema, tableName));
goto PkEnd;
}
}
table.PrimaryKey = primaryKey;
PkEnd: ;
}
// Foreign keys
foreach (var foreignKeyRecord in tableGroup.Where(ddr => ddr.GetFieldValue<string>("contype") == "f"))
{
var fkName = foreignKeyRecord.GetFieldValue<string>("conname");
var principalTableSchema = foreignKeyRecord.GetFieldValue<string>("fr_nspname");
var principalTableName = foreignKeyRecord.GetFieldValue<string>("fr_relname");
var onDeleteAction = foreignKeyRecord.GetFieldValue<string>("confdeltype");
var principalTable =
tables.FirstOrDefault(
t =>
principalTableSchema == t.Schema && principalTableName == t.Name)
?? tables.FirstOrDefault(
t =>
principalTableSchema.Equals(t.Schema, StringComparison.OrdinalIgnoreCase)
&& principalTableName.Equals(t.Name, StringComparison.OrdinalIgnoreCase));
if (principalTable is null)
{
logger.ForeignKeyReferencesMissingPrincipalTableWarning(
fkName,
DisplayName(table.Schema, table.Name),
DisplayName(principalTableSchema, principalTableName));
continue;
}
var foreignKey = new DatabaseForeignKey
{
Table = table,
Name = fkName,
PrincipalTable = principalTable,
OnDelete = ConvertToReferentialAction(onDeleteAction)
};
var columnIndices = foreignKeyRecord.GetFieldValue<short[]>("conkey");
var principalColumnIndices = foreignKeyRecord.GetFieldValue<short[]>("confkey");
if (columnIndices.Length != principalColumnIndices.Length)
{
throw new InvalidOperationException("Found varying lengths for column and principal column indices.");
}
var principalColumns = (List<DatabaseColumn>)principalTable.Columns;
for (var i = 0; i < columnIndices.Length; i++)
{
var foreignKeyColumn = table.Columns[columnIndices[i] - 1];
var foreignKeyPrincipalColumn = principalColumns[principalColumnIndices[i] - 1];
if (foreignKeyColumn is null || foreignKeyPrincipalColumn is null)
{
logger.UnsupportedColumnConstraintSkippedWarning(foreignKey.Name, DisplayName(tableSchema, tableName));
goto ForeignKeyEnd;
}
foreignKey.Columns.Add(foreignKeyColumn);
foreignKey.PrincipalColumns.Add(foreignKeyPrincipalColumn);
}
table.ForeignKeys.Add(foreignKey);
ForeignKeyEnd: ;
}
// Unique constraints
foreach (var record in tableGroup.Where(ddr => ddr.GetValueOrDefault<string>("contype") == "u"))
{
var name = record.GetValueOrDefault<string>("conname");
logger.UniqueConstraintFound(name, DisplayName(tableSchema, tableName));
var uniqueConstraint = new DatabaseUniqueConstraint { Table = table, Name = name };
foreach (var columnIndex in record.GetFieldValue<short[]>("conkey"))
{
var constraintColumn = table.Columns[columnIndex - 1];
if (constraintColumn is null)
{
logger.UnsupportedColumnConstraintSkippedWarning(uniqueConstraint.Name, DisplayName(tableSchema, tableName));
goto UniqueConstraintEnd;
}
uniqueConstraint.Columns.Add(constraintColumn);
}
table.UniqueConstraints.Add(uniqueConstraint);
constraintIndexes.Add(record.GetValueOrDefault<uint>("conindid"));
UniqueConstraintEnd: ;
}
}
}
/// <summary>
/// Queries the database for defined sequences and registers them with the model.
/// </summary>
private static IEnumerable<DatabaseSequence> GetSequences(
NpgsqlConnection connection,
DatabaseModel databaseModel,
Func<string, string>? schemaFilter,
IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger)
{
// pg_sequence was only introduced in PG 10; we prefer that (cleaner and also exposes sequence caching info), but retain the old
// code for backwards compat