Skip to content

Decide what to do with ParameterDirection.ReturnValue #5793

Closed

Description

@Youlounn

Before submitting

We recently migrated our application from Npgsql version 6.0.6 to 8.0.3 and encountered an issue with the ResolveTypeInfo method when using Dapper. Our codebase uses a mix of standard ADO.NET classes and Dapper for database interactions. We have observed that the issue specifically arises when executing stored procedures with Dapper.

Steps to reproduce

Here is the code for the test method using Dapper which encounters the issue:

    [TestMethod]
    public void StoredProcedureWithDapper()
    {
        using (DbConnection conn = System.Data.Common.DbProviderFactories.GetFactory("Npgsql").CreateConnection())
        {
            conn.ConnectionString = "Host=x.x.x.x;Port=5432;Database=db_name;PWD=xxx;UID=username";
            conn.Open();

            // Ensure the types are resolved before using Dapper
            ResolveNpgsqlTypeInfo(conn);

            DynamicParameters parameters = new DynamicParameters();

            parameters.Add("result", dbType: DbType.Boolean, direction: ParameterDirection.ReturnValue);
            parameters.Add("param1", "value1", DbType.String);
            parameters.Add("param2", "value2", DbType.String);

            IEnumerable<bool> results = SqlMapper.Query<bool>(
                cnn: conn, 
                sql: "npgsql803_function_returns_bool", 
                parameters, 
                transaction: null, 
                buffered: true, 
                commandTimeout: null, 
                commandType: CommandType.StoredProcedure);

            bool result = results.Count() > 0 ? results.First() : parameters.Get<bool>("result");
        }
    }

    private void ResolveNpgsqlTypeInfo(DbConnection conn)
    {
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT 1"; // Dummy query to trigger type resolution
            cmd.ExecuteNonQuery();
        }
    }

The issue

An exception is raised during the call of SqlMapper.Query function.

Exception message: System.InvalidOperationException: Missing type info, ResolveTypeInfo needs to be called before Bind
Stack trace:
    Npgsql.ThrowHelper.ThrowInvalidOperationException(string) in ThrowHelper.cs
    Npgsql.NpgsqlParameter.Bind(out Npgsql.Internal.DataFormat, out Npgsql.Internal.Size, Npgsql.Internal.DataFormat?) in NpgsqlParameter.cs
    Npgsql.Internal.NpgsqlConnector.WriteBind(System.Collections.Generic.List<Npgsql.NpgsqlParameter>, string, byte[], bool, bool[], bool, System.Threading.CancellationToken) in NpgsqlConnector.FrontendMessages.cs
    Npgsql.NpgsqlCommand.Write.__WriteExecute|100_0(Npgsql.Internal.NpgsqlConnector, bool, bool, System.Threading.CancellationToken) in NpgsqlCommand.cs
    Npgsql.NpgsqlCommand.ExecuteReader(bool, System.Data.CommandBehavior, System.Threading.CancellationToken) in NpgsqlCommand.cs
    Npgsql.NpgsqlCommand.ExecuteReader(bool, System.Data.CommandBehavior, System.Threading.CancellationToken) in NpgsqlCommand.cs
    Npgsql.NpgsqlCommand.ExecuteReader(System.Data.CommandBehavior) in NpgsqlCommand.cs
    Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(System.Data.IDbCommand, bool, System.Data.CommandBehavior) in SqlMapper.cs
    Dapper.SqlMapper.QueryImpl<T>(System.Data.IDbConnection, Dapper.CommandDefinition, System.Type) in SqlMapper.cs
    System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>) in Enumerable.cs

Attempts to Resolve

  1. We tried manually resolving type info by executing a dummy query (SELECT 1) before the actual Dapper call, but it didn't resolve the issue.
  2. Ensuring that all necessary types are mapped globally using NpgsqlConnection.GlobalTypeMapper.

Further technical details

Npgsql version: 8.0.3
PostgreSQL version: 14
Operating system: Windows Server 2019

Other details about my project setup:
Dapper.StrongName version: 2.0.0.0
.NET version: .NET Framework 4.7.2

We would appreciate any guidance or solutions on how to handle this issue. Are there any specific changes or configurations required for Npgsql 8.0.3 when used in conjunction with Dapper to avoid this error?
Thank you for your help and support.
Best regards

Activity

  1. Alexandre-Schwarze commented on Jul 30, 2024

    @Alexandre-Schwarze

    We've encountered the same ResolveTypeInfo error both with and without using Dapper. Our investigation shows that this issue specifically arises when there is a return value parameter in the stored procedure call.

    As demonstrated in the Npgsql source code, specifically in the NpgsqlParameterCollection.cs file, when a parameter has a ParameterDirection.ReturnValue, the loop exits before calling ResolveTypeInfo. This suggests that the handling of return value parameters is contributing to the issue.

    Here is the relevant code snippet from NpgsqlParameterCollection.cs in ProcessParameters function :

    switch (p.Direction)
    {
        case ParameterDirection.Input:
            break;
    
        case ParameterDirection.InputOutput:
            if (PlaceholderType.Positional && commandType != CommandType.StoredProcedure)
                ThrowHelper.ThrowNotSupportedException("Output parameters are not supported in positional mode (unless used with CommandType.StoredProcedure)");
            HasOutputParameters = true;
            break;
    
        case ParameterDirection.Output:
            if (PlaceholderType.Positional && commandType != CommandType.StoredProcedure)
                ThrowHelper.ThrowNotSupportedException("Output parameters are not supported in positional mode (unless used with CommandType.StoredProcedure)");
            HasOutputParameters = true;
            continue;
    
        case ParameterDirection.ReturnValue:
            // Simply ignored
            continue;
    
        default:
            ThrowHelper.ThrowArgumentOutOfRangeException(nameof(ParameterDirection), $"Unhandled {nameof(ParameterDirection)} value: {p.Direction}");
            break;
    }
    
    p.ResolveTypeInfo(options);
    if (validateValues)
    {
        p.Bind(out _, out _);
    }
    

    As you can see, in the case of ParameterDirection.ReturnValue, the loop continues without calling ResolveTypeInfo. This oversight appears to be the root cause of the issue.

    We hope this additional detail helps to identify and resolve the problem.

  2. self-assigned this
    on Jul 31, 2024
  3. added this to the 8.0.4 milestone on Jul 31, 2024
  4. vonzshik commented on Jul 31, 2024

    @vonzshik
    Contributor

    The problem isn't because of that switch but because while before we've never sent params with ParameterDirection.ReturnValue, we do that now.

    But anyway, any particular reason to even use ParameterDirection.ReturnValue? AFAIK it has been ignored in npgsql 6.0 and probably even before that.

  5. Alexandre-Schwarze commented on Jul 31, 2024

    @Alexandre-Schwarze

    Thank you for flagging our issue as a bug. We use stored procedure parameters of type ReturnValue because our PostgreSQL instance has several functions and procedures that return values, such as booleans for procedures like CAN_DELETE_ENTITIES etc ... These return values are integral to our application logic. We have been using ReturnValue parameters since version 6.0.6 without encountering these errors. We have not tested other versions between 6.0.6 and 8.0.3.
    Do you have an estimation of when the 8.0.4 would be released ?

    Thank you for your attention

  6. vonzshik commented on Jul 31, 2024

    @vonzshik
    Contributor

    We use stored procedure parameters of type ReturnValue because our PostgreSQL instance has several functions and procedures that return values, such as booleans for procedures like CAN_DELETE_ENTITIES etc ... These return values are integral to our application logic.

    I would like to reiterate that ReturnValue doesn't do anything and was completely ignored in npgsql 6.0. It was never set, any values returned by functions/procedures you can only get either via ExecuteScalar or ExecuteReader. You can pretty much get rid of it without any sort of issue.

    Do you have an estimation of when the 8.0.4 would be released ?

    Probably in around a month. But again, you can just remove ReturnValue altogether since it doesn't do anything anyway.

  7. Alexandre-Schwarze commented on Aug 1, 2024

    @Alexandre-Schwarze

    Thank you for flagging our issue as a bug. I forgot to mention that our code needs to be compatible with both PostgreSQL and Oracle. We centrally manage stored procedure calls, and Oracle requires parameters of type ReturnValue. For example:

    public bool ExecuteBooleanStoredFunction(string functionName, long requestId)
    {
        using (DbConnection ebrConnection = CreateConnection())
        {
            var p = new Dapper.DynamicParameters();
            p.Add("result", dbType: DbType.Boolean, direction: ParameterDirection.ReturnValue);
            p.Add("inRequestId", requestId);
    
            IEnumerable<bool> result = ebrConnection.Query<bool>(functionName, p, commandType: CommandType.StoredProcedure);
    
            if (result.Any())
                return result.First();
            else
                return p.Get<bool>("result");
        }
    }
    

    We have been using ReturnValue parameters since version 6.0.6 without encountering such errors. We haven't tested other versions between 6.0.6 and 8.0.3.

    That's why we need to avoid such ResolveTypeInfo error.

    Thank you for your understanding.

  8. removed their assignment
    on Sep 4, 2024
  9. modified the milestones: 8.0.4, Backlog on Sep 4, 2024
  10. roji commented on Sep 4, 2024

    @roji
    Member

    After some internal discussion, we're not quite sure we should be simply reimplementing the 6.0 behavior, which was to completely ignore ReturnValue. As written above, PG simply doesn't have the concept of ReturnValue; while we understand the desire to use the same code across Oracle and PostgreSQL, it seems like a bug for Npgsql to silently not populate the parameter with anything - which presumably most reasonable usages would expect.

    So we'd like to see other users requesting this, and especially how they intend to actually use that ReturnValue parameter... Based on that we can better decide what to do.

  11. changed the title [-]Issues with ResolveTypeInfo in Npgsql 8.0.3 when using Dapper[/-] [+]Decide what to do with ParameterDirection.ReturnValue[/+] on Sep 4, 2024
  12. roji commented on Sep 4, 2024

    @roji
    Member

    After some additional discussion, we decided to patch 8.0.4 to ignore ParameterDirection.ReturnValue as originally planned here, and like previous versions were doing. We're still not sure if that's the right behavior we want going forward, but we'll discuss that for future versions in #5825.

  13. self-assigned this
    on Sep 25, 2024
  14. modified the milestones: Backlog, 8.0.4 on Oct 3, 2024
  15. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions