Quiero recibir una notificación cuando haya una nueva entrada en una tabla específica "FileInfos"
en PostgreSQL 12, así que escribí el siguiente disparador:
create trigger trigger1 after insert or update on public."FileInfos" for each row execute procedure notify_id_trigger();
y la siguiente función:
create or replace function notify_id_trigger() returns trigger as $$ begin perform pg_notify('new_Id'::text, NEW."Id"::text); return new; end; $$ language plpgsql;
para recibir las notificaciones, uso la biblioteca python psycopg2 :
import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT import select def dblistener(): connection = psycopg2.connect( host="127.0.0.1", database="DBNAME", user="postgres", password="....") connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = connection.cursor() cur.execute("LISTEN new_Id;") while True: select.select([connection], [], []) connection.poll() while connection.notifies: notify = connection.notifies.pop() print("Got NOTIFY:", notify.pid, notify.channel, notify.payload) if __name__ == '__main__': dblistener()
Pero desafortunadamente mi código python no funciona, ¿qué hice mal? Por cierto: la base de datos y la tabla se crearon con Entity Framework (C#).
Según la sintaxis de NOTIFY , el canal es un identificador. Eso significa que new_Id
en
LISTEN new_Id
se convierte automáticamente a new_id
. Desafortunadamente, pg_notify('new_Id'::text, new."Id"::text)
notifica en el canal new_Id
. Tienes dos opciones. Cambia el canal en el disparador:
perform pg_notify('new_id'::text, new."Id"::text);
o encierre el canal entre comillas dobles en LISTEN
:
LISTEN "new_Id"
El uso de mayúsculas en Postgres puede causar sorpresas.