Voglio verificare la correttezza delle migrazioni del database che aggiungono trigger ad alcune tabelle. Sto usando sqitch, quindi mi piacerebbe trovare un modo per controllarlo con query SQL. Credo che dovrebbe essere possibile con le tabelle di sistema di Postgres, ma al momento non riesco a trovare un modo per farlo.Come verificare se il trigger esiste in PostgreSQL?
6
A
risposta
11
Utilizzare il catalogo pg_trigger.
Una semplice ricerca per un tavolo books
:
select tgname
from pg_trigger
where not tgisinternal
and tgrelid = 'books'::regclass;
tgname
---------------
books_trigger
(1 row)
Utilizzando pg_proc
per ottenere la fonte della funzione trigger:
select tgname, proname, prosrc
from pg_trigger
join pg_proc p on p.oid = tgfoid
where not tgisinternal
and tgrelid = 'books'::regclass;
tgname | proname | prosrc
---------------+---------------+------------------------------------------------
books_trigger | books_trigger | +
| | begin +
| | if tg_op = 'UPDATE' then +
| | if new.listorder > old.listorder then +
| | update books +
| | set listorder = listorder- 1 +
| | where listorder <= new.listorder +
| | and listorder > old.listorder +
| | and id <> new.id; +
| | else +
| | update books +
| | set listorder = listorder+ 1 +
| | where listorder >= new.listorder +
| | and listorder < old.listorder +
| | and id <> new.id; +
| | end if; +
| | else +
| | update books +
| | set listorder = listorder+ 1 +
| | where listorder >= new.listorder +
| | and id <> new.id; +
| | end if; +
| | return new; +
| | end
(1 row)
Esempio di utilizzo pg_get_triggerdef()
funzione di:
select pg_get_triggerdef(t.oid) as "trigger declaration"
from pg_trigger t
where not tgisinternal
and tgrelid = 'books'::regclass;
trigger declaration
--------------------------------------------------------------------------------------------------------------
CREATE TRIGGER books_trigger BEFORE INSERT OR UPDATE ON books FOR EACH ROW EXECUTE PROCEDURE books_trigger()
(1 row)
In realtà ho provato questo ed ero abbastanza confuso. La cosa strana è che sto ricevendo 7 'tgname's simile a questo' RI_ConstraintTrigger_c_195564', invece di 1. Sto usando postgresql 9.4. – dredozubov
Sono trigger di vincoli interni. Usa 'non tgisinternal' per saltarli, come nella risposta modificata. – klin
Grazie! Ha aiutato! – dredozubov