| 1 | = Напредни извештаи од базата (SQL) |
| 2 | == Целосен приказ на дискусии, заедно со топикот на кој припаѓаат и нивната длабочина. |
| 3 | {{{ |
| 4 | create or replace view v_discussion_thread |
| 5 | as |
| 6 | with recursive |
| 7 | depth_table as |
| 8 | (select parent_id, id, 0 as depth |
| 9 | from discussion_thread |
| 10 | UNION ALL |
| 11 | select discuss.parent_id, dpth.id, dpth.depth + 1 |
| 12 | from depth_table dpth |
| 13 | join discussion_thread discuss |
| 14 | on dpth.parent_id = discuss.id), |
| 15 | tmp as (select id, max(depth) as depth |
| 16 | from depth_table |
| 17 | group by id) |
| 18 | select d.id as id, t.user_id as user_id, d.depth as depth, d1.parent_id as parent_id, t.created_at as "created_at" |
| 19 | from tmp d |
| 20 | join depth_table d1 |
| 21 | on d.id = d1.id and d1.depth = d.depth |
| 22 | join thread t |
| 23 | on t.id = d.id; |
| 24 | }}} |
| 25 | == Проверка на уникатноста на имињата на топиците во даден проект |
| 26 | {{{ |
| 27 | CREATE OR REPLACE FUNCTION fn_validate_topic_title() |
| 28 | RETURNS TRIGGER |
| 29 | LANGUAGE plpgsql |
| 30 | AS |
| 31 | $$ |
| 32 | BEGIN |
| 33 | IF new.title IN |
| 34 | (SELECT title |
| 35 | FROM topic_thread |
| 36 | AS t |
| 37 | WHERE t.parent_id = new.parent_id |
| 38 | OR (t.parent_id IS NULL AND new.parent_id IS NULL)) |
| 39 | THEN |
| 40 | RAISE EXCEPTION 'There already exists a topic with title % in parent topic with id %',new.title,new.parent_id; |
| 41 | END IF; |
| 42 | RETURN new; |
| 43 | END; |
| 44 | $$; |
| 45 | |
| 46 | CREATE OR REPLACE TRIGGER tr_check_topic_name |
| 47 | BEFORE INSERT OR UPDATE |
| 48 | ON topic_thread |
| 49 | FOR EACH ROW |
| 50 | EXECUTE FUNCTION fn_validate_topic_title(); |
| 51 | }}} |
| 52 | == Тригер за отстранување на неискористени тагови |
| 53 | {{{ |
| 54 | create or replace function fn_remove_unused_tags() |
| 55 | returns trigger |
| 56 | language plpgsql |
| 57 | as |
| 58 | $$ |
| 59 | BEGIN |
| 60 | IF not check_if_user_exists_in('tag_threads', 'tag_name', old.tag_name) |
| 61 | THEN |
| 62 | raise notice 'kakosi'; |
| 63 | delete from tag t where t.name = old.tag_name; |
| 64 | end if; |
| 65 | return old; |
| 66 | end; |
| 67 | $$; |
| 68 | |
| 69 | create or replace trigger tr_remove_unused_tags |
| 70 | after delete |
| 71 | on tag_threads |
| 72 | for each row |
| 73 | execute function fn_remove_unused_tags(); |
| 74 | }}} |
| 75 | |