如何将复合类型传递给PL / pgsql函数?

时间:2018-05-18 19:49:21

标签: c# postgresql plpgsql npgsql

我正在尝试(不成功)将PostgreSql复合类型传递给PL / pgsql函数。错误消息和示例代码如下所示。我还尝试了几种不同的代码变体(例如this但未成功 - 每个版本生成不同的错误消息)。我是SQL的新手,希望我犯了一个简单的错误。如果有人可以查看下面的示例代码并解释我所犯的错误,我将不胜感激。

错误消息


    System.InvalidCastException: When specifying NpgsqlDbType.Enum, SpecificType must be specified as well
       at Npgsql.TypeHandlerRegistry.get_Item(NpgsqlDbType npgsqlDbType, Type specificType)
       at Npgsql.NpgsqlParameter.ResolveHandler(TypeHandlerRegistry registry)
       at Npgsql.NpgsqlParameter.Bind(TypeHandlerRegistry registry)
       at Npgsql.NpgsqlCommand.ValidateParameters()
       at Npgsql.NpgsqlCommand.d__71.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
       at Npgsql.NpgsqlCommand.d__87.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
       at Npgsql.NpgsqlCommand.ExecuteScalar()
       at TestDatabase.TestCompositeType.Test() in F:\Visual Studio 2017\Projects\TestDatabase\TestDatabase\TestCompositeType.cs:line 42
       at TestDatabase.Program.Main(String[] args) in F:\Visual Studio 2017\Projects\TestDatabase\TestDatabase\Program.cs:line 17

系统信息


    Windows 10, 64 bit
    PostgreSQL 10.3, compiled by Visual C++ build 1800, 64-bit
    Npgsql, Version=3.2.6.0

PostgreSql代码


    create schema if not exists MySchema;

    create type MySchema.MyType as(
            X real,
            Y real
        );

    create table if not exists MySchema.MyTable(
        ItemID int primary key generated by default as identity,
        MyType MySchema.MyType
    );

    create or replace function MySchema.SetMyType( 
        ItemID2 int,
        MyType2 MySchema.MyType
    ) 
    returns int
    as $$
    declare
        resultID int;
    begin
        resultID := ItemID2;

        if( exists( select 1 from MySchema.MyTable as mt where mt.ItemID = ItemID2 ) ) then
            insert into MySchema.MyTable( MyType ) 
            values ( MyType2 )
            returning mt.ItemID into resultID;
        else
            update MySchema.MyTable as mt 
            set MyType = MyType2
            where mt.ItemID = ItemID2;
        end if;

        return resultID;
    end;
    $$ language plpgsql;

C#代码


    public void Test()
    {
        NpgsqlConnection.MapCompositeGlobally( "MySchema.MyType" );

        var connection = new NpgsqlConnection( "Host=localhost;Username=postgres;Password=123456;database=testdb" );
        if( null == connection )
            throw new NullReferenceException( "connection" );
        try
        {
            connection.Open();

            var cmd = new NpgsqlCommand( "MySchema.SetMyType", connection );
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            var par = new NpgsqlParameter( "ItemID2", NpgsqlDbType.Integer );
            par.Value = 1;
            cmd.Parameters.Add( par );

            par = new NpgsqlParameter( "MyType2", NpgsqlDbType.Composite );
            MyType myType = new MyType();
            myType.X = 1;
            myType.Y = 2;
            par.Value = myType;
            cmd.Parameters.Add( par );

            int id = Convert.ToInt32( cmd.ExecuteScalar() );
        }
        finally
        {
            connection.Close();
        }
    }   

2 个答案:

答案 0 :(得分:1)

在调用connection.Open()之前,您必须使用NpgsqlConnection.MapCompositeGlobally<>()中的C#类型调用<>来将您的C#类型映射到数据库类型(我想知道您的代码是否为是不是有<MyType>部分,甚至编译过?如果我尝试的话,我会收到错误。)

...
NpgsqlConnection.MapCompositeGlobally<MyType>( "MySchema.MyType" );

var connection = new NpgsqlConnection( "Host=localhost;Username=postgres;Password=123456;database=testdb" );
...

MyType必须有一个公共构造函数,不会为NpgsqlConnection.MapCompositeGlobally<>()使用任何参数来处理它。但你可能已经知道了。)

此外,您必须将SpecificType的属性NpgsqlParameter设置为您的C#类型。这似乎是你真正错过的。 (无论你在哪里做到这一点都没有关系(只要在ExecuteScalar()的调用之前和当然创建参数之后),例如让我们把它放在一起在您设置了参数“Value。”

之后
...
myType.X = 1;
myType.Y = 2;
par.Value = myType;
par.SpecificType = typeof(MyType);
cmd.Parameters.Add( par );
...

所有这些都在"Accessing PostgreSQL Enums and Composites"中解释。

显然,在Npgsql 4.0版本中它会变得更容易。我用Npgsql版本3.2.7 BTW自己测试了它。

编辑:

另一种解决方案不是指定NpgsqlDbType,而是在构造函数中传递MyType对象。

...
MyType myType = new MyType();
myType.X = 1;
myType.Y = 2;
par = new NpgsqlParameter( "MyType2", myType );
cmd.Parameters.Add( par );
...

然后,正确的Postgres类型由C#类型转换为先前使用MapCompositeGlobally<>()的Prostgres类型映射集。然后,不需要明确设置SpecificType

答案 1 :(得分:1)

&#39;粘性位&#39;提出的建议纠正了这个问题。我已将下面更新的示例代码包含在可能处理同一问题的任何其他人中。使用&#39; ToLower()&#39;将所有字符串转换为小写字母。但这只是在“NpgsqlConnection.MapCompositeGlobally&#39;”中映射数据库类型所必需的。


    namespace TestDatabase
    {
        public class MyType
        {
            public float X;
            public float Y;
        };

        public class TestCompositeType
        {
            public void Test()
            {
                NpgsqlConnection.MapCompositeGlobally<TestDatabase.MyType>( "MySchema.MyType".ToLower() );

                var connection = new NpgsqlConnection( "Host=localhost;Username=postgres;Password=123456;database=testdb".ToLower() );
                if( null == connection )
                    throw new NullReferenceException( "connection" );
                try
                {
                    connection.Open();

                    var cmd = new NpgsqlCommand( "MySchema.SetMyType".ToLower(), connection );
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    var par = new NpgsqlParameter( "ItemID2".ToLower(), NpgsqlDbType.Integer );
                    par.Value = 1;
                    cmd.Parameters.Add( par );

                    par = new NpgsqlParameter( "MyType2".ToLower(), NpgsqlDbType.Composite );
                    MyType myType = new MyType();
                    myType.X = 1;
                    myType.Y = 2;
                    par.Value = myType;
                    par.SpecificType = typeof( MyType );
                    cmd.Parameters.Add( par );

                    int id = Convert.ToInt32( cmd.ExecuteScalar() );
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }