From 981df43fbe9df2877500e8d177f0e74ef9ccd546 Mon Sep 17 00:00:00 2001
From: Mark Dilger <mark.dilger@enterprisedb.com>
Date: Sun, 2 Feb 2020 10:14:26 -0800
Subject: [PATCH v2 1/3] Migrating commandTag from string to enum.

The backend was using strings to represent command tags and doing string
comparisons in multiple places.  Fixing that by creating a new
CommandTag enum and using it instead.

Replacing numerous occurrences of char *completionTag with a
QueryCompletionData struct so that the code no longer stores information
about completed queries in a cstring.  Only at the last moment, in
EndCommand(), does this get converted to a string.
---
 .../pg_stat_statements/pg_stat_statements.c   |  18 +-
 contrib/sepgsql/hooks.c                       |   6 +-
 src/backend/commands/async.c                  |   2 +-
 src/backend/commands/copy.c                   |   2 +-
 src/backend/commands/createas.c               |  14 +-
 src/backend/commands/event_trigger.c          | 377 +++++++---
 src/backend/commands/matview.c                |   2 +-
 src/backend/commands/portalcmds.c             |  16 +-
 src/backend/commands/prepare.c                |   4 +-
 src/backend/commands/sequence.c               |   8 +-
 src/backend/executor/functions.c              |   4 +-
 src/backend/executor/spi.c                    |  22 +-
 src/backend/replication/walsender.c           |  18 +-
 src/backend/tcop/dest.c                       |  42 +-
 src/backend/tcop/postgres.c                   |  24 +-
 src/backend/tcop/pquery.c                     | 123 ++--
 src/backend/tcop/utility.c                    | 643 +++++++++---------
 src/backend/utils/adt/txid.c                  |   2 +-
 src/backend/utils/cache/plancache.c           |   4 +-
 src/backend/utils/misc/Makefile               |   1 +
 src/backend/utils/misc/commandtag.c           | 320 +++++++++
 src/backend/utils/mmgr/portalmem.c            |   7 +-
 src/include/commands/createas.h               |   2 +-
 src/include/commands/matview.h                |   2 +-
 src/include/commands/portalcmds.h             |   2 +-
 src/include/commands/prepare.h                |   2 +-
 src/include/miscadmin.h                       |  10 +-
 src/include/nodes/parsenodes.h                |   1 +
 src/include/tcop/dest.h                       |   6 +-
 src/include/tcop/pquery.h                     |   2 +-
 src/include/tcop/utility.h                    |   9 +-
 src/include/utils/commandtag.h                | 248 +++++++
 src/include/utils/plancache.h                 |   6 +-
 src/include/utils/portal.h                    |   6 +-
 src/include/utils/querycompletion.h           |  60 ++
 src/pl/plpgsql/src/pl_exec.c                  |   7 +-
 .../test_ddl_deparse/test_ddl_deparse.c       |   2 +-
 37 files changed, 1439 insertions(+), 585 deletions(-)
 create mode 100644 src/backend/utils/misc/commandtag.c
 create mode 100644 src/include/utils/commandtag.h
 create mode 100644 src/include/utils/querycompletion.h

diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 6f82a671ee..cd1d98114e 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -307,7 +307,7 @@ static void pgss_ExecutorEnd(QueryDesc *queryDesc);
 static void pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 								ProcessUtilityContext context, ParamListInfo params,
 								QueryEnvironment *queryEnv,
-								DestReceiver *dest, char *completionTag);
+								DestReceiver *dest, QueryCompletionData *qc);
 static uint64 pgss_hash_string(const char *str, int len);
 static void pgss_store(const char *query, uint64 queryId,
 					   int query_location, int query_len,
@@ -960,7 +960,7 @@ static void
 pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 					ProcessUtilityContext context,
 					ParamListInfo params, QueryEnvironment *queryEnv,
-					DestReceiver *dest, char *completionTag)
+					DestReceiver *dest, QueryCompletionData *qc)
 {
 	Node	   *parsetree = pstmt->utilityStmt;
 
@@ -998,11 +998,11 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 			if (prev_ProcessUtility)
 				prev_ProcessUtility(pstmt, queryString,
 									context, params, queryEnv,
-									dest, completionTag);
+									dest, qc);
 			else
 				standard_ProcessUtility(pstmt, queryString,
 										context, params, queryEnv,
-										dest, completionTag);
+										dest, qc);
 		}
 		PG_FINALLY();
 		{
@@ -1013,10 +1013,8 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 		INSTR_TIME_SET_CURRENT(duration);
 		INSTR_TIME_SUBTRACT(duration, start);
 
-		/* parse command tag to retrieve the number of affected rows. */
-		if (completionTag &&
-			strncmp(completionTag, "COPY ", 5) == 0)
-			rows = pg_strtouint64(completionTag + 5, NULL, 10);
+		if (qc && qc->commandTag == COMMANDTAG_COPY)
+			rows = qc->nprocessed;
 		else
 			rows = 0;
 
@@ -1060,11 +1058,11 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 		if (prev_ProcessUtility)
 			prev_ProcessUtility(pstmt, queryString,
 								context, params, queryEnv,
-								dest, completionTag);
+								dest, qc);
 		else
 			standard_ProcessUtility(pstmt, queryString,
 									context, params, queryEnv,
-									dest, completionTag);
+									dest, qc);
 	}
 }
 
diff --git a/contrib/sepgsql/hooks.c b/contrib/sepgsql/hooks.c
index 997a64c87e..999a67bd00 100644
--- a/contrib/sepgsql/hooks.c
+++ b/contrib/sepgsql/hooks.c
@@ -317,7 +317,7 @@ sepgsql_utility_command(PlannedStmt *pstmt,
 						ParamListInfo params,
 						QueryEnvironment *queryEnv,
 						DestReceiver *dest,
-						char *completionTag)
+						QueryCompletionData *qc)
 {
 	Node	   *parsetree = pstmt->utilityStmt;
 	sepgsql_context_info_t saved_context_info = sepgsql_context_info;
@@ -380,11 +380,11 @@ sepgsql_utility_command(PlannedStmt *pstmt,
 		if (next_ProcessUtility_hook)
 			(*next_ProcessUtility_hook) (pstmt, queryString,
 										 context, params, queryEnv,
-										 dest, completionTag);
+										 dest, qc);
 		else
 			standard_ProcessUtility(pstmt, queryString,
 									context, params, queryEnv,
-									dest, completionTag);
+									dest, qc);
 	}
 	PG_FINALLY();
 	{
diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 9aa2b61600..5322c14ce4 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -594,7 +594,7 @@ pg_notify(PG_FUNCTION_ARGS)
 		payload = text_to_cstring(PG_GETARG_TEXT_PP(1));
 
 	/* For NOTIFY as a statement, this is checked in ProcessUtility */
-	PreventCommandDuringRecovery("NOTIFY");
+	PreventCommandDuringRecovery(COMMANDTAG_NOTIFY);
 
 	Async_Notify(channel, payload);
 
diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c
index 40a8ec1abd..4828e75bd5 100644
--- a/src/backend/commands/copy.c
+++ b/src/backend/commands/copy.c
@@ -1063,7 +1063,7 @@ DoCopy(ParseState *pstate, const CopyStmt *stmt,
 
 		/* check read-only transaction and parallel mode */
 		if (XactReadOnly && !rel->rd_islocaltemp)
-			PreventCommandIfReadOnly("COPY FROM");
+			PreventCommandIfReadOnly(COMMANDTAG_COPY_FROM);
 
 		cstate = BeginCopyFrom(pstate, rel, stmt->filename, stmt->is_program,
 							   NULL, stmt->attlist, stmt->options);
diff --git a/src/backend/commands/createas.c b/src/backend/commands/createas.c
index cc02cf824e..a969c777be 100644
--- a/src/backend/commands/createas.c
+++ b/src/backend/commands/createas.c
@@ -10,7 +10,7 @@
  *
  * Formerly, CTAS was implemented as a variant of SELECT, which led
  * to assorted legacy behaviors that we still try to preserve, notably that
- * we must return a tuples-processed count in the completionTag.  (We no
+ * we must return a tuples-processed count in the qcdata.  (We no
  * longer do that for CTAS ... WITH NO DATA, however.)
  *
  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
@@ -225,7 +225,7 @@ create_ctas_nodata(List *tlist, IntoClause *into)
 ObjectAddress
 ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt,
 				  ParamListInfo params, QueryEnvironment *queryEnv,
-				  char *completionTag)
+				  QueryCompletionData *qc)
 {
 	Query	   *query = castNode(Query, stmt->query);
 	IntoClause *into = stmt->into;
@@ -270,7 +270,7 @@ ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt,
 		ExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt);
 
 		Assert(!is_matview);	/* excluded by syntax */
-		ExecuteQuery(pstate, estmt, into, params, dest, completionTag);
+		ExecuteQuery(pstate, estmt, into, params, dest, qc);
 
 		/* get object address that intorel_startup saved for us */
 		address = ((DR_intorel *) dest)->reladdr;
@@ -352,11 +352,9 @@ ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt,
 		/* run the plan to completion */
 		ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
 
-		/* save the rowcount if we're given a completionTag to fill */
-		if (completionTag)
-			snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-					 "SELECT " UINT64_FORMAT,
-					 queryDesc->estate->es_processed);
+		/* save the rowcount if we're given a qc to fill */
+		if (qc)
+			SetQC(qc, COMMANDTAG_SELECT, queryDesc->estate->es_processed, DISPLAYFORMAT_NPROCESSED);
 
 		/* get object address that intorel_startup saved for us */
 		address = ((DR_intorel *) dest)->reladdr;
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index 71911d4067..6cd9437367 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -41,6 +41,7 @@
 #include "tcop/utility.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
+#include "utils/commandtag.h"
 #include "utils/evtcache.h"
 #include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
@@ -85,52 +86,6 @@ typedef enum
 	EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED
 } event_trigger_command_tag_check_result;
 
-/* XXX merge this with ObjectTypeMap? */
-static const event_trigger_support_data event_trigger_support[] = {
-	{"ACCESS METHOD", true},
-	{"AGGREGATE", true},
-	{"CAST", true},
-	{"CONSTRAINT", true},
-	{"COLLATION", true},
-	{"CONVERSION", true},
-	{"DATABASE", false},
-	{"DOMAIN", true},
-	{"EXTENSION", true},
-	{"EVENT TRIGGER", false},
-	{"FOREIGN DATA WRAPPER", true},
-	{"FOREIGN TABLE", true},
-	{"FUNCTION", true},
-	{"INDEX", true},
-	{"LANGUAGE", true},
-	{"MATERIALIZED VIEW", true},
-	{"OPERATOR", true},
-	{"OPERATOR CLASS", true},
-	{"OPERATOR FAMILY", true},
-	{"POLICY", true},
-	{"PROCEDURE", true},
-	{"PUBLICATION", true},
-	{"ROLE", false},
-	{"ROUTINE", true},
-	{"RULE", true},
-	{"SCHEMA", true},
-	{"SEQUENCE", true},
-	{"SERVER", true},
-	{"STATISTICS", true},
-	{"SUBSCRIPTION", true},
-	{"TABLE", true},
-	{"TABLESPACE", false},
-	{"TRANSFORM", true},
-	{"TRIGGER", true},
-	{"TEXT SEARCH CONFIGURATION", true},
-	{"TEXT SEARCH DICTIONARY", true},
-	{"TEXT SEARCH PARSER", true},
-	{"TEXT SEARCH TEMPLATE", true},
-	{"TYPE", true},
-	{"USER MAPPING", true},
-	{"VIEW", true},
-	{NULL, false}
-};
-
 /* Support for dropped objects */
 typedef struct SQLDropObject
 {
@@ -150,8 +105,8 @@ typedef struct SQLDropObject
 static void AlterEventTriggerOwner_internal(Relation rel,
 											HeapTuple tup,
 											Oid newOwnerId);
-static event_trigger_command_tag_check_result check_ddl_tag(const char *tag);
-static event_trigger_command_tag_check_result check_table_rewrite_ddl_tag(const char *tag);
+static event_trigger_command_tag_check_result check_ddl_tag(CommandTag commandTag);
+static event_trigger_command_tag_check_result check_table_rewrite_ddl_tag(CommandTag commandTag);
 static void error_duplicate_filter_variable(const char *defname);
 static Datum filter_list_to_array(List *filterlist);
 static Oid	insert_event_trigger_tuple(const char *trigname, const char *eventname,
@@ -259,69 +214,260 @@ validate_ddl_tags(const char *filtervar, List *taglist)
 
 	foreach(lc, taglist)
 	{
-		const char *tag = strVal(lfirst(lc));
+		const char *tagstr = strVal(lfirst(lc));
+		CommandTag	commandTag = GetCommandTagEnum(tagstr);
 		event_trigger_command_tag_check_result result;
 
-		result = check_ddl_tag(tag);
+		result = check_ddl_tag(commandTag);
 		if (result == EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED)
 			ereport(ERROR,
 					(errcode(ERRCODE_SYNTAX_ERROR),
 					 errmsg("filter value \"%s\" not recognized for filter variable \"%s\"",
-							tag, filtervar)));
+							tagstr, filtervar)));
 		if (result == EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED)
 			ereport(ERROR,
 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 			/* translator: %s represents an SQL statement name */
 					 errmsg("event triggers are not supported for %s",
-							tag)));
+							tagstr)));
 	}
 }
 
 static event_trigger_command_tag_check_result
