admin管理员组文章数量:1314514
Using Supabase/Postgres, I have 3 tables. auth.users
, public.boards
, and public.user_boards
.
When a user creates a new board, I need to insert a record into public.boards
and return the id
so that I can create a new record in public.user_boards
that shows the user owns that board.
But with RLS enabled, the user can't select from boards and get the ID it just created.
const { data: newBoard, error } = await supabase
.from('boards')
.insert([{ title: newBoardTitle.trim() }])
.select() // <--- this fails unless I allow all users to select everything
.single()
Using Supabase/Postgres, I have 3 tables. auth.users
, public.boards
, and public.user_boards
.
When a user creates a new board, I need to insert a record into public.boards
and return the id
so that I can create a new record in public.user_boards
that shows the user owns that board.
But with RLS enabled, the user can't select from boards and get the ID it just created.
const { data: newBoard, error } = await supabase
.from('boards')
.insert([{ title: newBoardTitle.trim() }])
.select() // <--- this fails unless I allow all users to select everything
.single()
Share
Improve this question
edited Jan 30 at 12:29
jonrsharpe
122k30 gold badges267 silver badges474 bronze badges
asked Jan 30 at 12:24
Kyle HKyle H
3,3035 gold badges33 silver badges39 bronze badges
1 Answer
Reset to default 1You will have to insert into user_boards
first. To do that, you need to
define the foreign key from
user_boards
toboards
as deferred constraint, so that it is checked at the end of the transaction:ALTER TABLE user_boards ADD FOREIGN KEY (id) REFERENCES boards DEFERRABLE INITIALLY DEFERRED;
know the name of the sequence that generates values for
boards.id
— let's assume it is calledboards_id_seq
Then you can do it as follows:
-- start a transaction
BEGIN;
-- no error, because the constraint is deferred
INSERT INTO public.user_boards
VALUES (nextval('public.boards_id_seq'), current_user)
RETURNING id;
-- let's assume the result value is 42
-- now the policy will allow the following statement
INSERT INTO public.boards (id) OVERRIDING SYSTEM VALUE VALUES (42);
-- now the constraint will be checked and is satisfied
COMMIT;
本文标签:
版权声明:本文标题:postgresql - How do I insert into a table with RLS and get the ID back before I have the record linked to the user? - Stack Over 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741965910a2407546.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论