Skip to content

Instantly share code, notes, and snippets.

@shrkw
Created August 7, 2014 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shrkw/70dc4e819fdd26926f22 to your computer and use it in GitHub Desktop.
Save shrkw/70dc4e819fdd26926f22 to your computer and use it in GitHub Desktop.
two PL/pgSQL functions for PostgreSQL. I wanted to use those functions for serial number on X.509 certificates, but I noticed serial number may be over the capacity of bigint, then gave up and stored serial number as hexadecimal format on varchar.
-- from decimal biginteger to hexdecimal text with any separator
CREATE OR REPLACE FUNCTION serialnumber_hex(serial bigint, sep varchar) RETURNS varchar AS $$
DECLARE
org varchar := '';
res varchar := '';
BEGIN
org := to_hex(serial);
WHILE 0 < length(org) LOOP
res := concat_ws(sep, res, substr(org, 1, 2));
org := substr(org, 3, length(org));
END LOOP;
RETURN substr(res, length(sep) + 1, length(res));
END;
$$ LANGUAGE plpgsql;
-- from hexdecimal text with ':' or ' ' as a separator to decimal biginteger
CREATE OR REPLACE FUNCTION serialnumber_dec(serial varchar) RETURNS varchar AS $$
DECLARE
res bigint;
serial_hex varchar;
BEGIN
serial_hex := replace(replace(serial, ':', ''), ' ', '');
EXECUTE 'SELECT x''' || serial_hex || '''::bigint' INTO res;
RETURN res;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment