B
B
Bogdan2019-12-05 16:09:21
PostgreSQL
Bogdan, 2019-12-05 16:09:21

Write access check?

Hello. Tell me please. How to solve such a case correctly:
1) there is a sign with users, but users can belong to other users

CREATE TABLE public."Users" (
  id serial NOT NULL,
  "parentId" int4 NULL,
  email varchar(100) NOT NULL DEFAULT ''::character varying,
       CONSTRAINT "Users_email_key" UNIQUE (email),
  CONSTRAINT "Users_pkey" PRIMARY KEY (id),
  CONSTRAINT "Users_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Users"(id) ON DELETE CASCADE,
);

2) There is a table "Cartridges" which has a connection with the table of users by the field "userId".
Edit, view the entry can only or directly the user or his parent
CREATE TABLE public."Cartridges" (
  id serial NOT NULL,
  code varchar(9) NOT NULL DEFAULT ''::character varying,
  printed int4 NOT NULL DEFAULT 0,
  "userId" int4 NULL,
  CONSTRAINT "Cartridges_pkey" PRIMARY KEY (id),
  CONSTRAINT "Cartridges_userId_fkey" FOREIGN KEY ("userId") REFERENCES "Users"(id) ON DELETE CASCADE
);

I do it by adding a CTE to each request, which recursively creates a table with the user and his parent, and then by the connection we check whether he is there.
WITH RECURSIVE "UsersTree" AS (
  SELECT
      id,
      email,
      "parentId"
    FROM "Users"
        WHERE id = 4

      UNION ALL

      SELECT
          "Users".id,
      "Users".email,
      "Users"."parentId"
    FROM "Users"
    INNER JOIN "UsersTree" ON "Users"."parentId" = "UsersTree".id
)
update "Cartridges" set printed = 5 
  from "UsersTree" where "Cartridges".id = 2 and "UsersTree".id = "Cartridges"."userId"
  returning *

But the construction that needs to be added to each request is somehow cumbersome. How do they do it in such cases? Thanks

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question