db/schema/0100_usr.sql

99 lines
2.4 KiB
MySQL
Raw Normal View History

2023-06-11 16:26:39 +00:00
select create_newtype_text('public.usr_tag');
2023-06-10 04:51:28 +00:00
2023-07-02 20:57:28 +00:00
select create_newtype_text('public.usr_tag_or_email');
create function usr_tag_or_email_to_email(toe public.usr_tag_or_email)
returns public.email
language plpgsql
immutable as $$
begin
if position('@' in usr_tag_or_email_to_string(toe)) > 0 then
return email_of_string(usr_tag_or_email_to_string(toe));
else
return null;
end if;
end;
$$;
create function usr_tag_or_email_to_tag(toe public.usr_tag_or_email)
returns public.usr_tag
language plpgsql
immutable as $$
begin
if usr_tag_or_email_to_email(toe) is null then
return usr_tag_of_string(usr_tag_or_email_to_string(toe));
else
return null;
end if;
end;
$$;
2023-06-10 04:51:28 +00:00
create table public.usr
( id int not null primary key generated always as identity
2023-07-16 02:03:16 +00:00
, uid human_uuid.huid not null unique default human_uuid.huid()
2023-06-10 04:51:28 +00:00
, deleted boolean not null default false
2023-06-11 16:26:39 +00:00
, tag public.usr_tag not null
2023-07-14 22:13:34 +00:00
, discrim int not null default 0
2023-06-10 04:51:28 +00:00
, password public.hashed_text not null
, email public.email not null unique
2023-07-07 21:20:07 +00:00
, unique (tag, discrim)
2023-06-10 04:51:28 +00:00
);
2023-07-14 22:13:34 +00:00
create function public.do_insert_usr_default_discrim()
returns trigger
stable
language plpgsql
as $$
begin
if new.discrim is null then
new.discrim := (select count(*) from public.usr u where u.tag = tag);
end if;
return new;
end;
2023-07-07 21:20:07 +00:00
$$;
2023-07-14 22:13:34 +00:00
create trigger insert_usr_default_discrim
before insert on public.usr
for each row execute function public.do_insert_usr_default_discrim();
create function public.usr_root()
returns public.usr
stable
language sql
as $$select * from public.usr where tag = public.usr_tag_of_string('root')$$;
2023-07-14 22:13:34 +00:00
create function public.do_check_usr_tag()
returns trigger
stable
language plpgsql
as $$
begin
if new.tag = usr_tag_of_string('root') then
2023-07-16 06:19:11 +00:00
raise exception 'tag_invalid';
2023-07-14 22:13:34 +00:00
else
return new;
end if;
end;
$$;
2023-07-07 21:20:07 +00:00
2023-07-14 22:13:34 +00:00
create trigger check_usr_tag
before insert on public.usr
for each row execute function public.do_check_usr_tag();
2023-06-11 17:01:51 +00:00
2023-06-11 16:26:39 +00:00
select audit( 'public'
, 'usr'
, array[ row('tag', 'public.usr_tag')
, row('password', 'public.hashed_text')
, row('email', 'public.email')
] :: audited_column[]
, soft_delete => true
);
2023-06-10 22:43:27 +00:00
2023-06-11 16:26:39 +00:00
select immutable( 'public'
, 'usr'
, array[ 'id'
, 'uid'
]
);