-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathurldecode.sql
56 lines (55 loc) · 1.56 KB
/
urldecode.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
--url解码
CREATE OR REPLACE FUNCTION urldecode(url text)
RETURNS text
AS
$$
DECLARE
ret text;
BEGIN
BEGIN
WITH STR AS (
SELECT
case when $1 ~ '^%[0-9a-fA-F][0-9a-fA-F]'
then array['']
end
|| regexp_split_to_array ($1,'(%[0-9a-fA-F][0-9a-fA-F])+', 'i') plain,
array(select (regexp_matches ($1,'((?:%[0-9a-fA-F][0-9a-fA-F])+)', 'gi'))[1]) encoded
)
SELECT string_agg(plain[i] || coalesce( convert_from(decode(replace(encoded[i], '%',''), 'hex'), 'utf8'),''),'')
FROM STR,
(SELECT generate_series(1, array_upper(encoded,1)+2) i FROM STR)blah
INTO ret;
EXCEPTION WHEN OTHERS THEN --'failed: %',url;
return $1;
END;
RETURN coalesce(ret,$1); -- when the string has no encoding;
END;
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION urldecode(url TEXT,msgEncoding TEXT='utf-8')
RETURNS text
AS
$$
DECLARE
ret text;
BEGIN
BEGIN
WITH STR AS (
SELECT
case when $1 ~ '^%[0-9a-fA-F][0-9a-fA-F]'
then array['']
end
|| regexp_split_to_array ($1,'(%[0-9a-fA-F][0-9a-fA-F])+', 'i') plain,
array(select (regexp_matches ($1,'((?:%[0-9a-fA-F][0-9a-fA-F])+)', 'gi'))[1]) encoded
)
SELECT string_agg(plain[i] || coalesce( convert_from(decode(replace(encoded[i], '%',''), 'hex'), msgEncoding),''),'')
FROM STR,
(SELECT generate_series(1, array_upper(encoded,1)+2) i FROM STR)blah
INTO ret;
EXCEPTION WHEN OTHERS THEN --'failed: %',url;
return $1;
END;
RETURN coalesce(ret,$1); -- when the string has no encoding;
END;
$$
LANGUAGE plpgsql;