-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathNpgsqlModelValidator.cs
More file actions
340 lines (293 loc) · 13.2 KB
/
NpgsqlModelValidator.cs
File metadata and controls
340 lines (293 loc) · 13.2 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
using Npgsql.EntityFrameworkCore.PostgreSQL.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class NpgsqlModelValidator(
ModelValidatorDependencies dependencies,
RelationalModelValidatorDependencies relationalDependencies,
INpgsqlSingletonOptions npgsqlSingletonOptions) : RelationalModelValidator(dependencies, relationalDependencies)
{
/// <summary>
/// The backend version to target.
/// </summary>
private readonly Version _postgresVersion = npgsqlSingletonOptions.PostgresVersion;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override void Validate(IModel model, IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.Validate(model, logger);
ValidateIdentityVersionCompatibility(model);
}
/// <summary>
/// Validates that identity columns are used only with PostgreSQL 10.0 or later (model-level check).
/// </summary>
/// <param name="model">The model to validate.</param>
protected virtual void ValidateIdentityVersionCompatibility(IModel model)
{
if (_postgresVersion.AtLeast(10))
{
return;
}
var strategy = model.GetValueGenerationStrategy();
if (strategy is NpgsqlValueGenerationStrategy.IdentityAlwaysColumn or NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
{
throw new InvalidOperationException(
$"'{strategy}' requires PostgreSQL 10.0 or later. "
+ "If you're using an older version, set PostgreSQL compatibility mode by calling "
+ $"'optionsBuilder.{nameof(NpgsqlDbContextOptionsBuilder.SetPostgresVersion)}()' in your model's OnConfiguring. "
+ "See the docs for more info.");
}
}
/// <inheritdoc />
protected override void ValidateProperty(
IProperty property,
ITypeBase structuralType,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateProperty(property, structuralType, logger);
var strategy = property.GetValueGenerationStrategy();
// Identity version compatibility (per-property check)
if (!_postgresVersion.AtLeast(10)
&& strategy is NpgsqlValueGenerationStrategy.IdentityAlwaysColumn
or NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
{
throw new InvalidOperationException(
$"{property.DeclaringType}.{property.Name}: '{strategy}' requires PostgreSQL 10.0 or later.");
}
// Value generation strategy compatibility
var propertyType = property.ClrType;
switch (strategy)
{
case NpgsqlValueGenerationStrategy.None:
break;
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
if (!NpgsqlPropertyExtensions.IsCompatibleWithValueGeneration(property))
{
throw new InvalidOperationException(
NpgsqlStrings.IdentityBadType(
property.Name, property.DeclaringType.DisplayName(), propertyType.ShortDisplayName()));
}
break;
case NpgsqlValueGenerationStrategy.SequenceHiLo:
case NpgsqlValueGenerationStrategy.Sequence:
case NpgsqlValueGenerationStrategy.SerialColumn:
if (!NpgsqlPropertyExtensions.IsCompatibleWithValueGeneration(property))
{
throw new InvalidOperationException(
NpgsqlStrings.SequenceBadType(
property.Name, property.DeclaringType.DisplayName(), propertyType.ShortDisplayName()));
}
break;
default:
throw new UnreachableException();
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override void ValidateValueGeneration(
IKey key,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
var entityType = key.DeclaringEntityType;
if (entityType.GetTableName() != null
&& (string?)entityType[RelationalAnnotationNames.MappingStrategy] == RelationalAnnotationNames.TpcMappingStrategy)
{
foreach (var storeGeneratedProperty in key.Properties.Where(
p => (p.ValueGenerated & ValueGenerated.OnAdd) != 0
&& p.GetValueGenerationStrategy() != NpgsqlValueGenerationStrategy.Sequence))
{
logger.TpcStoreGeneratedIdentityWarning(storeGeneratedProperty);
}
}
}
/// <inheritdoc />
protected override void ValidateIndex(
IIndex index,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateIndex(index, logger);
var includeProperties = index.GetIncludeProperties();
if (includeProperties?.Count > 0)
{
var notFound = includeProperties
.FirstOrDefault(i => index.DeclaringEntityType.FindProperty(i) is null);
if (notFound is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyNotFound(index.DeclaringEntityType.DisplayName(), notFound));
}
var duplicate = includeProperties
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.FirstOrDefault();
if (duplicate is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyDuplicated(index.DeclaringEntityType.DisplayName(), duplicate));
}
var inIndex = includeProperties
.FirstOrDefault(i => index.Properties.Any(p => i == p.Name));
if (inIndex is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyInIndex(index.DeclaringEntityType.DisplayName(), inIndex));
}
}
}
/// <inheritdoc />
protected override void ValidateKey(
IKey key,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateKey(key, logger);
if (key.GetWithoutOverlaps() == true)
{
ValidateWithoutOverlapsKey(key);
}
}
/// <inheritdoc />
protected override void ValidateForeignKey(
IForeignKey foreignKey,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateForeignKey(foreignKey, logger);
if (foreignKey.GetPeriod() == true)
{
ValidatePeriodForeignKey(foreignKey);
}
}
/// <inheritdoc />
protected override void ValidateStoredProcedures(
IEntityType entityType,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateStoredProcedures(entityType, logger);
if (entityType.GetDeleteStoredProcedure() is { } deleteStoredProcedure)
{
ValidateSproc(deleteStoredProcedure, logger);
}
if (entityType.GetInsertStoredProcedure() is { } insertStoredProcedure)
{
ValidateSproc(insertStoredProcedure, logger);
}
if (entityType.GetUpdateStoredProcedure() is { } updateStoredProcedure)
{
ValidateSproc(updateStoredProcedure, logger);
}
static void ValidateSproc(IStoredProcedure sproc, IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
var entityType = sproc.EntityType;
var storeObjectIdentifier = sproc.GetStoreIdentifier();
if (sproc.ResultColumns.Any())
{
throw new InvalidOperationException(
NpgsqlStrings.StoredProcedureResultColumnsNotSupported(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName()));
}
if (sproc.IsRowsAffectedReturned)
{
throw new InvalidOperationException(
NpgsqlStrings.StoredProcedureReturnValueNotSupported(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName()));
}
}
}
/// <inheritdoc />
protected override void ValidateCompatible(
IProperty property,
IProperty duplicateProperty,
string columnName,
in StoreObjectIdentifier storeObject,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateCompatible(property, duplicateProperty, columnName, storeObject, logger);
if (property.GetCompressionMethod(storeObject) != duplicateProperty.GetCompressionMethod(storeObject))
{
throw new InvalidOperationException(
NpgsqlStrings.DuplicateColumnCompressionMethodMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
}
private void ValidateWithoutOverlapsKey(IKey key)
{
var keyName = key.IsPrimaryKey() ? "primary key" : $"alternate key {key.Properties.Format()}";
var entityType = key.DeclaringEntityType;
// Check PostgreSQL version requirement
if (!_postgresVersion.AtLeast(18))
{
throw new InvalidOperationException(
NpgsqlStrings.WithoutOverlapsRequiresPostgres18(keyName, entityType.DisplayName()));
}
// Check that the last property is a range type
var lastProperty = key.Properties[^1];
var typeMapping = lastProperty.FindTypeMapping();
if (typeMapping is not NpgsqlRangeTypeMapping)
{
throw new InvalidOperationException(
NpgsqlStrings.WithoutOverlapsRequiresRangeType(
keyName,
entityType.DisplayName(),
lastProperty.Name,
lastProperty.ClrType.ShortDisplayName()));
}
}
private void ValidatePeriodForeignKey(IForeignKey foreignKey)
{
var entityType = foreignKey.DeclaringEntityType;
var fkName = foreignKey.Properties.Format();
var principalKey = foreignKey.PrincipalKey;
var principalEntityType = principalKey.DeclaringEntityType;
if (!_postgresVersion.AtLeast(18))
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresPostgres18(fkName, entityType.DisplayName()));
}
// Check that the principal key has WITHOUT OVERLAPS (check this before range type)
if (principalKey.GetWithoutOverlaps() != true)
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresWithoutOverlapsOnPrincipal(
fkName,
entityType.DisplayName(),
principalKey.IsPrimaryKey()
? "primary key"
: $"alternate key {principalKey.Properties.Format()}",
principalEntityType.DisplayName()));
}
// Check that the last property is a range type
var lastProperty = foreignKey.Properties[^1];
var typeMapping = lastProperty.FindTypeMapping();
if (typeMapping is not NpgsqlRangeTypeMapping)
{
throw new InvalidOperationException(
NpgsqlStrings.PeriodRequiresRangeType(
fkName,
entityType.DisplayName(),
lastProperty.Name,
lastProperty.ClrType.ShortDisplayName()));
}
}
}