-check_ddl_tag(const char *tag)
+check_ddl_tag(CommandTag commandTag)
 {
-	const char *obtypename;
-	const event_trigger_support_data *etsd;
+	switch (commandTag)
+	{
+			/*
+			 * Supported idiosyncratic special cases.
+			 */
+		case COMMANDTAG_ALTER_DEFAULT_PRIVILEGES:
+		case COMMANDTAG_ALTER_LARGE_OBJECT:
+		case COMMANDTAG_COMMENT:
+		case COMMANDTAG_CREATE_TABLE_AS:
+		case COMMANDTAG_DROP_OWNED:
+		case COMMANDTAG_GRANT:
+		case COMMANDTAG_IMPORT_FOREIGN_SCHEMA:
+		case COMMANDTAG_REFRESH_MATERIALIZED_VIEW:
+		case COMMANDTAG_REVOKE:
+		case COMMANDTAG_SECURITY_LABEL:
+		case COMMANDTAG_SELECT_INTO:
 
-	/*
-	 * Handle some idiosyncratic special cases.
-	 */
-	if (pg_strcasecmp(tag, "CREATE TABLE AS") == 0 ||
-		pg_strcasecmp(tag, "SELECT INTO") == 0 ||
-		pg_strcasecmp(tag, "REFRESH MATERIALIZED VIEW") == 0 ||
-		pg_strcasecmp(tag, "ALTER DEFAULT PRIVILEGES") == 0 ||
-		pg_strcasecmp(tag, "ALTER LARGE OBJECT") == 0 ||
-		pg_strcasecmp(tag, "COMMENT") == 0 ||
-		pg_strcasecmp(tag, "GRANT") == 0 ||
-		pg_strcasecmp(tag, "REVOKE") == 0 ||
-		pg_strcasecmp(tag, "DROP OWNED") == 0 ||
-		pg_strcasecmp(tag, "IMPORT FOREIGN SCHEMA") == 0 ||
-		pg_strcasecmp(tag, "SECURITY LABEL") == 0)
-		return EVENT_TRIGGER_COMMAND_TAG_OK;
+			/*
+			 * Supported CREATE commands
+			 */
+		case COMMANDTAG_CREATE_ACCESS_METHOD:
+		case COMMANDTAG_CREATE_AGGREGATE:
+		case COMMANDTAG_CREATE_CAST:
+		case COMMANDTAG_CREATE_COLLATION:
+		case COMMANDTAG_CREATE_CONSTRAINT:
+		case COMMANDTAG_CREATE_CONVERSION:
+		case COMMANDTAG_CREATE_DOMAIN:
+		case COMMANDTAG_CREATE_EXTENSION:
+		case COMMANDTAG_CREATE_FOREIGN_DATA_WRAPPER:
+		case COMMANDTAG_CREATE_FOREIGN_TABLE:
+		case COMMANDTAG_CREATE_FUNCTION:
+		case COMMANDTAG_CREATE_INDEX:
+		case COMMANDTAG_CREATE_LANGUAGE:
+		case COMMANDTAG_CREATE_MATERIALIZED_VIEW:
+		case COMMANDTAG_CREATE_OPERATOR:
+		case COMMANDTAG_CREATE_OPERATOR_CLASS:
+		case COMMANDTAG_CREATE_OPERATOR_FAMILY:
+		case COMMANDTAG_CREATE_POLICY:
+		case COMMANDTAG_CREATE_PROCEDURE:
+		case COMMANDTAG_CREATE_PUBLICATION:
+		case COMMANDTAG_CREATE_ROUTINE:
+		case COMMANDTAG_CREATE_RULE:
+		case COMMANDTAG_CREATE_SCHEMA:
+		case COMMANDTAG_CREATE_SEQUENCE:
+		case COMMANDTAG_CREATE_SERVER:
+		case COMMANDTAG_CREATE_STATISTICS:
+		case COMMANDTAG_CREATE_SUBSCRIPTION:
+		case COMMANDTAG_CREATE_TABLE:
+		case COMMANDTAG_CREATE_TEXT_SEARCH_CONFIGURATION:
+		case COMMANDTAG_CREATE_TEXT_SEARCH_DICTIONARY:
+		case COMMANDTAG_CREATE_TEXT_SEARCH_PARSER:
+		case COMMANDTAG_CREATE_TEXT_SEARCH_TEMPLATE:
+		case COMMANDTAG_CREATE_TRANSFORM:
+		case COMMANDTAG_CREATE_TRIGGER:
+		case COMMANDTAG_CREATE_TYPE:
+		case COMMANDTAG_CREATE_USER_MAPPING:
+		case COMMANDTAG_CREATE_VIEW:
 
-	/*
-	 * Otherwise, command should be CREATE, ALTER, or DROP.
-	 */
-	if (pg_strncasecmp(tag, "CREATE ", 7) == 0)
-		obtypename = tag + 7;
-	else if (pg_strncasecmp(tag, "ALTER ", 6) == 0)
-		obtypename = tag + 6;
-	else if (pg_strncasecmp(tag, "DROP ", 5) == 0)
-		obtypename = tag + 5;
-	else
-		return EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED;
+			/*
+			 * Supported ALTER commands
+			 */
+		case COMMANDTAG_ALTER_ACCESS_METHOD:
+		case COMMANDTAG_ALTER_AGGREGATE:
+		case COMMANDTAG_ALTER_CAST:
+		case COMMANDTAG_ALTER_COLLATION:
+		case COMMANDTAG_ALTER_CONSTRAINT:
+		case COMMANDTAG_ALTER_CONVERSION:
+		case COMMANDTAG_ALTER_DOMAIN:
+		case COMMANDTAG_ALTER_EXTENSION:
+		case COMMANDTAG_ALTER_FOREIGN_DATA_WRAPPER:
+		case COMMANDTAG_ALTER_FOREIGN_TABLE:
+		case COMMANDTAG_ALTER_FUNCTION:
+		case COMMANDTAG_ALTER_INDEX:
+		case COMMANDTAG_ALTER_LANGUAGE:
+		case COMMANDTAG_ALTER_MATERIALIZED_VIEW:
+		case COMMANDTAG_ALTER_OPERATOR:
+		case COMMANDTAG_ALTER_OPERATOR_CLASS:
+		case COMMANDTAG_ALTER_OPERATOR_FAMILY:
+		case COMMANDTAG_ALTER_POLICY:
+		case COMMANDTAG_ALTER_PROCEDURE:
+		case COMMANDTAG_ALTER_PUBLICATION:
+		case COMMANDTAG_ALTER_ROUTINE:
+		case COMMANDTAG_ALTER_RULE:
+		case COMMANDTAG_ALTER_SCHEMA:
+		case COMMANDTAG_ALTER_SEQUENCE:
+		case COMMANDTAG_ALTER_SERVER:
+		case COMMANDTAG_ALTER_STATISTICS:
+		case COMMANDTAG_ALTER_SUBSCRIPTION:
+		case COMMANDTAG_ALTER_TABLE:
+		case COMMANDTAG_ALTER_TEXT_SEARCH_CONFIGURATION:
+		case COMMANDTAG_ALTER_TEXT_SEARCH_DICTIONARY:
+		case COMMANDTAG_ALTER_TEXT_SEARCH_PARSER:
+		case COMMANDTAG_ALTER_TEXT_SEARCH_TEMPLATE:
+		case COMMANDTAG_ALTER_TRANSFORM:
+		case COMMANDTAG_ALTER_TRIGGER:
+		case COMMANDTAG_ALTER_TYPE:
+		case COMMANDTAG_ALTER_USER_MAPPING:
+		case COMMANDTAG_ALTER_VIEW:
 
-	/*
-	 * ...and the object type should be something recognizable.
-	 */
-	for (etsd = event_trigger_support; etsd->obtypename != NULL; etsd++)
-		if (pg_strcasecmp(etsd->obtypename, obtypename) == 0)
+			/*
+			 * Supported DROP commands
+			 */
+		case COMMANDTAG_DROP_ACCESS_METHOD:
+		case COMMANDTAG_DROP_AGGREGATE:
+		case COMMANDTAG_DROP_CAST:
+		case COMMANDTAG_DROP_COLLATION:
+		case COMMANDTAG_DROP_CONSTRAINT:
+		case COMMANDTAG_DROP_CONVERSION:
+		case COMMANDTAG_DROP_DOMAIN:
+		case COMMANDTAG_DROP_EXTENSION:
+		case COMMANDTAG_DROP_FOREIGN_DATA_WRAPPER:
+		case COMMANDTAG_DROP_FOREIGN_TABLE:
+		case COMMANDTAG_DROP_FUNCTION:
+		case COMMANDTAG_DROP_INDEX:
+		case COMMANDTAG_DROP_LANGUAGE:
+		case COMMANDTAG_DROP_MATERIALIZED_VIEW:
+		case COMMANDTAG_DROP_OPERATOR:
+		case COMMANDTAG_DROP_OPERATOR_CLASS:
+		case COMMANDTAG_DROP_OPERATOR_FAMILY:
+		case COMMANDTAG_DROP_POLICY:
+		case COMMANDTAG_DROP_PROCEDURE:
+		case COMMANDTAG_DROP_PUBLICATION:
+		case COMMANDTAG_DROP_ROUTINE:
+		case COMMANDTAG_DROP_RULE:
+		case COMMANDTAG_DROP_SCHEMA:
+		case COMMANDTAG_DROP_SEQUENCE:
+		case COMMANDTAG_DROP_SERVER:
+		case COMMANDTAG_DROP_STATISTICS:
+		case COMMANDTAG_DROP_SUBSCRIPTION:
+		case COMMANDTAG_DROP_TABLE:
+		case COMMANDTAG_DROP_TEXT_SEARCH_CONFIGURATION:
+		case COMMANDTAG_DROP_TEXT_SEARCH_DICTIONARY:
+		case COMMANDTAG_DROP_TEXT_SEARCH_PARSER:
+		case COMMANDTAG_DROP_TEXT_SEARCH_TEMPLATE:
+		case COMMANDTAG_DROP_TRANSFORM:
+		case COMMANDTAG_DROP_TRIGGER:
+		case COMMANDTAG_DROP_TYPE:
+		case COMMANDTAG_DROP_USER_MAPPING:
+		case COMMANDTAG_DROP_VIEW:
+			return EVENT_TRIGGER_COMMAND_TAG_OK;
+
+			/*
+			 * Unsupported CREATE commands
+			 */
+		case COMMANDTAG_CREATE_DATABASE:
+		case COMMANDTAG_CREATE_EVENT_TRIGGER:
+		case COMMANDTAG_CREATE_ROLE:
+		case COMMANDTAG_CREATE_TABLESPACE:
+
+			/*
+			 * Unsupported ALTER commands
+			 */
+		case COMMANDTAG_ALTER_DATABASE:
+		case COMMANDTAG_ALTER_EVENT_TRIGGER:
+		case COMMANDTAG_ALTER_ROLE:
+		case COMMANDTAG_ALTER_TABLESPACE:
+
+			/*
+			 * Unsupported DROP commands
+			 */
+		case COMMANDTAG_DROP_DATABASE:
+		case COMMANDTAG_DROP_EVENT_TRIGGER:
+		case COMMANDTAG_DROP_ROLE:
+		case COMMANDTAG_DROP_TABLESPACE:
+
+			/*
+			 * Other unsupported commands.  These used to return
+			 * EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED prior to the
+			 * conversion of commandTag from string to enum.
+			 */
+		case COMMANDTAG_ALTER_SYSTEM:
+		case COMMANDTAG_ANALYZE:
+		case COMMANDTAG_BEGIN:
+		case COMMANDTAG_CALL:
+		case COMMANDTAG_CHECKPOINT:
+		case COMMANDTAG_CLOSE:
+		case COMMANDTAG_CLOSE_CURSOR:
+		case COMMANDTAG_CLOSE_CURSOR_ALL:
+		case COMMANDTAG_CLUSTER:
+		case COMMANDTAG_COMMIT:
+		case COMMANDTAG_COMMIT_PREPARED:
+		case COMMANDTAG_COPY:
+		case COMMANDTAG_COPY_FROM:
+		case COMMANDTAG_DEALLOCATE:
+		case COMMANDTAG_DEALLOCATE_ALL:
+		case COMMANDTAG_DECLARE_CURSOR:
+		case COMMANDTAG_DELETE:
+		case COMMANDTAG_DISCARD:
+		case COMMANDTAG_DISCARD_ALL:
+		case COMMANDTAG_DISCARD_PLANS:
+		case COMMANDTAG_DISCARD_SEQUENCES:
+		case COMMANDTAG_DISCARD_TEMP:
+		case COMMANDTAG_DO:
+		case COMMANDTAG_DROP_REPLICATION_SLOT:
+		case COMMANDTAG_EXECUTE:
+		case COMMANDTAG_EXPLAIN:
+		case COMMANDTAG_FETCH:
+		case COMMANDTAG_GRANT_ROLE:
+		case COMMANDTAG_INSERT:
+		case COMMANDTAG_LISTEN:
+		case COMMANDTAG_LOAD:
+		case COMMANDTAG_LOCK_TABLE:
+		case COMMANDTAG_MOVE:
+		case COMMANDTAG_NOTIFY:
+		case COMMANDTAG_PREPARE:
+		case COMMANDTAG_PREPARE_TRANSACTION:
+		case COMMANDTAG_REASSIGN_OWNED:
+		case COMMANDTAG_REINDEX:
+		case COMMANDTAG_RELEASE:
+		case COMMANDTAG_RESET:
+		case COMMANDTAG_REVOKE_ROLE:
+		case COMMANDTAG_ROLLBACK:
+		case COMMANDTAG_ROLLBACK_PREPARED:
+		case COMMANDTAG_SAVEPOINT:
+		case COMMANDTAG_SELECT:
+		case COMMANDTAG_SELECT_FOR_KEY_SHARE:
+		case COMMANDTAG_SELECT_FOR_NO_KEY_UPDATE:
+		case COMMANDTAG_SELECT_FOR_SHARE:
+		case COMMANDTAG_SELECT_FOR_UPDATE:
+		case COMMANDTAG_SET:
+		case COMMANDTAG_SET_CONSTRAINTS:
+		case COMMANDTAG_SHOW:
+		case COMMANDTAG_START_TRANSACTION:
+		case COMMANDTAG_TRUNCATE_TABLE:
+		case COMMANDTAG_UNLISTEN:
+		case COMMANDTAG_UPDATE:
+		case COMMANDTAG_VACUUM:
+			return EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED;
+		case COMMANDTAG_UNKNOWN:
 			break;
-	if (etsd->obtypename == NULL)
-		return EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED;
-	if (!etsd->supported)
-		return EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED;
-	return EVENT_TRIGGER_COMMAND_TAG_OK;
+	}
+	return EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED;
 }
 
 /*
@@ -334,26 +480,37 @@ validate_table_rewrite_tags(const char *filtervar, List *taglist)
 
 	foreach(lc, taglist)
 	{
-		const char *tag = strVal(lfirst(lc));
+		const char *tagstr = strVal(lfirst(lc));
+		CommandTag	commandTag = GetCommandTagEnum(tagstr);
 		event_trigger_command_tag_check_result result;
 
-		result = check_table_rewrite_ddl_tag(tag);
-		if (result == EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED)
-			ereport(ERROR,
-					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-			/* translator: %s represents an SQL statement name */
-					 errmsg("event triggers are not supported for %s",
-							tag)));
+		result = check_table_rewrite_ddl_tag(commandTag);
+		switch (result)
+		{
+			case EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED:
+			case EVENT_TRIGGER_COMMAND_TAG_NOT_RECOGNIZED:
+				ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				/* translator: %s represents an SQL statement name */
+						 errmsg("event triggers are not supported for %s",
+								tagstr)));
+			case EVENT_TRIGGER_COMMAND_TAG_OK:
+				break;
+		}
 	}
 }
 
 static event_trigger_command_tag_check_result
-check_table_rewrite_ddl_tag(const char *tag)
+check_table_rewrite_ddl_tag(CommandTag commandTag)
 {
-	if (pg_strcasecmp(tag, "ALTER TABLE") == 0 ||
-		pg_strcasecmp(tag, "ALTER TYPE") == 0)
-		return EVENT_TRIGGER_COMMAND_TAG_OK;
-
+	switch (commandTag)
+	{
+		case COMMANDTAG_ALTER_TABLE:
+		case COMMANDTAG_ALTER_TYPE:
+			return EVENT_TRIGGER_COMMAND_TAG_OK;
+		default:
+			break;
+	}
 	return EVENT_TRIGGER_COMMAND_TAG_NOT_SUPPORTED;
 }
 
@@ -721,7 +878,7 @@ EventTriggerCommonSetup(Node *parsetree,
 	 */
 #ifdef USE_ASSERT_CHECKING
 	{
-		const char *dbgtag;
+		CommandTag	dbgtag;
 
 		dbgtag = CreateCommandTag(parsetree);
 		if (event == EVT_DDLCommandStart ||
@@ -729,12 +886,12 @@ EventTriggerCommonSetup(Node *parsetree,
 			event == EVT_SQLDrop)
 		{
 			if (check_ddl_tag(dbgtag) != EVENT_TRIGGER_COMMAND_TAG_OK)
-				elog(ERROR, "unexpected command tag \"%s\"", dbgtag);
+				elog(ERROR, "unexpected command tag \"%s\"", GetCommandTagName(dbgtag));
 		}
 		else if (event == EVT_TableRewrite)
 		{
 			if (check_table_rewrite_ddl_tag(dbgtag) != EVENT_TRIGGER_COMMAND_TAG_OK)
-				elog(ERROR, "unexpected command tag \"%s\"", dbgtag);
+				elog(ERROR, "unexpected command tag \"%s\"", GetCommandTagName(dbgtag));
 		}
 	}
 #endif
@@ -745,7 +902,7 @@ EventTriggerCommonSetup(Node *parsetree,
 		return NIL;
 
 	/* Get the command tag. */
-	tag = CreateCommandTag(parsetree);
+	tag = GetCommandTagName(CreateCommandTag(parsetree));
 
 	/*
 	 * Filter list of event triggers by command tag, and copy them into our
@@ -2136,7 +2293,7 @@ pg_event_trigger_ddl_commands(PG_FUNCTION_ARGS)
 					/* objsubid */
 					values[i++] = Int32GetDatum(addr.objectSubId);
 					/* command tag */
-					values[i++] = CStringGetTextDatum(CreateCommandTag(cmd->parsetree));
+					values[i++] = CStringGetTextDatum(GetCommandTagName(CreateCommandTag(cmd->parsetree)));
 					/* object_type */
 					values[i++] = CStringGetTextDatum(type);
 					/* schema */
@@ -2161,7 +2318,7 @@ pg_event_trigger_ddl_commands(PG_FUNCTION_ARGS)
 				/* objsubid */
 				nulls[i++] = true;
 				/* command tag */
-				values[i++] = CStringGetTextDatum(CreateCommandTag(cmd->parsetree));
+				values[i++] = CStringGetTextDatum(GetCommandTagName(CreateCommandTag(cmd->parsetree)));
 				/* object_type */
 				values[i++] = CStringGetTextDatum(stringify_adefprivs_objtype(cmd->d.defprivs.objtype));
 				/* schema */
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index 1ee37c1aeb..45eafd4472 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -136,7 +136,7 @@ SetMatViewPopulatedState(Relation relation, bool newstate)
  */
 ObjectAddress
 ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
-				   ParamListInfo params, char *completionTag)
+				   ParamListInfo params, QueryCompletionData *qc)
 {
 	Oid			matviewOid;
 	Relation	matviewRel;
diff --git a/src/backend/commands/portalcmds.c b/src/backend/commands/portalcmds.c
index 7e5c805a1e..f4ac53a711 100644
--- a/src/backend/commands/portalcmds.c
+++ b/src/backend/commands/portalcmds.c
@@ -106,7 +106,8 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
 	PortalDefineQuery(portal,
 					  NULL,
 					  queryString,
-					  "SELECT", /* cursor's query is always a SELECT */
+					  COMMANDTAG_SELECT,	/* cursor's query is always a
+											 * SELECT */
 					  list_make1(plan),
 					  NULL);
 
@@ -160,15 +161,14 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
  *
  *	stmt: parsetree node for command
  *	dest: where to send results
- *	completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
- *		in which to store a command completion status string.
+ *	qc: where to store a command completion status data.
  *
- * completionTag may be NULL if caller doesn't want a status string.
+ * qc may be NULL if caller doesn't want status data.
  */
 void
 PerformPortalFetch(FetchStmt *stmt,
 				   DestReceiver *dest,
-				   char *completionTag)
+				   QueryCompletionData *qc)
 {
 	Portal		portal;
 	uint64		nprocessed;
@@ -203,10 +203,8 @@ PerformPortalFetch(FetchStmt *stmt,
 								dest);
 
 	/* Return command status if wanted */
-	if (completionTag)
-		snprintf(completionTag, COMPLETION_TAG_BUFSIZE, "%s " UINT64_FORMAT,
-				 stmt->ismove ? "MOVE" : "FETCH",
-				 nprocessed);
+	if (qc)
+		SetQC(qc, stmt->ismove ? COMMANDTAG_MOVE : COMMANDTAG_FETCH, nprocessed, DISPLAYFORMAT_NPROCESSED);
 }
 
 /*
diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c
index c4e4b6eaec..18f6227fde 100644
--- a/src/backend/commands/prepare.c
+++ b/src/backend/commands/prepare.c
@@ -187,7 +187,7 @@ void
 ExecuteQuery(ParseState *pstate,
 			 ExecuteStmt *stmt, IntoClause *intoClause,
 			 ParamListInfo params,
-			 DestReceiver *dest, char *completionTag)
+			 DestReceiver *dest, QueryCompletionData *qc)
 {
 	PreparedStatement *entry;
 	CachedPlan *cplan;
@@ -288,7 +288,7 @@ ExecuteQuery(ParseState *pstate,
 	 */
 	PortalStart(portal, paramLI, eflags, GetActiveSnapshot());
 
-	(void) PortalRun(portal, count, false, true, dest, dest, completionTag);
+	(void) PortalRun(portal, count, false, true, dest, dest, qc);
 
 	PortalDrop(portal, false);
 
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index 6aab73bfd4..d6c06fec9f 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -612,14 +612,14 @@ nextval_internal(Oid relid, bool check_permissions)
 
 	/* read-only transactions may only modify temp sequences */
 	if (!seqrel->rd_islocaltemp)
-		PreventCommandIfReadOnly("nextval()");
+		PreventCommandStrIfReadOnly("nextval()");
 
 	/*
 	 * Forbid this during parallel operation because, to make it work, the
 	 * cooperating backends would need to share the backend-local cached
 	 * sequence information.  Currently, we don't support that.
 	 */
-	PreventCommandIfParallelMode("nextval()");
+	PreventCommandStrIfParallelMode("nextval()");
 
 	if (elm->last != elm->cached)	/* some numbers were cached */
 	{
@@ -937,14 +937,14 @@ do_setval(Oid relid, int64 next, bool iscalled)
 
 	/* read-only transactions may only modify temp sequences */
 	if (!seqrel->rd_islocaltemp)
-		PreventCommandIfReadOnly("setval()");
+		PreventCommandStrIfReadOnly("setval()");
 
 	/*
 	 * Forbid this during parallel operation because, to make it work, the
 	 * cooperating backends would need to share the backend-local cached
 	 * sequence information.  Currently, we don't support that.
 	 */
-	PreventCommandIfParallelMode("setval()");
+	PreventCommandStrIfParallelMode("setval()");
 
 	/* lock page' buffer and read tuple */
 	seq = read_seq_tuple(seqrel, &buf, &seqdatatuple);
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 5cff6c4321..57ae9b6c7f 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -530,7 +530,7 @@ init_execution_state(List *queryTree_list,
 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 					/* translator: %s is a SQL statement name */
 							 errmsg("%s is not allowed in a SQL function",
-									CreateCommandTag(stmt->utilityStmt))));
+									GetCommandTagName(CreateCommandTag(stmt->utilityStmt)))));
 			}
 
 			if (fcache->readonly_func && !CommandIsReadOnly(stmt))
@@ -538,7 +538,7 @@ init_execution_state(List *queryTree_list,
 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				/* translator: %s is a SQL statement name */
 						 errmsg("%s is not allowed in a non-volatile function",
-								CreateCommandTag((Node *) stmt))));
+								GetCommandTagName(CreateCommandTag((Node *) stmt)))));
 
 			/* OK, build the execution_state for this query */
 			newes = (execution_state *) palloc(sizeof(execution_state));
diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c
index c46764bf42..04365beac9 100644
--- a/src/backend/executor/spi.c
+++ b/src/backend/executor/spi.c
@@ -1338,7 +1338,7 @@ SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
 				(errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
 		/* translator: %s is name of a SQL command, eg INSERT */
 				 errmsg("cannot open %s query as cursor",
-						plansource->commandTag)));
+						GetCommandTagName(plansource->commandTag))));
 	}
 
 	Assert(list_length(plan->plancache_list) == 1);
@@ -1469,7 +1469,7 @@ SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				/* translator: %s is a SQL statement name */
 						 errmsg("%s is not allowed in a non-volatile function",
-								CreateCommandTag((Node *) pstmt))));
+								GetCommandTagName(CreateCommandTag((Node *) pstmt)))));
 		}
 	}
 
@@ -2255,7 +2255,7 @@ _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				/* translator: %s is a SQL statement name */
 						 errmsg("%s is not allowed in a non-volatile function",
-								CreateCommandTag((Node *) stmt))));
+								GetCommandTagName(CreateCommandTag((Node *) stmt)))));
 
 			/*
 			 * If not read-only mode, advance the command counter before each
@@ -2291,9 +2291,11 @@ _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
 			}
 			else
 			{
-				char		completionTag[COMPLETION_TAG_BUFSIZE];
+				QueryCompletionData	qcdata;
 				ProcessUtilityContext context;
 
+				InitializeQC(&qcdata);
+
 				/*
 				 * If the SPI context is atomic, or we are asked to manage
 				 * snapshots, then we are in an atomic execution context.
@@ -2312,7 +2314,7 @@ _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
 							   paramLI,
 							   _SPI_current->queryEnv,
 							   dest,
-							   completionTag);
+							   &qcdata);
 
 				/* Update "processed" if stmt returned tuples */
 				if (_SPI_current->tuptable)
@@ -2328,9 +2330,8 @@ _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
 				{
 					CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
 
-					if (strncmp(completionTag, "SELECT ", 7) == 0)
-						_SPI_current->processed =
-							pg_strtouint64(completionTag + 7, NULL, 10);
+					if (qcdata.commandTag == COMMANDTAG_SELECT)
+						_SPI_current->processed = qcdata.nprocessed;
 					else
 					{
 						/*
@@ -2351,9 +2352,8 @@ _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
 				}
 				else if (IsA(stmt->utilityStmt, CopyStmt))
 				{
-					Assert(strncmp(completionTag, "COPY ", 5) == 0);
-					_SPI_current->processed = pg_strtouint64(completionTag + 5,
-															 NULL, 10);
+					Assert(qcdata.commandTag == COMMANDTAG_COPY);
+					_SPI_current->processed = qcdata.nprocessed;
 				}
 			}
 
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index abb533b9d0..78169868c4 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -1074,8 +1074,11 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
 static void
 DropReplicationSlot(DropReplicationSlotCmd *cmd)
 {
+	QueryCompletionData	qcdata;
+
 	ReplicationSlotDrop(cmd->slotname, !cmd->wait);
-	EndCommand("DROP_REPLICATION_SLOT", DestRemote);
+	SetQC(&qcdata, COMMANDTAG_DROP_REPLICATION_SLOT, 0, DISPLAYFORMAT_PLAIN);
+	EndCommand(&qcdata, DestRemote);
 }
 
 /*
@@ -1086,6 +1089,7 @@ static void
 StartLogicalReplication(StartReplicationCmd *cmd)
 {
 	StringInfoData buf;
+	QueryCompletionData qcdata;
 
 	/* make sure that our requirements are still fulfilled */
 	CheckLogicalDecodingRequirements();
@@ -1160,7 +1164,8 @@ StartLogicalReplication(StartReplicationCmd *cmd)
 	WalSndSetState(WALSNDSTATE_STARTUP);
 
 	/* Get out of COPY mode (CommandComplete). */
-	EndCommand("COPY 0", DestRemote);
+	SetQC(&qcdata, COMMANDTAG_COPY, 0, DISPLAYFORMAT_NPROCESSED);
+	EndCommand(&qcdata, DestRemote);
 }
 
 /*
@@ -1464,6 +1469,7 @@ exec_replication_command(const char *cmd_string)
 	Node	   *cmd_node;
 	MemoryContext cmd_context;
 	MemoryContext old_context;
+	QueryCompletionData	qcdata;
 
 	/*
 	 * If WAL sender has been told that shutdown is getting close, switch its
@@ -1614,7 +1620,8 @@ exec_replication_command(const char *cmd_string)
 	MemoryContextDelete(cmd_context);
 
 	/* Send CommandComplete message */
-	EndCommand("SELECT", DestRemote);
+	SetQC(&qcdata, COMMANDTAG_SELECT, 0, DISPLAYFORMAT_PLAIN);
+	EndCommand(&qcdata, DestRemote);
 
 	/* Report to pgstat that this process is now idle */
 	pgstat_report_activity(STATE_IDLE, NULL);
@@ -2867,8 +2874,11 @@ WalSndDone(WalSndSendDataCallback send_data)
 	if (WalSndCaughtUp && sentPtr == replicatedPtr &&
 		!pq_is_send_pending())
 	{
+		QueryCompletionData	qcdata;
+
 		/* Inform the standby that XLOG streaming is done */
-		EndCommand("COPY 0", DestRemote);
+		SetQC(&qcdata, COMMANDTAG_COPY, 0, DISPLAYFORMAT_NPROCESSED);
+		EndCommand(&qcdata, DestRemote);
 		pq_flush();
 
 		proc_exit(0);
diff --git a/src/backend/tcop/dest.c b/src/backend/tcop/dest.c
index 09c1dcbb53..ba1416da00 100644
--- a/src/backend/tcop/dest.c
+++ b/src/backend/tcop/dest.c
@@ -100,7 +100,7 @@ DestReceiver *None_Receiver = (DestReceiver *) &donothingDR;
  * ----------------
  */
 void
-BeginCommand(const char *commandTag, CommandDest dest)
+BeginCommand(CommandTag commandTag, CommandDest dest)
 {
 	/* Nothing to do at present */
 }
@@ -163,8 +163,11 @@ CreateDestReceiver(CommandDest dest)
  * ----------------
  */
 void
-EndCommand(const char *commandTag, CommandDest dest)
+EndCommand(const QueryCompletionData *qc, CommandDest dest)
 {
+	char completionTag[COMPLETION_TAG_BUFSIZE];
+	const char *tagname;
+
 	switch (dest)
 	{
 		case DestRemote:
@@ -172,11 +175,38 @@ EndCommand(const char *commandTag, CommandDest dest)
 		case DestRemoteSimple:
 
 			/*
-			 * We assume the commandTag is plain ASCII and therefore requires
-			 * no encoding conversion.
+			 * We assume the tagname is plain ASCII and therefore
+			 * requires no encoding conversion.
 			 */
-			pq_putmessage('C', commandTag, strlen(commandTag) + 1);
-			break;
+			tagname = GetCommandTagName(qc->commandTag);
+			switch (qc->display_format)
+			{
+				case DISPLAYFORMAT_PLAIN:
+					pq_putmessage('C', tagname, strlen(tagname) + 1);
+					break;
+				case DISPLAYFORMAT_LAST_OID:
+					/*
+					 * We no longer display LastOid, but to preserve the wire protocol,
+					 * we write InvalidOid where the LastOid used to be written.  For
+					 * efficiency in the snprintf(), hard-code InvalidOid as zero.
+					 */
+					Assert(InvalidOid == 0);
+					snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
+								"%s 0 " UINT64_FORMAT,
+								tagname,
+								qc->nprocessed);
+					pq_putmessage('C', completionTag, strlen(completionTag) + 1);
+					break;
+				case DISPLAYFORMAT_NPROCESSED:
+					snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
+							"%s " UINT64_FORMAT,
+							tagname,
+							qc->nprocessed);
+					pq_putmessage('C', completionTag, strlen(completionTag) + 1);
+					break;
+				default:
+					elog(ERROR, "Invalid display_format in EndCommand");
+			}
 
 		case DestNone:
 		case DestDebug:
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 0a6f80963b..a3ecd27547 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -1064,8 +1064,8 @@ exec_simple_query(const char *query_string)
 	{
 		RawStmt    *parsetree = lfirst_node(RawStmt, parsetree_item);
 		bool		snapshot_set = false;
-		const char *commandTag;
-		char		completionTag[COMPLETION_TAG_BUFSIZE];
+		CommandTag	commandTag;
+		QueryCompletionData	qcdata;
 		MemoryContext per_parsetree_context = NULL;
 		List	   *querytree_list,
 				   *plantree_list;
@@ -1081,7 +1081,7 @@ exec_simple_query(const char *query_string)
 		 */
 		commandTag = CreateCommandTag(parsetree->stmt);
 
-		set_ps_display(commandTag, false);
+		set_ps_display(GetCommandTagName(commandTag), false);
 
 		BeginCommand(commandTag, dest);
 
@@ -1230,7 +1230,7 @@ exec_simple_query(const char *query_string)
 						 true,
 						 receiver,
 						 receiver,
-						 completionTag);
+						 &qcdata);
 
 		receiver->rDestroy(receiver);
 
@@ -1281,7 +1281,7 @@ exec_simple_query(const char *query_string)
 		 * command the client sent, regardless of rewriting. (But a command
 		 * aborted by error will not send an EndCommand report at all.)
 		 */
-		EndCommand(completionTag, dest);
+		EndCommand(&qcdata, dest);
 
 		/* Now we may drop the per-parsetree context, if one was created. */
 		if (per_parsetree_context)
@@ -1343,7 +1343,7 @@ exec_parse_message(const char *query_string,	/* string to execute */
 	MemoryContext oldcontext;
 	List	   *parsetree_list;
 	RawStmt    *raw_parse_tree;
-	const char *commandTag;
+	CommandTag	commandTag;
 	List	   *querytree_list;
 	CachedPlanSource *psrc;
 	bool		is_named;
@@ -1505,7 +1505,7 @@ exec_parse_message(const char *query_string,	/* string to execute */
 	{
 		/* Empty input string.  This is legal. */
 		raw_parse_tree = NULL;
-		commandTag = NULL;
+		commandTag = COMMANDTAG_UNKNOWN;
 		psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
 		querytree_list = NIL;
 	}
@@ -2022,7 +2022,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 	DestReceiver *receiver;
 	Portal		portal;
 	bool		completed;
-	char		completionTag[COMPLETION_TAG_BUFSIZE];
+	QueryCompletionData	qcdata;
 	const char *sourceText;
 	const char *prepStmtName;
 	ParamListInfo portalParams;
@@ -2049,7 +2049,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 	 * If the original query was a null string, just return
 	 * EmptyQueryResponse.
 	 */
-	if (portal->commandTag == NULL)
+	if (portal->commandTag == COMMANDTAG_UNKNOWN)
 	{
 		Assert(portal->stmts == NIL);
 		NullCommand(dest);
@@ -2095,7 +2095,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 
 	pgstat_report_activity(STATE_RUNNING, sourceText);
 
-	set_ps_display(portal->commandTag, false);
+	set_ps_display(GetCommandTagName(portal->commandTag), false);
 
 	if (save_log_statement_stats)
 		ResetUsage();
@@ -2176,7 +2176,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 						  !execute_is_fetch && max_rows == FETCH_ALL,
 						  receiver,
 						  receiver,
-						  completionTag);
+						  &qcdata);
 
 	receiver->rDestroy(receiver);
 
@@ -2209,7 +2209,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 		}
 
 		/* Send appropriate CommandComplete to client */
-		EndCommand(completionTag, dest);
+		EndCommand(&qcdata, dest);
 	}
 	else
 	{
diff --git a/src/backend/tcop/pquery.c b/src/backend/tcop/pquery.c
index 0f5801e046..fe1a7672cb 100644
--- a/src/backend/tcop/pquery.c
+++ b/src/backend/tcop/pquery.c
@@ -40,7 +40,7 @@ static void ProcessQuery(PlannedStmt *plan,
 						 ParamListInfo params,
 						 QueryEnvironment *queryEnv,
 						 DestReceiver *dest,
-						 char *completionTag);
+						 QueryCompletionData *qc);
 static void FillPortalStore(Portal portal, bool isTopLevel);
 static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count,
 						   DestReceiver *dest);
@@ -48,11 +48,11 @@ static uint64 PortalRunSelect(Portal portal, bool forward, long count,
 							  DestReceiver *dest);
 static void PortalRunUtility(Portal portal, PlannedStmt *pstmt,
 							 bool isTopLevel, bool setHoldSnapshot,
-							 DestReceiver *dest, char *completionTag);
+							 DestReceiver *dest, QueryCompletionData *qc);
 static void PortalRunMulti(Portal portal,
 						   bool isTopLevel, bool setHoldSnapshot,
 						   DestReceiver *dest, DestReceiver *altdest,
-						   char *completionTag);
+						   QueryCompletionData *qc);
 static uint64 DoPortalRunFetch(Portal portal,
 							   FetchDirection fdirection,
 							   long count,
@@ -125,10 +125,9 @@ FreeQueryDesc(QueryDesc *qdesc)
  *	sourceText: the source text of the query
  *	params: any parameters needed
  *	dest: where to send results
- *	completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
- *		in which to store a command completion status string.
+ *	qc: where to store the command completion status data.
  *
- * completionTag may be NULL if caller doesn't want a status string.
+ * qc may be NULL if caller doesn't want a status string.
  *
  * Must be called in a memory context that will be reset or deleted on
  * error; otherwise the executor's memory usage will be leaked.
@@ -139,7 +138,7 @@ ProcessQuery(PlannedStmt *plan,
 			 ParamListInfo params,
 			 QueryEnvironment *queryEnv,
 			 DestReceiver *dest,
-			 char *completionTag)
+			 QueryCompletionData *qc)
 {
 	QueryDesc  *queryDesc;
 
@@ -161,38 +160,26 @@ ProcessQuery(PlannedStmt *plan,
 	ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
 
 	/*
-	 * Build command completion status string, if caller wants one.
+	 * Build command completion status data, if caller wants one.
 	 */
-	if (completionTag)
+	if (qc)
 	{
-		Oid			lastOid;
-
 		switch (queryDesc->operation)
 		{
 			case CMD_SELECT:
-				snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-						 "SELECT " UINT64_FORMAT,
-						 queryDesc->estate->es_processed);
+				SetQC(qc, COMMANDTAG_SELECT, queryDesc->estate->es_processed, DISPLAYFORMAT_NPROCESSED);
 				break;
 			case CMD_INSERT:
-				/* lastoid doesn't exist anymore */
-				lastOid = InvalidOid;
-				snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-						 "INSERT %u " UINT64_FORMAT,
-						 lastOid, queryDesc->estate->es_processed);
+				SetQC(qc, COMMANDTAG_INSERT, queryDesc->estate->es_processed, DISPLAYFORMAT_LAST_OID);
 				break;
 			case CMD_UPDATE:
-				snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-						 "UPDATE " UINT64_FORMAT,
-						 queryDesc->estate->es_processed);
+				SetQC(qc, COMMANDTAG_UPDATE, queryDesc->estate->es_processed, DISPLAYFORMAT_NPROCESSED);
 				break;
 			case CMD_DELETE:
-				snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-						 "DELETE " UINT64_FORMAT,
-						 queryDesc->estate->es_processed);
+				SetQC(qc, COMMANDTAG_DELETE, queryDesc->estate->es_processed, DISPLAYFORMAT_NPROCESSED);
 				break;
 			default:
-				strcpy(completionTag, "???");
+				SetQC(qc, COMMANDTAG_UNKNOWN, queryDesc->estate->es_processed, DISPLAYFORMAT_PLAIN);
 				break;
 		}
 	}
@@ -675,9 +662,8 @@ PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
  *
  * altdest: where to send output of non-primary queries
  *
- * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
- *		in which to store a command completion status string.
- *		May be NULL if caller doesn't want a status string.
+ * qc: where to store command completion status data.
+ *		May be NULL if caller doesn't want status data.
  *
  * Returns true if the portal's execution is complete, false if it was
  * suspended due to exhaustion of the count parameter.
@@ -685,7 +671,7 @@ PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
 bool
 PortalRun(Portal portal, long count, bool isTopLevel, bool run_once,
 		  DestReceiver *dest, DestReceiver *altdest,
-		  char *completionTag)
+		  QueryCompletionData *qc)
 {
 	bool		result;
 	uint64		nprocessed;
@@ -700,9 +686,9 @@ PortalRun(Portal portal, long count, bool isTopLevel, bool run_once,
 
 	TRACE_POSTGRESQL_QUERY_EXECUTE_START();
 
-	/* Initialize completion tag to empty string */
-	if (completionTag)
-		completionTag[0] = '\0';
+	/* Initialize empty completion data */
+	if (qc)
+		InitializeQC(qc);
 
 	if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
 	{
@@ -774,13 +760,12 @@ PortalRun(Portal portal, long count, bool isTopLevel, bool run_once,
 				 * gave us a pointer to store it, copy it. Patch the "SELECT"
 				 * tag to also provide the rowcount.
 				 */
-				if (completionTag && portal->commandTag)
+				if (qc && portal->qcdata.commandTag != COMMANDTAG_UNKNOWN)
 				{
-					if (strcmp(portal->commandTag, "SELECT") == 0)
-						snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-								 "SELECT " UINT64_FORMAT, nprocessed);
-					else
-						strcpy(completionTag, portal->commandTag);
+					CopyQC(qc, &portal->qcdata);
+					qc->nprocessed = nprocessed;
+					if (portal->commandTag == COMMANDTAG_SELECT)
+						qc->display_format = DISPLAYFORMAT_NPROCESSED;
 				}
 
 				/* Mark portal not active */
@@ -794,7 +779,7 @@ PortalRun(Portal portal, long count, bool isTopLevel, bool run_once,
 
 			case PORTAL_MULTI_QUERY:
 				PortalRunMulti(portal, isTopLevel, false,
-							   dest, altdest, completionTag);
+							   dest, altdest, qc);
 
 				/* Prevent portal's commands from being re-executed */
 				MarkPortalDone(portal);
@@ -1005,8 +990,9 @@ static void
 FillPortalStore(Portal portal, bool isTopLevel)
 {
 	DestReceiver *treceiver;
-	char		completionTag[COMPLETION_TAG_BUFSIZE];
+	QueryCompletionData	qcdata;
 
+	InitializeQC(&qcdata);
 	PortalCreateHoldStore(portal);
 	treceiver = CreateDestReceiver(DestTuplestore);
 	SetTuplestoreDestReceiverParams(treceiver,
@@ -1014,8 +1000,6 @@ FillPortalStore(Portal portal, bool isTopLevel)
 									portal->holdContext,
 									false);
 
-	completionTag[0] = '\0';
-
 	switch (portal->strategy)
 	{
 		case PORTAL_ONE_RETURNING:
@@ -1028,12 +1012,12 @@ FillPortalStore(Portal portal, bool isTopLevel)
 			 * portal's holdSnapshot to the snapshot used (or a copy of it).
 			 */
 			PortalRunMulti(portal, isTopLevel, true,
-						   treceiver, None_Receiver, completionTag);
+						   treceiver, None_Receiver, &qcdata);
 			break;
 
 		case PORTAL_UTIL_SELECT:
 			PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
-							 isTopLevel, true, treceiver, completionTag);
+							 isTopLevel, true, treceiver, &qcdata);
 			break;
 
 		default:
@@ -1042,9 +1026,9 @@ FillPortalStore(Portal portal, bool isTopLevel)
 			break;
 	}
 
-	/* Override default completion tag with actual command result */
-	if (completionTag[0] != '\0')
-		portal->commandTag = pstrdup(completionTag);
+	/* Override portal completion data with actual command results */
+	if (qcdata.commandTag != COMMANDTAG_UNKNOWN)
+		CopyQC(&portal->qcdata, &qcdata);
 
 	treceiver->rDestroy(treceiver);
 }
@@ -1130,7 +1114,7 @@ RunFromStore(Portal portal, ScanDirection direction, uint64 count,
 static void
 PortalRunUtility(Portal portal, PlannedStmt *pstmt,
 				 bool isTopLevel, bool setHoldSnapshot,
-				 DestReceiver *dest, char *completionTag)
+				 DestReceiver *dest, QueryCompletionData *qc)
 {
 	Node	   *utilityStmt = pstmt->utilityStmt;
 	Snapshot	snapshot;
@@ -1178,7 +1162,7 @@ PortalRunUtility(Portal portal, PlannedStmt *pstmt,
 				   portal->portalParams,
 				   portal->queryEnv,
 				   dest,
-				   completionTag);
+				   qc);
 
 	/* Some utility statements may change context on us */
 	MemoryContextSwitchTo(portal->portalContext);
