Skip to content

Commit

Permalink
Update SQL Server type mappings for strings
Browse files Browse the repository at this point in the history
Fixes #19327

Create fixed-length type mappings by default, and then use the correct DbType in the parameter if the length of the value matches the parameter length. This has a better chance of hitting an index. In other cases, change the DbType to match what we did before so that SQLClient doesn't truncate or pad.

Fixes #14555

If the parameter value length is greater than the max length but less than the max bounded length, then using the max bounded length rather than going immediately to unbounded.
  • Loading branch information
ajcvickers committed Dec 30, 2019
1 parent 498a452 commit 04c8a58
Show file tree
Hide file tree
Showing 9 changed files with 129 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,6 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p
/// </summary>
protected override void ConfigureParameter(DbParameter parameter)
{
// For strings and byte arrays, set the max length to the size facet if specified, or
// 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
// fragmentation by setting lots of different Size values otherwise always set to
// -1 (unbounded) to avoid SQL client size inference.

var value = parameter.Value;
var length = (value as byte[])?.Length;
var maxSpecificSize = CalculateSize(Size);
Expand All @@ -96,9 +91,29 @@ protected override void ConfigureParameter(DbParameter parameter)
sqlParameter.SqlDbType = _sqlDbType.Value;
}

parameter.Size = value == null || value == DBNull.Value || length != null && length <= maxSpecificSize
? maxSpecificSize
: -1;
if (value == null
|| value == DBNull.Value)
{
parameter.Size = maxSpecificSize;
}
else
{
if (length != null
&& length <= maxSpecificSize)
{
// Fixed-sized parameters get exact length to avoid padding/truncation.
parameter.Size = IsFixedLength ? length.Value : maxSpecificSize;
}
else if (length != null
&& length <= MaxSize)
{
parameter.Size = IsFixedLength ? length.Value : MaxSize;
}
else
{
parameter.Size = -1;
}
}
}

/// <summary>
Expand Down
75 changes: 55 additions & 20 deletions src/EFCore.SqlServer/Storage/Internal/SqlServerStringTypeMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class SqlServerStringTypeMapping : StringTypeMapping

private readonly SqlDbType? _sqlDbType;
private readonly int _maxSpecificSize;
private readonly int _maxSize;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand Down Expand Up @@ -57,8 +58,12 @@ private static string GetStoreName(bool unicode, bool fixedLength) => unicode
: "varchar";

private static DbType? GetDbType(bool unicode, bool fixedLength) => unicode
? (fixedLength ? System.Data.DbType.String : (DbType?)null)
: System.Data.DbType.AnsiString;
? (fixedLength
? System.Data.DbType.StringFixedLength
: (DbType?)null)
: (fixedLength
? System.Data.DbType.AnsiStringFixedLength
: System.Data.DbType.AnsiString);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand All @@ -69,19 +74,20 @@ private static string GetStoreName(bool unicode, bool fixedLength) => unicode
protected SqlServerStringTypeMapping(RelationalTypeMappingParameters parameters, SqlDbType? sqlDbType)
: base(parameters)
{
_maxSpecificSize = CalculateSize(parameters.Unicode, parameters.Size);
if (parameters.Unicode)
{
_maxSpecificSize = parameters.Size.HasValue && parameters.Size <= UnicodeMax ? parameters.Size.Value : UnicodeMax;
_maxSize = UnicodeMax;
}
else
{
_maxSpecificSize = parameters.Size.HasValue && parameters.Size <= AnsiMax ? parameters.Size.Value : AnsiMax;
_maxSize = AnsiMax;
}

_sqlDbType = sqlDbType;
}

private static int CalculateSize(bool unicode, int? size)
=> unicode
? size.HasValue && size <= UnicodeMax
? size.Value
: UnicodeMax
: size.HasValue && size <= AnsiMax
? size.Value
: AnsiMax;

/// <summary>
/// Creates a copy of this mapping.
/// </summary>
Expand All @@ -98,11 +104,6 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p
/// </summary>
protected override void ConfigureParameter(DbParameter parameter)
{
// For strings and byte arrays, set the max length to the size facet if specified, or
// 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
// fragmentation by setting lots of different Size values otherwise always set to
// -1 (unbounded) to avoid SQL client size inference.

var value = parameter.Value;
var length = (value as string)?.Length;

Expand All @@ -112,9 +113,43 @@ protected override void ConfigureParameter(DbParameter parameter)
sqlParameter.SqlDbType = _sqlDbType.Value;
}

