问题出在标题上。我们有一个 postgreSQL 数据库,我们想在其中保存一些路径,并且数据库从路径中删除反斜杠( \
)。
功能:
CREATE OR REPLACE FUNCTION public.add_filenotification_array(IN fninput public.filenotification_input [])
RETURNS Table(TYPE public."filenotification") AS
$$
DECLARE
fn public.filenotification_input;
filenotification public.filenotification;
filenotificationlist public.filenotification [];
BEGIN
FOREACH fn IN ARRAY fninput LOOP
INSERT INTO public."FileNotification"("FileLocation", "FileTargetLocation", "DocumentLanguage", "LastUpdate", "idStatus", "FileSize")
VALUES (fn.filelocation, fn.filetargetlocation, fn.documentlanguage, CURRENT_TIMESTAMP, 0, 0)
RETURNING "id", "FileLocation", "FileTargetLocation", "DocumentLanguage", "LastUpdate", "idStatus"
INTO filenotification.id, filenotification.filelocation, filenotification.filetargetlocation, filenotification.documentlanguage, filenotification.lastupdate, filenotification.idstatus;
filenotificationlist := array_append(filenotificationlist, filenotification);
END LOOP;
RETURN QUERY
SELECT * FROM unnest(filenotificationlist::public.filenotification []);
END;
$$
LANGUAGE plpgsql;
文件类型:
TYPE filenotification AS (
"id" integer,
"filelocation" character varying,
"filetargetlocation" character varying,
"documentlanguage" character varying,
"lastupdate" timestamp,
"idstatus" integer
);
TYPE filenotification_input AS (
"filelocation" character varying,
"filetargetlocation" character varying,
"documentlanguage" character varying
);
从应用程序中,我们发送 filenotification
的 java.sql.Array
,并在 filelocation
和 filetargetlocation
处提供正确的路径> 参数和结果完全没有间隙。我们的问题是:这是怎么回事?为什么它会删除反斜杠?
编辑:如果我们在函数参数中放入 4 个反斜杠,那么它会输出 1 个反斜杠。如果我们在函数参数中放入 8 个反斜杠,那么它会输出 2 个反斜杠
最佳答案
好的,根据 dbfiddle 我可以看到问题是什么。 (顺便说一句,它不喜欢在那里引用美元,这就是为什么你不能运行它。你只需要将 $$
替换为 '
将其作为字符串引用,然后它就会运行。)
您的输入是'{"(c:\\\\\\\rs\\me, Path, lang)"}'
。它是一个类型的数组。
让我们采用一个简单的类型:CREATE TYPE public.t AS (txt TEXT)
。当您选择类型作为行而不是展开字段时,任何“特殊”字符都将被转义。
所以:SELECT ROW('C:\temp')::public.t
返回("C:\\temp")
,并通过 SELECT (ROW('C:\temp')::public.t).*
扩展它返回C:\temp
.
您的输入是一行(它使用(data1,data2,etc)
符号,这是行文字,并且未展开),因此所有反斜杠都被转义。扩展行 ( SELECT ('(c:\\\\\\\rs\\me, Path, lang)'::public.filenotification_input).*
) 的路径部分将是 c:\\\rs\me
.
然而,还有一层转义:数据位于数组中这一事实。与未展开的行相同,特殊字符将在数组中进行转义。运行SELECT ARRAY['C:\temp']
返回["C:\\temp"]
.
将它们放在一起,您的行中需要转义反斜杠,并且每个反斜杠都需要在数组中转义。因此,要在“正常”文本中获得单个反斜杠,您必须在行( \\
)中对其进行转义,然后对数组中的每个反斜杠( \\\\
)进行转义。
因此,考虑到您提供输入的方式,您需要 4 个反斜杠才能在表中插入一个反斜杠。
运行它并查看各种输出:https://www.db-fiddle.com/f/83wBZsztETriNtZGDVXdcN/0
关于java - 在 PostgreSQL 中保存文件路径,删除反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183567/