@@ -1202,7 +1186,7 @@ static void
 PortalRunMulti(Portal portal,
 			   bool isTopLevel, bool setHoldSnapshot,
 			   DestReceiver *dest, DestReceiver *altdest,
-			   char *completionTag)
+			   QueryCompletionData *qc)
 {
 	bool		active_snapshot_set = false;
 	ListCell   *stmtlist_item;
@@ -1284,7 +1268,7 @@ PortalRunMulti(Portal portal,
 							 portal->sourceText,
 							 portal->portalParams,
 							 portal->queryEnv,
-							 dest, completionTag);
+							 dest, qc);
 			}
 			else
 			{
@@ -1319,7 +1303,7 @@ PortalRunMulti(Portal portal,
 				Assert(!active_snapshot_set);
 				/* statement can set tag string */
 				PortalRunUtility(portal, pstmt, isTopLevel, false,
-								 dest, completionTag);
+								 dest, qc);
 			}
 			else
 			{
@@ -1350,8 +1334,8 @@ PortalRunMulti(Portal portal,
 		PopActiveSnapshot();
 
 	/*
-	 * If a command completion tag was supplied, use it.  Otherwise use the
-	 * portal's commandTag as the default completion tag.
+	 * If a query completion data was supplied, use it.  Otherwise use the
+	 * portal's query completion data.
 	 *
 	 * Exception: Clients expect INSERT/UPDATE/DELETE tags to have counts, so
 	 * fake them with zeros.  This can happen with DO INSTEAD rules if there
@@ -1361,18 +1345,25 @@ PortalRunMulti(Portal portal,
 	 * e.g.  an INSERT that does an UPDATE instead should not print "0 1" if
 	 * one row was updated.  See QueryRewrite(), step 3, for details.
 	 */
-	if (completionTag && completionTag[0] == '\0')
+	if (qc && qc->commandTag == COMMANDTAG_UNKNOWN)
 	{
-		if (portal->commandTag)
-			strcpy(completionTag, portal->commandTag);
-		if (strcmp(completionTag, "SELECT") == 0)
-			sprintf(completionTag, "SELECT 0 0");
-		else if (strcmp(completionTag, "INSERT") == 0)
-			strcpy(completionTag, "INSERT 0 0");
-		else if (strcmp(completionTag, "UPDATE") == 0)
-			strcpy(completionTag, "UPDATE 0");
-		else if (strcmp(completionTag, "DELETE") == 0)
-			strcpy(completionTag, "DELETE 0");
+		if (portal->qcdata.commandTag != COMMANDTAG_UNKNOWN)
+			CopyQC(qc, &portal->qcdata);
+		/* If the caller supplied a qc, we should have set it by now. */
+		Assert(qc->commandTag != COMMANDTAG_UNKNOWN);
+		switch (qc->commandTag)
+		{
+			case COMMANDTAG_SELECT:
+			case COMMANDTAG_INSERT:
+				qc->display_format = DISPLAYFORMAT_LAST_OID;
+				break;
+			case COMMANDTAG_UPDATE:
+			case COMMANDTAG_DELETE:
+				qc->display_format = DISPLAYFORMAT_NPROCESSED;
+				break;
+			default:
+				break;
+		}
 	}
 }
 
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index bb85b5e52a..fb9ea6673a 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -83,7 +83,7 @@ static void ProcessUtilitySlow(ParseState *pstate,
 							   ParamListInfo params,
 							   QueryEnvironment *queryEnv,
 							   DestReceiver *dest,
-							   char *completionTag);
+							   QueryCompletionData *qc);
 static void ExecDropStmt(DropStmt *stmt, bool isTopLevel);
 
 
@@ -396,20 +396,33 @@ ClassifyUtilityCommandAsReadOnly(Node *parsetree)
 }
 
 /*
- * PreventCommandIfReadOnly: throw error if XactReadOnly
+ * PreventCommandStrIfReadOnly: throw error if XactReadOnly
  *
  * This is useful partly to ensure consistency of the error message wording;
  * some callers have checked XactReadOnly for themselves.
  */
+static inline void
+PreventCommandReadOnly(const char *commandstr)
+{
+	ereport(ERROR,
+			(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
+	/* translator: %s is name of a SQL command, eg CREATE */
+			 errmsg("cannot execute %s in a read-only transaction",
+					commandstr)));
+}
+
 void
-PreventCommandIfReadOnly(const char *cmdname)
+PreventCommandStrIfReadOnly(const char *commandstr)
 {
 	if (XactReadOnly)
-		ereport(ERROR,
-				(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
-		/* translator: %s is name of a SQL command, eg CREATE */
-				 errmsg("cannot execute %s in a read-only transaction",
-						cmdname)));
+		PreventCommandReadOnly(commandstr);
+}
+
+void
+PreventCommandIfReadOnly(CommandTag commandTag)
+{
+	if (XactReadOnly)
+		PreventCommandReadOnly(GetCommandTagName(commandTag));
 }
 
 /*
@@ -419,15 +432,28 @@ PreventCommandIfReadOnly(const char *cmdname)
  * This is useful partly to ensure consistency of the error message wording;
  * some callers have checked IsInParallelMode() for themselves.
  */
+static inline void
+PreventCommandParallelMode(const char *commandstr)
+{
+	ereport(ERROR,
+			(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
+	/* translator: %s is name of a SQL command, eg CREATE */
+			 errmsg("cannot execute %s during a parallel operation",
+					commandstr)));
+}
+
 void
-PreventCommandIfParallelMode(const char *cmdname)
+PreventCommandStrIfParallelMode(const char *commandstr)
 {
 	if (IsInParallelMode())
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
-		/* translator: %s is name of a SQL command, eg CREATE */
-				 errmsg("cannot execute %s during a parallel operation",
-						cmdname)));
+		PreventCommandParallelMode(commandstr);
+}
+
+void
+PreventCommandIfParallelMode(CommandTag commandTag)
+{
+	if (IsInParallelMode())
+		PreventCommandParallelMode(GetCommandTagName(commandTag));
 }
 
 /*
@@ -438,15 +464,28 @@ PreventCommandIfParallelMode(const char *cmdname)
  * commands that are allowed in "read-only" xacts but cannot be allowed
  * in Hot Standby mode.  Those commands should call this function.
  */
+static inline void
+PreventCommandRecovery(const char *commandstr)
+{
+	ereport(ERROR,
+			(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
+	/* translator: %s is name of a SQL command, eg CREATE */
+			 errmsg("cannot execute %s during recovery",
+					commandstr)));
+}
+
 void
-PreventCommandDuringRecovery(const char *cmdname)
+PreventCommandStrDuringRecovery(const char *commandstr)
 {
 	if (RecoveryInProgress())
-		ereport(ERROR,
-				(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
-		/* translator: %s is name of a SQL command, eg CREATE */
-				 errmsg("cannot execute %s during recovery",
-						cmdname)));
+		PreventCommandRecovery(commandstr);
+}
+
+void
+PreventCommandDuringRecovery(CommandTag commandTag)
+{
+	if (RecoveryInProgress())
+		PreventCommandRecovery(GetCommandTagName(commandTag));
 }
 
 /*
@@ -457,14 +496,14 @@ PreventCommandDuringRecovery(const char *cmdname)
  * better-defined protection mechanism, such as ownership.
  */
 static void
-CheckRestrictedOperation(const char *cmdname)
+CheckRestrictedOperation(CommandTag commandTag)
 {
 	if (InSecurityRestrictedOperation())
 		ereport(ERROR,
 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 		/* translator: %s is name of a SQL command, eg PREPARE */
 				 errmsg("cannot execute %s within security-restricted operation",
-						cmdname)));
+						GetCommandTagName(commandTag))));
 }
 
 
@@ -480,16 +519,13 @@ CheckRestrictedOperation(const char *cmdname)
  *	queryEnv: environment for parse through execution (e.g., ephemeral named
  *		tables like trigger transition tables).  May be NULL.
  *	dest: where to send results
- *	completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
- *		in which to store a command completion status string.
+ *	qc: where to store command completion status data.
  *
  * Caller MUST supply a queryString; it is not allowed (anymore) to pass NULL.
  * If you really don't have source text, you can pass a constant string,
  * perhaps "(query not available)".
  *
- * completionTag is only set nonempty if we want to return a nondefault status.
- *
- * completionTag may be NULL if caller doesn't want a status string.
+ * qc may be NULL if caller doesn't want status data.
  *
  * Note for users of ProcessUtility_hook: the same queryString may be passed
  * to multiple invocations of ProcessUtility when processing a query string
@@ -507,7 +543,7 @@ ProcessUtility(PlannedStmt *pstmt,
 			   ParamListInfo params,
 			   QueryEnvironment *queryEnv,
 			   DestReceiver *dest,
-			   char *completionTag)
+			   QueryCompletionData *qc)
 {
 	Assert(IsA(pstmt, PlannedStmt));
 	Assert(pstmt->commandType == CMD_UTILITY);
@@ -521,11 +557,11 @@ ProcessUtility(PlannedStmt *pstmt,
 	if (ProcessUtility_hook)
 		(*ProcessUtility_hook) (pstmt, queryString,
 								context, params, queryEnv,
-								dest, completionTag);
+								dest, qc);
 	else
 		standard_ProcessUtility(pstmt, queryString,
 								context, params, queryEnv,
-								dest, completionTag);
+								dest, qc);
 }
 
 /*
@@ -546,7 +582,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 						ParamListInfo params,
 						QueryEnvironment *queryEnv,
 						DestReceiver *dest,
-						char *completionTag)
+						QueryCompletionData *qc)
 {
 	Node	   *parsetree = pstmt->utilityStmt;
 	bool		isTopLevel = (context == PROCESS_UTILITY_TOPLEVEL);
@@ -562,7 +598,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 	if (readonly_flags != COMMAND_IS_STRICTLY_READ_ONLY &&
 		(XactReadOnly || IsInParallelMode()))
 	{
-		const char *commandtag = CreateCommandTag(parsetree);
+		CommandTag	commandtag = CreateCommandTag(parsetree);
 
 		if ((readonly_flags & COMMAND_OK_IN_READ_ONLY_TXN) == 0)
 			PreventCommandIfReadOnly(commandtag);
@@ -572,8 +608,8 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			PreventCommandDuringRecovery(commandtag);
 	}
 
-	if (completionTag)
-		completionTag[0] = '\0';
+	if (qc)
+		InitializeQC(qc);
 
 	pstate = make_parsestate(NULL);
 	pstate->p_sourcetext = queryString;
@@ -623,18 +659,18 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 					case TRANS_STMT_COMMIT:
 						if (!EndTransactionBlock(stmt->chain))
 						{
-							/* report unsuccessful commit in completionTag */
-							if (completionTag)
-								strcpy(completionTag, "ROLLBACK");
+							/* report unsuccessful commit in qc */
+							if (qc)
+								SetQC(qc, COMMANDTAG_ROLLBACK, 0, DISPLAYFORMAT_PLAIN);
 						}
 						break;
 
 					case TRANS_STMT_PREPARE:
 						if (!PrepareTransactionBlock(stmt->gid))
 						{
-							/* report unsuccessful commit in completionTag */
-							if (completionTag)
-								strcpy(completionTag, "ROLLBACK");
+							/* report unsuccessful commit in qc */
+							if (qc)
+								SetQC(qc, COMMANDTAG_ROLLBACK, 0, DISPLAYFORMAT_PLAIN);
 						}
 						break;
 
@@ -687,14 +723,13 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			{
 				ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree;
 
-				CheckRestrictedOperation("CLOSE");
+				CheckRestrictedOperation(COMMANDTAG_CLOSE);
 				PerformPortalClose(stmt->portalname);
 			}
 			break;
 
 		case T_FetchStmt:
-			PerformPortalFetch((FetchStmt *) parsetree, dest,
-							   completionTag);
+			PerformPortalFetch((FetchStmt *) parsetree, dest, qc);
 			break;
 
 		case T_DoStmt:
@@ -729,14 +764,13 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				DoCopy(pstate, (CopyStmt *) parsetree,
 					   pstmt->stmt_location, pstmt->stmt_len,
 					   &processed);
-				if (completionTag)
-					snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
-							 "COPY " UINT64_FORMAT, processed);
+				if (qc)
+					SetQC(qc, COMMANDTAG_COPY, processed, DISPLAYFORMAT_NPROCESSED);
 			}
 			break;
 
 		case T_PrepareStmt:
-			CheckRestrictedOperation("PREPARE");
+			CheckRestrictedOperation(COMMANDTAG_PREPARE);
 			PrepareQuery(pstate, (PrepareStmt *) parsetree,
 						 pstmt->stmt_location, pstmt->stmt_len);
 			break;
@@ -745,11 +779,11 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			ExecuteQuery(pstate,
 						 (ExecuteStmt *) parsetree, NULL,
 						 params,
-						 dest, completionTag);
+						 dest, qc);
 			break;
 
 		case T_DeallocateStmt:
-			CheckRestrictedOperation("DEALLOCATE");
+			CheckRestrictedOperation(COMMANDTAG_DEALLOCATE);
 			DeallocateQuery((DeallocateStmt *) parsetree);
 			break;
 
@@ -793,7 +827,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			{
 				ListenStmt *stmt = (ListenStmt *) parsetree;
 
-				CheckRestrictedOperation("LISTEN");
+				CheckRestrictedOperation(COMMANDTAG_LISTEN);
 				Async_Listen(stmt->conditionname);
 			}
 			break;
@@ -802,7 +836,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			{
 				UnlistenStmt *stmt = (UnlistenStmt *) parsetree;
 
-				CheckRestrictedOperation("UNLISTEN");
+				CheckRestrictedOperation(COMMANDTAG_UNLISTEN);
 				if (stmt->conditionname)
 					Async_Unlisten(stmt->conditionname);
 				else
@@ -855,7 +889,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 
 		case T_DiscardStmt:
 			/* should we allow DISCARD PLANS? */
-			CheckRestrictedOperation("DISCARD");
+			CheckRestrictedOperation(COMMANDTAG_DISCARD);
 			DiscardCommand((DiscardStmt *) parsetree, isTopLevel);
 			break;
 
@@ -974,7 +1008,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objtype))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecuteGrantStmt(stmt);
 			}
@@ -987,7 +1021,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->removeType))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecDropStmt(stmt, isTopLevel);
 			}
@@ -1000,7 +1034,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->renameType))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecRenameStmt(stmt);
 			}
@@ -1013,7 +1047,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objectType))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecAlterObjectDependsStmt(stmt, NULL);
 			}
@@ -1026,7 +1060,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objectType))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecAlterObjectSchemaStmt(stmt, NULL);
 			}
@@ -1039,7 +1073,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objectType))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecAlterOwnerStmt(stmt);
 			}
@@ -1052,7 +1086,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objtype))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					CommentObject(stmt);
 				break;
@@ -1065,7 +1099,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 				if (EventTriggerSupportsObjectType(stmt->objtype))
 					ProcessUtilitySlow(pstate, pstmt, queryString,
 									   context, params, queryEnv,
-									   dest, completionTag);
+									   dest, qc);
 				else
 					ExecSecLabelStmt(stmt);
 				break;
@@ -1075,7 +1109,7 @@ standard_ProcessUtility(PlannedStmt *pstmt,
 			/* All other statement types have event trigger support */
 			ProcessUtilitySlow(pstate, pstmt, queryString,
 							   context, params, queryEnv,
-							   dest, completionTag);
+							   dest, qc);
 			break;
 	}
 
