我有一个PostgreSQL函数,可以通过dblink
进行插入或更新并保存日志。在.net Core上的项目中,我尝试调用函数,如下所示,并且得到PostgresException
42710: duplicate connection name
,但是如果删除行using (NpgsqlTransaction tran = conn.BeginTransaction())
和tran.Commit();
,一切正常>
我的问题是为什么它能起作用,或者我不了解某些东西?
internal static void Client_Save(int id_user, Client client) {
using (NpgsqlConnection conn = new NpgsqlConnection(Globals.pcs)) {
conn.Open();
using (NpgsqlTransaction tran = conn.BeginTransaction())
using (NpgsqlCommand cmd = new NpgsqlCommand("Client_Save", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id_moderator", NpgsqlTypes.NpgsqlDbType.Integer, id_user);
cmd.Parameters.AddWithValue("id_client", NpgsqlTypes.NpgsqlDbType.Integer, client.Id_Client);
cmd.Parameters.AddWithValue("clientname", NpgsqlTypes.NpgsqlDbType.Varchar, client.Name);
object res = cmd.ExecuteScalar();
tran.Commit();
conn.Close();
}
}
return response;
}
下面的我的PostgreSQL函数
create or replace function User_Save (ID_Moderator integer, ID_User integer, Username varchar(32), Fullname varchar(256), ID_Role integer, Pass varchar(32))
returns integer
as $$
declare
var_ID_User integer := ID_User;
var_Action varchar(64) := '';
var_Log varchar(4000) := '';
var_Return integer := 0;
begin
if (var_ID_User > 0) then
update "User" set
"Username" = Username,
"Fullname" = Fullname,
"Role" = ID_Role
where "id" = var_ID_User;
select
case when u."Fullname" <> Fullname then 'Fullname: ' || u."Fullname" || ' > ' || Fullname || '. ' else '' end ||
case when u."Username" <> Username then 'Username: ' || u."Username" || ' > ' || Username || '. 'else '' end,
'Update'
into var_Log, var_Action
from "User" as u
where u."id" = var_ID_User;
else
insert into "User" (
"Username",
"Fullname",
"Role",
"PassHash"
) values (
Username,
Fullname,
ID_Role,
hash_int(Pass)
) returning "id" into var_ID_User;
var_Action := 'Create';
var_Log := 'Fullname: ' || Fullname || ', Username: ' || Username;
end if;
perform Log_Save(ID_Moderator, 'User', var_ID_User, var_Action, var_Log);
return var_Return;
end; $$
language 'plpgsql';
还有我保存日志的功能
create or replace function Log_Save (Moderator integer, Subject varchar(32), ID_Subject integer, LogAction varchar(64), LogText varchar(4000))
returns void as $$
begin
perform dblink_connect('log_save', 'dbname=myDbName');
perform dblink_exec('log_save', 'insert into "Log" ("Moderator", "Subject", "ID_Subject", "Text", "Action", "LogDate") values (' ||
Moderator || ', ''' ||
Subject || ''',' ||
ID_Subject || ',''' ||
LogText || ''', ''' ||
LogAction || ''', ''' ||
now() || ''');');
perform dblink_exec('log_save', 'commit;');
perform dblink_disconnect('log_save');
end; $$
language plpgsql;