Skip to content

Support user-defined ranges - #608

Merged
roji merged 6 commits into
npgsql:devfrom
roji:user-ranges
Aug 21, 2018
Merged

roji merged 6 commits into
npgsql:devfrom
roji:user-ranges

Conversation

@roji

@roji roji commented Aug 18, 2018

Copy link
Copy Markdown
Member
  • 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 #329

* 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 austindrenski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The syntax looks sharp!

Check.NotEmpty(name, nameof(name));
Check.NotEmpty(subtype, nameof(subtype));

modelBuilder.Model.Npgsql().GetOrAddPostgresRange(schema, name, subtype, canonicalFunction, subtypeOpClass,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: stagger the parameters down as in the method signature

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

/// 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add [NotNull]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

{
var clone = (NpgsqlOptionsExtension)Clone();

clone.RangeMappings.Add((elementClrType, rangeName, subtypeName));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this point to the backing field?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Annotate with [NotNull]/[CanBeNull]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

string subtypeOpClass = null,
string collation = null,
string subtypeDiff = null)
=> PostgresRange.GetOrAddPostgresRange((IMutableModel)Model, schema, name, subtype, canonicalFunction,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: stagger down params.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

ClrTypeMappings = new ConcurrentDictionary<Type, RelationalTypeMapping>(clrTypeMappings);

if (npgsqlOptions?.Plugins != null)
if (npgsqlOptions != null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be inverted to reduce nesting?

RelationalTypeMapping subtypeMapping;
if (subtypeName == null)
{
if (!ClrTypeMappings.TryGetValue(elementClrType, out subtypeMapping))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merge these if statements?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, converted to expression.

public NpgsqlRange<int> Range { get; set; }

/// <summary>
/// The range of integers.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "The range of floats"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice syntax!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks :)

/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder builder) { }
protected override void OnModelCreating(ModelBuilder builder)
=> builder.ForNpgsqlHasRange("floatrange", "real");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice syntax!

@austindrenski

austindrenski commented Aug 18, 2018 •

Copy link
Copy Markdown
Contributor

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.

@roji

roji commented Aug 19, 2018

Copy link
Copy Markdown
Member Author

I just realized that we've got the parameters flipped between these two:
[...]
Could we sync these up so that the subtype always comes first?

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.

Also, is it possible to allow the subtype in both to be specified by the CLR type (as an overload)?

So as I mentioned in this comment, ForNpgsqHasRange() is an extension method on ModelBuilder. As such it simply doesn't have access (as far as I can tell) to all the provider services such as the TypeMappingSource, which would be needed her to translate from a CLR type to a PostgreSQL type name (string). All it does at the end of the day is translate a nice fluent API call into a string-based annotation.

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...

@roji

roji commented Aug 19, 2018

Copy link
Copy Markdown
Member Author

Pushed a commit addressing comments, please re-review.

@roji

roji commented Aug 19, 2018 •

Copy link
Copy Markdown
Member Author

One note... A bit like with the comments, I'm not sure the adding [NotNull] absolutely everywhere really improves our code base :) This introduces a huge amount of code clutter, which can be mitigated via implicit nullability if you're using R# or Rider. We also know that non-nullable references are coming in C# 8.0, at which point this will all go away.

In the meantime I added [NotNull] in this PR, but I suggest we don't spend too much time on this...

@roji

roji commented Aug 19, 2018

Copy link
Copy Markdown
Member Author

Note: pushed another commit that adds docs for this feature.

@austindrenski

Copy link
Copy Markdown
Contributor

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.

That makes more sense!

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...

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 .HasColumnType(...) looks syntax-wise.

/// <code>NpgsqlTypeMappingSource.MapRange("real", typeof(float));</code>
/// </example>
public virtual void MapRange([NotNull] string rangeName, [NotNull] Type elementClrType,
string subtypeName = null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: partially chopped argumnet

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

/// <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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: indents

@roji roji Aug 20, 2018 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

/// </summary>
[NotNull]
internal virtual NpgsqlOptionsExtension WithRangeMapping(string rangeName, Type elementClrType,
string subtypeName)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: partially chopped arguments

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


[NotNull]
static string BuildAnnotationName(string schema, string name)
=> NpgsqlAnnotationNames.RangePrefix + (schema == null ? name : schema + '.' + name);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I would go with interpolation

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@roji

roji commented Aug 20, 2018

Copy link
Copy Markdown
Member Author

@austindrenski pushed another commit

Comment thread doc/mapping/range.md
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()`:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lost code block opening.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

/// The list of range mappings specified by the user.
/// </summary>
[NotNull]
public IReadOnlyList<(string RangeName, Type ElementClrType, string SubTypeName)> RangeMappings => _rangeMappings;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you mind to make a new type instead of repeatable value tuples?

clone._rangeMappings.Add((rangeName, elementClrType, subtypeName));

return clone;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Does these empty lines improve readability?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to add a generic version of the method.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/EFCore.PG/Internal/NpgsqlOptions.cs Outdated

/// <inheritdoc />
[NotNull]
public virtual IReadOnlyList<(string RangeName, Type ElementClrType, string SubTypeName)> RangeMappings { get; private set; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, it repeats too many times.

Comment thread src/EFCore.PG/Internal/NpgsqlOptions.cs Outdated

public NpgsqlOptions()
{
RangeMappings = new (string, Type, string)[0];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We really should have a new type instead that tuple. Otherwise, it looks like copy-paste programming.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK OK I replaced it with RangeMappingInfo...


#region User-defined range types

#endregion User-defined range types

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty region.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

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...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be throw an exception?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, also copied better LINQ construct from range.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@@ -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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not only an extension or enum, but also a range.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@roji

roji commented Aug 20, 2018

Copy link
Copy Markdown
Member Author

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if it's a readonly struct, I think it would be better to have public properties instead of fields.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@roji
roji merged commit ec2f2c0 into npgsql:dev Aug 21, 2018
@roji

roji commented Aug 21, 2018

Copy link
Copy Markdown
Member Author

Thanks for the valuable review comments guys...!

@roji
roji deleted the user-ranges branch September 8, 2020 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants