Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Npgsql.EntityFramework/NpgsqlProviderManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,45 @@ protected override XmlReader GetDbInformation(string informationType)
private const string PrecisionFacet = "Precision";
private const string FixedLengthFacet = "FixedLength";

internal static DbType GetDbType(PrimitiveTypeKind _primitiveType)
{
switch (_primitiveType)
{
case PrimitiveTypeKind.Binary:
return DbType.Binary;
case PrimitiveTypeKind.Boolean:
return DbType.Boolean;
case PrimitiveTypeKind.Byte:
return DbType.Byte;
case PrimitiveTypeKind.SByte:
return DbType.SByte;
case PrimitiveTypeKind.DateTime:
return DbType.DateTime;
case PrimitiveTypeKind.DateTimeOffset:
return DbType.DateTimeOffset;
case PrimitiveTypeKind.Decimal:
return DbType.Decimal;
case PrimitiveTypeKind.Double:
return DbType.Double;
case PrimitiveTypeKind.Int16:
return DbType.Int16;
case PrimitiveTypeKind.Int32:
return DbType.Int32;
case PrimitiveTypeKind.Int64:
return DbType.Int64;
case PrimitiveTypeKind.Single:
return DbType.Single;
case PrimitiveTypeKind.Time:
return DbType.Time;
case PrimitiveTypeKind.Guid:
return DbType.Guid;
case PrimitiveTypeKind.String:
return DbType.String;
default:
return DbType.Object;
}
}

public override TypeUsage GetEdmType(TypeUsage storeType)
{
if (storeType == null)
Expand Down
1 change: 1 addition & 0 deletions Npgsql.EntityFramework/NpgsqlServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ internal DbCommand CreateDbCommand(DbCommandTree commandTree)
{
DbParameter dbParameter = command.CreateParameter();
dbParameter.ParameterName = parameter.Key;
dbParameter.DbType = NpgsqlProviderManifest.GetDbType(((PrimitiveType)parameter.Value.EdmType).PrimitiveTypeKind);
command.Parameters.Add(dbParameter);
}

Expand Down
21 changes: 5 additions & 16 deletions Npgsql.EntityFramework/SqlGenerators/VisitedExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,12 @@ internal override void WriteSql(StringBuilder sqlText)
sqlText.Append(((bool)_value) ? "TRUE" : "FALSE");
break;
case PrimitiveTypeKind.Guid:
NpgsqlTypesHelper.TryGetNativeTypeInfo(NpgsqlProviderManifest.GetDbType(_primitiveType), out typeInfo);
sqlText.Append(BackendEncoding.UTF8Encoding.GetString(typeInfo.ConvertToBackend(_value, false)));
sqlText.Append("::uuid");
break;
case PrimitiveTypeKind.String:
NpgsqlTypesHelper.TryGetNativeTypeInfo(GetDbType(_primitiveType), out typeInfo);
NpgsqlTypesHelper.TryGetNativeTypeInfo(NpgsqlProviderManifest.GetDbType(_primitiveType), out typeInfo);
// Escape syntax is needed for strings with escape values.
// We don't check if there are escaped strings for performance reasons.
// Check https://github.com/franciscojunior/Npgsql2/pull/10 for more info.
Expand All @@ -169,21 +173,6 @@ internal override void WriteSql(StringBuilder sqlText)
}
base.WriteSql(sqlText);
}

private DbType GetDbType(PrimitiveTypeKind _primitiveType)
{
switch (_primitiveType)
{
case PrimitiveTypeKind.Boolean:
return DbType.Boolean;
case PrimitiveTypeKind.Guid:
return DbType.Guid;
case PrimitiveTypeKind.String:
return DbType.String;
default:
return DbType.Object;
}
}
}

internal class InsertExpression : VisitedExpression
Expand Down
104 changes: 65 additions & 39 deletions Npgsql/NpgsqlCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -423,32 +423,78 @@ void PrepareInternal()

_preparedCommandText = GetCommandText(true);
NpgsqlRowDescription returnRowDesc = null;
ParameterDescriptionResponse parameterDescription = null;


var numInputParameters = 0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This code should probably be Linqified, something along the lines of:

var parameterTypeOIDs = _parameters
    .Where(p => p.IsInputDirection)
    .Select(p => p.TypeInfo.NpgsqlDbType == NpgsqlDbType.Unknown ? 0 : _connector.OidToNameMapping[_parameters[i].TypeInfo.Name].OID)
    .ToArray()

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.

I'd like to, but if we strive for zero allocation that is not an option.

That example would make at least 7 allocations.
3 enumerator objects.
2 lambda function objects that contain captured variables.
ToArray doesn't know in advance how many elements to put in the array, so
it creates a buffer which size is doubled and copied on overflow and
finally copies all elements to a new destination array.
We also get function call overhead.
Den 21 okt 2014 10:41 skrev "Shay Rojansky" [email protected]:

In Npgsql/NpgsqlCommand.cs:

@@ -423,32 +423,78 @@ void PrepareInternal()

         _preparedCommandText = GetCommandText(true);
         NpgsqlRowDescription returnRowDesc = null;
  •        ParameterDescriptionResponse parameterDescription = null;
    
  •        var numInputParameters = 0;
    

This code should probably be Linqified, something along the lines of:

var parameterTypeOIDs = _parameters
.Where(p => p.IsInputDirection)
.Select(p => p.TypeInfo.NpgsqlDbType == NpgsqlDbType.Unknown ? 0 : _connector.OidToNameMapping[_parameters[i].TypeInfo.Name].OID)
.ToArray()

—
Reply to this email directly or view it on GitHub
https://github.com/npgsql/npgsql/pull/390/files#r19135562.

for (var i = 0; i < _parameters.Count; i++)
{
if (_parameters[i].IsInputDirection)
{
numInputParameters++;
}
}

var parameterTypeOIDs = new int[numInputParameters];

for (int i = 0, j = 0; i < _parameters.Count; i++)
{
if (_parameters[i].IsInputDirection)
{
parameterTypeOIDs[j++] = _parameters[i].TypeInfo.NpgsqlDbType == NpgsqlDbType.Unknown ? 0 : _connector.OidToNameMapping[_parameters[i].TypeInfo.Name].OID;
}
}

// Write Parse, Describe, and Sync messages to the wire.
_connector.SendParse(_planName, _preparedCommandText, new int[] { });
_connector.SendParse(_planName, _preparedCommandText, parameterTypeOIDs);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

By using the parameters collection to populate the parameterTypeOids in a 1-1 mapping, you can get a problem when the same parameter is used more than one time in the query string. For example, in the following query:

select * from table where column1= :param1 and column2= :param1

or, you also could invert the order of the parameters:

select * from table where column1= :param2 and column2= :param1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

When I thought about this problem, my idea was to populate this parameterTypeOIDs collection from the procedure which handled the parameters substitution because there you would know which parameters were being used in the query and its order.

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.

The order of appearance of the parameters in the query is not important. It is the order in the parameters collection that matters.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Excellent! I didn't notice that the parameter substitution logic already took care of the parameters mapping in the query string regardless of their position and/or repetition when preparing the command. Parameters in the prepared query are numbered in the same order as they appear in the parameters list! Sweet!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One more comment (maybe I'm confused). What happens if this is a function call and some parameters are OUT parameters? If we're only sending OIDs for input parameters can't the order get confused?

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.

Therefore the IsInputDirection check. In the parameter substitution logic, the number each input parameter get is the index of input parameter in the parameter collection. So it will be correct. This was not handled correctly before.

_connector.SendDescribeStatement(_planName);
_connector.SendSync();

// Tell to mediator what command is being sent.
_connector.Mediator.SetSqlSent(_preparedCommandText, NpgsqlMediator.SQLSentType.Parse);


// Look for ParameterDescriptionResponse, NpgsqlRowDescription in the responses, discarding everything else.
while (true)
{
var msg = _connector.ReadMessage();
if (msg is ReadyForQueryMsg) {
break;
}
var asParameterDescription = msg as ParameterDescriptionResponse;
if (asParameterDescription != null)
{
parameterDescription = asParameterDescription;
continue;
}
var asRowDesc = msg as NpgsqlRowDescription;
if (asRowDesc != null) {
if (asRowDesc != null)
{
returnRowDesc = asRowDesc;
continue;
}
var asDisposable = msg as IDisposable;
if (asDisposable != null) {
if (asDisposable != null)
{
asDisposable.Dispose();
}
}

if (parameterDescription != null)
{
if (parameterDescription.TypeOIDs.Length != numInputParameters)
{
throw new InvalidOperationException("Wrong number of parameters. Got " + numInputParameters + " but expected " + parameterDescription.TypeOIDs.Length + ".");
}

for (int i = 0, j = 0; j < numInputParameters; i++)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reuse array from above rather than reiterating?

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.

How do you mean?

{
if (_parameters[i].IsInputDirection)
{
_parameters[i].SetTypeOID(parameterDescription.TypeOIDs[j++], _connector.NativeToBackendTypeConverterOptions);
}
}
}

if (returnRowDesc != null)
{
_resultFormatCodes = new short[returnRowDesc.NumFields];
Expand Down Expand Up @@ -532,7 +578,7 @@ bool CheckFunctionNeedsColumnDefinitionList()
var seenDef = false;
foreach (NpgsqlParameter p in Parameters)
{
if ((p.Direction == ParameterDirection.Input) || (p.Direction == ParameterDirection.InputOutput))
if (p.IsInputDirection)
{
parameterTypes.Append(Connection.Connector.OidToNameMapping[p.TypeInfo.Name].OID.ToString() + " ");
}
Expand Down Expand Up @@ -717,10 +763,7 @@ void AppendParameterPlaceHolders(Stream dest)
{
var parameter = _parameters[i];

if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
if (parameter.IsInputDirection)
{
if (first)
{
Expand All @@ -738,22 +781,15 @@ void AppendParameterPlaceHolders(Stream dest)

void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber)
{
var parameterSize = "";

dest.WriteByte((byte)ASCIIBytes.ParenLeft);

if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
if (parameter.UseCast && parameter.Size > 0)
{
parameterSize = string.Format("({0})", parameter.Size);
}

if (parameter.UseCast)
{
dest.WriteString("${0}::{1}{2}", paramNumber, parameter.TypeInfo.CastName, parameterSize);
dest.WriteString("${0}::{1}", paramNumber, parameter.TypeInfo.GetCastName(parameter.Size));
}
else
{
dest.WriteString("${0}{1}", paramNumber, parameterSize);
dest.WriteString("$" + paramNumber);
}

dest.WriteByte((byte)ASCIIBytes.ParenRight);
Expand All @@ -767,10 +803,7 @@ void AppendParameterValues(Stream dest)
{
var parameter = _parameters[i];

if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
if (parameter.IsInputDirection)
{
if (first)
{
Expand Down Expand Up @@ -801,12 +834,7 @@ void AppendParameterValue(Stream dest, NpgsqlParameter parameter)

if (parameter.UseCast)
{
dest.WriteString("::{0}", parameter.TypeInfo.CastName);

if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
{
dest.WriteString("({0})", parameter.Size);
}
dest.WriteString("::{0}", parameter.TypeInfo.GetCastName(parameter.Size));
}

dest.WriteByte((byte)ASCIIBytes.ParenRight);
Expand Down Expand Up @@ -869,9 +897,12 @@ bool AppendCommandReplacingParameterValues(Stream dest, string src, bool prepare
{
paramOrdinalMap = new Dictionary<NpgsqlParameter, int>();

for (int i = 0; i < _parameters.Count; i++)
for (int i = 0, cnt = 0; i < _parameters.Count; i++)
{
paramOrdinalMap[_parameters[i]] = i + 1;
if (_parameters[i].IsInputDirection)
{
paramOrdinalMap[_parameters[i]] = ++cnt;
}
}
}

Expand Down Expand Up @@ -946,7 +977,7 @@ bool AppendCommandReplacingParameterValues(Stream dest, string src, bool prepare

if (_parameters.TryGetValue(paramName, out parameter))
{
if (parameter.Direction == ParameterDirection.Input || parameter.Direction == ParameterDirection.InputOutput)
if (parameter.IsInputDirection)
{
if (prepare)
{
Expand Down Expand Up @@ -1260,19 +1291,14 @@ byte[] GetExecuteCommandText()

byte[] serialization;

serialization = p.TypeInfo.ConvertToBackend(p.Value, false, Connector.NativeToBackendTypeConverterOptions);
serialization = p.TypeInfo.ConvertToBackend(p.NpgsqlValue, false, Connector.NativeToBackendTypeConverterOptions);

result.WriteBytes(serialization);
result.WriteByte((byte)ASCIIBytes.ParenRight);

if (p.UseCast)
{
result.WriteString(string.Format("::{0}", p.TypeInfo.CastName));

if (p.TypeInfo.UseSize && (p.Size > 0))
{
result.WriteString("({0})", p.Size);
}
result.WriteString(string.Format("::{0}", p.TypeInfo.GetCastName(p.Size)));
}
}

Expand Down
14 changes: 7 additions & 7 deletions Npgsql/NpgsqlCommandBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ private static void DoDeriveParameters(NpgsqlCommand command)

string[] names = null;
int[] types = null;
string[] modes = null;
char[] modes = null;

using (NpgsqlDataReader rdr = c.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
Expand All @@ -190,7 +190,7 @@ private static void DoDeriveParameters(NpgsqlCommand command)
if (!rdr.IsDBNull(2))
types = rdr.GetValue(2) as int[];
if (!rdr.IsDBNull(3))
modes = rdr.GetValue(3) as String[];
modes = rdr.GetValue(3) as char[];
}
if (types == null)
{
Expand Down Expand Up @@ -223,18 +223,18 @@ private static void DoDeriveParameters(NpgsqlCommand command)
{
switch (modes[i])
{
case "i":
case 'i':
param.Direction = ParameterDirection.Input;
break;
case "o":
case 'o':
param.Direction = ParameterDirection.Output;
break;
case "b":
case 'b':
param.Direction = ParameterDirection.InputOutput;
break;
case "v":
case 'v':
throw new NotImplementedException("Cannot derive function parameter of type VARIADIC");
case "t":
case 't':
throw new NotImplementedException("Cannot derive function parameter of type TABLE");
default:
throw new ArgumentOutOfRangeException("proargmode", modes[i],
Expand Down
Loading