@@ -1102,7 +1136,7 @@ ProcessUtilitySlow(ParseState *pstate,
 				   ParamListInfo params,
 				   QueryEnvironment *queryEnv,
 				   DestReceiver *dest,
-				   char *completionTag)
+				   QueryCompletionData *qc)
 {
 	Node	   *parsetree = pstmt->utilityStmt;
 	bool		isTopLevel = (context == PROCESS_UTILITY_TOPLEVEL);
@@ -1605,7 +1639,7 @@ ProcessUtilitySlow(ParseState *pstate,
 
 			case T_CreateTableAsStmt:
 				address = ExecCreateTableAs(pstate, (CreateTableAsStmt *) parsetree,
-											params, queryEnv, completionTag);
+											params, queryEnv, qc);
 				break;
 
 			case T_RefreshMatViewStmt:
@@ -1620,7 +1654,7 @@ ProcessUtilitySlow(ParseState *pstate,
 				PG_TRY();
 				{
 					address = ExecRefreshMatView((RefreshMatViewStmt *) parsetree,
-												 queryString, params, completionTag);
+												 queryString, params, qc);
 				}
 				PG_FINALLY();
 				{
@@ -2099,137 +2133,137 @@ UtilityContainsQuery(Node *parsetree)
  *
  * This covers most cases where ALTER is used with an ObjectType enum.
  */
-static const char *
+static CommandTag
 AlterObjectTypeCommandTag(ObjectType objtype)
 {
-	const char *tag;
+	CommandTag	tag;
 
 	switch (objtype)
 	{
 		case OBJECT_AGGREGATE:
-			tag = "ALTER AGGREGATE";
+			tag = COMMANDTAG_ALTER_AGGREGATE;
 			break;
 		case OBJECT_ATTRIBUTE:
-			tag = "ALTER TYPE";
+			tag = COMMANDTAG_ALTER_TYPE;
 			break;
 		case OBJECT_CAST:
-			tag = "ALTER CAST";
+			tag = COMMANDTAG_ALTER_CAST;
 			break;
 		case OBJECT_COLLATION:
-			tag = "ALTER COLLATION";
+			tag = COMMANDTAG_ALTER_COLLATION;
 			break;
 		case OBJECT_COLUMN:
-			tag = "ALTER TABLE";
+			tag = COMMANDTAG_ALTER_TABLE;
 			break;
 		case OBJECT_CONVERSION:
-			tag = "ALTER CONVERSION";
+			tag = COMMANDTAG_ALTER_CONVERSION;
 			break;
 		case OBJECT_DATABASE:
-			tag = "ALTER DATABASE";
+			tag = COMMANDTAG_ALTER_DATABASE;
 			break;
 		case OBJECT_DOMAIN:
 		case OBJECT_DOMCONSTRAINT:
-			tag = "ALTER DOMAIN";
+			tag = COMMANDTAG_ALTER_DOMAIN;
 			break;
 		case OBJECT_EXTENSION:
-			tag = "ALTER EXTENSION";
+			tag = COMMANDTAG_ALTER_EXTENSION;
 			break;
 		case OBJECT_FDW:
-			tag = "ALTER FOREIGN DATA WRAPPER";
+			tag = COMMANDTAG_ALTER_FOREIGN_DATA_WRAPPER;
 			break;
 		case OBJECT_FOREIGN_SERVER:
-			tag = "ALTER SERVER";
+			tag = COMMANDTAG_ALTER_SERVER;
 			break;
 		case OBJECT_FOREIGN_TABLE:
-			tag = "ALTER FOREIGN TABLE";
+			tag = COMMANDTAG_ALTER_FOREIGN_TABLE;
 			break;
 		case OBJECT_FUNCTION:
-			tag = "ALTER FUNCTION";
+			tag = COMMANDTAG_ALTER_FUNCTION;
 			break;
 		case OBJECT_INDEX:
-			tag = "ALTER INDEX";
+			tag = COMMANDTAG_ALTER_INDEX;
 			break;
 		case OBJECT_LANGUAGE:
-			tag = "ALTER LANGUAGE";
+			tag = COMMANDTAG_ALTER_LANGUAGE;
 			break;
 		case OBJECT_LARGEOBJECT:
-			tag = "ALTER LARGE OBJECT";
+			tag = COMMANDTAG_ALTER_LARGE_OBJECT;
 			break;
 		case OBJECT_OPCLASS:
-			tag = "ALTER OPERATOR CLASS";
+			tag = COMMANDTAG_ALTER_OPERATOR_CLASS;
 			break;
 		case OBJECT_OPERATOR:
-			tag = "ALTER OPERATOR";
+			tag = COMMANDTAG_ALTER_OPERATOR;
 			break;
 		case OBJECT_OPFAMILY:
-			tag = "ALTER OPERATOR FAMILY";
+			tag = COMMANDTAG_ALTER_OPERATOR_FAMILY;
 			break;
 		case OBJECT_POLICY:
-			tag = "ALTER POLICY";
+			tag = COMMANDTAG_ALTER_POLICY;
 			break;
 		case OBJECT_PROCEDURE:
-			tag = "ALTER PROCEDURE";
+			tag = COMMANDTAG_ALTER_PROCEDURE;
 			break;
 		case OBJECT_ROLE:
-			tag = "ALTER ROLE";
+			tag = COMMANDTAG_ALTER_ROLE;
 			break;
 		case OBJECT_ROUTINE:
-			tag = "ALTER ROUTINE";
+			tag = COMMANDTAG_ALTER_ROUTINE;
 			break;
 		case OBJECT_RULE:
-			tag = "ALTER RULE";
+			tag = COMMANDTAG_ALTER_RULE;
 			break;
 		case OBJECT_SCHEMA:
-			tag = "ALTER SCHEMA";
+			tag = COMMANDTAG_ALTER_SCHEMA;
 			break;
 		case OBJECT_SEQUENCE:
-			tag = "ALTER SEQUENCE";
+			tag = COMMANDTAG_ALTER_SEQUENCE;
 			break;
 		case OBJECT_TABLE:
 		case OBJECT_TABCONSTRAINT:
-			tag = "ALTER TABLE";
+			tag = COMMANDTAG_ALTER_TABLE;
 			break;
 		case OBJECT_TABLESPACE:
-			tag = "ALTER TABLESPACE";
+			tag = COMMANDTAG_ALTER_TABLESPACE;
 			break;
 		case OBJECT_TRIGGER:
-			tag = "ALTER TRIGGER";
+			tag = COMMANDTAG_ALTER_TRIGGER;
 			break;
 		case OBJECT_EVENT_TRIGGER:
-			tag = "ALTER EVENT TRIGGER";
+			tag = COMMANDTAG_ALTER_EVENT_TRIGGER;
 			break;
 		case OBJECT_TSCONFIGURATION:
-			tag = "ALTER TEXT SEARCH CONFIGURATION";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_CONFIGURATION;
 			break;
 		case OBJECT_TSDICTIONARY:
-			tag = "ALTER TEXT SEARCH DICTIONARY";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_DICTIONARY;
 			break;
 		case OBJECT_TSPARSER:
-			tag = "ALTER TEXT SEARCH PARSER";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_PARSER;
 			break;
 		case OBJECT_TSTEMPLATE:
-			tag = "ALTER TEXT SEARCH TEMPLATE";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_TEMPLATE;
 			break;
 		case OBJECT_TYPE:
-			tag = "ALTER TYPE";
+			tag = COMMANDTAG_ALTER_TYPE;
 			break;
 		case OBJECT_VIEW:
-			tag = "ALTER VIEW";
+			tag = COMMANDTAG_ALTER_VIEW;
 			break;
 		case OBJECT_MATVIEW:
-			tag = "ALTER MATERIALIZED VIEW";
+			tag = COMMANDTAG_ALTER_MATERIALIZED_VIEW;
 			break;
 		case OBJECT_PUBLICATION:
-			tag = "ALTER PUBLICATION";
+			tag = COMMANDTAG_ALTER_PUBLICATION;
 			break;
 		case OBJECT_SUBSCRIPTION:
-			tag = "ALTER SUBSCRIPTION";
+			tag = COMMANDTAG_ALTER_SUBSCRIPTION;
 			break;
 		case OBJECT_STATISTIC_EXT:
-			tag = "ALTER STATISTICS";
+			tag = COMMANDTAG_ALTER_STATISTICS;
 			break;
 		default:
-			tag = "???";
+			tag = COMMANDTAG_UNKNOWN;
 			break;
 	}
 
@@ -2238,20 +2272,17 @@ AlterObjectTypeCommandTag(ObjectType objtype)
 
 /*
  * CreateCommandTag
- *		utility to get a string representation of the command operation,
+ *		utility to get a CommandTag for the command operation,
  *		given either a raw (un-analyzed) parsetree, an analyzed Query,
  *		or a PlannedStmt.
  *
  * This must handle all command types, but since the vast majority
  * of 'em are utility commands, it seems sensible to keep it here.
- *
- * NB: all result strings must be shorter than COMPLETION_TAG_BUFSIZE.
- * Also, the result must point at a true constant (permanent storage).
  */
-const char *
+CommandTag
 CreateCommandTag(Node *parsetree)
 {
-	const char *tag;
+	CommandTag	tag;
 
 	switch (nodeTag(parsetree))
 	{
@@ -2262,19 +2293,19 @@ CreateCommandTag(Node *parsetree)
 
 			/* raw plannable queries */
 		case T_InsertStmt:
-			tag = "INSERT";
+			tag = COMMANDTAG_INSERT;
 			break;
 
 		case T_DeleteStmt:
-			tag = "DELETE";
+			tag = COMMANDTAG_DELETE;
 			break;
 
 		case T_UpdateStmt:
-			tag = "UPDATE";
+			tag = COMMANDTAG_UPDATE;
 			break;
 
 		case T_SelectStmt:
-			tag = "SELECT";
+			tag = COMMANDTAG_SELECT;
 			break;
 
 			/* utility statements --- same whether raw or cooked */
@@ -2285,51 +2316,51 @@ CreateCommandTag(Node *parsetree)
 				switch (stmt->kind)
 				{
 					case TRANS_STMT_BEGIN:
-						tag = "BEGIN";
+						tag = COMMANDTAG_BEGIN;
 						break;
 
 					case TRANS_STMT_START:
-						tag = "START TRANSACTION";
+						tag = COMMANDTAG_START_TRANSACTION;
 						break;
 
 					case TRANS_STMT_COMMIT:
-						tag = "COMMIT";
+						tag = COMMANDTAG_COMMIT;
 						break;
 
 					case TRANS_STMT_ROLLBACK:
 					case TRANS_STMT_ROLLBACK_TO:
-						tag = "ROLLBACK";
+						tag = COMMANDTAG_ROLLBACK;
 						break;
 
 					case TRANS_STMT_SAVEPOINT:
-						tag = "SAVEPOINT";
+						tag = COMMANDTAG_SAVEPOINT;
 						break;
 
 					case TRANS_STMT_RELEASE:
-						tag = "RELEASE";
+						tag = COMMANDTAG_RELEASE;
 						break;
 
 					case TRANS_STMT_PREPARE:
-						tag = "PREPARE TRANSACTION";
+						tag = COMMANDTAG_PREPARE_TRANSACTION;
 						break;
 
 					case TRANS_STMT_COMMIT_PREPARED:
-						tag = "COMMIT PREPARED";
+						tag = COMMANDTAG_COMMIT_PREPARED;
 						break;
 
 					case TRANS_STMT_ROLLBACK_PREPARED:
-						tag = "ROLLBACK PREPARED";
+						tag = COMMANDTAG_ROLLBACK_PREPARED;
 						break;
 
 					default:
-						tag = "???";
+						tag = COMMANDTAG_UNKNOWN;
 						break;
 				}
 			}
 			break;
 
 		case T_DeclareCursorStmt:
-			tag = "DECLARE CURSOR";
+			tag = COMMANDTAG_DECLARE_CURSOR;
 			break;
 
 		case T_ClosePortalStmt:
@@ -2337,9 +2368,9 @@ CreateCommandTag(Node *parsetree)
 				ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree;
 
 				if (stmt->portalname == NULL)
-					tag = "CLOSE CURSOR ALL";
+					tag = COMMANDTAG_CLOSE_CURSOR_ALL;
 				else
-					tag = "CLOSE CURSOR";
+					tag = COMMANDTAG_CLOSE_CURSOR;
 			}
 			break;
 
@@ -2347,209 +2378,209 @@ CreateCommandTag(Node *parsetree)
 			{
 				FetchStmt  *stmt = (FetchStmt *) parsetree;
 
-				tag = (stmt->ismove) ? "MOVE" : "FETCH";
+				tag = (stmt->ismove) ? COMMANDTAG_MOVE : COMMANDTAG_FETCH;
 			}
 			break;
 
 		case T_CreateDomainStmt:
-			tag = "CREATE DOMAIN";
+			tag = COMMANDTAG_CREATE_DOMAIN;
 			break;
 
 		case T_CreateSchemaStmt:
-			tag = "CREATE SCHEMA";
+			tag = COMMANDTAG_CREATE_SCHEMA;
 			break;
 
 		case T_CreateStmt:
-			tag = "CREATE TABLE";
+			tag = COMMANDTAG_CREATE_TABLE;
 			break;
 
 		case T_CreateTableSpaceStmt:
-			tag = "CREATE TABLESPACE";
+			tag = COMMANDTAG_CREATE_TABLESPACE;
 			break;
 
 		case T_DropTableSpaceStmt:
-			tag = "DROP TABLESPACE";
+			tag = COMMANDTAG_DROP_TABLESPACE;
 			break;
 
 		case T_AlterTableSpaceOptionsStmt:
-			tag = "ALTER TABLESPACE";
+			tag = COMMANDTAG_ALTER_TABLESPACE;
 			break;
 
 		case T_CreateExtensionStmt:
-			tag = "CREATE EXTENSION";
+			tag = COMMANDTAG_CREATE_EXTENSION;
 			break;
 
 		case T_AlterExtensionStmt:
-			tag = "ALTER EXTENSION";
+			tag = COMMANDTAG_ALTER_EXTENSION;
 			break;
 
 		case T_AlterExtensionContentsStmt:
-			tag = "ALTER EXTENSION";
+			tag = COMMANDTAG_ALTER_EXTENSION;
 			break;
 
 		case T_CreateFdwStmt:
-			tag = "CREATE FOREIGN DATA WRAPPER";
+			tag = COMMANDTAG_CREATE_FOREIGN_DATA_WRAPPER;
 			break;
 
 		case T_AlterFdwStmt:
-			tag = "ALTER FOREIGN DATA WRAPPER";
+			tag = COMMANDTAG_ALTER_FOREIGN_DATA_WRAPPER;
 			break;
 
 		case T_CreateForeignServerStmt:
-			tag = "CREATE SERVER";
+			tag = COMMANDTAG_CREATE_SERVER;
 			break;
 
 		case T_AlterForeignServerStmt:
-			tag = "ALTER SERVER";
+			tag = COMMANDTAG_ALTER_SERVER;
 			break;
 
 		case T_CreateUserMappingStmt:
-			tag = "CREATE USER MAPPING";
+			tag = COMMANDTAG_CREATE_USER_MAPPING;
 			break;
 
 		case T_AlterUserMappingStmt:
-			tag = "ALTER USER MAPPING";
+			tag = COMMANDTAG_ALTER_USER_MAPPING;
 			break;
 
 		case T_DropUserMappingStmt:
-			tag = "DROP USER MAPPING";
+			tag = COMMANDTAG_DROP_USER_MAPPING;
 			break;
 
 		case T_CreateForeignTableStmt:
-			tag = "CREATE FOREIGN TABLE";
+			tag = COMMANDTAG_CREATE_FOREIGN_TABLE;
 			break;
 
 		case T_ImportForeignSchemaStmt:
-			tag = "IMPORT FOREIGN SCHEMA";
+			tag = COMMANDTAG_IMPORT_FOREIGN_SCHEMA;
 			break;
 
 		case T_DropStmt:
 			switch (((DropStmt *) parsetree)->removeType)
 			{
 				case OBJECT_TABLE:
-					tag = "DROP TABLE";
+					tag = COMMANDTAG_DROP_TABLE;
 					break;
 				case OBJECT_SEQUENCE:
-					tag = "DROP SEQUENCE";
+					tag = COMMANDTAG_DROP_SEQUENCE;
 					break;
 				case OBJECT_VIEW:
-					tag = "DROP VIEW";
+					tag = COMMANDTAG_DROP_VIEW;
 					break;
 				case OBJECT_MATVIEW:
-					tag = "DROP MATERIALIZED VIEW";
+					tag = COMMANDTAG_DROP_MATERIALIZED_VIEW;
 					break;
 				case OBJECT_INDEX:
-					tag = "DROP INDEX";
+					tag = COMMANDTAG_DROP_INDEX;
 					break;
 				case OBJECT_TYPE:
-					tag = "DROP TYPE";
+					tag = COMMANDTAG_DROP_TYPE;
 					break;
 				case OBJECT_DOMAIN:
-					tag = "DROP DOMAIN";
+					tag = COMMANDTAG_DROP_DOMAIN;
 					break;
 				case OBJECT_COLLATION:
-					tag = "DROP COLLATION";
+					tag = COMMANDTAG_DROP_COLLATION;
 					break;
 				case OBJECT_CONVERSION:
-					tag = "DROP CONVERSION";
+					tag = COMMANDTAG_DROP_CONVERSION;
 					break;
 				case OBJECT_SCHEMA:
-					tag = "DROP SCHEMA";
+					tag = COMMANDTAG_DROP_SCHEMA;
 					break;
 				case OBJECT_TSPARSER:
-					tag = "DROP TEXT SEARCH PARSER";
+					tag = COMMANDTAG_DROP_TEXT_SEARCH_PARSER;
 					break;
 				case OBJECT_TSDICTIONARY:
-					tag = "DROP TEXT SEARCH DICTIONARY";
+					tag = COMMANDTAG_DROP_TEXT_SEARCH_DICTIONARY;
 					break;
 				case OBJECT_TSTEMPLATE:
-					tag = "DROP TEXT SEARCH TEMPLATE";
+					tag = COMMANDTAG_DROP_TEXT_SEARCH_TEMPLATE;
 					break;
 				case OBJECT_TSCONFIGURATION:
-					tag = "DROP TEXT SEARCH CONFIGURATION";
+					tag = COMMANDTAG_DROP_TEXT_SEARCH_CONFIGURATION;
 					break;
 				case OBJECT_FOREIGN_TABLE:
-					tag = "DROP FOREIGN TABLE";
+					tag = COMMANDTAG_DROP_FOREIGN_TABLE;
 					break;
 				case OBJECT_EXTENSION:
-					tag = "DROP EXTENSION";
+					tag = COMMANDTAG_DROP_EXTENSION;
 					break;
 				case OBJECT_FUNCTION:
-					tag = "DROP FUNCTION";
+					tag = COMMANDTAG_DROP_FUNCTION;
 					break;
 				case OBJECT_PROCEDURE:
-					tag = "DROP PROCEDURE";
+					tag = COMMANDTAG_DROP_PROCEDURE;
 					break;
 				case OBJECT_ROUTINE:
-					tag = "DROP ROUTINE";
+					tag = COMMANDTAG_DROP_ROUTINE;
 					break;
 				case OBJECT_AGGREGATE:
-					tag = "DROP AGGREGATE";
+					tag = COMMANDTAG_DROP_AGGREGATE;
 					break;
 				case OBJECT_OPERATOR:
-					tag = "DROP OPERATOR";
+					tag = COMMANDTAG_DROP_OPERATOR;
 					break;
 				case OBJECT_LANGUAGE:
-					tag = "DROP LANGUAGE";
+					tag = COMMANDTAG_DROP_LANGUAGE;
 					break;
 				case OBJECT_CAST:
-					tag = "DROP CAST";
+					tag = COMMANDTAG_DROP_CAST;
 					break;
 				case OBJECT_TRIGGER:
-					tag = "DROP TRIGGER";
+					tag = COMMANDTAG_DROP_TRIGGER;
 					break;
 				case OBJECT_EVENT_TRIGGER:
-					tag = "DROP EVENT TRIGGER";
+					tag = COMMANDTAG_DROP_EVENT_TRIGGER;
 					break;
 				case OBJECT_RULE:
-					tag = "DROP RULE";
+					tag = COMMANDTAG_DROP_RULE;
 					break;
 				case OBJECT_FDW:
-					tag = "DROP FOREIGN DATA WRAPPER";
+					tag = COMMANDTAG_DROP_FOREIGN_DATA_WRAPPER;
 					break;
 				case OBJECT_FOREIGN_SERVER:
-					tag = "DROP SERVER";
+					tag = COMMANDTAG_DROP_SERVER;
 					break;
 				case OBJECT_OPCLASS:
-					tag = "DROP OPERATOR CLASS";
+					tag = COMMANDTAG_DROP_OPERATOR_CLASS;
 					break;
 				case OBJECT_OPFAMILY:
-					tag = "DROP OPERATOR FAMILY";
+					tag = COMMANDTAG_DROP_OPERATOR_FAMILY;
 					break;
 				case OBJECT_POLICY:
-					tag = "DROP POLICY";
+					tag = COMMANDTAG_DROP_POLICY;
 					break;
 				case OBJECT_TRANSFORM:
-					tag = "DROP TRANSFORM";
+					tag = COMMANDTAG_DROP_TRANSFORM;
 					break;
 				case OBJECT_ACCESS_METHOD:
-					tag = "DROP ACCESS METHOD";
+					tag = COMMANDTAG_DROP_ACCESS_METHOD;
 					break;
 				case OBJECT_PUBLICATION:
-					tag = "DROP PUBLICATION";
+					tag = COMMANDTAG_DROP_PUBLICATION;
 					break;
 				case OBJECT_STATISTIC_EXT:
-					tag = "DROP STATISTICS";
+					tag = COMMANDTAG_DROP_STATISTICS;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
 		case T_TruncateStmt:
-			tag = "TRUNCATE TABLE";
+			tag = COMMANDTAG_TRUNCATE_TABLE;
 			break;
 
 		case T_CommentStmt:
-			tag = "COMMENT";
+			tag = COMMANDTAG_COMMENT;
 			break;
 
 		case T_SecLabelStmt:
-			tag = "SECURITY LABEL";
+			tag = COMMANDTAG_SECURITY_LABEL;
 			break;
 
 		case T_CopyStmt:
-			tag = "COPY";
+			tag = COMMANDTAG_COPY;
 			break;
 
 		case T_RenameStmt:
@@ -2584,23 +2615,23 @@ CreateCommandTag(Node *parsetree)
 			break;
 
 		case T_AlterDomainStmt:
-			tag = "ALTER DOMAIN";
+			tag = COMMANDTAG_ALTER_DOMAIN;
 			break;
 
 		case T_AlterFunctionStmt:
 			switch (((AlterFunctionStmt *) parsetree)->objtype)
 			{
 				case OBJECT_FUNCTION:
-					tag = "ALTER FUNCTION";
+					tag = COMMANDTAG_ALTER_FUNCTION;
 					break;
 				case OBJECT_PROCEDURE:
-					tag = "ALTER PROCEDURE";
+					tag = COMMANDTAG_ALTER_PROCEDURE;
 					break;
 				case OBJECT_ROUTINE:
-					tag = "ALTER ROUTINE";
+					tag = COMMANDTAG_ALTER_ROUTINE;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
@@ -2608,7 +2639,7 @@ CreateCommandTag(Node *parsetree)
 			{
 				GrantStmt  *stmt = (GrantStmt *) parsetree;
 
-				tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
+				tag = (stmt->is_grant) ? COMMANDTAG_GRANT : COMMANDTAG_REVOKE;
 			}
 			break;
 
@@ -2616,145 +2647,145 @@ CreateCommandTag(Node *parsetree)
 			{
 				GrantRoleStmt *stmt = (GrantRoleStmt *) parsetree;
 
-				tag = (stmt->is_grant) ? "GRANT ROLE" : "REVOKE ROLE";
+				tag = (stmt->is_grant) ? COMMANDTAG_GRANT_ROLE : COMMANDTAG_REVOKE_ROLE;
 			}
 			break;
 
 		case T_AlterDefaultPrivilegesStmt:
-			tag = "ALTER DEFAULT PRIVILEGES";
+			tag = COMMANDTAG_ALTER_DEFAULT_PRIVILEGES;
 			break;
 
 		case T_DefineStmt:
 			switch (((DefineStmt *) parsetree)->kind)
 			{
 				case OBJECT_AGGREGATE:
-					tag = "CREATE AGGREGATE";
+					tag = COMMANDTAG_CREATE_AGGREGATE;
 					break;
 				case OBJECT_OPERATOR:
-					tag = "CREATE OPERATOR";
+					tag = COMMANDTAG_CREATE_OPERATOR;
 					break;
 				case OBJECT_TYPE:
-					tag = "CREATE TYPE";
+					tag = COMMANDTAG_CREATE_TYPE;
 					break;
 				case OBJECT_TSPARSER:
-					tag = "CREATE TEXT SEARCH PARSER";
+					tag = COMMANDTAG_CREATE_TEXT_SEARCH_PARSER;
 					break;
 				case OBJECT_TSDICTIONARY:
-					tag = "CREATE TEXT SEARCH DICTIONARY";
+					tag = COMMANDTAG_CREATE_TEXT_SEARCH_DICTIONARY;
 					break;
 				case OBJECT_TSTEMPLATE:
-					tag = "CREATE TEXT SEARCH TEMPLATE";
+					tag = COMMANDTAG_CREATE_TEXT_SEARCH_TEMPLATE;
 					break;
 				case OBJECT_TSCONFIGURATION:
-					tag = "CREATE TEXT SEARCH CONFIGURATION";
+					tag = COMMANDTAG_CREATE_TEXT_SEARCH_CONFIGURATION;
 					break;
 				case OBJECT_COLLATION:
-					tag = "CREATE COLLATION";
+					tag = COMMANDTAG_CREATE_COLLATION;
 					break;
 				case OBJECT_ACCESS_METHOD:
-					tag = "CREATE ACCESS METHOD";
+					tag = COMMANDTAG_CREATE_ACCESS_METHOD;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
 		case T_CompositeTypeStmt:
-			tag = "CREATE TYPE";
+			tag = COMMANDTAG_CREATE_TYPE;
 			break;
 
 		case T_CreateEnumStmt:
-			tag = "CREATE TYPE";
+			tag = COMMANDTAG_CREATE_TYPE;
 			break;
 
 		case T_CreateRangeStmt:
-			tag = "CREATE TYPE";
+			tag = COMMANDTAG_CREATE_TYPE;
 			break;
 
 		case T_AlterEnumStmt:
-			tag = "ALTER TYPE";
+			tag = COMMANDTAG_ALTER_TYPE;
 			break;
 
 		case T_ViewStmt:
-			tag = "CREATE VIEW";
+			tag = COMMANDTAG_CREATE_VIEW;
 			break;
 
 		case T_CreateFunctionStmt:
 			if (((CreateFunctionStmt *) parsetree)->is_procedure)
-				tag = "CREATE PROCEDURE";
+				tag = COMMANDTAG_CREATE_PROCEDURE;
 			else
-				tag = "CREATE FUNCTION";
+				tag = COMMANDTAG_CREATE_FUNCTION;
 			break;
 
 		case T_IndexStmt:
-			tag = "CREATE INDEX";
+			tag = COMMANDTAG_CREATE_INDEX;
 			break;
 
 		case T_RuleStmt:
-			tag = "CREATE RULE";
+			tag = COMMANDTAG_CREATE_RULE;
 			break;
 
 		case T_CreateSeqStmt:
-			tag = "CREATE SEQUENCE";
+			tag = COMMANDTAG_CREATE_SEQUENCE;
 			break;
 
 		case T_AlterSeqStmt:
-			tag = "ALTER SEQUENCE";
+			tag = COMMANDTAG_ALTER_SEQUENCE;
 			break;
 
 		case T_DoStmt:
-			tag = "DO";
+			tag = COMMANDTAG_DO;
 			break;
 
 		case T_CreatedbStmt:
-			tag = "CREATE DATABASE";
+			tag = COMMANDTAG_CREATE_DATABASE;
 			break;
 
 		case T_AlterDatabaseStmt:
-			tag = "ALTER DATABASE";
+			tag = COMMANDTAG_ALTER_DATABASE;
 			break;
 
 		case T_AlterDatabaseSetStmt:
-			tag = "ALTER DATABASE";
+			tag = COMMANDTAG_ALTER_DATABASE;
 			break;
 
 		case T_DropdbStmt:
-			tag = "DROP DATABASE";
+			tag = COMMANDTAG_DROP_DATABASE;
 			break;
 
 		case T_NotifyStmt:
-			tag = "NOTIFY";
+			tag = COMMANDTAG_NOTIFY;
 			break;
 
 		case T_ListenStmt:
-			tag = "LISTEN";
+			tag = COMMANDTAG_LISTEN;
 			break;
 
 		case T_UnlistenStmt:
-			tag = "UNLISTEN";
+			tag = COMMANDTAG_UNLISTEN;
 			break;
 
 		case T_LoadStmt:
-			tag = "LOAD";
+			tag = COMMANDTAG_LOAD;
 			break;
 
 		case T_CallStmt:
-			tag = "CALL";
+			tag = COMMANDTAG_CALL;
 			break;
 
 		case T_ClusterStmt:
-			tag = "CLUSTER";
+			tag = COMMANDTAG_CLUSTER;
 			break;
 
 		case T_VacuumStmt:
 			if (((VacuumStmt *) parsetree)->is_vacuumcmd)
-				tag = "VACUUM";
+				tag = COMMANDTAG_VACUUM;
 			else
-				tag = "ANALYZE";
+				tag = COMMANDTAG_ANALYZE;
 			break;
 
 		case T_ExplainStmt:
-			tag = "EXPLAIN";
+			tag = COMMANDTAG_EXPLAIN;
 			break;
 
 		case T_CreateTableAsStmt:
@@ -2762,24 +2793,24 @@ CreateCommandTag(Node *parsetree)
 			{
 				case OBJECT_TABLE:
 					if (((CreateTableAsStmt *) parsetree)->is_select_into)
-						tag = "SELECT INTO";
+						tag = COMMANDTAG_SELECT_INTO;
 					else
-						tag = "CREATE TABLE AS";
+						tag = COMMANDTAG_CREATE_TABLE_AS;
 					break;
 				case OBJECT_MATVIEW:
-					tag = "CREATE MATERIALIZED VIEW";
+					tag = COMMANDTAG_CREATE_MATERIALIZED_VIEW;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
 		case T_RefreshMatViewStmt:
-			tag = "REFRESH MATERIALIZED VIEW";
+			tag = COMMANDTAG_REFRESH_MATERIALIZED_VIEW;
 			break;
 
 		case T_AlterSystemStmt:
-			tag = "ALTER SYSTEM";
+			tag = COMMANDTAG_ALTER_SYSTEM;
 			break;
 
 		case T_VariableSetStmt:
@@ -2789,183 +2820,183 @@ CreateCommandTag(Node *parsetree)
 				case VAR_SET_CURRENT:
 				case VAR_SET_DEFAULT:
 				case VAR_SET_MULTI:
-					tag = "SET";
+					tag = COMMANDTAG_SET;
 					break;
 				case VAR_RESET:
 				case VAR_RESET_ALL:
-					tag = "RESET";
+					tag = COMMANDTAG_RESET;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
 		case T_VariableShowStmt:
-			tag = "SHOW";
+			tag = COMMANDTAG_SHOW;
 			break;
 
 		case T_DiscardStmt:
 			switch (((DiscardStmt *) parsetree)->target)
 			{
 				case DISCARD_ALL:
-					tag = "DISCARD ALL";
+					tag = COMMANDTAG_DISCARD_ALL;
 					break;
 				case DISCARD_PLANS:
-					tag = "DISCARD PLANS";
+					tag = COMMANDTAG_DISCARD_PLANS;
 					break;
 				case DISCARD_TEMP:
-					tag = "DISCARD TEMP";
+					tag = COMMANDTAG_DISCARD_TEMP;
 					break;
 				case DISCARD_SEQUENCES:
-					tag = "DISCARD SEQUENCES";
+					tag = COMMANDTAG_DISCARD_SEQUENCES;
 					break;
 				default:
-					tag = "???";
+					tag = COMMANDTAG_UNKNOWN;
 			}
 			break;
 
 		case T_CreateTransformStmt:
-			tag = "CREATE TRANSFORM";
+			tag = COMMANDTAG_CREATE_TRANSFORM;
 			break;
 
 		case T_CreateTrigStmt:
-			tag = "CREATE TRIGGER";
+			tag = COMMANDTAG_CREATE_TRIGGER;
 			break;
 
 		case T_CreateEventTrigStmt:
-			tag = "CREATE EVENT TRIGGER";
+			tag = COMMANDTAG_CREATE_EVENT_TRIGGER;
 			break;
 
 		case T_AlterEventTrigStmt:
-			tag = "ALTER EVENT TRIGGER";
+			tag = COMMANDTAG_ALTER_EVENT_TRIGGER;
 			break;
 
 		case T_CreatePLangStmt:
-			tag = "CREATE LANGUAGE";
+			tag = COMMANDTAG_CREATE_LANGUAGE;
 			break;
 
 		case T_CreateRoleStmt:
-			tag = "CREATE ROLE";
+			tag = COMMANDTAG_CREATE_ROLE;
 			break;
 
 		case T_AlterRoleStmt:
-			tag = "ALTER ROLE";
+			tag = COMMANDTAG_ALTER_ROLE;
 			break;
 
 		case T_AlterRoleSetStmt:
-			tag = "ALTER ROLE";
+			tag = COMMANDTAG_ALTER_ROLE;
 			break;
 
 		case T_DropRoleStmt:
-			tag = "DROP ROLE";
+			tag = COMMANDTAG_DROP_ROLE;
 			break;
 
 		case T_DropOwnedStmt:
-			tag = "DROP OWNED";
+			tag = COMMANDTAG_DROP_OWNED;
 			break;
 
 		case T_ReassignOwnedStmt:
-			tag = "REASSIGN OWNED";
+			tag = COMMANDTAG_REASSIGN_OWNED;
 			break;
 
 		case T_LockStmt:
-			tag = "LOCK TABLE";
+			tag = COMMANDTAG_LOCK_TABLE;
 			break;
 
 		case T_ConstraintsSetStmt:
-			tag = "SET CONSTRAINTS";
+			tag = COMMANDTAG_SET_CONSTRAINTS;
 			break;
 
 		case T_CheckPointStmt:
-			tag = "CHECKPOINT";
+			tag = COMMANDTAG_CHECKPOINT;
 			break;
 
 		case T_ReindexStmt:
-			tag = "REINDEX";
+			tag = COMMANDTAG_REINDEX;
 			break;
 
 		case T_CreateConversionStmt:
-			tag = "CREATE CONVERSION";
+			tag = COMMANDTAG_CREATE_CONVERSION;
 			break;
 
 		case T_CreateCastStmt:
-			tag = "CREATE CAST";
+			tag = COMMANDTAG_CREATE_CAST;
 			break;
 
 		case T_CreateOpClassStmt:
-			tag = "CREATE OPERATOR CLASS";
+			tag = COMMANDTAG_CREATE_OPERATOR_CLASS;
 			break;
 
 		case T_CreateOpFamilyStmt:
-			tag = "CREATE OPERATOR FAMILY";
+			tag = COMMANDTAG_CREATE_OPERATOR_FAMILY;
 			break;
 
 		case T_AlterOpFamilyStmt:
-			tag = "ALTER OPERATOR FAMILY";
+			tag = COMMANDTAG_ALTER_OPERATOR_FAMILY;
 			break;
 
 		case T_AlterOperatorStmt:
-			tag = "ALTER OPERATOR";
+			tag = COMMANDTAG_ALTER_OPERATOR;
 			break;
 
 		case T_AlterTSDictionaryStmt:
-			tag = "ALTER TEXT SEARCH DICTIONARY";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_DICTIONARY;
 			break;
 
 		case T_AlterTSConfigurationStmt:
-			tag = "ALTER TEXT SEARCH CONFIGURATION";
+			tag = COMMANDTAG_ALTER_TEXT_SEARCH_CONFIGURATION;
 			break;
 
 		case T_CreatePolicyStmt:
-			tag = "CREATE POLICY";
+			tag = COMMANDTAG_CREATE_POLICY;
 			break;
 
 		case T_AlterPolicyStmt:
-			tag = "ALTER POLICY";
+			tag = COMMANDTAG_ALTER_POLICY;
 			break;
 
 		case T_CreateAmStmt:
-			tag = "CREATE ACCESS METHOD";
+			tag = COMMANDTAG_CREATE_ACCESS_METHOD;
 			break;
 
 		case T_CreatePublicationStmt:
-			tag = "CREATE PUBLICATION";
+			tag = COMMANDTAG_CREATE_PUBLICATION;
 			break;
 
 		case T_AlterPublicationStmt:
-			tag = "ALTER PUBLICATION";
+			tag = COMMANDTAG_ALTER_PUBLICATION;
 			break;
 
 		case T_CreateSubscriptionStmt:
-			tag = "CREATE SUBSCRIPTION";
+			tag = COMMANDTAG_CREATE_SUBSCRIPTION;
 			break;
 
 		case T_AlterSubscriptionStmt:
-			tag = "ALTER SUBSCRIPTION";
+			tag = COMMANDTAG_ALTER_SUBSCRIPTION;
 			break;
 
 		case T_DropSubscriptionStmt:
-			tag = "DROP SUBSCRIPTION";
+			tag = COMMANDTAG_DROP_SUBSCRIPTION;
 			break;
 
 		case T_AlterCollationStmt:
-			tag = "ALTER COLLATION";
+			tag = COMMANDTAG_ALTER_COLLATION;
 			break;
 
 		case T_PrepareStmt:
-			tag = "PREPARE";
+			tag = COMMANDTAG_PREPARE;
 			break;
 
 		case T_ExecuteStmt:
-			tag = "EXECUTE";
+			tag = COMMANDTAG_EXECUTE;
 			break;
 
 		case T_CreateStatsStmt:
-			tag = "CREATE STATISTICS";
+			tag = COMMANDTAG_CREATE_STATISTICS;
 			break;
 
 		case T_AlterStatsStmt:
-			tag = "ALTER STATISTICS";
+			tag = COMMANDTAG_ALTER_STATISTICS;
 			break;
 
 		case T_DeallocateStmt:
@@ -2973,9 +3004,9 @@ CreateCommandTag(Node *parsetree)
 				DeallocateStmt *stmt = (DeallocateStmt *) parsetree;
 
 				if (stmt->name == NULL)
-					tag = "DEALLOCATE ALL";
+					tag = COMMANDTAG_DEALLOCATE_ALL;
 				else
-					tag = "DEALLOCATE";
+					tag = COMMANDTAG_DEALLOCATE;
 			}
 			break;
 
@@ -2999,33 +3030,33 @@ CreateCommandTag(Node *parsetree)
 							switch (((PlanRowMark *) linitial(stmt->rowMarks))->strength)
 							{
 								case LCS_FORKEYSHARE:
-									tag = "SELECT FOR KEY SHARE";
+									tag = COMMANDTAG_SELECT_FOR_KEY_SHARE;
 									break;
 								case LCS_FORSHARE:
-									tag = "SELECT FOR SHARE";
+									tag = COMMANDTAG_SELECT_FOR_SHARE;
 									break;
 								case LCS_FORNOKEYUPDATE:
-									tag = "SELECT FOR NO KEY UPDATE";
+									tag = COMMANDTAG_SELECT_FOR_NO_KEY_UPDATE;
 									break;
 								case LCS_FORUPDATE:
-									tag = "SELECT FOR UPDATE";
+									tag = COMMANDTAG_SELECT_FOR_UPDATE;
 									break;
 								default:
-									tag = "SELECT";
+									tag = COMMANDTAG_SELECT;
 									break;
 							}
 						}
 						else
-							tag = "SELECT";
+							tag = COMMANDTAG_SELECT;
 						break;
 					case CMD_UPDATE:
-						tag = "UPDATE";
+						tag = COMMANDTAG_UPDATE;
 						break;
 					case CMD_INSERT:
-						tag = "INSERT";
+						tag = COMMANDTAG_INSERT;
 						break;
 					case CMD_DELETE:
-						tag = "DELETE";
+						tag = COMMANDTAG_DELETE;
 						break;
 					case CMD_UTILITY:
 						tag = CreateCommandTag(stmt->utilityStmt);
@@ -3033,7 +3064,7 @@ CreateCommandTag(Node *parsetree)
 					default:
 						elog(WARNING, "unrecognized commandType: %d",
 							 (int) stmt->commandType);
-						tag = "???";
+						tag = COMMANDTAG_UNKNOWN;
 						break;
 				}
 			}
@@ -3059,33 +3090,33 @@ CreateCommandTag(Node *parsetree)
 							switch (((RowMarkClause *) linitial(stmt->rowMarks))->strength)
 							{
 								case LCS_FORKEYSHARE:
-									tag = "SELECT FOR KEY SHARE";
+									tag = COMMANDTAG_SELECT_FOR_KEY_SHARE;
 									break;
 								case LCS_FORSHARE:
-									tag = "SELECT FOR SHARE";
+									tag = COMMANDTAG_SELECT_FOR_SHARE;
 									break;
 								case LCS_FORNOKEYUPDATE:
-									tag = "SELECT FOR NO KEY UPDATE";
+									tag = COMMANDTAG_SELECT_FOR_NO_KEY_UPDATE;
 									break;
 								case LCS_FORUPDATE:
-									tag = "SELECT FOR UPDATE";
+									tag = COMMANDTAG_SELECT_FOR_UPDATE;
 									break;
 								default:
-									tag = "???";
+									tag = COMMANDTAG_UNKNOWN;
 									break;
 							}
 						}
 						else
-							tag = "SELECT";
+							tag = COMMANDTAG_SELECT;
 						break;
 					case CMD_UPDATE:
-						tag = "UPDATE";
+						tag = COMMANDTAG_UPDATE;
 						break;
 					case CMD_INSERT:
-						tag = "INSERT";
+						tag = COMMANDTAG_INSERT;
 						break;
 					case CMD_DELETE:
-						tag = "DELETE";
+						tag = COMMANDTAG_DELETE;
 						break;
 					case CMD_UTILITY:
 						tag = CreateCommandTag(stmt->utilityStmt);
@@ -3093,7 +3124,7 @@ CreateCommandTag(Node *parsetree)
 					default:
 						elog(WARNING, "unrecognized commandType: %d",
 							 (int) stmt->commandType);
-						tag = "???";
+						tag = COMMANDTAG_UNKNOWN;
 						break;
 				}
 			}
