Skip to content

WIP - Separate Type Mappings for each type (DO NOT MERGE) - #8612

Closed
lajones wants to merge 5 commits into
devfrom
170526_7434_SeparateTypeMappings_02
Closed

lajones wants to merge 5 commits into
devfrom
170526_7434_SeparateTypeMappings_02

Conversation

@lajones

@lajones lajones commented May 26, 2017

Copy link
Copy Markdown
Contributor

Note: this is just work in progress - there are still lots of commented out lines, classes that should be deleted, tests which haven't been updated... The purpose of this is just to get feedback on the approach so far - its benefits and costs.

I've been working on removing the double-dispatch that we currently use in RelationalTypeMapping when generating literals, in favor of one where each CLR-type has its own kind of XyzTypeMapping class - which knows how to map between CLR type, store type and DbType and knows how to generate SQL (and later C#) literals of its own type. This is in contrast to the existing setup where any TypeMapping class knows how to generate literals for any value that is passed to it regardless of whether the type of the value is a match to that originally intended when the TypeMapping was created.

The good things:

This nicely separates out concerns: e.g. IntTypeMapping now knows how to deal with int's and does not have to carry around the baggage of knowing what to do with e.g. strings. If you have to change how mappings/generation of literals are handled for a given provider then you just inherit from the appropriate TypeMapping and specify your own special behavior. This makes each class much cleaner and smaller.

It's arguable, but I also think this also sets us up better/more cleanly to support completely new type mappings in the future.

Things that need work:

I got the Sqlite.Tests and SqlServer.Tests test projects to work using this new approach. But the functional tests still have ~20 failures. They all seem to be related to the query pipeline specifically DefaultQuerySqlGenerator and its subclasses.

DefaultQuerySqlGenerator contains a _typeMapping. It uses this to store off the "ambient" type mapping it is using. Then there is the GetTypeMapping() method below:

        private RelationalTypeMapping GetTypeMapping(object value)
            => _typeMapping ?? Dependencies.RelationalTypeMapper.GetMappingForValue(value);

This is used in numerous places and, as you see above, will return the "ambient" TypeMapping if one exists rather than a new type mapping based on the value. This often happens when interpreting a ConstantExpression e.g. the 1 in TOP(1) or when interpreting the arguments of SomeFunction(SomeArgs).

@maumar, @smitpatel and I talked and we tried to work around this by entries you'll see in e.g. DefaultQuerySqlGenerator where I've put code like this:

                var existingTypeMapping = _typeMapping;
                _typeMapping = null;
                // do whatever needs doing - now will get TypeMapping from value, not from _typeMapping
                _typeMapping = existingTypeMapping;

The problem is that sometimes you need the ambient type mapping rather than what you might generate from the value by itself. E.g. when trying to produce SQL that looks like this:

WHERE [SomeNonUnicodeColumn] IN ('These', 'Values', 'Must', 'Be', 'Non-Unicode', 'Strings')

(by default if you ask for the SQL store type for a string you get a unicode string which has N'Values');

Whereas sometimes it's important that they not be the "ambient" TypeMapping. E.g. in

SUBSTRING('expression', start, length)

even if the 'expression' results in an ambient TypeMapping of SqlServerStringTypeMapping it's important (in the new setup) that start and length use an integer type mapping, e.g. LongTypeMapping. (This works in the existing setup because you'd would have e.g. an ambient SqlServerMaxLengthMapping which didn't care when you passed it integer values - the double-dispatch would output the correct SQL literal anyway.)

I've not managed to solve this problem yet - I don't think it's insuperable, but it might mean more changes to the query pipeline code than I anticipated when I started this.

So do we want to continue to pursue this, or do we decide that double-dispatch is acceptable (perhaps even preferable?) to help with scenarios like the above?

@lajones
lajones requested review from ajcvickers and maumar and removed request for maumar May 26, 2017 18:05
@lajones lajones self-assigned this May 26, 2017
/// <param name="storeType"> The name of the database type. </param>
/// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
/// <returns> The newly created mapping. </returns>
public override RelationalTypeMapping CreateCopyT([NotNull] string storeType, int? size)

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.

CreateCopyT?

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.

Also can we name this something different?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Don't get bogged down in the names of things - they'll probably change anyway. This particular one is just a hold-over from my editing - there will end up being just one CreateCopy() method - though I'm disappointed I have to repeat it everywhere.

IsUnicode,
size,
HasNonDefaultUnicode,
hasNonDefaultSize: size != Size);

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.

Is this correct?
What if you create a nondefault size ByteMapping and then call CreateCopy on that with same size?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is how the code works right now. I agree it's not very robust - but the copies are only ever made from the default-sized version - so it works, but as I say not very robust.

private IReadOnlyDictionary<string, object> _parametersValues;
private ParameterNameGenerator _parameterNameGenerator;
private RelationalTypeMapping _typeMapping;
protected RelationalTypeMapping _typeMapping;

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.

Why this became protected?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because the SQLServerQuerySqlGenerator needed to do:

                var existingTypeMapping = _typeMapping;
                _typeMapping = null;
                // do whatever needs doing - now will get TypeMapping from value, not from _typeMapping
                _typeMapping = existingTypeMapping;

@ajcvickers

Copy link
Copy Markdown
Contributor

@lajones So I think the "ambient" type mapping is there to make sure that we correlate type mappings with metadata from our model for things like string comparisons. For example, if we have a string literal being compared to a non-unicode string property, then we want to make sure that the literal is created as non-unicode. Otherwise the query may not be sargable. Therefore, I think we want to use the ambient mapping whenever we can. However:

  • We may want to file an issue to do this correlation more robustly
  • For now, can we check if the CLR type matches the CLR type in the ambient mapping. If it does, use the mapping. If it doesn't, request a mapping and use that instead.,

}

return GenerateSqlLiteralValue((dynamic)value);
return "Unknown type " + value.GetType() +

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 just be something like string.Format(CultureInfo.InvariantCulture, "{0}", value);? If not, should throw an exception? Or be an abstract method maybe using the template method pattern?

@lajones lajones May 26, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We can talk about what should be there finally. But that's just there right now as an error-catcher while I was updating the code - anything except null should have been handled by the parent class - or we are trying to use the wrong value on the wrong TypeMapping - which is a situation I want to spot.

