Hey! I'm trying to create an app with 1. `collec...
# sql
j
Hey! I'm trying to create an app with 1.
collections
2.
user_collections
(join table between the two and gives a user access to a
collection
I've setup RLS such that +
select
is only for
collections
where there's a
user_collections.collections_id = collections.id AND user_collections.user_id = user.id
which is working +
insert
is only for
authenticated
users since I want to let anyone do it The problem is that because
insert
seems to use
select
I can't actually insert even though my logic seems to be right The workaround is that I can get
insert
to work if I use
{returning: "minimal}
so that it doesn't return anything (https://supabase.com/docs/reference/javascript/insert#notes) but then I don't have the
id
to create the join table and give permissions for the
select
Any thoughts on how to do this correctly? I imagine join table permissions is a very common design that there's probably an elegant solution I'm missing
> No easy work around. Either have to generate own unique ID at client so you know it, (something like uid and time) or without thinking about it too much use an rpc function for the insert and then return your value, or do the rest of your operation on the other table at the same time in the function. Warning, late for me and just throwing out ideas to think about. > > - @User Actually on that note. Is there a way to know who the current executing user is while in SQL? e.g. I had a similar idea and put a
created_by_id
on the
collection
and then created the record on the join table based on the
created_by_id
which seems kinda hacky, but it works. Wondering if there's another way to get the user than saving it and reading it
Copy code
create or replace function public.handle_new_collection() 
returns trigger as $$
begin
  insert into public.user_collections (collection_id, user_id)
  values (
    new.id,
    new.created_by_id
  );

  return new;
end;
$$ language plpgsql security definer;

-- Only needed once to create the trigger
create trigger on_public_collection_created
  after insert on public.collections
  for each row execute procedure public.handle_new_collection();
g
auth.uid() returns the current user id if that is what you are looking for.
j
amazing, thanks!