@@ -3102,7 +3133,7 @@ CreateCommandTag(Node *parsetree)
 		default:
 			elog(WARNING, "unrecognized node type: %d",
 				 (int) nodeTag(parsetree));
-			tag = "???";
+			tag = COMMANDTAG_UNKNOWN;
 			break;
 	}
 
diff --git a/src/backend/utils/adt/txid.c b/src/backend/utils/adt/txid.c
index 33272f8030..37e3cc70f8 100644
--- a/src/backend/utils/adt/txid.c
+++ b/src/backend/utils/adt/txid.c
@@ -425,7 +425,7 @@ txid_current(PG_FUNCTION_ARGS)
 	 * to always return a valid current xid, so we should not change this to
 	 * return NULL or similar invalid xid.
 	 */
-	PreventCommandDuringRecovery("txid_current()");
+	PreventCommandStrDuringRecovery("txid_current()");
 
 	load_xid_epoch(&state);
 
diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index c47be0ba4c..53401bd4e9 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -163,7 +163,7 @@ InitPlanCache(void)
 CachedPlanSource *
 CreateCachedPlan(RawStmt *raw_parse_tree,
 				 const char *query_string,
-				 const char *commandTag)
+				 CommandTag commandTag)
 {
 	CachedPlanSource *plansource;
 	MemoryContext source_context;
@@ -246,7 +246,7 @@ CreateCachedPlan(RawStmt *raw_parse_tree,
 CachedPlanSource *
 CreateOneShotCachedPlan(RawStmt *raw_parse_tree,
 						const char *query_string,
-						const char *commandTag)
+						CommandTag commandTag)
 {
 	CachedPlanSource *plansource;
 
diff --git a/src/backend/utils/misc/Makefile b/src/backend/utils/misc/Makefile
index 2397fc2453..e67b8ab4fe 100644
--- a/src/backend/utils/misc/Makefile
+++ b/src/backend/utils/misc/Makefile
@@ -15,6 +15,7 @@ include $(top_builddir)/src/Makefile.global
 override CPPFLAGS := -I. -I$(srcdir) $(CPPFLAGS)
 
 OBJS = \
+	commandtag.o \
 	guc.o \
 	help_config.o \
 	pg_config.o \
diff --git a/src/backend/utils/misc/commandtag.c b/src/backend/utils/misc/commandtag.c
new file mode 100644
index 0000000000..aac13fbe5e
--- /dev/null
+++ b/src/backend/utils/misc/commandtag.c
@@ -0,0 +1,320 @@
+/*-------------------------------------------------------------------------
+ *
+ * commandtag.c
+ *	  Data and routines for commandtag names and enumeration.
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *	  src/backend/utils/misc/commandtag.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include "c.h"
+#include "utils/commandtag.h"
+
+static const char * tag_names[] = {
+	"???",
+	"ALTER ACCESS METHOD",
+	"ALTER AGGREGATE",
+	"ALTER CAST",
+	"ALTER COLLATION",
+	"ALTER CONSTRAINT",
+	"ALTER CONVERSION",
+	"ALTER DATABASE",
+	"ALTER DEFAULT PRIVILEGES",
+	"ALTER DOMAIN",
+	"ALTER EVENT TRIGGER",
+	"ALTER EXTENSION",
+	"ALTER FOREIGN DATA WRAPPER",
+	"ALTER FOREIGN TABLE",
+	"ALTER FUNCTION",
+	"ALTER INDEX",
+	"ALTER LANGUAGE",
+	"ALTER LARGE OBJECT",
+	"ALTER MATERIALIZED VIEW",
+	"ALTER OPERATOR",
+	"ALTER OPERATOR CLASS",
+	"ALTER OPERATOR FAMILY",
+	"ALTER POLICY",
+	"ALTER PROCEDURE",
+	"ALTER PUBLICATION",
+	"ALTER ROLE",
+	"ALTER ROUTINE",
+	"ALTER RULE",
+	"ALTER SCHEMA",
+	"ALTER SEQUENCE",
+	"ALTER SERVER",
+	"ALTER STATISTICS",
+	"ALTER SUBSCRIPTION",
+	"ALTER SYSTEM",
+	"ALTER TABLE",
+	"ALTER TABLESPACE",
+	"ALTER TEXT SEARCH CONFIGURATION",
+	"ALTER TEXT SEARCH DICTIONARY",
+	"ALTER TEXT SEARCH PARSER",
+	"ALTER TEXT SEARCH TEMPLATE",
+	"ALTER TRANSFORM",
+	"ALTER TRIGGER",
+	"ALTER TYPE",
+	"ALTER USER MAPPING",
+	"ALTER VIEW",
+	"ANALYZE",
+	"BEGIN",
+	"CALL",
+	"CHECKPOINT",
+	"CLOSE",
+	"CLOSE CURSOR",
+	"CLOSE CURSOR ALL",
+	"CLUSTER",
+	"COMMENT",
+	"COMMIT",
+	"COMMIT PREPARED",
+	"COPY",
+	"COPY FROM",
+	"CREATE ACCESS METHOD",
+	"CREATE AGGREGATE",
+	"CREATE CAST",
+	"CREATE COLLATION",
+	"CREATE CONSTRAINT",
+	"CREATE CONVERSION",
+	"CREATE DATABASE",
+	"CREATE DOMAIN",
+	"CREATE EVENT TRIGGER",
+	"CREATE EXTENSION",
+	"CREATE FOREIGN DATA WRAPPER",
+	"CREATE FOREIGN TABLE",
+	"CREATE FUNCTION",
+	"CREATE INDEX",
+	"CREATE LANGUAGE",
+	"CREATE MATERIALIZED VIEW",
+	"CREATE OPERATOR",
+	"CREATE OPERATOR CLASS",
+	"CREATE OPERATOR FAMILY",
+	"CREATE POLICY",
+	"CREATE PROCEDURE",
+	"CREATE PUBLICATION",
+	"CREATE ROLE",
+	"CREATE ROUTINE",
+	"CREATE RULE",
+	"CREATE SCHEMA",
+	"CREATE SEQUENCE",
+	"CREATE SERVER",
+	"CREATE STATISTICS",
+	"CREATE SUBSCRIPTION",
+	"CREATE TABLE",
+	"CREATE TABLE AS",
+	"CREATE TABLESPACE",
+	"CREATE TEXT SEARCH CONFIGURATION",
+	"CREATE TEXT SEARCH DICTIONARY",
+	"CREATE TEXT SEARCH PARSER",
+	"CREATE TEXT SEARCH TEMPLATE",
+	"CREATE TRANSFORM",
+	"CREATE TRIGGER",
+	"CREATE TYPE",
+	"CREATE USER MAPPING",
+	"CREATE VIEW",
+	"DEALLOCATE",
+	"DEALLOCATE ALL",
+	"DECLARE CURSOR",
+	"DELETE",
+	"DISCARD",
+	"DISCARD ALL",
+	"DISCARD PLANS",
+	"DISCARD SEQUENCES",
+	"DISCARD TEMP",
+	"DO",
+	"DROP ACCESS METHOD",
+	"DROP AGGREGATE",
+	"DROP CAST",
+	"DROP COLLATION",
+	"DROP CONSTRAINT",
+	"DROP CONVERSION",
+	"DROP DATABASE",
+	"DROP DOMAIN",
+	"DROP EVENT TRIGGER",
+	"DROP EXTENSION",
+	"DROP FOREIGN DATA WRAPPER",
+	"DROP FOREIGN TABLE",
+	"DROP FUNCTION",
+	"DROP INDEX",
+	"DROP LANGUAGE",
+	"DROP MATERIALIZED VIEW",
+	"DROP OPERATOR",
+	"DROP OPERATOR CLASS",
+	"DROP OPERATOR FAMILY",
+	"DROP OWNED",
+	"DROP POLICY",
+	"DROP PROCEDURE",
+	"DROP PUBLICATION",
+	"DROP REPLICATION SLOT",
+	"DROP ROLE",
+	"DROP ROUTINE",
+	"DROP RULE",
+	"DROP SCHEMA",
+	"DROP SEQUENCE",
+	"DROP SERVER",
+	"DROP STATISTICS",
+	"DROP SUBSCRIPTION",
+	"DROP TABLE",
+	"DROP TABLESPACE",
+	"DROP TEXT SEARCH CONFIGURATION",
+	"DROP TEXT SEARCH DICTIONARY",
+	"DROP TEXT SEARCH PARSER",
+	"DROP TEXT SEARCH TEMPLATE",
+	"DROP TRANSFORM",
+	"DROP TRIGGER",
+	"DROP TYPE",
+	"DROP USER MAPPING",
+	"DROP VIEW",
+	"EXECUTE",
+	"EXPLAIN",
+	"FETCH",
+	"GRANT",
+	"GRANT ROLE",
+	"IMPORT FOREIGN SCHEMA",
+	"INSERT",
+	"LISTEN",
+	"LOAD",
+	"LOCK TABLE",
+	"MOVE",
+	"NOTIFY",
+	"PREPARE",
+	"PREPARE TRANSACTION",
+	"REASSIGN OWNED",
+	"REFRESH MATERIALIZED VIEW",
+	"REINDEX",
+	"RELEASE",
+	"RESET",
+	"REVOKE",
+	"REVOKE ROLE",
+	"ROLLBACK",
+	"ROLLBACK PREPARED",
+	"SAVEPOINT",
+	"SECURITY LABEL",
+	"SELECT",
+	"SELECT FOR KEY SHARE",
+	"SELECT FOR NO KEY UPDATE",
+	"SELECT FOR SHARE",
+	"SELECT FOR UPDATE",
+	"SELECT INTO",
+	"SET",
+	"SET CONSTRAINTS",
+	"SHOW",
+	"START TRANSACTION",
+	"TRUNCATE TABLE",
+	"UNLISTEN",
+	"UPDATE",
+	"VACUUM"
+};
+
+#ifdef COMMANDTAG_CHECKING
+static bool CheckCommandTagEnum(void);
+#endif
+
+static const unsigned int tag_name_length = lengthof(tag_names);
+
+#ifdef COMMANDTAG_CHECKING
+static bool commandtags_have_been_checked = false;
+static inline void
+OPTIONALLY_CHECK_COMMAND_TAGS()
+{
+	if (!commandtags_have_been_checked)
+	{
+		Assert(CheckCommandTagEnum());
+		commandtags_have_been_checked = true;
+	}
+}
+#else
+#define OPTIONALLY_CHECK_COMMAND_TAGS()
+#endif
+
+/*
+ * Search CommandTag by name
+ *
+ * Returns CommandTag, or COMMANDTAG_UNKNOWN if not recognized
+ */
+CommandTag
+GetCommandTagEnum(const char *commandname)
+{
+	const char **base, **last, **position;
+	int		 result;
+
+	OPTIONALLY_CHECK_COMMAND_TAGS();
+	if (commandname == NULL || *commandname == '\0')
+		return COMMANDTAG_UNKNOWN;
+
+	base = tag_names;
+	last = tag_names + tag_name_length - 1;
+	while (last >= base)
+	{
+		position = base + ((last - base) >> 1);
+		result = pg_strcasecmp(commandname, *position);
+		if (result == 0)
+			return (CommandTag) (position - tag_names);
+		else if (result < 0)
+			last = position - 1;
+		else
+			base = position + 1;
+	}
+	return COMMANDTAG_UNKNOWN;
+}
+
+const char *
+GetCommandTagName(CommandTag commandTag)
+{
+	OPTIONALLY_CHECK_COMMAND_TAGS();
+	if (PG_VALID_COMMANDTAG(commandTag))
+		return tag_names[commandTag];
+	return "???";
+}
+
+#ifdef COMMANDTAG_CHECKING
+bool
+CheckCommandTagEnum()
+{
+	CommandTag	i, j;
+
+	if (FIRST_COMMAND_TAG < 0 || LAST_COMMAND_TAG < 0 || LAST_COMMAND_TAG < FIRST_COMMAND_TAG)
+	{
+		elog(ERROR, "FIRST_COMMAND_TAG (%u), LAST_COMMAND_TAG (%u) not reasonable",
+			 (unsigned int) FIRST_COMMAND_TAG, (unsigned int) LAST_COMMAND_TAG);
+		return false;
+	}
+	if (FIRST_COMMAND_TAG != (CommandTag)0)
+	{
+		elog(ERROR, "FIRST_COMMAND_TAG (%u) != 0", (unsigned int) FIRST_COMMAND_TAG);
+		return false;
+	}
+	if (LAST_COMMAND_TAG != (CommandTag)(tag_name_length - 1))
+	{
+		elog(ERROR, "LAST_COMMAND_TAG (%u) != tag_name_length (%u)",
+			 (unsigned int) LAST_COMMAND_TAG, (unsigned int) tag_name_length);
+		return false;
+	}
+
+	for (i = FIRST_COMMAND_TAG; i < LAST_COMMAND_TAG; i++)
+	{
+		for (j = i+1; j < LAST_COMMAND_TAG; j++)
+		{
+			int cmp = strcmp(tag_names[i], tag_names[j]);
+			if (cmp == 0)
+			{
+				elog(ERROR, "Found duplicate tag_name: \"%s\"",
+					tag_names[i]);
+				return false;
+			}
+			if (cmp > 0)
+			{
+				elog(ERROR, "Found commandnames out of order: \"%s\" before \"%s\"",
+					tag_names[i], tag_names[j]);
+				return false;
+			}
+		}
+	}
+	return true;
+}
+#endif
diff --git a/src/backend/utils/mmgr/portalmem.c b/src/backend/utils/mmgr/portalmem.c
index b675575c31..b6328a049b 100644
--- a/src/backend/utils/mmgr/portalmem.c
+++ b/src/backend/utils/mmgr/portalmem.c
@@ -281,7 +281,7 @@ void
 PortalDefineQuery(Portal portal,
 				  const char *prepStmtName,
 				  const char *sourceText,
-				  const char *commandTag,
+				  CommandTag commandTag,
 				  List *stmts,
 				  CachedPlan *cplan)
 {
@@ -289,10 +289,13 @@ PortalDefineQuery(Portal portal,
 	AssertState(portal->status == PORTAL_NEW);
 
 	AssertArg(sourceText != NULL);
-	AssertArg(commandTag != NULL || stmts == NIL);
+	AssertArg(commandTag != COMMANDTAG_UNKNOWN || stmts == NIL);
 
 	portal->prepStmtName = prepStmtName;
 	portal->sourceText = sourceText;
+	portal->qcdata.commandTag = commandTag;
+	portal->qcdata.nprocessed = 0;
+	portal->qcdata.display_format = DISPLAYFORMAT_PLAIN;
 	portal->commandTag = commandTag;
 	portal->stmts = stmts;
 	portal->cplan = cplan;
diff --git a/src/include/commands/createas.h b/src/include/commands/createas.h
index 7743851a38..6e6bb8e567 100644
--- a/src/include/commands/createas.h
+++ b/src/include/commands/createas.h
@@ -22,7 +22,7 @@
 
 
 extern ObjectAddress ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt,
-									   ParamListInfo params, QueryEnvironment *queryEnv, char *completionTag);
+									   ParamListInfo params, QueryEnvironment *queryEnv, QueryCompletionData *qc);
 
 extern int	GetIntoRelEFlags(IntoClause *intoClause);
 
diff --git a/src/include/commands/matview.h b/src/include/commands/matview.h
index 6bdb7ca258..12147a8339 100644
--- a/src/include/commands/matview.h
+++ b/src/include/commands/matview.h
@@ -24,7 +24,7 @@
 extern void SetMatViewPopulatedState(Relation relation, bool newstate);
 
 extern ObjectAddress ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
-										ParamListInfo params, char *completionTag);
+										ParamListInfo params, QueryCompletionData *qc);
 
 extern DestReceiver *CreateTransientRelDestReceiver(Oid oid);
 
diff --git a/src/include/commands/portalcmds.h b/src/include/commands/portalcmds.h
index 4ecc1a2ecd..667cae0a7a 100644
--- a/src/include/commands/portalcmds.h
+++ b/src/include/commands/portalcmds.h
@@ -23,7 +23,7 @@ extern void PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, Para
 							  bool isTopLevel);
 
 extern void PerformPortalFetch(FetchStmt *stmt, DestReceiver *dest,
-							   char *completionTag);
+							   QueryCompletionData *qc);
 
 extern void PerformPortalClose(const char *name);
 
diff --git a/src/include/commands/prepare.h b/src/include/commands/prepare.h
index a0509e1f33..b1ea4e837a 100644
--- a/src/include/commands/prepare.h
+++ b/src/include/commands/prepare.h
@@ -40,7 +40,7 @@ extern void PrepareQuery(ParseState *pstate, PrepareStmt *stmt,
 extern void ExecuteQuery(ParseState *pstate,
 						 ExecuteStmt *stmt, IntoClause *intoClause,
 						 ParamListInfo params,
-						 DestReceiver *dest, char *completionTag);
+						 DestReceiver *dest, QueryCompletionData *qc);
 extern void DeallocateQuery(DeallocateStmt *stmt);
 extern void ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into,
 								ExplainState *es, const char *queryString,
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 62d64aa0a1..afaf098be3 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -27,6 +27,7 @@
 
 #include "datatype/timestamp.h" /* for TimestampTz */
 #include "pgtime.h"				/* for pg_time_t */
+#include "utils/commandtag.h"	/* for CommandTag enum */
 
 
 #define InvalidPid				(-1)
@@ -280,9 +281,12 @@ extern void check_stack_depth(void);
 extern bool stack_is_too_deep(void);
 
 /* in tcop/utility.c */
-extern void PreventCommandIfReadOnly(const char *cmdname);
-extern void PreventCommandIfParallelMode(const char *cmdname);
-extern void PreventCommandDuringRecovery(const char *cmdname);
+extern void PreventCommandStrIfReadOnly(const char *commandstr);
+extern void PreventCommandStrIfParallelMode(const char *commandstr);
+extern void PreventCommandStrDuringRecovery(const char *commandstr);
+extern void PreventCommandIfReadOnly(CommandTag commandTag);
+extern void PreventCommandIfParallelMode(CommandTag commandTag);
+extern void PreventCommandDuringRecovery(CommandTag commandTag);
 
 /* in utils/misc/guc.c */
 extern int	trace_recovery_messages;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index da0706add5..2c3ae6b603 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -27,6 +27,7 @@
 #include "nodes/primnodes.h"
 #include "nodes/value.h"
 #include "partitioning/partdefs.h"
+#include "utils/commandtag.h"
 
 
 typedef enum OverridingKind
diff --git a/src/include/tcop/dest.h b/src/include/tcop/dest.h
index 35bce731a1..29bf9fbd2a 100644
--- a/src/include/tcop/dest.h
+++ b/src/include/tcop/dest.h
@@ -68,6 +68,8 @@
 #define DEST_H
 
 #include "executor/tuptable.h"
+#include "utils/commandtag.h"
+#include "utils/querycompletion.h"
 
 
 /* buffer size to use for command completion tags */
@@ -134,9 +136,9 @@ extern PGDLLIMPORT DestReceiver *None_Receiver; /* permanent receiver for
 
 /* The primary destination management functions */
 
-extern void BeginCommand(const char *commandTag, CommandDest dest);
+extern void BeginCommand(CommandTag commandTag, CommandDest dest);
 extern DestReceiver *CreateDestReceiver(CommandDest dest);
-extern void EndCommand(const char *commandTag, CommandDest dest);
+extern void EndCommand(const QueryCompletionData *qc, CommandDest dest);
 
 /* Additional functions that go with destination management, more or less. */
 
diff --git a/src/include/tcop/pquery.h b/src/include/tcop/pquery.h
index 4ad6324e2d..457ba3f415 100644
--- a/src/include/tcop/pquery.h
+++ b/src/include/tcop/pquery.h
@@ -35,7 +35,7 @@ extern void PortalSetResultFormat(Portal portal, int nFormats,
 
 extern bool PortalRun(Portal portal, long count, bool isTopLevel,
 					  bool run_once, DestReceiver *dest, DestReceiver *altdest,
-					  char *completionTag);
+					  QueryCompletionData *qc);
 
 extern uint64 PortalRunFetch(Portal portal,
 							 FetchDirection fdirection,
diff --git a/src/include/tcop/utility.h b/src/include/tcop/utility.h
index a551e08cb8..90d28949d0 100644
--- a/src/include/tcop/utility.h
+++ b/src/include/tcop/utility.h
@@ -15,6 +15,7 @@
 #define UTILITY_H
 
 #include "tcop/tcopprot.h"
+#include "utils/querycompletion.h"
 
 typedef enum
 {
@@ -71,17 +72,17 @@ typedef void (*ProcessUtility_hook_type) (PlannedStmt *pstmt,
 										  const char *queryString, ProcessUtilityContext context,
 										  ParamListInfo params,
 										  QueryEnvironment *queryEnv,
-										  DestReceiver *dest, char *completionTag);
+										  DestReceiver *dest, QueryCompletionData *qc);
 extern PGDLLIMPORT ProcessUtility_hook_type ProcessUtility_hook;
 
 extern void ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 						   ProcessUtilityContext context, ParamListInfo params,
 						   QueryEnvironment *queryEnv,
-						   DestReceiver *dest, char *completionTag);
+						   DestReceiver *dest, QueryCompletionData *qc);
 extern void standard_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
 									ProcessUtilityContext context, ParamListInfo params,
 									QueryEnvironment *queryEnv,
-									DestReceiver *dest, char *completionTag);
+									DestReceiver *dest, QueryCompletionData *qc);
 
 extern void ProcessUtilityForAlterTable(Node *stmt,
 										AlterTableUtilityContext *context);
