Repository navigation
Support user-defined ranges - #608
Conversation
* Added an Npgsql options extension to allow users to map user-defined ranges. * Added modeling for range types, to allow creation of user-defined range types in migrations. * Simplified and improved range mapping. Closes npgsql#329
austindrenski
left a comment
There was a problem hiding this comment.
The syntax looks sharp!
| Check.NotEmpty(name, nameof(name)); | ||
| Check.NotEmpty(subtype, nameof(subtype)); | ||
|
|
||
| modelBuilder.Model.Npgsql().GetOrAddPostgresRange(schema, name, subtype, canonicalFunction, subtypeOpClass, |
There was a problem hiding this comment.
nit: stagger the parameters down as in the method signature
| /// See https://www.postgresql.org/docs/current/static/rangetypes.html, | ||
| /// https://www.postgresql.org/docs/current/static/sql-createtype.html, | ||
| /// </remarks> | ||
| public static ModelBuilder ForNpgsqlHasRange( |
| { | ||
| var clone = (NpgsqlOptionsExtension)Clone(); | ||
|
|
||
| clone.RangeMappings.Add((elementClrType, rangeName, subtypeName)); |
There was a problem hiding this comment.
Shouldn't this point to the backing field?
There was a problem hiding this comment.
Thanks, definitely - and in fact the publicly-accessible RangeMappings was a List instead of an IReadOnlyList.
| /// To map a range of PostgreSQL real, use the following: | ||
| /// <code>NpgsqlTypeMappingSource.MapRange("real", typeof(float));</code> | ||
| /// </example> | ||
| public virtual void MapRange(Type elementClrType, string rangeName, string subtypeName=null) |
There was a problem hiding this comment.
Annotate with [NotNull]/[CanBeNull]
| string subtypeOpClass = null, | ||
| string collation = null, | ||
| string subtypeDiff = null) | ||
| => PostgresRange.GetOrAddPostgresRange((IMutableModel)Model, schema, name, subtype, canonicalFunction, |
There was a problem hiding this comment.
nit: stagger down params.
| ClrTypeMappings = new ConcurrentDictionary<Type, RelationalTypeMapping>(clrTypeMappings); | ||
|
|
||
| if (npgsqlOptions?.Plugins != null) | ||
| if (npgsqlOptions != null) |
There was a problem hiding this comment.
Can this be inverted to reduce nesting?
| RelationalTypeMapping subtypeMapping; | ||
| if (subtypeName == null) | ||
| { | ||
| if (!ClrTypeMappings.TryGetValue(elementClrType, out subtypeMapping)) |
There was a problem hiding this comment.
Merge these if statements?
There was a problem hiding this comment.
Done, converted to expression.
| public NpgsqlRange<int> Range { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// The range of integers. |
There was a problem hiding this comment.
nit: "The range of floats"
There was a problem hiding this comment.
I ended up removing the comments altogether (this seems like a particularly useless place for them...)
| .UseNpgsql(_testStore.ConnectionString, b => b.ApplyConfiguration()) | ||
| .UseNpgsql(_testStore.ConnectionString, b => | ||
| { | ||
| b.MapRange(typeof(float), "floatrange"); |
| /// <inheritdoc /> | ||
| protected override void OnModelCreating(ModelBuilder builder) { } | ||
| protected override void OnModelCreating(ModelBuilder builder) | ||
| => builder.ForNpgsqlHasRange("floatrange", "real"); |
|
I just realized that we've got the parameters flipped between these two: .ForNpgsqlHasRange("floatrange", "real");
.MapRange(typeof(float), "floatrange");Could we sync these up so that the subtype always comes first? Also, is it possible to allow the subtype in both to be specified by the CLR type (as an overload)? .ForNpgsqlHasRange(typeof(float), "floatrange");
.MapRange(typeof(float), "floatrange");I'm thinking that this would simplify things and reduce the number of user questions we get related to the range type and subtype being flipped. |
Good point! But I ended up going the other way: it seems to make more sense for the first parameter to identify the range type being mapped, rather than its subtype.
So as I mentioned in this comment, The other option would be to not translate the type to a string at that point, but to somehow represent the CLR type inside the annotation (as a string). Then, when it is picked up by the MigrationSqlGenerator, translate it to a PostgreSQL string there, since that service can access the TypeMappingSource. However, this will make the annotation much more complex and ugly (need to support two formats, one type-based and one string-based), it just doesn't seem worth it. I also think there's a small advantage to having users think directly in terms of PostgreSQL types in this specific context, when specifying what their database range type should look like... |
|
Pushed a commit addressing comments, please re-review. |
|
One note... A bit like with the comments, I'm not sure the adding In the meantime I added |
|
Note: pushed another commit that adds docs for this feature. |
That makes more sense!
That's a good point. And not so different from other model builder extensions work. I was thinking about the explicit CLR type helping protect users from mismatched CLR/PG types, but it could also go the other way too. Plus, this is how |
| /// <code>NpgsqlTypeMappingSource.MapRange("real", typeof(float));</code> | ||
| /// </example> | ||
| public virtual void MapRange([NotNull] string rangeName, [NotNull] Type elementClrType, | ||
| string subtypeName = null) |
There was a problem hiding this comment.
nit: partially chopped argumnet
| /// <param name="rangeName">The name of the PostgreSQL range type to be mapped.</param> | ||
| /// <param name="elementClrType"> | ||
| /// The CLR type of the range's element. The actual mapped type will be an <code>NpgsqlRange{T}</code> over | ||
| /// this type. |
| /// </summary> | ||
| [NotNull] | ||
| internal virtual NpgsqlOptionsExtension WithRangeMapping(string rangeName, Type elementClrType, | ||
| string subtypeName) |
There was a problem hiding this comment.
nit: partially chopped arguments
|
|
||
| [NotNull] | ||
| static string BuildAnnotationName(string schema, string name) | ||
| => NpgsqlAnnotationNames.RangePrefix + (schema == null ? name : schema + '.' + name); |
There was a problem hiding this comment.
nit: I would go with interpolation
There was a problem hiding this comment.
I tried, but it doesn't look any better (the ternary expression has to be there anyway).
| } | ||
|
|
||
| (string Schema, string Name, string Subtype, string CanonicalFunction, string SubtypeOpClass, string Collation, | ||
| string SubtypeDiff) GetData() |
There was a problem hiding this comment.
nit: partially chopped return type.
This might be a wide enough tuple to justify defining a full type... But not a big deal either way.
There was a problem hiding this comment.
PostgresRange itself already represents more or less the tuple of all these variables, with the capability to serialize/deserialize itself to and from annotations... It's not the prettiest, I agree.
At some point we can look at refactor how all our annotations are implemented, but for now let's continue in the way others are done.
|
@austindrenski pushed another commit |
| This allows you to have properties of type `NpgsqlRange<float>`, which will be mapped to PostgreSQL `floatrange`. | ||
|
|
||
| The above does *not* create the `floatrange` type for you. In order to do that, include the following in your context's `OnModelCreating()`: | ||
|
|
There was a problem hiding this comment.
Lost code block opening.
| /// The list of range mappings specified by the user. | ||
| /// </summary> | ||
| [NotNull] | ||
| public IReadOnlyList<(string RangeName, Type ElementClrType, string SubTypeName)> RangeMappings => _rangeMappings; |
There was a problem hiding this comment.
Would you mind to make a new type instead of repeatable value tuples?
| clone._rangeMappings.Add((rangeName, elementClrType, subtypeName)); | ||
|
|
||
| return clone; | ||
| } |
There was a problem hiding this comment.
nit: Does these empty lines improve readability?
There was a problem hiding this comment.
Not really, but this is the way it was when copied from EF Core... Let's leave the same for now (we can clean up later)
| /// <code>NpgsqlTypeMappingSource.MapRange("real", typeof(float));</code> | ||
| /// </example> | ||
| public virtual void MapRange([NotNull] string rangeName, [NotNull] Type elementClrType, string subtypeName = null) | ||
| => WithOption(e => e.WithRangeMapping(rangeName, elementClrType, subtypeName)); |
There was a problem hiding this comment.
I think it makes sense to add a generic version of the method.
There was a problem hiding this comment.
Done. Also renamed from element to subtype, which is the PostgreSQL naming for ranges (unlike arrays).
Also corrected comments and variable names from element to subtype.
|
|
||
| /// <inheritdoc /> | ||
| [NotNull] | ||
| public virtual IReadOnlyList<(string RangeName, Type ElementClrType, string SubTypeName)> RangeMappings { get; private set; } |
There was a problem hiding this comment.
Oh, it repeats too many times.
|
|
||
| public NpgsqlOptions() | ||
| { | ||
| RangeMappings = new (string, Type, string)[0]; |
There was a problem hiding this comment.
We really should have a new type instead that tuple. Otherwise, it looks like copy-paste programming.
There was a problem hiding this comment.
OK OK I replaced it with RangeMappingInfo...
|
|
||
| #region User-defined range types | ||
|
|
||
| #endregion User-defined range types |
| join oldEnum in PostgresEnum.GetPostgresEnums(operation.OldDatabase) on newEnum.Name equals oldEnum.Name | ||
| select new { newEnum.Name, OldLabels = oldEnum.Labels, newLabels = newEnum.Labels }) | ||
| { | ||
| // TODO: Some forms of enum alterations are actually supported... At least log... |
There was a problem hiding this comment.
May be throw an exception?
There was a problem hiding this comment.
Done, also copied better LINQ construct from range.
There was a problem hiding this comment.
I don't know.... wouldn't that make standard code throw?
| PostgresRange.GetPostgresRanges(operation.OldDatabase).Any(or => or.Name == nr.Name) | ||
| ) is PostgresRange rangeTypeToAlter) | ||
| { | ||
| throw new NotSupportedException($"Altering range type ${rangeTypeToAlter} isn't supported."); |
| @@ -317,9 +317,13 @@ public override void CreateTables() | |||
| var commands = Dependencies.MigrationsSqlGenerator.Generate(operations, Dependencies.Model); | |||
|
|
|||
| // If a PostgreSQL extension or enum was added, we want Npgsql to reload all types at the ADO.NET level. | |||
There was a problem hiding this comment.
Not only an extension or enum, but also a range.
|
Ready for another review guys :) |
| /// Optionally, the name of the range's PostgreSQL subtype (or element). | ||
| /// This is usually not needed - the subtype will be inferred based on <see cref="SubtypeClrType"/>. | ||
| /// </summary> | ||
| public readonly string SubtypeName; |
There was a problem hiding this comment.
Even if it's a readonly struct, I think it would be better to have public properties instead of fields.
There was a problem hiding this comment.
Just my two cents, but for readonly struct I would actually stick with the public readonly fields. Adding back the layer of indirection feels....indirect.
There was a problem hiding this comment.
Agreed, but the common practice is to continue to use properties. Therefore, these fields could be replaced by readonly properties. No additional code for back storage is required:
public string RangeName { get; }There is an article about readonly structs, immutability and performance. The ‘in’-modifier and the readonly structs in C#.
Anyway I don't think that it's a blocking issue. Just would like to hear @roji's thought on it (:
There was a problem hiding this comment.
The compiler checks that the struct is indeed immutable and consists only of readonly fields and/or readonly properties (properties like
public int Foo {get; private set;}are not readonly).
Ahh, I read that a while back but overlooked the comments on read-only instance properties being eligible! Thanks for pointing that out!
There was a problem hiding this comment.
I briefly thought about this when doing these changes... I agree that there's no perf impact or anything like that. My thinking was that in general, we use properties as opposed to fields in order to encapsulate, in order words, to have the possibility of refactoring later and having the property change (i.e. convert from auto-property to real code which delegates, say, to some other class or something). However, in this case this really is a bundle of values, exactly like a tuple - nothing more. So the usual logic for preferring properties over fields doesn't really hold here IMHO.
Note also that this type is a bit of a "false" public type, users are almost never meant to interact with it directly - they'll use the builder extensions which will create and pass this type for them. So I don't give the API here as much attention as I do with real, user-facing APIs.
On the other hand I don't have a very good reason against properties here, I'll make the change.
|
Thanks for the valuable review comments guys...! |
Closes #329