Repository navigation
Description
Still investigating into ways to interact with composite types in the postgresql database, we defined a composite that uses a database defined enum. While following this outline we added ModelBuilder.ForNpgsqlHasEnum invocations and further added a plugin that translates composite type members such that the composite type member is mapped in the query. It does so by implementing a custom Expression that basically does this:
// a class that extends Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.IMemberTranslator
public Expression Translate(MemberExpression memberExpression)
{
if (memberExpression.Member == ValueMember)
{
return new GetCompositeTypeMemberExpression(NpgsqlNameTranslator, memberExpression.Expression, memberExpression.Member);
}
if (memberExpression.Member == UnitMember)
{
return new GetCompositeTypeMemberExpression(NpgsqlNameTranslator, memberExpression.Expression, memberExpression.Member);
}
return null;
}
// a class that extends System.Linq.Expressions.Expression
protected override Expression Accept(ExpressionVisitor visitor)
{
var leftBracket = new CustomUnaryExpression(Instance, "(", Instance.Type, false);
var rightBracket = new CustomUnaryExpression(leftBracket, ")", Instance.Type, true);
var memberExpression = new CustomUnaryExpression(rightBracket, $".{MemberName}", Type, true);
return memberExpression;
}This works exceptionally well and generates good queries that look alike:
2018-08-14 16:01:27.065 +02:00 [Error] [7856816] [14] [] [] [:] [Microsoft.EntityFrameworkCore.Database.Command] Failed executing DbCommand ("11"ms) [Parameters=[""], CommandType='Text', CommandTimeout='600']"
""SELECT t.id, (t.weight).value, (t.weight).unit
FROM sandbox.weighing AS t"
Unfortunately when adding a simple where clause in the query as follows:
storage
.WeighingRecords
.Where(t => t.Weight.Unit == WeightUnit.Tonne)the following happens:
2018-08-14 16:01:27.065 +02:00 [Error] [7856816] [14] [] [] [:] [Microsoft.EntityFrameworkCore.Database.Command] Failed executing DbCommand ("11"ms) [Parameters=[""], CommandType='Text', CommandTimeout='600']"
""SELECT t.id, (t.weight).value, (t.weight).unit
FROM sandbox.weighing AS t
WHERE (t.weight).unit = 6"
Npgsql.PostgresException (0x80004005): 42883: operator does not exist: units.weight_unit = integer
When I refactor the where argument out of the query such that it becomes a query parameter the query works as expected:
var weightUnit = WeightUnit.Tonne;
var actualWeighingRecords = storage
.WeighingRecords
.Where(t => t.Weight.Unit == weightUnit)2018-08-14 16:13:28.360 +02:00 [Information] [8553120] [17] [] [] [:] [Microsoft.EntityFrameworkCore.Database.Command] Executed DbCommand ("10"ms) [Parameters=["@__weightUnit_0='Tonne' (DbType = Object)"], CommandType='Text', CommandTimeout='600']"
""SELECT t.id, (t.weight).value, (t.weight).unit
FROM sandbox.weighing AS t
WHERE (t.weight).unit = @__weightUnit_0"
Is there a way to make this query work without that extra parameter?
Activity
dpsenner commentedon Aug 14, 2018
I just noticed that changing this:
to a const variable as the roslynator code analyzer warns about RCS1118:
causes the query to fail again because the underlying int value of the enumeration is passed into the query as the parameter.
austindrenski commentedon Aug 15, 2018
@dpsenner You're running into a few open issues here...
The constant
enumissue is similar to thecharliteral issue. Basically the expression tree stores the underlying value directly (making this issue fairly intractable). There's been some discussion of how to tackle this, such as adding some heuristics to determine when a literalcharorenumcomparison is happening, but that work is still ongoing. (#450, #489)As for composite mapping, there's some work that needs to happen at the ADO.NET driver before we can add first-class support to the EF Core provider. One recent consideration has been to transparently map composites to
ValueTuple. (#563)Based on your snippets, it looks like you're planning to replace some services internal to the EF Core provider. If you're already set on doing this, you should take a look at the separation of responsibilities between our custom expressions, the
NpgsqlSqlTranslatingExpressionVisitor, and theNpgsqlQuerySqlGenerator.Right now it looks like you're using
CustomUnaryExpressionto generate SQL for the composite types. While creative, this type of work is much better suited for a service replacingNpgsqlQuerySqlGenerator.dpsenner commentedon Aug 16, 2018
@austindrenski Thanks, #593 reads like a duplicate of #489. It seems like I misinterpreted the error because it read to me like being related to composite types. Are the changes of #490 up for the next release? If these changes should be part of
2.1.1.1then #490 does not work for types mapped from a plugin.The following is a little bit off topic to this issue, I do however feel that parts of what we are doing could become a part of the postgresql integration with EF core.
We're not considering to replace EF core services or are not seeing that we should do so. Currently the following snippets are part of an
NpgsqlEntityFrameworkPluginthat adds database enums and composite types that we have defined in the database. It does so by addingRelationalTypeMappers andIMemberTranslators and is a spinoff from this conversation.Feel free to have a look at the plugin. As you see below, we use the
NpgsqlEntityFrameworkPluginsystem to add support for our types and I assume that this is the initial purpose of this plugin. We have no need to replace ef core internal services. We are somehow abusing the relational type mapping system to inject non-relational composite types. It would be better if there was a way to add composite type mappings in the plugin, also because it would allow us to delegate the member translation of composite types toNpgsqlQuerySqlGeneratorwhich appears to be the right place for this.The following is the plugin:
dpsenner commentedon Aug 16, 2018
I just added an enumeration member to one of the models that maps to a database enum. The following is the script to create the database enum and table:
It appears like the query generator does indeed map the enum to the enum member:
This is what is run against the database:
However, by refactoring the query to this:
the following happens:
The query is semantically correct but fails on the syntax because it added quotes around
sandbox.weighing_meaning. The query without quotes works fine when run in pgadmin, i.e.:It appears that somewhere the integral value is converted back to the enumeration and properly mapped to the correct enumeration member. The fix #490 addresses some issues, but there are still other usecases that do not work as one would expect.
[-]Navigating into composite type members[/-][+]Underlying enum values are not mapped to the database enumeration for types registered into the npgsql type mapping[/+]austindrenski commentedon Aug 16, 2018
@dpsenner I'll take another look at this tonight, but in the meantime take a look at #554 and let me know if you believe part of your issue overlaps.
Part of this is needing to differentiate between known enum issues, and issues related to composites + your plugin. Any help delineating the two would help immensely.
dpsenner commentedon Aug 16, 2018
For one, enumerations that are not added before any dbcontext is created do not work as expected. It is mandatory to add enumerations to the underlying type mapper by invocation of
NpgsqlConnection.GlobalTypeMapper.MapEnum<TEnum>(pgName)right here:If one does not do this, queries fail with the following symptom:
What does not work is adding enumeration types during the model builder phase. To mitigate the issue I just implemented the following extension method which does register npgsql enumeration members but requires the enumeration type to have been registered earlier:
This process feels terrible because there are several places and several times where types have to be registered but knowing this, one can make sure that it works. With enumerations added at the right time, queries fail again with this symptom:
dpsenner commentedon Aug 16, 2018
Next I just tried to create the enumeration in the public schema:
Doing so and mapping the enumeration along with the schema appears to fail with the same symptom.
dpsenner commentedon Aug 16, 2018
When I instead register the enum without a schema all my queries and tests pass. I.e. the following works:
while the following fails:
austindrenski commentedon Aug 16, 2018
Good to hear. This is part of what #554 is looking to fix.
dpsenner commentedon Aug 17, 2018
After further investigation I can confirm that we observe exactly two symptoms:
To me it is still unclear whether the second symptom can and should be fixed by improving the plugin. The plugin currently does implement expressions to navigate into composite types members (via
IMemberTranslator) and therefore feels like it could be the right place but at the same time it feels to be the wrong place for this. As outlined in a previous comment, it would be ideal if theNpgsqlEntityFrameworkPluginclass provided an api to inject composite types.NpgsqlEntityFrameworkPlugincould then set up composite type members' mappings to work both in select tuples and where queries.