Repository navigation
Description
In a PostgreSQL 10.3 database I have multiplecitext columns for string properties and for simple keyword searches the Contains() method of the string properties is used.
For example I have an entity Institute with property string Name and a configured column type of citext set via the fluent API. When debugging, the mapper yields the correct NpgsqlCitextTypeMapping for the property.
The generated LINQ query is a simple conjunction of institute.Name.Contains(keyword) predicates that yields the following query for a single keyword:
SELECT [...]
FROM "Institutes" AS institute
WHERE STRPOS(institute."Name", @__token_0) > 0
ORDER BY institute."Name", institute."Id"If executed manually with a string used for the token, the expected rows are returned. Within the application, no matches are found. It seems, that the Npgsql type for the string parameter is (explicitly?) set to text instead of citext; according to the citext documentation, all parameters for the case-insensitive function variants must be citext (which is easily confirmed by running the query manually with 'searchtoken'::text, which also wouldn't yield a row).
Just to ensure that citext is working as expected: if I replace the Contains() method by a simple comparison, I get a case-insensitive match for a full name.
This is probably easily fixed by adding an explicit citext type cast for the argument within NpgsqlStringContainsTranslator if the expression object has a configured column type of citext, similar to #319.
Issue appears with both versions 2.0.2 and 2.1.0-rc1-ci.298.
For correctness, a generic approach may be useful: all string methods on citext objects that return a string should probably ensure that the returned value retains the citext type (if the PostgreSQL function itself doesn't, as in #319) and if the object of a method is citext (either due to the configured column type as here, or as a result of transformations, e.g. function calls such as institute.Name.Replace(...).Contains(...)), other parameters should maybe be cast to citext, carefully considering side effects.
If a column is explicitly set as citext, a true per-default case-insensitive handling could be achieved.
Activity
roji commentedon May 6, 2018
@takerukoushirou thanks for raising this and the analysis - everything you say is correct. I find it a bit unfortunate that citext behaves this way, i.e. that various string functions perform in a case-sensitive way if their main parameter is a citext. I would have expected
STRPOS()to be case-insensitive even when the substring parameter is text. I sent a question to the PG hackers list, let's see what they say.In any case, there are two different issues in what you mention:
citexttype is probably not going to be possible. As you can see in StartsWith on citext column does not return results #319, we can detect acitexttype by looking at the EF property's column configuration - property in the sense of a property on an entity in the model. If a string doesn't correspond to a property (i.e. it's a constant string literal, or just some string variable/parameter), there's no column configuration. So I don't think there's a way for one of our function translators to "return" a citext, just a string.One possible solution would be to provide users with a way to explicitly cast to citext (or any other arbitrary store type). We probably need something like this for other cases anyway, although this probably belongs in EF Core and not in the Npgsql provider.
In a more general way, these citext issues are the result of a bit of type hacking we're doing here: there's no CLR equivalent to PG
citext, and we're coercing string to do the job.String.Contains()is always case-sensitive - it's never insensitive - and yet we're trying to use it to express a case-insensitive operation.Are you interested in working on a PR for this? You seem to already have a good understanding of what's going on in there.
roji commentedon May 6, 2018
BTW the idea of having an arbitrary cast operation (which would allow users to explicitly specify
citext) has already been discussed, I've just opened dotnet/efcore#11921 to track adding this in EF Core.takerukoushirou commentedon May 6, 2018
@roji I was myself surprised by this and expected by explicitly using
citextfor columns to get case-insensitive behaviour for common string operations (similar to a replacement for a case-insensitive collation); the little hint in the documentation, that each argument must be of typecitextis easily over-read. Thanks for the question on the PG hackers list, our suspicions were confirmed, including the way an unknown parameter is cast tocitext.True, in .NET
String.Contains()is always case-sensitive. I somewhat remember having read a thread (likely in the EF Core issue tracker) regarding case-(in)sensitivity and that some databases operate differently on strings than .NET would, and instead of EF Core trying to force every provider to somehow provide the same behaviour as .NET (if even possible), the decision was to let the database intention win.In my scenario several databases are supported (currently MySQL, SQLite, PostgreSQL and SQLServer), and based on the EF Core handling of case-(in)sensitivity, I decided that it would be best to have the databases/tables configured in such a way, that they behave similar, instead of adding more complexity to queries and likely degrade performance (e.g. adding a
ToLower()for both properties and arguments; also have the ability for case-independent PKEYs, where a functional index isn't possible, in case this may be needed someday). That is also why using explicit cast operations would not be a suitable solution for my scenario, as all queries should be provider-agnostic (cast operations would generally be a very useful extension for EF Core though).I had another idea yesterday but I do not know how feasible this would be, as I am not familiar with the internals: As PostgreSQL casts
unknowntocitextin this context, would it be possible to set the parameter type for string parameters in Npgsql tounknownin these cases, so PostgreSQL could implicitly do the cast? I am not sure though what side effects this may have though.I'll gladly look into working on a PR, but unfortunately currently and in the foreseeable weeks I won't have any time to look into any details. I'll at least try to have a look at the
Contains()transformation for now and think about some more generic approaches later.Fixes npgsql#384 via conditional argument cast to citext
roji commentedon May 6, 2018
Thanks for PR #384.
This is definitely possible when working at the ADO level (without EF Core) - when you create NpgsqlCommand and NpgsqlParameter yourself, you can set the parameter's NpgsqlDbType to Unknown, allowing PostgreSQL to implicitly cast it according to context. However, it's not easy to see how this would work in EF Core, where you don't manually specify parameter types; the O/RM does it for you, according to the provider's type mappings. We could expose some API for the user to specify NpgsqlDbType.Unknown, but that would be similar to an
EF.Functions.Cast()which explicitly casts to an arbitrary datatype... In fact,EF.Functions.Cast()at least has the advantage of being somewhat portable - even if the actual string datatype specified is database-specific - whereas the NpgsqlDbType.Unknown API would be totally Npgsql-specific.I don't think there can be a better solution to this problem aside from the change you've already submitted, and hopefully also changes on the PostgreSQL side which would provide the proper overloads and yield the expected behavior out-of-the-box.
But I'm definitely open for suggestions if you have other ideas.
rwasef1830 commentedon May 6, 2018
@roji there's also matching the overload of string.contains that takes the ignorecase enum members.
roji commentedon May 7, 2018
@rwasef1830 I can't see any overload of
String.Contains()that accepts aStringComparisonenum, the docs page does show a sample extension method that implements this by callingIndexOf(), but the built-inContains()itself doesn't seem to have that overload.If you're referring to
String.IndexOf()translation, then yeah, you're right - that also needs to be fixed to properly support citext, as well as several other methods (EndsWith, probably Replace)...I've opened #388 to track this, do you want to give a hand with that?
takerukoushirou commentedon May 7, 2018
@roji You're welcome! I'll look into the other ideas once time allows.
Thanks for the description on how EF Core handles this internally. I saw while debugging that mappings are created solely from the CLR type & property configuration and are cached for further use, and if I remember correctly, these mappings then also hold the
NpgsqlDbType. How does EF Core invoke the provider to actually perform the query on the back-end? If the unparse is performed separately & is possibly/likely cached and the back-end invocation only receives the SQL string plus a set of parameters, any context-specific type change would be impossible.I agree that an
EF.Functions.Cast()if favourable to exposing an API to set aNpgsqlDbType; my thought was that this should happen transparently internally, whenever the provider could decide that in a certain situation PostgreSQL should select the proper parameter type itself such that a better matching overload can be chosen depending on the installed extensions.I came up with another idea though and also found a previous inconsistency (using the original example query): If a constant is used, the generated SQL directly contains the constant string without any explicit type. In this case, PostgreSQL would resolve the
citextoverload instead (prior to my PR, thus yielding different results for a constant string or a parameter with the same string value). If the parameter would be explicitly cast tounknown, PostgreSQL should then select the correct overload also for other types than justcitext, as long as the first argument (the object) is explicitly typed. The current solution should work well and stable forcitextthough.@rwasef1830 The overload is new and comes with .NET Core 2.1. So far it seems all string overloads that take a
StringComparisonargument are not covered (looking at the Sqlite and SqlServer providers). There is an open EF Core issue from 2014 on adding support for it though: dotnet/efcore#1222roji commentedon May 7, 2018
@takerukoushirou here are some clarifications.
You probably want to take a look at NpgsqlTypeMappingSource (and possibly its superclasses in EF Core) to understand exactly how the mechanism works. In a nutshell, whenever EF Core needs a type mapping, it calls the
FindMapping()method on that class, passing it aRelationalTypeMappingInfowhich contains all the info it has. The TypeMappingSource then returns a mapping, based on:I understand what you're proposing but it probably isn't as simple as it looks. The SQL translation process would have to make decisions on where to insert these casts in the expression tree, based on criteria which aren't easy to define (or code). You're definitely welcome to take a look at this, but I think it will end up far too complex for what we're trying to achieve here, especially when a simple explicit
EF.Functions.Cast()from the user provides an acceptable solution (although I do realize there's a cross-database portability issue).Regarding constants (or literals), the SQL generation is handled by each mapping's
GenerateNonNullSqlLiteral(). So when EF Core sees a literal/constant in a query, it looks up the mapping for that CLR type, then calls that method and embeds the string result in the query. It's true that string's literal mapping weakly type - there's no specific type. This was done for the basic/simple types (string, int...) in order to make the generated SQL lighter. As a side-effect it also allows the literal to be cast to any type necessary according to context, which is why comparison of a citext column to a string literal does actually work.Let me know if you need more info on the whole process.
Finally,
Oh sorry, I didn't realize that. We can quite easily add support for that overload then, and don't have to actually target .NET Core 2.1 - the translator can simply try to find the overload and translate appropriately. On pre-.NET Core 2.1 it would fail to find the method.
Fixes npgsql#384 via conditional argument cast to citext (npgsql#387)
roji commentedon Aug 24, 2019
Note: with the new type inference coming in EF Core 3.0, this will probably be fixed.