通过Npgsql调用时,“Upsert”/ Merge函数的数据提交失败

时间:2015-11-11 13:49:49

标签: c# .net postgresql transactions npgsql

我在Postgres 9.4中使用Npgsql 3.0.3。这是我在Postgres中的代码:

CREATE TABLE temp_test
(
  id serial NOT NULL,
  name text,
  CONSTRAINT temp_test_pk PRIMARY KEY (id)
)

和“Upsert”/ merge函数,它将更改的记录作为refcursor返回:

CREATE OR REPLACE FUNCTION test_save(
    v_ref refcursor,
    iv_id integer,
    v_name character varying)
  RETURNS refcursor AS
$BODY$ 
DECLARE
  v_ref alias for $1;
  v_id integer := iv_id;
BEGIN

  UPDATE onepm.temp_test
  SET name   = v_name
  WHERE id         = v_id;
  IF NOT FOUND THEN
  INSERT INTO onepm.temp_test
      (name)
  VALUES
      (v_name)
  RETURNING id INTO v_id;
  END IF;

  OPEN v_ref FOR
  SELECT id 
       , name
  FROM onepm.temp_test
  WHERE id = v_id;

  RETURN v_ref;
END;

$BODY$
  LANGUAGE plpgsql;

在我的.net项目中,我有以下函数返回IDatareader:

public static IDataReader ExecuteReader()
        {
            NpgsqlConnection conn = new NpgsqlConnection(connectionString);
            conn.Open();

            NpgsqlTransaction _tran = conn.BeginTransaction();

            NpgsqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT onepm.test_save(@ref, @id, @name)";

            NpgsqlParameter _p = new NpgsqlParameter();
            _p.ParameterName = "@ref";
            _p.NpgsqlDbType = NpgsqlDbType.Refcursor;
            _p.NpgsqlValue = "ref";
            _p.Direction = ParameterDirection.InputOutput;
            cmd.Parameters.Add(_p);

            cmd.Parameters.Add(new NpgsqlParameter("@id", 1));
            cmd.Parameters.Add(new NpgsqlParameter("@name", "test"));

            cmd.ExecuteNonQuery();
            cmd.CommandText = "fetch all in \"ref\"";
            cmd.CommandType = CommandType.Text;

            return cmd.ExecuteReader();
        }

这一切都很好,我确实接受了读取器中插入或更新的记录,除了数据永远不会提交到表 - pgAdmin中没有数据。如果我在pgAdmin中调用相同的函数,一切正常 - 记录被提交:

SELECT onepm.test_save('v_ref', 1, 'xxxxxx');

FETCH ALL IN "v_ref";

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

嗯,我想你需要提交你开始的交易......!

无论如何,您可能还想看看PostgreSQL 9.5的新内置upsert功能......