Skip to content

Instantly share code, notes, and snippets.

@mdnmdn
Last active June 12, 2023 21:48
Show Gist options
  • Save mdnmdn/dad47b1ec02cd030db95990da027a800 to your computer and use it in GitHub Desktop.
Save mdnmdn/dad47b1ec02cd030db95990da027a800 to your computer and use it in GitHub Desktop.
postgres short uuid custom domain for human management with cast and equality operators
CREATE DOMAIN public.sid AS CHAR(8);
CREATE OR REPLACE FUNCTION cast_uuid_as_sid(uuid)
RETURNS sid
LANGUAGE SQL AS
$$ SELECT substr($1::text,1,8)::sid $$;
CREATE OR REPLACE FUNCTION eq_uuid_sid(id1 uuid, id2 sid)
RETURNS BOOLEAN
LANGUAGE SQL AS
$$ SELECT id1::sid = id2 $$;
CREATE OR REPLACE FUNCTION eq_sid_uuid(id2 sid, id1 uuid)
RETURNS BOOLEAN
LANGUAGE SQL AS
$$ SELECT id1::sid = id2 $$;
CREATE CAST ( uuid AS sid )
WITH FUNCTION cast_uuid_as_sid(uuid) AS IMPLICIT;
create operator = (
leftarg = uuid,
rightarg = sid,
procedure = eq_uuid_sid,
commutator = =);
create operator = (
leftarg = sid,
rightarg = uuid,
procedure = eq_sid_uuid,
commutator = =);
/*
drop operator = (uuid, sid), = (sid, uuid);
drop cast ( uuid AS sid );
drop function cast_uuid_as_sid, eq_sid_uuid, eq_uuid_sid;
drop domain sid;
*/
select t.id, t.id::sid, t.id = t.id::sid, t.id::sid = t.id
from (select gen_random_uuid() as id) t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment