set check_function_bodies = off;

CREATE OR REPLACE FUNCTION public.create_newtype_text(qualified_name text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  execute concat('create type ', qualified_name, ' as (str text);');
  execute concat( 'create function '
                , qualified_name || '_to_string(val ' || qualified_name || ')'
                , E' returns text language sql as \'select (val.str);\';'
                );
  execute concat( 'create function '
                , qualified_name || '_of_string(val text)'
                , ' returns ' || qualified_name || E' language sql as \'select row(val);\';'
                );
  execute concat( 'create cast '
                , ' (' || qualified_name || ' as text)'
                , ' with function ' || qualified_name || E'_to_string(' || qualified_name || ')'
                , ' as assignment;'
                );
  execute concat( 'create cast '
                , ' (text as ' || qualified_name || ')'
                , ' with function ' || qualified_name || E'_of_string(text)'
                , ' as assignment;'
                );
end;
$function$
;

create cast (public.usr_tag as text) with function public.usr_tag_to_string(public.usr_tag) as assignment;
create cast (text as public.usr_tag) with function public.usr_tag_of_string(text) as assignment;

create cast (public.usr_session_key as text) with function public.usr_session_key_to_string(public.usr_session_key) as assignment;
create cast (text as public.usr_session_key) with function public.usr_session_key_of_string(text) as assignment;

create cast (public.grp_tag as text) with function public.grp_tag_to_string(public.grp_tag) as assignment;
create cast (text as public.grp_tag) with function public.grp_tag_of_string(text) as assignment;

create cast (public.community_tag as text) with function public.community_tag_to_string(public.community_tag) as assignment;
create cast (text as public.community_tag) with function public.community_tag_of_string(text) as assignment;

create cast (public.email as text) with function public.email_to_string(public.email) as assignment;
create cast (text as public.email) with function public.email_of_string(text) as assignment;

create cast (public.hashed_text as text) with function public.hashed_text_to_string(public.hashed_text) as assignment;
create cast (text as public.hashed_text) with function public.hashed_text_of_string(text) as assignment;

create cast (human_uuid.huid as text) with function human_uuid.huid_to_string(human_uuid.huid) as assignment;
create cast (text as human_uuid.huid) with function human_uuid.huid_of_string(text) as assignment;
