--
-- This file is part of TALER
-- Copyright (C) 2026 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--
DROP FUNCTION IF EXISTS uri_escape;
CREATE FUNCTION uri_escape(input TEXT)
RETURNS TEXT
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
AS $$
SELECT COALESCE(string_agg(
  CASE
    WHEN chr(get_byte(b, i)) ~ '[A-Za-z0-9._~-]'
      THEN chr(get_byte(b, i))
    ELSE '%' || lpad(upper(to_hex(get_byte(b, i))), 2, '0')
  END,
  ''
), '')
FROM (
  SELECT convert_to(input, 'UTF8') AS b
) s,
generate_series(0, length(b) - 1) AS i;
$$;
COMMENT ON FUNCTION uri_escape(TEXT)
  IS 'Percent-encodes all characters except RFC 3986 unreserved chars: A-Z a-z 0-9 - . _ ~';
