L
L
Ler Den2018-12-07 20:33:10
PostgreSQL
Ler Den, 2018-12-07 20:33:10

How to limit the number of records per user in a PostgreSQL table?

In the post table, you need to limit the number of posts per user, for example to 3.
For example, NodeJS and pg-promise are used for requests.

let db = require("./connection");
let post= function () {
    self = this;
    self.create = function (obj) {
        return db.query(`INSERT INTO public.post (user_id, title, message) VALUES ($(userId), $(title), $(message));`, obj);
    };
};
module.exports = post;

You can send a query to the database before each call to `post.create()`, get the number of posts, and if it is less than 3, then send a new request and create a post, if more, send an error to the client.
But it seems to me that such things are implemented in a good way at the DBMS level (or am I mistaken?)
Something like this, but I can’t figure out how to pass the userId from the NodeJS routing inside the trigger?
CREATE OR REPLACE FUNCTION check_number_of_row_per_user()
RETURNS TRIGGER AS
$body$
BEGIN
   -- КАК ПЕРЕДАТЬ ПАРАМЕТР $(userId) ИЗ ЗАПРОСА?
    IF (SELECT count(*) FROM public.post WHERE user_id = $(userId)) > 2
    THEN 
        RAISE EXCEPTION 'INSERT statement exceeding maximum number of rows for table filter';
    END IF;
    RETURN NULL;
END;
$body$
LANGUAGE plpgsql;

CREATE TRIGGER tr_check_number_of_row_per_user 
BEFORE INSERT ON public.post
FOR EACH ROW EXECUTE PROCEDURE check_number_of_row_per_user();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Koryukov, 2018-12-07
@givemoneybiatch

Throwing business logic into the database makes sense in two cases: 1 - to increase performance in very critical places, 2 - when the database is used by different systems for which it is impossible to allocate a common code.
Your case is not like that, so it's more correct to check for JS.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question