@@ -92,7 +93,7 @@ extern TupleDesc UtilityTupleDescriptor(Node *parsetree);
 
 extern Query *UtilityContainsQuery(Node *parsetree);
 
-extern const char *CreateCommandTag(Node *parsetree);
+extern CommandTag CreateCommandTag(Node *parsetree);
 
 extern LogStmtLevel GetCommandLogLevel(Node *parsetree);
 
diff --git a/src/include/utils/commandtag.h b/src/include/utils/commandtag.h
new file mode 100644
index 0000000000..ab69c92d0a
--- /dev/null
+++ b/src/include/utils/commandtag.h
@@ -0,0 +1,248 @@
+/*-------------------------------------------------------------------------
+ *
+ * commandtag.h
+ *	  Declarations for commandtag names and enumeration.
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/commandtag.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef COMMANDTAG_H
+#define COMMANDTAG_H
+
+/*
+ * BEWARE: These are in sorted order, but ordered by their printed
+ *         values in the tag_name list (see common/commandtag.c).
+ *         In particular it matters because the sort ordering changes
+ *         when you replace a space with an underscore.  To wit:
+ *
+ *             "CREATE TABLE"
+ *             "CREATE TABLE AS"
+ *             "CREATE TABLESPACE"
+ *
+ *         but...
+ *
+ *             CREATE_TABLE
+ *             CREATE_TABLESPACE
+ *             CREATE_TABLE_AS
+ *
+ *         It also matters that COMMANDTAG_UNKNOWN is written "???".
+ *
+ * If you add a value here, add it in common/commandtag.c also, and
+ * be careful to get the ordering right.  You can build with
+ * COMMANDTAG_CHECKING to have this automatically checked
+ * at runtime, but that adds considerable overhead, so do so sparingly.
+ */
+typedef enum CommandTag
+{
+#define FIRST_COMMAND_TAG COMMANDTAG_UNKNOWN
+	COMMANDTAG_UNKNOWN,
+	COMMANDTAG_ALTER_ACCESS_METHOD,
+	COMMANDTAG_ALTER_AGGREGATE,
+	COMMANDTAG_ALTER_CAST,
+	COMMANDTAG_ALTER_COLLATION,
+	COMMANDTAG_ALTER_CONSTRAINT,
+	COMMANDTAG_ALTER_CONVERSION,
+	COMMANDTAG_ALTER_DATABASE,
+	COMMANDTAG_ALTER_DEFAULT_PRIVILEGES,
+	COMMANDTAG_ALTER_DOMAIN,
+	COMMANDTAG_ALTER_EVENT_TRIGGER,
+	COMMANDTAG_ALTER_EXTENSION,
+	COMMANDTAG_ALTER_FOREIGN_DATA_WRAPPER,
+	COMMANDTAG_ALTER_FOREIGN_TABLE,
+	COMMANDTAG_ALTER_FUNCTION,
+	COMMANDTAG_ALTER_INDEX,
+	COMMANDTAG_ALTER_LANGUAGE,
+	COMMANDTAG_ALTER_LARGE_OBJECT,
+	COMMANDTAG_ALTER_MATERIALIZED_VIEW,
+	COMMANDTAG_ALTER_OPERATOR,
+	COMMANDTAG_ALTER_OPERATOR_CLASS,
+	COMMANDTAG_ALTER_OPERATOR_FAMILY,
+	COMMANDTAG_ALTER_POLICY,
+	COMMANDTAG_ALTER_PROCEDURE,
+	COMMANDTAG_ALTER_PUBLICATION,
+	COMMANDTAG_ALTER_ROLE,
+	COMMANDTAG_ALTER_ROUTINE,
+	COMMANDTAG_ALTER_RULE,
+	COMMANDTAG_ALTER_SCHEMA,
+	COMMANDTAG_ALTER_SEQUENCE,
+	COMMANDTAG_ALTER_SERVER,
+	COMMANDTAG_ALTER_STATISTICS,
+	COMMANDTAG_ALTER_SUBSCRIPTION,
+	COMMANDTAG_ALTER_SYSTEM,
+	COMMANDTAG_ALTER_TABLE,
+	COMMANDTAG_ALTER_TABLESPACE,
+	COMMANDTAG_ALTER_TEXT_SEARCH_CONFIGURATION,
+	COMMANDTAG_ALTER_TEXT_SEARCH_DICTIONARY,
+	COMMANDTAG_ALTER_TEXT_SEARCH_PARSER,
+	COMMANDTAG_ALTER_TEXT_SEARCH_TEMPLATE,
+	COMMANDTAG_ALTER_TRANSFORM,
+	COMMANDTAG_ALTER_TRIGGER,
+	COMMANDTAG_ALTER_TYPE,
+	COMMANDTAG_ALTER_USER_MAPPING,
+	COMMANDTAG_ALTER_VIEW,
+	COMMANDTAG_ANALYZE,
+	COMMANDTAG_BEGIN,
+	COMMANDTAG_CALL,
+	COMMANDTAG_CHECKPOINT,
+	COMMANDTAG_CLOSE,
+	COMMANDTAG_CLOSE_CURSOR,
+	COMMANDTAG_CLOSE_CURSOR_ALL,
+	COMMANDTAG_CLUSTER,
+	COMMANDTAG_COMMENT,
+	COMMANDTAG_COMMIT,
+	COMMANDTAG_COMMIT_PREPARED,
+	COMMANDTAG_COPY,
+	COMMANDTAG_COPY_FROM,
+	COMMANDTAG_CREATE_ACCESS_METHOD,
+	COMMANDTAG_CREATE_AGGREGATE,
+	COMMANDTAG_CREATE_CAST,
+	COMMANDTAG_CREATE_COLLATION,
+	COMMANDTAG_CREATE_CONSTRAINT,
+	COMMANDTAG_CREATE_CONVERSION,
+	COMMANDTAG_CREATE_DATABASE,
+	COMMANDTAG_CREATE_DOMAIN,
+	COMMANDTAG_CREATE_EVENT_TRIGGER,
+	COMMANDTAG_CREATE_EXTENSION,
+	COMMANDTAG_CREATE_FOREIGN_DATA_WRAPPER,
+	COMMANDTAG_CREATE_FOREIGN_TABLE,
+	COMMANDTAG_CREATE_FUNCTION,
+	COMMANDTAG_CREATE_INDEX,
+	COMMANDTAG_CREATE_LANGUAGE,
+	COMMANDTAG_CREATE_MATERIALIZED_VIEW,
+	COMMANDTAG_CREATE_OPERATOR,
+	COMMANDTAG_CREATE_OPERATOR_CLASS,
+	COMMANDTAG_CREATE_OPERATOR_FAMILY,
+	COMMANDTAG_CREATE_POLICY,
+	COMMANDTAG_CREATE_PROCEDURE,
+	COMMANDTAG_CREATE_PUBLICATION,
+	COMMANDTAG_CREATE_ROLE,
+	COMMANDTAG_CREATE_ROUTINE,
+	COMMANDTAG_CREATE_RULE,
+	COMMANDTAG_CREATE_SCHEMA,
+	COMMANDTAG_CREATE_SEQUENCE,
+	COMMANDTAG_CREATE_SERVER,
+	COMMANDTAG_CREATE_STATISTICS,
+	COMMANDTAG_CREATE_SUBSCRIPTION,
+	COMMANDTAG_CREATE_TABLE,
+	COMMANDTAG_CREATE_TABLE_AS,
+	COMMANDTAG_CREATE_TABLESPACE,
+	COMMANDTAG_CREATE_TEXT_SEARCH_CONFIGURATION,
+	COMMANDTAG_CREATE_TEXT_SEARCH_DICTIONARY,
+	COMMANDTAG_CREATE_TEXT_SEARCH_PARSER,
+	COMMANDTAG_CREATE_TEXT_SEARCH_TEMPLATE,
+	COMMANDTAG_CREATE_TRANSFORM,
+	COMMANDTAG_CREATE_TRIGGER,
+	COMMANDTAG_CREATE_TYPE,
+	COMMANDTAG_CREATE_USER_MAPPING,
+	COMMANDTAG_CREATE_VIEW,
+	COMMANDTAG_DEALLOCATE,
+	COMMANDTAG_DEALLOCATE_ALL,
+	COMMANDTAG_DECLARE_CURSOR,
+	COMMANDTAG_DELETE,
+	COMMANDTAG_DISCARD,
+	COMMANDTAG_DISCARD_ALL,
+	COMMANDTAG_DISCARD_PLANS,
+	COMMANDTAG_DISCARD_SEQUENCES,
+	COMMANDTAG_DISCARD_TEMP,
+	COMMANDTAG_DO,
+	COMMANDTAG_DROP_ACCESS_METHOD,
+	COMMANDTAG_DROP_AGGREGATE,
+	COMMANDTAG_DROP_CAST,
+	COMMANDTAG_DROP_COLLATION,
+	COMMANDTAG_DROP_CONSTRAINT,
+	COMMANDTAG_DROP_CONVERSION,
+	COMMANDTAG_DROP_DATABASE,
+	COMMANDTAG_DROP_DOMAIN,
+	COMMANDTAG_DROP_EVENT_TRIGGER,
+	COMMANDTAG_DROP_EXTENSION,
+	COMMANDTAG_DROP_FOREIGN_DATA_WRAPPER,
+	COMMANDTAG_DROP_FOREIGN_TABLE,
+	COMMANDTAG_DROP_FUNCTION,
+	COMMANDTAG_DROP_INDEX,
+	COMMANDTAG_DROP_LANGUAGE,
+	COMMANDTAG_DROP_MATERIALIZED_VIEW,
+	COMMANDTAG_DROP_OPERATOR,
+	COMMANDTAG_DROP_OPERATOR_CLASS,
+	COMMANDTAG_DROP_OPERATOR_FAMILY,
+	COMMANDTAG_DROP_OWNED,
+	COMMANDTAG_DROP_POLICY,
+	COMMANDTAG_DROP_PROCEDURE,
+	COMMANDTAG_DROP_PUBLICATION,
+	COMMANDTAG_DROP_REPLICATION_SLOT,
+	COMMANDTAG_DROP_ROLE,
+	COMMANDTAG_DROP_ROUTINE,
+	COMMANDTAG_DROP_RULE,
+	COMMANDTAG_DROP_SCHEMA,
+	COMMANDTAG_DROP_SEQUENCE,
+	COMMANDTAG_DROP_SERVER,
+	COMMANDTAG_DROP_STATISTICS,
+	COMMANDTAG_DROP_SUBSCRIPTION,
+	COMMANDTAG_DROP_TABLE,
+	COMMANDTAG_DROP_TABLESPACE,
+	COMMANDTAG_DROP_TEXT_SEARCH_CONFIGURATION,
+	COMMANDTAG_DROP_TEXT_SEARCH_DICTIONARY,
+	COMMANDTAG_DROP_TEXT_SEARCH_PARSER,
+	COMMANDTAG_DROP_TEXT_SEARCH_TEMPLATE,
+	COMMANDTAG_DROP_TRANSFORM,
+	COMMANDTAG_DROP_TRIGGER,
+	COMMANDTAG_DROP_TYPE,
+	COMMANDTAG_DROP_USER_MAPPING,
+	COMMANDTAG_DROP_VIEW,
+	COMMANDTAG_EXECUTE,
+	COMMANDTAG_EXPLAIN,
+	COMMANDTAG_FETCH,
+	COMMANDTAG_GRANT,
+	COMMANDTAG_GRANT_ROLE,
+	COMMANDTAG_IMPORT_FOREIGN_SCHEMA,
+	COMMANDTAG_INSERT,
+	COMMANDTAG_LISTEN,
+	COMMANDTAG_LOAD,
+	COMMANDTAG_LOCK_TABLE,
+	COMMANDTAG_MOVE,
+	COMMANDTAG_NOTIFY,
+	COMMANDTAG_PREPARE,
+	COMMANDTAG_PREPARE_TRANSACTION,
+	COMMANDTAG_REASSIGN_OWNED,
+	COMMANDTAG_REFRESH_MATERIALIZED_VIEW,
+	COMMANDTAG_REINDEX,
+	COMMANDTAG_RELEASE,
+	COMMANDTAG_RESET,
+	COMMANDTAG_REVOKE,
+	COMMANDTAG_REVOKE_ROLE,
+	COMMANDTAG_ROLLBACK,
+	COMMANDTAG_ROLLBACK_PREPARED,
+	COMMANDTAG_SAVEPOINT,
+	COMMANDTAG_SECURITY_LABEL,
+	COMMANDTAG_SELECT,
+	COMMANDTAG_SELECT_FOR_KEY_SHARE,
+	COMMANDTAG_SELECT_FOR_NO_KEY_UPDATE,
+	COMMANDTAG_SELECT_FOR_SHARE,
+	COMMANDTAG_SELECT_FOR_UPDATE,
+	COMMANDTAG_SELECT_INTO,
+	COMMANDTAG_SET,
+	COMMANDTAG_SET_CONSTRAINTS,
+	COMMANDTAG_SHOW,
+	COMMANDTAG_START_TRANSACTION,
+	COMMANDTAG_TRUNCATE_TABLE,
+	COMMANDTAG_UNLISTEN,
+	COMMANDTAG_UPDATE,
+	COMMANDTAG_VACUUM
+#define LAST_COMMAND_TAG COMMANDTAG_VACUUM
+}			CommandTag;
+
+static inline bool
+PG_VALID_COMMANDTAG(CommandTag commandTag)
+{
+	return (commandTag >= FIRST_COMMAND_TAG &&
+			commandTag <= LAST_COMMAND_TAG);
+}
+
+extern const char *GetCommandTagName(CommandTag commandTag);
+extern CommandTag GetCommandTagEnum(const char *tagname);
+
+#endif							/* COMMANDTAG_H */
diff --git a/src/include/utils/plancache.h b/src/include/utils/plancache.h
index e48661ebec..04b02c083b 100644
--- a/src/include/utils/plancache.h
+++ b/src/include/utils/plancache.h
@@ -95,7 +95,7 @@ typedef struct CachedPlanSource
 	int			magic;			/* should equal CACHEDPLANSOURCE_MAGIC */
 	struct RawStmt *raw_parse_tree; /* output of raw_parser(), or NULL */
 	const char *query_string;	/* source text of query */
-	const char *commandTag;		/* command tag (a constant!), or NULL */
+	CommandTag	commandTag;
 	Oid		   *param_types;	/* array of parameter type OIDs, or NULL */
 	int			num_params;		/* length of param_types array */
 	ParserSetupHook parserSetup;	/* alternative parameter spec method */
@@ -186,10 +186,10 @@ extern void ResetPlanCache(void);
 
 extern CachedPlanSource *CreateCachedPlan(struct RawStmt *raw_parse_tree,
 										  const char *query_string,
-										  const char *commandTag);
+										  CommandTag commandTag);
 extern CachedPlanSource *CreateOneShotCachedPlan(struct RawStmt *raw_parse_tree,
 												 const char *query_string,
-												 const char *commandTag);
+												 CommandTag commandTag);
 extern void CompleteCachedPlan(CachedPlanSource *plansource,
 							   List *querytree_list,
 							   MemoryContext querytree_context,
diff --git a/src/include/utils/portal.h b/src/include/utils/portal.h
index 0b69433722..2365883acd 100644
--- a/src/include/utils/portal.h
+++ b/src/include/utils/portal.h
@@ -48,6 +48,7 @@
 
 #include "datatype/timestamp.h"
 #include "executor/execdesc.h"
+#include "utils/commandtag.h"
 #include "utils/plancache.h"
 #include "utils/resowner.h"
 
@@ -132,7 +133,8 @@ typedef struct PortalData
 
 	/* The query or queries the portal will execute */
 	const char *sourceText;		/* text of query (as of 8.4, never NULL) */
-	const char *commandTag;		/* command tag for original query */
+	CommandTag	commandTag;		/* command tag for original query */
+	QueryCompletionData	qcdata;	/* command completion data for executed query */
 	List	   *stmts;			/* list of PlannedStmts */
 	CachedPlan *cplan;			/* CachedPlan, if stmts are from one */
 
@@ -227,7 +229,7 @@ extern Portal GetPortalByName(const char *name);
 extern void PortalDefineQuery(Portal portal,
 							  const char *prepStmtName,
 							  const char *sourceText,
-							  const char *commandTag,
+							  CommandTag commandTag,
 							  List *stmts,
 							  CachedPlan *cplan);
 extern PlannedStmt *PortalGetPrimaryStmt(Portal portal);
diff --git a/src/include/utils/querycompletion.h b/src/include/utils/querycompletion.h
new file mode 100644
index 0000000000..b666e1fdc3
--- /dev/null
+++ b/src/include/utils/querycompletion.h
@@ -0,0 +1,60 @@
+/*-------------------------------------------------------------------------
+ *
+ * queryenvironment.h
+ *	  Access to functions to mutate the query environment and retrieve the
+ *	  actual data related to entries (if any).
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/queryenvironment.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef QUERYCOMPLETION_H
+#define QUERYCOMPLETION_H
+
+#include "utils/commandtag.h"
+
+typedef enum QueryCompletionDisplayFormat
+{
+	DISPLAYFORMAT_PLAIN,
+	DISPLAYFORMAT_NPROCESSED,
+	DISPLAYFORMAT_LAST_OID
+} QueryCompletionDisplayFormat;
+
+typedef struct QueryCompletionData
+{
+	CommandTag	commandTag;
+	uint64		nprocessed;
+	/* Wire-protocol backwards-compatibility hack */
+	QueryCompletionDisplayFormat	display_format;
+} QueryCompletionData;
+
+typedef QueryCompletionData *QueryCompletion;
+
+static inline void
+InitializeQC(QueryCompletionData *qc)
+{
+	qc->commandTag = COMMANDTAG_UNKNOWN;
+	qc->nprocessed = 0;
+	qc->display_format = DISPLAYFORMAT_PLAIN;
+}
+
+static inline void
+SetQC(QueryCompletionData *qc, CommandTag commandTag, uint64 nprocessed, QueryCompletionDisplayFormat display_format)
+{
+	qc->commandTag = commandTag;
+	qc->nprocessed = nprocessed;
+	qc->display_format = display_format;
+}
+
+static inline void
+CopyQC(QueryCompletionData *dst, const QueryCompletionData *src)
+{
+	dst->commandTag = src->commandTag;
+	dst->nprocessed = src->nprocessed;
+	dst->display_format = src->display_format;
+}
+
+#endif							/* QUERYCOMPLETION_H */
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 5acf604f63..8a0f31b4b8 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -4115,10 +4115,9 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
 			 * tree(s), since those are the result of rewriting and could have
 			 * been transmogrified into something else entirely.
 			 */
-			if (plansource->commandTag &&
-				(strcmp(plansource->commandTag, "INSERT") == 0 ||
-				 strcmp(plansource->commandTag, "UPDATE") == 0 ||
-				 strcmp(plansource->commandTag, "DELETE") == 0))
+			if (plansource->commandTag == COMMANDTAG_INSERT ||
+				plansource->commandTag == COMMANDTAG_UPDATE ||
+				plansource->commandTag == COMMANDTAG_DELETE)
 			{
 				stmt->mod_stmt = true;
 				break;
diff --git a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
index e1629ec618..d10c465a24 100644
--- a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
+++ b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
@@ -74,7 +74,7 @@ get_command_tag(PG_FUNCTION_ARGS)
 	if (!cmd->parsetree)
 		PG_RETURN_NULL();
 
-	PG_RETURN_TEXT_P(cstring_to_text(CreateCommandTag(cmd->parsetree)));
+	PG_RETURN_TEXT_P(cstring_to_text(GetCommandTagName(CreateCommandTag(cmd->parsetree))));
 }
 
 /*
-- 
2.21.1 (Apple Git-122.3)

