summaryrefslogtreecommitdiff
path: root/src/db/rest/comment/api_comment_insert.sql
blob: f3c78aa01a2f512f0d26a1e782c46e17f35b91d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
CREATE FUNCTION _api.comment_insert()
RETURNS TRIGGER
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_user_id INTEGER;
BEGIN
	_user_id = _api.get_user_id();

	NEW.content	:= _api.trim(NEW.content);
	PERFORM _api.validate_text(
		_text => NEW.content,
		_column => 'content',
		_min => 1,
		_max => 1024
	);

	PERFORM TRUE
	FROM xssbook.post
	WHERE id = NEW.post_id;

	IF NOT FOUND THEN
		PERFORM _api.raise(
			_msg => 'api_null_post',
			_err => 400
		);
	END IF;

	INSERT INTO xssbook.comment (
		user_id,
		post_id,
		content
	) VALUES (
		_user_id,
		NEW.post_id,
		NEW.content
	)
	RETURNING id
	INTO NEW.id;

	RETURN NEW;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.comment_insert()
	TO rest_user;
GRANT INSERT ON TABLE api.comment
	TO rest_user;
GRANT INSERT ON TABLE xssbook.comment
	TO rest_user;
GRANT UPDATE ON TABLE sys.comment_id_seq
	TO rest_user;

CREATE TRIGGER api_comment_insert_trgr
	INSTEAD OF INSERT
			ON api.comment
			FOR EACH ROW
				EXECUTE PROCEDURE _api.comment_insert();