public override string GenerateSqlLiteral([CanBeNull]object value)
{
return value != null
? ((long)value).ToString(CultureInfo.InvariantCulture)

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.

Splitting this into a method that external code calls and a template method that can be overridden could be a way to handle the null check in a single place.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not following - could you explain? null is a valid value to be passed to all the methods - but I wanted to have only 1 place that actually returned "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.

Something like this:

public virtual string GenerateSqlLiteral([CanBeNull]object value) 
    => value == null ? "NULL" : GenerateNonNullSqlLiteral(value);

protected virtual string GenerateNonNullSqlLiteral([NotNull] object value)
{
    Check.NotNull(value, nameof(value));

    return string.Format(CultureInfo.InvariantCulture, "{0}", value);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

OK. That makes sense.

/// </summary>
public class SqliteDateTimeOffsetTypeMapping : DateTimeOffsetTypeMapping
{
private const string DateTimeOffsetFormatConst = @"yyyy\-MM\-dd HH\:mm\:ss.FFFFFFFzzz";

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.

@"yyyy-MM-dd HH:mm:ss.FFFFFFFzzz" [](start = 56, length = 38)

Could this be factored to not need another class, but to allow the format string to be passed to the base class, or overridden in a template method?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That is already done. Unfortunately the string (and not just the format of the DateTimeOffset) that is output is different too. That could be changed so that the whole string is the format and then what you say would work (the way above is the way we currently do it).

{ typeof(sbyte), new IntTypeMapping(_integerTypeName) },
{ typeof(short), new ShortTypeMapping(_integerTypeName) },
{ typeof(uint), new LongTypeMapping(_integerTypeName) },
{ typeof(ulong), new LongTypeMapping(_integerTypeName) }, //LAJLAJ - ulong does not fit in long??

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.

{ typeof(ulong), new LongTypeMapping(_integerTypeName) } [](start = 20, length = 56)

ULongTypeMapping?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes. I was trying to avoid having another full set for TypeMappings for the ulong|uint... set of types but they might be necessary. This was also just a note to myself to investigate if setting up a ulong property on Sqlite fails right now.


private readonly SqlServerMaxLengthMapping _nvarchar450
= new SqlServerMaxLengthMapping("nvarchar(450)", typeof(string), dbType: null, unicode: true, size: 450);
private readonly SqlServerStringTypeMapping _nvarchar450 //LAJLAJ - shouldn't dbType be DbType.String?

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.

//LAJLAJ - shouldn't dbType be DbType.String? [](start = 64, length = 46)

Nope. Things will break if the DbType is set explicitly. We went though a process to get to figure out which DbType values to use, and when to not use them at all. We might have got some wrong, but we shouldn't change this without being sure the change it correct.

@lajones lajones May 26, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

OK. I'll bear that in mind. Though that is putting functionality on the DbType getter that was not immediately apparent when editing it / to providers who provide their own TypeMappings.

I would like to know why the Guid one wasn't set though - that seems like it would only ever map to DbType.Guid?

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.

Probably because, for SQL Server, we found the most pragmatic approach to be not setting the DbType unless it was needed.

Can we factor it in a way that the DbType is not assumed? That is, regardless of what CLR type the mapping is for, the DbType is always passed in the constructor? I know this seems wrong, but the way DbTypes is used is very provider-specific, so in reality we can't really assume a DbType just because we know the CLR type.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

OK. I can make the DbType not have a default value in all of the constructors.

Note: as well as the usage of what's really a mapping DbType -> store type mentioned in #8609, DbType is used when creating DbParameter - some of that is shared between providers in RelationalTypeMapping.CreateParameter() so it would be nice to add a comment to the DbType getter along the lines of "a null value implies xyz..." so that anyone so sets it to null knows what others will assume about it.

@p3: 00000001-0000-0000-0000-000000000001 (DbType = String)
@p1: 00000000-0000-0000-0003-000000000001
@p3: 00000001-0000-0000-0000-000000000001

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 shouldn't be seeing any changes in these tests--we should fix the root cause of the DbType being different here.

@lajones lajones May 26, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is the ambient _typeMapper issue. As you see the value being passed was a Guid but the TypeMapping that was generating it had a DbType set to String. This only worked because string TypeMappings knew how to generate Guid literals. That will no longer be the case with the new setup. It's clearer in the other test where the value being passed is 1 but it is nevertheless being treated as a string.

@lajones

lajones commented May 26, 2017

Copy link
Copy Markdown
Contributor Author

@ajcvickers All the comments so far are about how to improve what's here. Please note I would also like a general comment on whether to pursue this approach at all or whether to stick with the existing double-dispatch approach given the downsides we encounter in DefaultQuerySqlGenerator. Personally I kind of like the new approach, but it may take some work to get DefaultQuerySqlGenerator to use it properly.

@ajcvickers

Copy link
Copy Markdown
Contributor

I'm happy with this approach.

@lajones

lajones commented May 28, 2017

Copy link
Copy Markdown
Contributor Author

@ajcvickers

For now, can we check if the CLR type matches the CLR type in the ambient mapping. If it does, use the mapping. If it doesn't, request a mapping and use that instead.,

This is working well. Good suggestion 👍

@lajones

lajones commented May 29, 2017

Copy link
Copy Markdown
Contributor Author

This has been replaced by PR #8631 - see there for further comments.

@lajones lajones closed this May 29, 2017
@lajones
lajones deleted the 170526_7434_SeparateTypeMappings_02 branch June 1, 2017 20:20
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.

5 participants