Skip to content

Instantly share code, notes, and snippets.

@emiel
Last active April 11, 2018 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emiel/49aa93baab83a55f17dca4f7d790a067 to your computer and use it in GitHub Desktop.
Save emiel/49aa93baab83a55f17dca4f7d790a067 to your computer and use it in GitHub Desktop.
Decode SendGrid Event ID in Postgres
create or replace function sendgrid_eid24_to_uuid(eid text)
returns uuid language sql immutable strict parallel safe
as $function$
select encode(decode(translate(eid, '-_', '+/'), 'base64'), 'hex')::uuid;
$function$;
create or replace function sendgrid_eid48_to_uuid(eid text)
returns uuid language sql immutable strict parallel safe
as $function$
select convert_from(decode(translate(eid, '-_', '+/'), 'base64'), 'UTF-8')::uuid;
$function$;
create or replace function sendgrid_eid_to_uuid(eid text)
returns uuid language plpgsql immutable strict parallel safe
as $function$
begin
case octet_length(eid)
when 22 then
return sendgrid_eid24_to_uuid(eid || '==');
when 24 then
return sendgrid_eid24_to_uuid(eid);
when 48 then
return sendgrid_eid48_to_uuid(eid);
else
raise exception 'Unsupported event id: %', eid;
end case;
end;
$function$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment