Answer the question
In order to leave comments, you need to log in
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;
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
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 questionAsk a Question
731 491 924 answers to any question