1 /*-------------------------------------------------------------------------
4 * Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/commands/async.c,v 1.113 2004/07/01 00:50:10 tgl Exp $
12 *-------------------------------------------------------------------------
15 /*-------------------------------------------------------------------------
16 * New Async Notification Model:
17 * 1. Multiple backends on same machine. Multiple backends listening on
18 * one relation. (Note: "listening on a relation" is not really the
19 * right way to think about it, since the notify names need not have
20 * anything to do with the names of relations actually in the database.
21 * But this terminology is all over the code and docs, and I don't feel
22 * like trying to replace it.)
24 * 2. There is a tuple in relation "pg_listener" for each active LISTEN,
25 * ie, each relname/listenerPID pair. The "notification" field of the
26 * tuple is zero when no NOTIFY is pending for that listener, or the PID
27 * of the originating backend when a cross-backend NOTIFY is pending.
28 * (We skip writing to pg_listener when doing a self-NOTIFY, so the
29 * notification field should never be equal to the listenerPID field.)
31 * 3. The NOTIFY statement itself (routine Async_Notify) just adds the target
32 * relname to a list of outstanding NOTIFY requests. Actual processing
33 * happens if and only if we reach transaction commit. At that time (in
34 * routine AtCommit_Notify) we scan pg_listener for matching relnames.
35 * If the listenerPID in a matching tuple is ours, we just send a notify
36 * message to our own front end. If it is not ours, and "notification"
37 * is not already nonzero, we set notification to our own PID and send a
38 * SIGUSR2 signal to the receiving process (indicated by listenerPID).
39 * BTW: if the signal operation fails, we presume that the listener backend
40 * crashed without removing this tuple, and remove the tuple for it.
42 * 4. Upon receipt of a SIGUSR2 signal, the signal handler can call inbound-
43 * notify processing immediately if this backend is idle (ie, it is
44 * waiting for a frontend command and is not within a transaction block).
45 * Otherwise the handler may only set a flag, which will cause the
46 * processing to occur just before we next go idle.
48 * 5. Inbound-notify processing consists of scanning pg_listener for tuples
49 * matching our own listenerPID and having nonzero notification fields.
50 * For each such tuple, we send a message to our frontend and clear the
51 * notification field. BTW: this routine has to start/commit its own
52 * transaction, since by assumption it is only called from outside any
55 * Although we grab ExclusiveLock on pg_listener for any operation,
56 * the lock is never held very long, so it shouldn't cause too much of
57 * a performance problem. (Previously we used AccessExclusiveLock, but
58 * there's no real reason to forbid concurrent reads.)
60 * An application that listens on the same relname it notifies will get
61 * NOTIFY messages for its own NOTIFYs. These can be ignored, if not useful,
62 * by comparing be_pid in the NOTIFY message to the application's own backend's
63 * PID. (As of FE/BE protocol 2.0, the backend's PID is provided to the
64 * frontend during startup.) The above design guarantees that notifies from
65 * other backends will never be missed by ignoring self-notifies. Note,
66 * however, that we do *not* guarantee that a separate frontend message will
67 * be sent for every outside NOTIFY. Since there is only room for one
68 * originating PID in pg_listener, outside notifies occurring at about the
69 * same time may be collapsed into a single message bearing the PID of the
70 * first outside backend to perform the NOTIFY.
71 *-------------------------------------------------------------------------
79 #include <netinet/in.h>
81 #include "access/heapam.h"
82 #include "catalog/catname.h"
83 #include "catalog/pg_listener.h"
84 #include "commands/async.h"
85 #include "libpq/libpq.h"
86 #include "libpq/pqformat.h"
87 #include "miscadmin.h"
88 #include "storage/ipc.h"
89 #include "storage/sinval.h"
90 #include "tcop/tcopprot.h"
91 #include "utils/fmgroids.h"
92 #include "utils/ps_status.h"
93 #include "utils/syscache.h"
97 * State for outbound notifies consists of a list of all relnames NOTIFYed
98 * in the current transaction. We do not actually perform a NOTIFY until
99 * and unless the transaction commits. pendingNotifies is NIL if no
100 * NOTIFYs have been done in the current transaction.
102 * The list is kept in CurTransactionContext. In subtransactions, each
103 * subtransaction has its own list in its own CurTransactionContext, but
104 * successful subtransactions attach their lists to their parent's list.
105 * Failed subtransactions simply discard their lists.
107 static List *pendingNotifies = NIL;
109 static List *upperPendingNotifies = NIL; /* list of upper-xact lists */
112 * State for inbound notifies consists of two flags: one saying whether
113 * the signal handler is currently allowed to call ProcessIncomingNotify
114 * directly, and one saying whether the signal has occurred but the handler
115 * was not allowed to call ProcessIncomingNotify at the time.
117 * NB: the "volatile" on these declarations is critical! If your compiler
118 * does not grok "volatile", you'd be best advised to compile this file
119 * with all optimization turned off.
121 static volatile int notifyInterruptEnabled = 0;
122 static volatile int notifyInterruptOccurred = 0;
124 /* True if we've registered an on_shmem_exit cleanup */
125 static bool unlistenExitRegistered = false;
127 bool Trace_notify = false;
130 static void Async_UnlistenAll(void);
131 static void Async_UnlistenOnExit(int code, Datum arg);
132 static void ProcessIncomingNotify(void);
133 static void NotifyMyFrontEnd(char *relname, int32 listenerPID);
134 static bool AsyncExistsPendingNotify(const char *relname);
135 static void ClearPendingNotifies(void);
139 *--------------------------------------------------------------
142 * This is executed by the SQL notify command.
144 * Adds the relation to the list of pending notifies.
145 * Actual notification happens during transaction commit.
146 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151 *--------------------------------------------------------------
154 Async_Notify(char *relname)
157 elog(DEBUG1, "Async_Notify(%s)", relname);
159 /* no point in making duplicate entries in the list ... */
160 if (!AsyncExistsPendingNotify(relname))
163 * The name list needs to live until end of transaction, so store
164 * it in the transaction context.
166 MemoryContext oldcontext;
168 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
170 pendingNotifies = lcons(pstrdup(relname), pendingNotifies);
172 MemoryContextSwitchTo(oldcontext);
177 *--------------------------------------------------------------
180 * This is executed by the SQL listen command.
182 * Register a backend (identified by its Unix PID) as listening
183 * on the specified relation.
189 * pg_listener is updated.
191 *--------------------------------------------------------------
194 Async_Listen(char *relname, int pid)
199 Datum values[Natts_pg_listener];
200 char nulls[Natts_pg_listener];
202 bool alreadyListener = false;
205 elog(DEBUG1, "Async_Listen(%s,%d)", relname, pid);
207 lRel = heap_openr(ListenerRelationName, ExclusiveLock);
209 /* Detect whether we are already listening on this relname */
210 scan = heap_beginscan(lRel, SnapshotNow, 0, NULL);
211 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
213 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple);
215 if (listener->listenerpid == pid &&
216 strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0)
218 alreadyListener = true;
219 /* No need to scan the rest of the table */
227 heap_close(lRel, ExclusiveLock);
232 * OK to insert a new tuple
235 for (i = 0; i < Natts_pg_listener; i++)
238 values[i] = PointerGetDatum(NULL);
242 values[i++] = (Datum) relname;
243 values[i++] = (Datum) pid;
244 values[i++] = (Datum) 0; /* no notifies pending */
246 tuple = heap_formtuple(RelationGetDescr(lRel), values, nulls);
247 simple_heap_insert(lRel, tuple);
249 #ifdef NOT_USED /* currently there are no indexes */
250 CatalogUpdateIndexes(lRel, tuple);
253 heap_freetuple(tuple);
255 heap_close(lRel, ExclusiveLock);
258 * now that we are listening, make sure we will unlisten before dying.
260 if (!unlistenExitRegistered)
262 on_shmem_exit(Async_UnlistenOnExit, 0);
263 unlistenExitRegistered = true;
268 *--------------------------------------------------------------
271 * This is executed by the SQL unlisten command.
273 * Remove the backend from the list of listening backends
274 * for the specified relation.
280 * pg_listener is updated.
282 *--------------------------------------------------------------
285 Async_Unlisten(char *relname, int pid)
291 /* Handle specially the `unlisten "*"' command */
292 if ((!relname) || (*relname == '\0') || (strcmp(relname, "*") == 0))
299 elog(DEBUG1, "Async_Unlisten(%s,%d)", relname, pid);
301 lRel = heap_openr(ListenerRelationName, ExclusiveLock);
303 scan = heap_beginscan(lRel, SnapshotNow, 0, NULL);
304 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
306 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple);
308 if (listener->listenerpid == pid &&
309 strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0)
311 /* Found the matching tuple, delete it */
312 simple_heap_delete(lRel, &tuple->t_self);
315 * We assume there can be only one match, so no need to scan
316 * the rest of the table
323 heap_close(lRel, ExclusiveLock);
326 * We do not complain about unlistening something not being listened;
332 *--------------------------------------------------------------
335 * Unlisten all relations for this backend.
337 * This is invoked by UNLISTEN "*" command, and also at backend exit.
343 * pg_listener is updated.
345 *--------------------------------------------------------------
348 Async_UnlistenAll(void)
357 elog(DEBUG1, "Async_UnlistenAll");
359 lRel = heap_openr(ListenerRelationName, ExclusiveLock);
360 tdesc = RelationGetDescr(lRel);
362 /* Find and delete all entries with my listenerPID */
364 Anum_pg_listener_pid,
365 BTEqualStrategyNumber, F_INT4EQ,
366 Int32GetDatum(MyProcPid));
367 scan = heap_beginscan(lRel, SnapshotNow, 1, key);
369 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
370 simple_heap_delete(lRel, &lTuple->t_self);
373 heap_close(lRel, ExclusiveLock);
377 *--------------------------------------------------------------
378 * Async_UnlistenOnExit
380 * Clean up the pg_listener table at backend exit.
382 * This is executed if we have done any LISTENs in this backend.
383 * It might not be necessary anymore, if the user UNLISTENed everything,
384 * but we don't try to detect that case.
390 * pg_listener is updated if necessary.
392 *--------------------------------------------------------------
395 Async_UnlistenOnExit(int code, Datum arg)
398 * We need to start/commit a transaction for the unlisten, but if
399 * there is already an active transaction we had better abort that one
400 * first. Otherwise we'd end up committing changes that probably
401 * ought to be discarded.
403 AbortOutOfAnyTransaction();
404 /* Now we can do the unlisten */
405 StartTransactionCommand();
407 CommitTransactionCommand();
411 *--------------------------------------------------------------
414 * This is called at transaction commit.
416 * If there are outbound notify requests in the pendingNotifies list,
417 * scan pg_listener for matching tuples, and either signal the other
418 * backend or send a message to our own frontend.
420 * NOTE: we are still inside the current transaction, therefore can
421 * piggyback on its committing of changes.
427 * Tuples in pg_listener that have matching relnames and other peoples'
428 * listenerPIDs are updated with a nonzero notification field.
430 *--------------------------------------------------------------
433 AtCommit_Notify(void)
440 Datum value[Natts_pg_listener];
441 char repl[Natts_pg_listener],
442 nulls[Natts_pg_listener];
444 if (pendingNotifies == NIL)
445 return; /* no NOTIFY statements in this
449 * NOTIFY is disabled if not normal processing mode. This test used to
450 * be in xact.c, but it seems cleaner to do it here.
452 if (!IsNormalProcessingMode())
454 ClearPendingNotifies();
459 elog(DEBUG1, "AtCommit_Notify");
461 /* preset data to update notify column to MyProcPid */
462 nulls[0] = nulls[1] = nulls[2] = ' ';
463 repl[0] = repl[1] = repl[2] = ' ';
464 repl[Anum_pg_listener_notify - 1] = 'r';
465 value[0] = value[1] = value[2] = (Datum) 0;
466 value[Anum_pg_listener_notify - 1] = Int32GetDatum(MyProcPid);
468 lRel = heap_openr(ListenerRelationName, ExclusiveLock);
469 tdesc = RelationGetDescr(lRel);
470 scan = heap_beginscan(lRel, SnapshotNow, 0, NULL);
472 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
474 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(lTuple);
475 char *relname = NameStr(listener->relname);
476 int32 listenerPID = listener->listenerpid;
478 if (!AsyncExistsPendingNotify(relname))
481 if (listenerPID == MyProcPid)
484 * Self-notify: no need to bother with table update. Indeed,
485 * we *must not* clear the notification field in this path, or
486 * we could lose an outside notify, which'd be bad for
487 * applications that ignore self-notify messages.
491 elog(DEBUG1, "AtCommit_Notify: notifying self");
493 NotifyMyFrontEnd(relname, listenerPID);
498 elog(DEBUG1, "AtCommit_Notify: notifying pid %d",
502 * If someone has already notified this listener, we don't
503 * bother modifying the table, but we do still send a SIGUSR2
504 * signal, just in case that backend missed the earlier signal
505 * for some reason. It's OK to send the signal first, because
506 * the other guy can't read pg_listener until we unlock it.
508 if (kill(listenerPID, SIGUSR2) < 0)
511 * Get rid of pg_listener entry if it refers to a PID that
512 * no longer exists. Presumably, that backend crashed
513 * without deleting its pg_listener entries. This code
514 * used to only delete the entry if errno==ESRCH, but as
515 * far as I can see we should just do it for any failure
516 * (certainly at least for EPERM too...)
518 simple_heap_delete(lRel, &lTuple->t_self);
520 else if (listener->notification == 0)
522 ItemPointerData ctid;
525 rTuple = heap_modifytuple(lTuple, lRel,
528 * We cannot use simple_heap_update here because the tuple
529 * could have been modified by an uncommitted transaction;
530 * specifically, since UNLISTEN releases exclusive lock on
531 * the table before commit, the other guy could already have
532 * tried to unlisten. There are no other cases where we
533 * should be able to see an uncommitted update or delete.
534 * Therefore, our response to a HeapTupleBeingUpdated result
535 * is just to ignore it. We do *not* wait for the other
536 * guy to commit --- that would risk deadlock, and we don't
537 * want to block while holding the table lock anyway for
538 * performance reasons. We also ignore HeapTupleUpdated,
539 * which could occur if the other guy commits between our
540 * heap_getnext and heap_update calls.
542 result = heap_update(lRel, &lTuple->t_self, rTuple,
544 GetCurrentCommandId(), SnapshotAny,
545 false /* no wait for commit */);
548 case HeapTupleSelfUpdated:
549 /* Tuple was already updated in current command? */
550 elog(ERROR, "tuple already updated by self");
553 case HeapTupleMayBeUpdated:
554 /* done successfully */
556 #ifdef NOT_USED /* currently there are no indexes */
557 CatalogUpdateIndexes(lRel, rTuple);
561 case HeapTupleBeingUpdated:
562 /* ignore uncommitted tuples */
565 case HeapTupleUpdated:
566 /* ignore just-committed tuples */
570 elog(ERROR, "unrecognized heap_update status: %u",
581 * We do NOT release the lock on pg_listener here; we need to hold it
582 * until end of transaction (which is about to happen, anyway) to
583 * ensure that notified backends see our tuple updates when they look.
584 * Else they might disregard the signal, which would make the
585 * application programmer very unhappy.
587 heap_close(lRel, NoLock);
589 ClearPendingNotifies();
592 elog(DEBUG1, "AtCommit_Notify: done");
596 *--------------------------------------------------------------
599 * This is called at transaction abort.
601 * Gets rid of pending outbound notifies that we would have executed
602 * if the transaction got committed.
607 *--------------------------------------------------------------
612 ClearPendingNotifies();
616 * AtSubStart_Notify() --- Take care of subtransaction start.
618 * Push empty state for the new subtransaction.
621 AtSubStart_Notify(void)
623 MemoryContext old_cxt;
625 /* Keep the list-of-lists in TopTransactionContext for simplicity */
626 old_cxt = MemoryContextSwitchTo(TopTransactionContext);
628 upperPendingNotifies = lcons(pendingNotifies, upperPendingNotifies);
630 pendingNotifies = NIL;
632 MemoryContextSwitchTo(old_cxt);
636 * AtSubCommit_Notify() --- Take care of subtransaction commit.
638 * Reassign all items in the pending notifies list to the parent transaction.
641 AtSubCommit_Notify(void)
643 List *parentPendingNotifies;
645 parentPendingNotifies = (List *) linitial(upperPendingNotifies);
646 upperPendingNotifies = list_delete_first(upperPendingNotifies);
649 * We could try to eliminate duplicates here, but it seems not worthwhile.
651 pendingNotifies = list_concat(parentPendingNotifies, pendingNotifies);
655 * AtSubAbort_Notify() --- Take care of subtransaction abort.
658 AtSubAbort_Notify(void)
661 * All we have to do is pop the stack --- the notifies made in this
662 * subxact are no longer interesting, and the space will be freed when
663 * CurTransactionContext is recycled.
665 pendingNotifies = (List *) linitial(upperPendingNotifies);
666 upperPendingNotifies = list_delete_first(upperPendingNotifies);
670 *--------------------------------------------------------------
671 * NotifyInterruptHandler
673 * This is the signal handler for SIGUSR2.
675 * If we are idle (notifyInterruptEnabled is set), we can safely invoke
676 * ProcessIncomingNotify directly. Otherwise, just set a flag
684 *--------------------------------------------------------------
687 NotifyInterruptHandler(SIGNAL_ARGS)
689 int save_errno = errno;
692 * Note: this is a SIGNAL HANDLER. You must be very wary what you do
693 * here. Some helpful soul had this routine sprinkled with TPRINTFs,
694 * which would likely lead to corruption of stdio buffers if they were
698 /* Don't joggle the elbow of proc_exit */
699 if (proc_exit_inprogress)
702 if (notifyInterruptEnabled)
704 bool save_ImmediateInterruptOK = ImmediateInterruptOK;
707 * We may be called while ImmediateInterruptOK is true; turn it
708 * off while messing with the NOTIFY state. (We would have to
709 * save and restore it anyway, because PGSemaphore operations
710 * inside ProcessIncomingNotify() might reset it.)
712 ImmediateInterruptOK = false;
715 * I'm not sure whether some flavors of Unix might allow another
716 * SIGUSR2 occurrence to recursively interrupt this routine. To
717 * cope with the possibility, we do the same sort of dance that
718 * EnableNotifyInterrupt must do --- see that routine for
721 notifyInterruptEnabled = 0; /* disable any recursive signal */
722 notifyInterruptOccurred = 1; /* do at least one iteration */
725 notifyInterruptEnabled = 1;
726 if (!notifyInterruptOccurred)
728 notifyInterruptEnabled = 0;
729 if (notifyInterruptOccurred)
731 /* Here, it is finally safe to do stuff. */
733 elog(DEBUG1, "NotifyInterruptHandler: perform async notify");
735 ProcessIncomingNotify();
738 elog(DEBUG1, "NotifyInterruptHandler: done");
743 * Restore ImmediateInterruptOK, and check for interrupts if
746 ImmediateInterruptOK = save_ImmediateInterruptOK;
747 if (save_ImmediateInterruptOK)
748 CHECK_FOR_INTERRUPTS();
753 * In this path it is NOT SAFE to do much of anything, except
756 notifyInterruptOccurred = 1;
763 * --------------------------------------------------------------
764 * EnableNotifyInterrupt
766 * This is called by the PostgresMain main loop just before waiting
767 * for a frontend command. If we are truly idle (ie, *not* inside
768 * a transaction block), then process any pending inbound notifies,
769 * and enable the signal handler to process future notifies directly.
771 * NOTE: the signal handler starts out disabled, and stays so until
772 * PostgresMain calls this the first time.
773 * --------------------------------------------------------------
776 EnableNotifyInterrupt(void)
778 if (IsTransactionOrTransactionBlock())
779 return; /* not really idle */
782 * This code is tricky because we are communicating with a signal
783 * handler that could interrupt us at any point. If we just checked
784 * notifyInterruptOccurred and then set notifyInterruptEnabled, we
785 * could fail to respond promptly to a signal that happens in between
786 * those two steps. (A very small time window, perhaps, but Murphy's
787 * Law says you can hit it...) Instead, we first set the enable flag,
788 * then test the occurred flag. If we see an unserviced interrupt has
789 * occurred, we re-clear the enable flag before going off to do the
790 * service work. (That prevents re-entrant invocation of
791 * ProcessIncomingNotify() if another interrupt occurs.) If an
792 * interrupt comes in between the setting and clearing of
793 * notifyInterruptEnabled, then it will have done the service work and
794 * left notifyInterruptOccurred zero, so we have to check again after
795 * clearing enable. The whole thing has to be in a loop in case
796 * another interrupt occurs while we're servicing the first. Once we
797 * get out of the loop, enable is set and we know there is no
798 * unserviced interrupt.
800 * NB: an overenthusiastic optimizing compiler could easily break this
801 * code. Hopefully, they all understand what "volatile" means these
806 notifyInterruptEnabled = 1;
807 if (!notifyInterruptOccurred)
809 notifyInterruptEnabled = 0;
810 if (notifyInterruptOccurred)
813 elog(DEBUG1, "EnableNotifyInterrupt: perform async notify");
815 ProcessIncomingNotify();
818 elog(DEBUG1, "EnableNotifyInterrupt: done");
824 * --------------------------------------------------------------
825 * DisableNotifyInterrupt
827 * This is called by the PostgresMain main loop just after receiving
828 * a frontend command. Signal handler execution of inbound notifies
829 * is disabled until the next EnableNotifyInterrupt call.
831 * The SIGUSR1 signal handler also needs to call this, so as to
832 * prevent conflicts if one signal interrupts the other. So we
833 * must return the previous state of the flag.
834 * --------------------------------------------------------------
837 DisableNotifyInterrupt(void)
839 bool result = (notifyInterruptEnabled != 0);
841 notifyInterruptEnabled = 0;
847 * --------------------------------------------------------------
848 * ProcessIncomingNotify
850 * Deal with arriving NOTIFYs from other backends.
851 * This is called either directly from the SIGUSR2 signal handler,
852 * or the next time control reaches the outer idle loop.
853 * Scan pg_listener for arriving notifies, report them to my front end,
854 * and clear the notification field in pg_listener until next time.
856 * NOTE: since we are outside any transaction, we must create our own.
857 * --------------------------------------------------------------
860 ProcessIncomingNotify(void)
868 Datum value[Natts_pg_listener];
869 char repl[Natts_pg_listener],
870 nulls[Natts_pg_listener];
871 bool catchup_enabled;
873 /* Must prevent SIGUSR1 interrupt while I am running */
874 catchup_enabled = DisableCatchupInterrupt();
877 elog(DEBUG1, "ProcessIncomingNotify");
879 set_ps_display("notify interrupt");
881 notifyInterruptOccurred = 0;
883 StartTransactionCommand();
885 lRel = heap_openr(ListenerRelationName, ExclusiveLock);
886 tdesc = RelationGetDescr(lRel);
888 /* Scan only entries with my listenerPID */
890 Anum_pg_listener_pid,
891 BTEqualStrategyNumber, F_INT4EQ,
892 Int32GetDatum(MyProcPid));
893 scan = heap_beginscan(lRel, SnapshotNow, 1, key);
895 /* Prepare data for rewriting 0 into notification field */
896 nulls[0] = nulls[1] = nulls[2] = ' ';
897 repl[0] = repl[1] = repl[2] = ' ';
898 repl[Anum_pg_listener_notify - 1] = 'r';
899 value[0] = value[1] = value[2] = (Datum) 0;
900 value[Anum_pg_listener_notify - 1] = Int32GetDatum(0);
902 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
904 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(lTuple);
905 char *relname = NameStr(listener->relname);
906 int32 sourcePID = listener->notification;
910 /* Notify the frontend */
913 elog(DEBUG1, "ProcessIncomingNotify: received %s from %d",
914 relname, (int) sourcePID);
916 NotifyMyFrontEnd(relname, sourcePID);
918 * Rewrite the tuple with 0 in notification column.
920 * simple_heap_update is safe here because no one else would
921 * have tried to UNLISTEN us, so there can be no uncommitted
924 rTuple = heap_modifytuple(lTuple, lRel, value, nulls, repl);
925 simple_heap_update(lRel, &lTuple->t_self, rTuple);
927 #ifdef NOT_USED /* currently there are no indexes */
928 CatalogUpdateIndexes(lRel, rTuple);
935 * We do NOT release the lock on pg_listener here; we need to hold it
936 * until end of transaction (which is about to happen, anyway) to
937 * ensure that other backends see our tuple updates when they look.
938 * Otherwise, a transaction started after this one might mistakenly
939 * think it doesn't need to send this backend a new NOTIFY.
941 heap_close(lRel, NoLock);
943 CommitTransactionCommand();
946 * Must flush the notify messages to ensure frontend gets them
951 set_ps_display("idle");
954 elog(DEBUG1, "ProcessIncomingNotify: done");
957 EnableCatchupInterrupt();
961 * Send NOTIFY message to my front end.
964 NotifyMyFrontEnd(char *relname, int32 listenerPID)
966 if (whereToSendOutput == Remote)
970 pq_beginmessage(&buf, 'A');
971 pq_sendint(&buf, listenerPID, sizeof(int32));
972 pq_sendstring(&buf, relname);
973 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
975 /* XXX Add parameter string here later */
976 pq_sendstring(&buf, "");
981 * NOTE: we do not do pq_flush() here. For a self-notify, it will
982 * happen at the end of the transaction, and for incoming notifies
983 * ProcessIncomingNotify will do it after finding all the
988 elog(INFO, "NOTIFY for %s", relname);
991 /* Does pendingNotifies include the given relname? */
993 AsyncExistsPendingNotify(const char *relname)
997 foreach(p, pendingNotifies)
999 /* Use NAMEDATALEN for relname comparison. DZ - 26-08-1996 */
1000 if (strncmp((const char *) lfirst(p), relname, NAMEDATALEN) == 0)
1007 /* Clear the pendingNotifies list. */
1009 ClearPendingNotifies(void)
1012 * We used to have to explicitly deallocate the list members and
1013 * nodes, because they were malloc'd. Now, since we know they are
1014 * palloc'd in CurTransactionContext, we need not do that --- they'll
1015 * go away automatically at transaction exit. We need only reset the
1016 * list head pointer.
1018 pendingNotifies = NIL;