From cd3413ec3683918c9cb9cfb39ae5b2c32f231e8b Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Tue, 11 Dec 2012 19:28:31 -0500
Subject: [PATCH] Disable event triggers in standalone mode.

Per discussion, this seems necessary to allow recovery from broken event
triggers, or broken indexes on pg_event_trigger.

Dimitri Fontaine
---
 doc/src/sgml/ref/create_event_trigger.sgml | 11 +++++++++--
 src/backend/commands/event_trigger.c       | 19 +++++++++++++++++++
 2 files changed, 28 insertions(+), 2 deletions(-)

diff --git a/doc/src/sgml/ref/create_event_trigger.sgml b/doc/src/sgml/ref/create_event_trigger.sgml
index 08894b22cfb..040df118153 100644
--- a/doc/src/sgml/ref/create_event_trigger.sgml
+++ b/doc/src/sgml/ref/create_event_trigger.sgml
@@ -108,7 +108,14 @@ CREATE EVENT TRIGGER <replaceable class="PARAMETER">name</replaceable>
   <title>Notes</title>
 
   <para>
-   To create a trigger on a event, the user must be superuser.
+   Only superusers can create event triggers.
+  </para>
+
+  <para>
+   Event triggers are disabled in single-user mode (see <xref
+   linkend="app-postgres">).  If an erroneous event trigger disables the
+   database so much that you can't even drop the trigger, restart in
+   single-user mode and you'll be able to do that.
   </para>
  </refsect1>
 
@@ -116,7 +123,7 @@ CREATE EVENT TRIGGER <replaceable class="PARAMETER">name</replaceable>
   <title>Examples</title>
 
   <para>
-   Forbid the execution of any <link linkend="ddl">ddl</link> command:
+   Forbid the execution of any <link linkend="ddl">DDL</link> command:
 
 <programlisting>
 CREATE OR REPLACE FUNCTION abort_any_command()
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index cb4e658a584..1edffee410e 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -566,6 +566,25 @@ EventTriggerDDLCommandStart(Node *parsetree)
 	const char *tag;
 	EventTriggerData	trigdata;
 
+	/*
+	 * Event Triggers are completely disabled in standalone mode.  There are
+	 * (at least) two reasons for this:
+	 *
+	 * 1. A sufficiently broken event trigger might not only render the
+	 * database unusable, but prevent disabling itself to fix the situation.
+	 * In this scenario, restarting in standalone mode provides an escape
+	 * hatch.
+	 *
+	 * 2. BuildEventTriggerCache relies on systable_beginscan_ordered, and
+	 * therefore will malfunction if pg_event_trigger's indexes are damaged.
+	 * To allow recovery from a damaged index, we need some operating mode
+	 * wherein event triggers are disabled.  (Or we could implement
+	 * heapscan-and-sort logic for that case, but having disaster recovery
+	 * scenarios depend on code that's otherwise untested isn't appetizing.)
+	 */
+	if (!IsUnderPostmaster)
+		return;
+
 	/*
 	 * We want the list of command tags for which this procedure is actually
 	 * invoked to match up exactly with the list that CREATE EVENT TRIGGER
-- 
GitLab