parameter.Size = value == null || value == DBNull.Value || length != null && length <= _maxSpecificSize
? _maxSpecificSize
: -1;
if ((value == null
|| value == DBNull.Value)
|| (IsFixedLength
&& length == _maxSpecificSize
&& Size.HasValue))
{
// A fixed-length parameter where the value matches the length can remain a fixed-length parameter
// because SQLClient will not do any padding or truncating.
parameter.Size = _maxSpecificSize;
}
else
{
if (IsFixedLength)
{
// Force the parameter type to be not fixed length to avoid SQLClient truncation and padding.
parameter.DbType = IsUnicode ? System.Data.DbType.String : System.Data.DbType.AnsiString;
}

// For strings and byte arrays, set the max length to the size facet if specified, or
// 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
// fragmentation by setting lots of different Size values otherwise set to the max bounded length
// if the value will fit, otherwise set to -1 (unbounded) to avoid SQL client size inference.
if (length != null
&& length <= _maxSpecificSize)
{
parameter.Size = _maxSpecificSize;
}
else if (length != null
&& length <= _maxSize)
{
parameter.Size = _maxSize;
}
else
{
parameter.Size = -1;
}
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1180,14 +1180,14 @@ public virtual void Can_insert_and_read_back_all_mapped_sized_data_types()
@p7='F' (Size = 3)
@p8='D' (Size = 3)
@p9='A' (Size = 3) (DbType = AnsiString)
@p10='Wor' (Size = 3) (DbType = AnsiString)
@p10='Wor' (Size = 3) (DbType = AnsiStringFixedLength)
@p11='Thr' (Size = 3) (DbType = AnsiString)
@p12='Lon' (Size = 3) (DbType = AnsiString)
@p12='Lon' (Size = 3) (DbType = AnsiStringFixedLength)
@p13='Let' (Size = 3) (DbType = AnsiString)
@p14='The' (Size = 3)
@p15='Squ' (Size = 3)
@p15='Squ' (Size = 3) (DbType = StringFixedLength)
@p16='Col' (Size = 3)
@p17='Won' (Size = 3)
@p17='Won' (Size = 3) (DbType = StringFixedLength)
@p18='Int' (Size = 3)
@p19='Tha' (Size = 3) (DbType = AnsiString)",
parameters,
Expand Down Expand Up @@ -1270,14 +1270,14 @@ public virtual void Can_insert_and_read_back_nulls_for_all_mapped_sized_data_typ
@p7=NULL (Size = 3)
@p8=NULL (Size = 3)
@p9=NULL (Size = 3) (DbType = AnsiString)
@p10=NULL (Size = 3) (DbType = AnsiString)
@p10=NULL (Size = 3) (DbType = AnsiStringFixedLength)
@p11=NULL (Size = 3) (DbType = AnsiString)
@p12=NULL (Size = 3) (DbType = AnsiString)
@p12=NULL (Size = 3) (DbType = AnsiStringFixedLength)
@p13=NULL (Size = 3) (DbType = AnsiString)
@p14=NULL (Size = 3)
@p15=NULL (Size = 3)
@p15=NULL (Size = 3) (DbType = StringFixedLength)
@p16=NULL (Size = 3)
@p17=NULL (Size = 3)
@p17=NULL (Size = 3) (DbType = StringFixedLength)
@p18=NULL (Size = 3)
@p19=NULL (Size = 3) (DbType = AnsiString)",
parameters,
Expand Down Expand Up @@ -1940,14 +1940,14 @@ public virtual void Can_insert_and_read_back_all_mapped_sized_data_types_with_id
@p7='D' (Size = 3)
@p8='A' (Size = 3) (DbType = AnsiString)
@p9='77'
@p10='Wor' (Size = 3) (DbType = AnsiString)
@p10='Wor' (Size = 3) (DbType = AnsiStringFixedLength)
@p11='Thr' (Size = 3) (DbType = AnsiString)
@p12='Lon' (Size = 3) (DbType = AnsiString)
@p12='Lon' (Size = 3) (DbType = AnsiStringFixedLength)
@p13='Let' (Size = 3) (DbType = AnsiString)
@p14='The' (Size = 3)
@p15='Squ' (Size = 3)
@p15='Squ' (Size = 3) (DbType = StringFixedLength)
@p16='Col' (Size = 3)
@p17='Won' (Size = 3)
@p17='Won' (Size = 3) (DbType = StringFixedLength)
@p18='Int' (Size = 3)
@p19='Tha' (Size = 3) (DbType = AnsiString)",
parameters,
Expand Down Expand Up @@ -2030,14 +2030,14 @@ public virtual void Can_insert_and_read_back_nulls_for_all_mapped_sized_data_typ
@p7=NULL (Size = 3)
@p8=NULL (Size = 3) (DbType = AnsiString)
@p9='78'
@p10=NULL (Size = 3) (DbType = AnsiString)
@p10=NULL (Size = 3) (DbType = AnsiStringFixedLength)
@p11=NULL (Size = 3) (DbType = AnsiString)
@p12=NULL (Size = 3) (DbType = AnsiString)
@p12=NULL (Size = 3) (DbType = AnsiStringFixedLength)
@p13=NULL (Size = 3) (DbType = AnsiString)
@p14=NULL (Size = 3)
@p15=NULL (Size = 3)
@p15=NULL (Size = 3) (DbType = StringFixedLength)
@p16=NULL (Size = 3)
@p17=NULL (Size = 3)
@p17=NULL (Size = 3) (DbType = StringFixedLength)
@p18=NULL (Size = 3)
@p19=NULL (Size = 3) (DbType = AnsiString)",
parameters,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ SELECT [UniqueNo]
FROM [Sample]
WHERE @@ROWCOUNT = 1 AND [UniqueNo] = scope_identity();",
//
@"@p0='VeryVeryVeryVeryVeryVeryLongString' (Size = -1)
@"@p0='VeryVeryVeryVeryVeryVeryLongString' (Size = 4000)
@p1='ValidString' (Nullable = false) (Size = 4000)
@p2='00000000-0000-0000-0000-000000000002'
@p3='Third Additional Name' (Size = 4000)
Expand Down Expand Up @@ -324,7 +324,7 @@ INSERT INTO [Two] ([Data])
FROM [Two]
WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();",
//
@"@p0='ValidButLongString' (Size = -1)
@"@p0='ValidButLongString' (Size = 4000)
SET NOCOUNT ON;
INSERT INTO [Two] ([Data])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ public override void Query_with_single_parameter()
base.Query_with_single_parameter();

AssertSql(
@"@__customerID='ALFKI' (Size = 5)
@"@__customerID='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
//
@"@__customerID='ANATR' (Size = 5)
@"@__customerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand All @@ -84,13 +84,13 @@ public override void First_query_with_single_parameter()
base.First_query_with_single_parameter();

AssertSql(
@"@__customerID='ALFKI' (Size = 5)
@"@__customerID='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
//
@"@__customerID='ANATR' (Size = 5)
@"@__customerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand All @@ -102,13 +102,13 @@ public override void Query_with_two_parameters()
base.Query_with_two_parameters();

AssertSql(
@"@__customerID='ALFKI' (Size = 5)
@"@__customerID='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
//
@"@__customerID='ANATR' (Size = 5)
@"@__customerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand All @@ -120,13 +120,13 @@ public override void Query_with_three_parameters()
base.Query_with_three_parameters();

AssertSql(
@"@__customerID='ALFKI' (Size = 5)
@"@__customerID='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
//
@"@__customerID='ANATR' (Size = 5)
@"@__customerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand Down Expand Up @@ -166,7 +166,7 @@ public override void Compiled_query_when_does_not_end_in_query_operator()
base.Compiled_query_when_does_not_end_in_query_operator();

AssertSql(
@"@__customerID='ALFKI' (Size = 5)
@"@__customerID='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT COUNT(*)
FROM [Customers] AS [c]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public override async Task Local_dictionary(bool async)
await base.Local_dictionary(async);

AssertSql(
@"@__p_0='ALFKI' (Size = 5)
@"@__p_0='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT TOP(2) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand All @@ -158,7 +158,7 @@ public override async Task Entity_equality_local(bool async)
await base.Entity_equality_local(async);

AssertSql(
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5)
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID]
FROM [Customers] AS [c]
Expand All @@ -183,7 +183,7 @@ public override async Task Entity_equality_local_double_check(bool async)
await base.Entity_equality_local_double_check(async);

AssertSql(
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5)
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID]
FROM [Customers] AS [c]
Expand All @@ -195,7 +195,7 @@ public override async Task Join_with_entity_equality_local_on_both_sources(bool
await base.Join_with_entity_equality_local_on_both_sources(async);

AssertSql(
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5)
@"@__entity_equality_local_0_CustomerID='ANATR' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID]
FROM [Customers] AS [c]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public override void Find()

AssertSql(
@"@__ef_filter__TenantPrefix_0='B' (Size = 4000)
@__p_0='ALFKI' (Size = 5)
@__p_0='ALFKI' (Size = 5) (DbType = StringFixedLength)
SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand Down Expand Up @@ -261,14 +261,14 @@ public override void Compiled_query()

AssertSql(
@"@__ef_filter__TenantPrefix_0='B' (Size = 4000)
@__customerID='BERGS' (Size = 5)
@__customerID='BERGS' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE ((@__ef_filter__TenantPrefix_0 = N'') OR ([c].[CompanyName] IS NOT NULL AND (LEFT([c].[CompanyName], LEN(@__ef_filter__TenantPrefix_0)) = @__ef_filter__TenantPrefix_0))) AND ([c].[CustomerID] = @__customerID)",
//
@"@__ef_filter__TenantPrefix_0='B' (Size = 4000)
@__customerID='BLAUS' (Size = 5)
@__customerID='BLAUS' (Size = 5) (DbType = StringFixedLength)
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
Expand Down
Loading

0 comments on commit 04c8a58

Please sign in to comment.