From a2463b98c1e4aa8018ec1595cedbf7c17433456a Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Thu, 4 Jun 2026 08:55:03 +0800
Subject: [PATCH v10 1/2] CREATE TABLE LIKE INCLUDING TRIGGERS

This will copy all source table's triggers to the new table. This functionality
also extends to CREATE FOREIGN TABLE LIKE statements.
If INCLUDING COMMENTS is specified, trigger comments will be copied to the new
table.
This command will fail if the source relation's triggers contain whole-row
reference.

Incompatible triggers will be skipped.  Internal triggers (such as foreign key
associated triggers) won't being copied to new table. Triggers from a source
view will not be copied to a new table. Additionally, constraint triggers and
triggers with transition tables will not be copied to a new foreign table.

Author: jian he <jian.universality@gmail.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Henson Choi <assam258@gmail.com>
Tested-by: 	lakshmi <lakshmigcdac@gmail.com>

discussion: https://postgr.es/m/CACJufxHJAr2FjbeB6ghg_-N5dxX5JVnjKSLOUxOyt4TeaAWQkg@mail.gmail.com
commitfest: https://commitfest.postgresql.org/patch/6087
---
 doc/src/sgml/ref/create_foreign_table.sgml    |  17 +-
 doc/src/sgml/ref/create_table.sgml            |  15 +-
 src/backend/catalog/index.c                   |   2 +
 src/backend/commands/tablecmds.c              |   8 +
 src/backend/commands/trigger.c                | 228 +++++++++++++++++-
 src/backend/parser/gram.y                     |   9 +-
 src/backend/parser/parse_utilcmd.c            |  54 ++++-
 src/include/commands/trigger.h                |   9 +
 src/include/nodes/parsenodes.h                |   4 +
 src/include/parser/kwlist.h                   |   1 +
 .../regress/expected/create_table_like.out    |  23 ++
 src/test/regress/expected/triggers.out        | 124 ++++++++++
 src/test/regress/sql/create_table_like.sql    |  24 ++
 src/test/regress/sql/triggers.sql             |  67 +++++
 14 files changed, 572 insertions(+), 13 deletions(-)

diff --git a/doc/src/sgml/ref/create_foreign_table.sgml b/doc/src/sgml/ref/create_foreign_table.sgml
index 083f16772b7..ed59d0a1e0c 100644
--- a/doc/src/sgml/ref/create_foreign_table.sgml
+++ b/doc/src/sgml/ref/create_foreign_table.sgml
@@ -60,7 +60,7 @@ CREATE FOREIGN TABLE [ IF NOT EXISTS ] <replaceable class="parameter">table_name
 
 <phrase>and <replaceable class="parameter">like_option</replaceable> is:</phrase>
 
-{ INCLUDING | EXCLUDING } { COMMENTS | CONSTRAINTS | DEFAULTS | GENERATED | STATISTICS | ALL }
+{ INCLUDING | EXCLUDING } { COMMENTS | CONSTRAINTS | DEFAULTS | GENERATED | STATISTICS | TRIGGERS | ALL }
 
 <phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase>
 
@@ -232,7 +232,7 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
         <term><literal>INCLUDING COMMENTS</literal></term>
         <listitem>
          <para>
-          Comments for the copied columns, constraints, and extended statistics
+          Comments for the copied columns, constraints, extended statistics, and triggers
           will be copied.  The default behavior is to exclude comments,
           resulting in the corresponding objects in the new table having no
           comments.
@@ -284,6 +284,19 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
         </listitem>
        </varlistentry>
 
+       <varlistentry id="sql-createforeigntable-parms-like-opt-triggers">
+        <term><literal>INCLUDING TRIGGERS</literal></term>
+        <listitem>
+         <para>
+          All non-internal triggers are copied to the new table.
+          Because triggers on views differ significantly from those on tables, triggers from
+          source view are not be copied.
+          Furthermore constraint triggers and triggers that use transition tables
+          will not be copied because foreign tables do not support these.
+         </para>
+        </listitem>
+       </varlistentry>
+
        <varlistentry id="sql-createforeigntable-parms-like-opt-all">
         <term><literal>INCLUDING ALL</literal></term>
         <listitem>
diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml
index e342585c7f0..e929da5c551 100644
--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -100,7 +100,7 @@ class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable cl
 
 <phrase>and <replaceable class="parameter">like_option</replaceable> is:</phrase>
 
-{ INCLUDING | EXCLUDING } { COMMENTS | COMPRESSION | CONSTRAINTS | DEFAULTS | GENERATED | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL }
+{ INCLUDING | EXCLUDING } { COMMENTS | COMPRESSION | CONSTRAINTS | DEFAULTS | GENERATED | IDENTITY | INDEXES | STATISTICS | STORAGE | TRIGGERS | ALL }
 
 <phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase>
 
@@ -693,7 +693,7 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
         <listitem>
          <para>
           Comments for the copied columns, check constraints,
-          not-null constraints, indexes, and extended statistics will be
+          not-null constraints, indexes, extended statistics, and triggers will be
           copied.  The default behavior is to exclude comments, resulting in
           the corresponding objects in the new table having no
           comments.
@@ -797,6 +797,17 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
         </listitem>
        </varlistentry>
 
+       <varlistentry id="sql-createtable-parms-like-opt-triggers">
+        <term><literal>INCLUDING TRIGGERS</literal></term>
+        <listitem>
+         <para>
+          All non-internal triggers are copied to the new table.
+          Because triggers on views differ significantly from those on tables, triggers from
+          source view are not be copied.
+         </para>
+        </listitem>
+       </varlistentry>
+
        <varlistentry id="sql-createtable-parms-like-opt-all">
         <term><literal>INCLUDING ALL</literal></term>
         <listitem>
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 9407c357f27..6aaaf738662 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -2057,6 +2057,8 @@ index_constraint_create(Relation heapRelation,
 		trigger->deferrable = true;
 		trigger->initdeferred = initdeferred;
 		trigger->constrrel = NULL;
+		trigger->trigcomment = NULL;
+		trigger->transformed = true;
 
 		(void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
 							 InvalidOid, conOid, indexRelationId, InvalidOid,
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index a1845240a98..09654aba5f0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -14115,6 +14115,8 @@ CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
 	fk_trigger->deferrable = fkconstraint->deferrable;
 	fk_trigger->initdeferred = fkconstraint->initdeferred;
 	fk_trigger->constrrel = NULL;
+	fk_trigger->trigcomment = NULL;
+	fk_trigger->transformed = true;
 
 	trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
 								constraintOid, indexOid, InvalidOid,
@@ -14160,6 +14162,8 @@ createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstr
 	fk_trigger->whenClause = NULL;
 	fk_trigger->transitionRels = NIL;
 	fk_trigger->constrrel = NULL;
+	fk_trigger->trigcomment = NULL;
+	fk_trigger->transformed = true;
 
 	switch (fkconstraint->fk_del_action)
 	{
@@ -14220,6 +14224,8 @@ createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstr
 	fk_trigger->whenClause = NULL;
 	fk_trigger->transitionRels = NIL;
 	fk_trigger->constrrel = NULL;
+	fk_trigger->trigcomment = NULL;
+	fk_trigger->transformed = true;
 
 	switch (fkconstraint->fk_upd_action)
 	{
@@ -21214,6 +21220,8 @@ CloneRowTriggersToPartition(Relation parent, Relation partition)
 		trigStmt->deferrable = trigForm->tgdeferrable;
 		trigStmt->initdeferred = trigForm->tginitdeferred;
 		trigStmt->constrrel = NULL; /* passed separately */
+		trigStmt->trigcomment = NULL;
+		trigStmt->transformed = true;
 
 		CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
 							  trigForm->tgconstrrelid, InvalidOid, InvalidOid,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index b87b4b40d07..f55a08f0088 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -31,6 +31,7 @@
 #include "catalog/pg_proc.h"
 #include "catalog/pg_trigger.h"
 #include "catalog/pg_type.h"
+#include "commands/comment.h"
 #include "commands/trigger.h"
 #include "executor/executor.h"
 #include "executor/instrument.h"
@@ -591,13 +592,19 @@ CreateTriggerFiringOn(const CreateTrigStmt *stmt, const char *queryString,
 											   false, false);
 		addNSItemToQuery(pstate, nsitem, false, true, true);
 
-		/* Transform expression.  Copy to be sure we don't modify original */
-		whenClause = transformWhereClause(pstate,
-										  copyObject(stmt->whenClause),
-										  EXPR_KIND_TRIGGER_WHEN,
-										  "WHEN");
-		/* we have to fix its collations too */
-		assign_expr_collations(pstate, whenClause);
+		if (stmt->transformed)
+			whenClause = stmt->whenClause;
+		else
+		{
+			/* Transform expression.  Copy to be sure we don't modify original */
+			whenClause = transformWhereClause(pstate,
+											  copyObject(stmt->whenClause),
+											  EXPR_KIND_TRIGGER_WHEN,
+											  "WHEN");
+
+			/* we have to fix its collations too */
+			assign_expr_collations(pstate, whenClause);
+		}
 
 		/*
 		 * Check for disallowed references to OLD/NEW.
@@ -1206,6 +1213,11 @@ CreateTriggerFiringOn(const CreateTrigStmt *stmt, const char *queryString,
 	/* Keep lock on target rel until end of xact */
 	table_close(rel, NoLock);
 
+	/* Add any requested comment */
+	if (stmt->trigcomment != NULL)
+		CreateComments(trigoid, TriggerRelationId, 0,
+					   stmt->trigcomment);
+
 	return myself;
 }
 
@@ -6904,3 +6916,205 @@ AfterTriggerIsActive(void)
 {
 	return afterTriggers.firing_depth > 0;
 }
+
+/*
+ * Duplicate the trigger definition for the new relation: Use the source trigger
+ * (source_trigid from source_rel) to initialize a CreateTrigStmt for the target
+ * relation (heapRel).
+ *
+ * Attribute numbers in expression Vars are adjusted according to attmap.
+ */
+CreateTrigStmt *
+generateClonedTriggerStmt(RangeVar *heapRel, Oid source_trigid,
+						  Relation source_rel, const AttrMap *attmap)
+{
+	HeapTuple	triggerTuple;
+	HeapTuple	proctup;
+	Form_pg_trigger trigForm;
+	Form_pg_proc procform;
+	Relation	pg_trigger;
+	RangeVar   *constrrel = NULL;
+	SysScanDesc tgscan;
+	ScanKeyData skey[1];
+	Datum		value;
+	bool		isnull;
+	Node	   *qual = NULL;
+	List	   *trigargs = NIL;
+	List	   *cols = NIL;
+	List	   *funcname = NIL;
+	List	   *transitionRels = NIL;
+	char	   *funcschema;
+	CreateTrigStmt *trigStmt;
+
+	pg_trigger = table_open(TriggerRelationId, AccessShareLock);
+
+	/* Find the trigger to copy */
+	ScanKeyInit(&skey[0],
+				Anum_pg_trigger_oid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(source_trigid));
+
+	tgscan = systable_beginscan(pg_trigger, TriggerOidIndexId, true,
+								NULL, 1, skey);
+
+	triggerTuple = systable_getnext(tgscan);
+	if (!HeapTupleIsValid(triggerTuple))
+		elog(ERROR, "could not find tuple for trigger %u", source_trigid);
+
+	trigForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
+
+	/* Reconstruct trigger function String list */
+	proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(trigForm->tgfoid));
+	if (!HeapTupleIsValid(proctup))
+		elog(ERROR, "cache lookup failed for function %u", trigForm->tgfoid);
+	procform = (Form_pg_proc) GETSTRUCT(proctup);
+
+	funcschema = get_namespace_name(procform->pronamespace);
+	funcname = list_make2(makeString(funcschema),
+						  makeString(pstrdup(NameStr(procform->proname))));
+	ReleaseSysCache(proctup);
+
+	/*
+	 * If there is a column list, transform it to a list of column names. Note
+	 * we don't need to map this list in any way ...
+	 */
+	if (trigForm->tgattr.dim1 > 0)
+	{
+		for (int i = 0; i < trigForm->tgattr.dim1; i++)
+		{
+			Form_pg_attribute col;
+
+			col = TupleDescAttr(RelationGetDescr(source_rel),
+								trigForm->tgattr.values[i] - 1);
+			cols = lappend(cols,
+						   makeString(pstrdup(NameStr(col->attname))));
+		}
+	}
+
+	/* Reconstruct trigger arguments list */
+	if (trigForm->tgnargs > 0)
+	{
+		bytea	   *val;
+		char	   *p;
+
+		val = DatumGetByteaPP(fastgetattr(triggerTuple,
+										  Anum_pg_trigger_tgargs,
+										  RelationGetDescr(pg_trigger),
+										  &isnull));
+		if (isnull)
+			elog(ERROR, "tgargs is null in trigger \"%s\" for relation \"%s\"",
+				 NameStr(trigForm->tgname),
+				 RelationGetRelationName(source_rel));
+
+		p = (char *) VARDATA_ANY(val);
+
+		for (int i = 0; i < trigForm->tgnargs; i++)
+		{
+			trigargs = lappend(trigargs, makeString(pstrdup(p)));
+			p += strlen(p) + 1;
+		}
+	}
+
+	/* If the trigger has a WHEN qualification, add that */
+	value = fastgetattr(triggerTuple, Anum_pg_trigger_tgqual,
+						RelationGetDescr(pg_trigger), &isnull);
+	if (!isnull)
+	{
+		bool		found_whole_row;
+
+		qual = stringToNode(TextDatumGetCString(value));
+
+		/* Adjust Vars to match new table's column numbering */
+		qual = map_variable_attnos(qual, PRS2_NEW_VARNO, 0,
+								   attmap,
+								   InvalidOid,
+								   &found_whole_row);
+
+		/* As in expandTableLikeClause, reject whole-row variables */
+		if (found_whole_row)
+			ereport(ERROR,
+					errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					errmsg("cannot convert whole-row table reference"),
+					errdetail("Trigger \"%s\" contains a whole-row table reference.",
+							  NameStr(trigForm->tgname)));
+
+		qual = map_variable_attnos(qual, PRS2_OLD_VARNO, 0,
+								   attmap,
+								   InvalidOid,
+								   &found_whole_row);
+
+		/* As in expandTableLikeClause, reject whole-row variables */
+		if (found_whole_row)
+			ereport(ERROR,
+					errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+					errmsg("cannot convert whole-row table reference"),
+					errdetail("Trigger \"%s\" contains a whole-row table reference.",
+							  NameStr(trigForm->tgname)));
+	}
+
+	/* Reconstruct trigger old transition table */
+	value = fastgetattr(triggerTuple, Anum_pg_trigger_tgoldtable,
+						RelationGetDescr(pg_trigger), &isnull);
+	if (!isnull)
+	{
+		TriggerTransition *old = makeNode(TriggerTransition);
+
+		old->isNew = false;
+		old->name = pstrdup(NameStr(*DatumGetName(value)));
+		old->isTable = true;
+		transitionRels = lappend(transitionRels, old);
+	}
+
+	/* Reconstruct trigger new transition table */
+	value = fastgetattr(triggerTuple, Anum_pg_trigger_tgnewtable,
+						RelationGetDescr(pg_trigger),
+						&isnull);
+	if (!isnull)
+	{
+		TriggerTransition *new = makeNode(TriggerTransition);
+
+		new->isNew = true;
+		new->name = pstrdup(NameStr(*DatumGetName(value)));
+		new->isTable = true;
+		transitionRels = lappend(transitionRels, new);
+	}
+
+	/* Reconstruct trigger constraint's FROM table */
+	if (OidIsValid(trigForm->tgconstrrelid))
+	{
+		/*
+		 * Acquire the AccessShareLock lock on tgconstrrelid now, as it will
+		 * be required later in CreateTriggerFiringOn.
+		 */
+		LockRelationOid(trigForm->tgconstrrelid, AccessShareLock);
+
+		constrrel =
+			makeRangeVar(get_namespace_name(get_rel_namespace(trigForm->tgconstrrelid)),
+						 get_rel_name(trigForm->tgconstrrelid),
+						 -1);
+	}
+
+	trigStmt = makeNode(CreateTrigStmt);
+	trigStmt->replace = false;
+	trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
+	trigStmt->trigname = pstrdup(NameStr(trigForm->tgname));
+	trigStmt->relation = heapRel;
+	trigStmt->funcname = funcname;
+	trigStmt->args = trigargs;
+	trigStmt->row = TRIGGER_FOR_ROW(trigForm->tgtype);
+	trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
+	trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
+	trigStmt->columns = cols;
+	trigStmt->whenClause = qual;
+	trigStmt->transitionRels = transitionRels;
+	trigStmt->deferrable = trigForm->tgdeferrable;
+	trigStmt->initdeferred = trigForm->tginitdeferred;
+	trigStmt->constrrel = constrrel;
+	trigStmt->trigcomment = NULL;
+	trigStmt->transformed = true;
+
+	systable_endscan(tgscan);
+	table_close(pg_trigger, AccessShareLock);
+
+	return trigStmt;
+}
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index ff4e1388c55..6fca2636116 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -822,7 +822,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 
 	TABLE TABLES TABLESAMPLE TABLESPACE TARGET TEMP TEMPLATE TEMPORARY TEXT_P THEN
 	TIES TIME TIMESTAMP TO TRAILING TRANSACTION TRANSFORM
-	TREAT TRIGGER TRIM TRUE_P
+	TREAT TRIGGER TRIGGERS TRIM TRUE_P
 	TRUNCATE TRUSTED TYPE_P TYPES_P
 
 	UESCAPE UNBOUNDED UNCONDITIONAL UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN
@@ -4353,6 +4353,7 @@ TableLikeOption:
 				| INDEXES			{ $$ = CREATE_TABLE_LIKE_INDEXES; }
 				| STATISTICS		{ $$ = CREATE_TABLE_LIKE_STATISTICS; }
 				| STORAGE			{ $$ = CREATE_TABLE_LIKE_STORAGE; }
+				| TRIGGERS			{ $$ = CREATE_TABLE_LIKE_TRIGGERS; }
 				| ALL				{ $$ = CREATE_TABLE_LIKE_ALL; }
 		;
 
@@ -6209,6 +6210,8 @@ CreateTrigStmt:
 					n->deferrable = false;
 					n->initdeferred = false;
 					n->constrrel = NULL;
+					n->trigcomment = NULL;
+					n->transformed = false;
 					$$ = (Node *) n;
 				}
 		  | CREATE opt_or_replace CONSTRAINT TRIGGER name AFTER TriggerEvents ON
@@ -6259,6 +6262,8 @@ CreateTrigStmt:
 								   &n->deferrable, &n->initdeferred, &dummy,
 								   NULL, NULL, yyscanner);
 					n->constrrel = $10;
+					n->trigcomment = NULL;
+					n->transformed = false;
 					$$ = (Node *) n;
 				}
 		;
@@ -19130,6 +19135,7 @@ unreserved_keyword:
 			| TRANSACTION
 			| TRANSFORM
 			| TRIGGER
+			| TRIGGERS
 			| TRUNCATE
 			| TRUSTED
 			| TYPE_P
@@ -19795,6 +19801,7 @@ bare_label_keyword:
 			| TRANSFORM
 			| TREAT
 			| TRIGGER
+			| TRIGGERS
 			| TRIM
 			| TRUE_P
 			| TRUNCATE
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index a049cc67ed6..9fefb9dc698 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -40,12 +40,14 @@
 #include "catalog/pg_opclass.h"
 #include "catalog/pg_operator.h"
 #include "catalog/pg_statistic_ext.h"
+#include "catalog/pg_trigger.h"
 #include "catalog/pg_type.h"
 #include "commands/comment.h"
 #include "commands/defrem.h"
 #include "commands/sequence.h"
 #include "commands/tablecmds.h"
 #include "commands/tablespace.h"
+#include "commands/trigger.h"
 #include "miscadmin.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -1316,7 +1318,8 @@ transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_cla
 		 CREATE_TABLE_LIKE_GENERATED |
 		 CREATE_TABLE_LIKE_CONSTRAINTS |
 		 CREATE_TABLE_LIKE_INDEXES |
-		 CREATE_TABLE_LIKE_STATISTICS))
+		 CREATE_TABLE_LIKE_STATISTICS |
+		 CREATE_TABLE_LIKE_TRIGGERS))
 	{
 		table_like_clause->relationOid = RelationGetRelid(relation);
 		cxt->likeclauses = lappend(cxt->likeclauses, table_like_clause);
@@ -1620,6 +1623,55 @@ expandTableLikeClause(RangeVar *heapRel, TableLikeClause *table_like_clause)
 		list_free(parent_extstats);
 	}
 
+	/* Process triggers if required */
+	if ((table_like_clause->options & CREATE_TABLE_LIKE_TRIGGERS) &&
+		(relation->trigdesc != NULL) &&
+		(relation->rd_rel->relkind == RELKIND_RELATION ||
+		 relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
+		 relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE))
+	{
+		bool		include_comments;
+
+		include_comments = (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS);
+
+		for (int nt = 0; nt < relation->trigdesc->numtriggers; nt++)
+		{
+			CreateTrigStmt *trig_stmt;
+			Trigger    *trig = relation->trigdesc->triggers + nt;
+			Oid			trigoid = trig->tgoid;
+
+			/* We do not copy internal trigger to the new table */
+			if (trig->tgisinternal)
+				continue;
+
+			/*
+			 * Foreign table cannot have constraint trigger or triggers with
+			 * transition table
+			 */
+			if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+			{
+				if (OidIsValid(trig->tgconstraint))
+					continue;
+
+				if (trig->tgoldtable != NULL || trig->tgnewtable != NULL)
+					continue;
+			}
+
+			trig_stmt = generateClonedTriggerStmt(heapRel, trigoid,
+												  relation, attmap);
+
+			/* Copy comment on trigger, if requested */
+			if (include_comments)
+			{
+				comment = GetComment(trigoid, TriggerRelationId, 0);
+
+				/* We make use of CreateTrigStmt's trigcomment option */
+				trig_stmt->trigcomment = comment;
+			}
+			result = lappend(result, trig_stmt);
+		}
+	}
+
 	/* Done with child rel */
 	table_close(childrel, NoLock);
 
diff --git a/src/include/commands/trigger.h b/src/include/commands/trigger.h
index 1d9869973c0..ce4b3cf1396 100644
--- a/src/include/commands/trigger.h
+++ b/src/include/commands/trigger.h
@@ -18,6 +18,11 @@
 #include "nodes/execnodes.h"
 #include "nodes/parsenodes.h"
 
+/*
+ * forward references in this file
+ */
+typedef struct AttrMap AttrMap;
+
 /*
  * TriggerData is the node type that is passed as fmgr "context" info
  * when a function is called by the trigger manager.
@@ -268,6 +273,10 @@ extern void AfterTriggerBeginSubXact(void);
 extern void AfterTriggerEndSubXact(bool isCommit);
 extern void AfterTriggerSetState(ConstraintsSetStmt *stmt);
 extern bool AfterTriggerPendingOnRel(Oid relid);
+extern CreateTrigStmt *generateClonedTriggerStmt(RangeVar *heapRel,
+												 Oid source_trigid,
+												 Relation source_rel,
+												 const AttrMap *attmap);
 
 
 /*
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 91377a6cde3..a7d01f5f9fd 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -811,6 +811,7 @@ typedef enum TableLikeOption
 	CREATE_TABLE_LIKE_INDEXES = 1 << 6,
 	CREATE_TABLE_LIKE_STATISTICS = 1 << 7,
 	CREATE_TABLE_LIKE_STORAGE = 1 << 8,
+	CREATE_TABLE_LIKE_TRIGGERS = 1 << 9,
 	CREATE_TABLE_LIKE_ALL = PG_INT32_MAX
 } TableLikeOption;
 
@@ -3234,6 +3235,9 @@ typedef struct CreateTrigStmt
 	bool		deferrable;		/* [NOT] DEFERRABLE */
 	bool		initdeferred;	/* INITIALLY {DEFERRED|IMMEDIATE} */
 	RangeVar   *constrrel;		/* opposite relation, if RI trigger */
+	char	   *trigcomment;	/* comment to apply to trigger, or NULL */
+	bool		transformed;	/* true means no need to do parse analysis for
+								 * whenClause */
 } CreateTrigStmt;
 
 /* ----------------------
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 51ead54f015..9733d4a796c 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -474,6 +474,7 @@ PG_KEYWORD("transaction", TRANSACTION, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("transform", TRANSFORM, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("treat", TREAT, COL_NAME_KEYWORD, BARE_LABEL)
 PG_KEYWORD("trigger", TRIGGER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("triggers", TRIGGERS, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("trim", TRIM, COL_NAME_KEYWORD, BARE_LABEL)
 PG_KEYWORD("true", TRUE_P, RESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("truncate", TRUNCATE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/test/regress/expected/create_table_like.out b/src/test/regress/expected/create_table_like.out
index 76069bde756..4f3214e4e91 100644
--- a/src/test/regress/expected/create_table_like.out
+++ b/src/test/regress/expected/create_table_like.out
@@ -635,6 +635,26 @@ Not-null constraints:
     "ctl_table_a_not_null" NOT NULL "a"
     "ctl_table_d_not_null" NOT NULL "d"
 
+CREATE OR REPLACE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS '
+BEGIN
+	RAISE NOTICE ''trigger_func(%) called: action = %, when = %, level = %'', TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL;
+	RETURN NULL;
+END;';
+CREATE TRIGGER trigtest_before_stmt BEFORE DELETE OR UPDATE ON ctl_table
+FOR EACH ROW WHEN (OLD.a > 0)
+EXECUTE PROCEDURE trigger_func('trigtest_before_stmt');
+CREATE TRIGGER trigtest_after_stmt AFTER UPDATE OF a, b ON ctl_table
+FOR EACH STATEMENT
+EXECUTE PROCEDURE trigger_func('trigtest_before_stmt');
+-- CREATE FOREIGN TABLE LIKE should not copy triggers that have transition tables
+CREATE TRIGGER trigtest_after_stmt1 AFTER INSERT ON ctl_table
+REFERENCING NEW TABLE AS new_table
+FOR EACH STATEMENT
+EXECUTE PROCEDURE trigger_func('trigtest_after_stmt1');
+-- CREATE FOREIGN TABLE LIKE should not copy source table cosntraint trigger
+CREATE CONSTRAINT TRIGGER constr_trig
+    AFTER INSERT ON ctl_table DEFERRABLE INITIALLY DEFERRED enforced FOR EACH ROW
+    EXECUTE PROCEDURE trigger_func ();
 -- Test EXCLUDING ALL
 CREATE FOREIGN TABLE ctl_foreign_table1(LIKE ctl_table EXCLUDING ALL) SERVER ctl_s0;
 \d+ ctl_foreign_table1
@@ -683,6 +703,9 @@ Statistics objects:
 Not-null constraints:
     "ctl_table_a_not_null" NOT NULL "a"
     "ctl_table_d_not_null" NOT NULL "d"
+Triggers:
+    trigtest_after_stmt AFTER UPDATE OF a, b ON ctl_foreign_table2 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('trigtest_before_stmt')
+    trigtest_before_stmt BEFORE DELETE OR UPDATE ON ctl_foreign_table2 FOR EACH ROW WHEN (old.a > 0) EXECUTE FUNCTION trigger_func('trigtest_before_stmt')
 Server: ctl_s0
 
 -- \d+ does not report the value of attcompression for a foreign table, so
diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out
index 8fcb33ac81a..f675786739d 100644
--- a/src/test/regress/expected/triggers.out
+++ b/src/test/regress/expected/triggers.out
@@ -174,6 +174,20 @@ CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_table
 FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_ins_stmt');
 CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_table
 FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_ins_stmt');
+CREATE TRIGGER wholetrig BEFORE UPDATE ON main_table FOR EACH ROW
+WHEN (OLD IS NOT NULL)
+EXECUTE PROCEDURE trigger_func('modified_a');
+CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS); -- error, wholerow reference not allowed
+ERROR:  cannot convert whole-row table reference
+DETAIL:  Trigger "wholetrig" contains a whole-row table reference.
+DROP TRIGGER wholetrig ON main_table;
+CREATE TRIGGER wholetrig BEFORE UPDATE ON main_table FOR EACH ROW
+WHEN (NEW IS NOT NULL)
+EXECUTE PROCEDURE trigger_func('modified_a');
+CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS); -- error, wholerow reference not allowed
+ERROR:  cannot convert whole-row table reference
+DETAIL:  Trigger "wholetrig" contains a whole-row table reference.
+DROP TRIGGER wholetrig ON main_table;
 --
 -- if neither 'FOR EACH ROW' nor 'FOR EACH STATEMENT' was specified,
 -- CREATE TRIGGER should default to 'FOR EACH STATEMENT'
@@ -394,6 +408,46 @@ NOTICE:  trigger_func(after_upd_a_b_row) called: action = UPDATE, when = AFTER,
 NOTICE:  trigger_func(after_upd_b_row) called: action = UPDATE, when = AFTER, level = ROW
 NOTICE:  trigger_func(after_upd_b_stmt) called: action = UPDATE, when = AFTER, level = STATEMENT
 NOTICE:  trigger_func(after_upd_stmt) called: action = UPDATE, when = AFTER, level = STATEMENT
+-- CREATE TABLE LIKE INCLUDING TRIGGERS tests
+COMMENT ON TRIGGER before_ins_stmt_trig ON main_table IS 'trigger before_ins_stmt_trig';
+CREATE TABLE main_table1(c int, LIKE main_table INCLUDING TRIGGERS INCLUDING COMMENTS);
+CREATE TABLE main_table2(c int, LIKE main_table EXCLUDING TRIGGERS INCLUDING COMMENTS);
+SELECT  pg_get_triggerdef(oid)
+FROM    pg_trigger
+WHERE NOT tgisinternal AND tgrelid IN ('main_table'::regclass, 'main_table1'::regclass, 'main_table2'::regclass)
+ORDER BY tgname, tgrelid::regclass::text COLLATE "C";
+                                                                  pg_get_triggerdef                                                                   
+------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON public.main_table FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_ins_stmt')
+ CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON public.main_table1 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_ins_stmt')
+ CREATE TRIGGER after_upd_a_b_row_trig AFTER UPDATE OF a, b ON public.main_table FOR EACH ROW EXECUTE FUNCTION trigger_func('after_upd_a_b_row')
+ CREATE TRIGGER after_upd_a_b_row_trig AFTER UPDATE OF a, b ON public.main_table1 FOR EACH ROW EXECUTE FUNCTION trigger_func('after_upd_a_b_row')
+ CREATE TRIGGER after_upd_b_row_trig AFTER UPDATE OF b ON public.main_table FOR EACH ROW EXECUTE FUNCTION trigger_func('after_upd_b_row')
+ CREATE TRIGGER after_upd_b_row_trig AFTER UPDATE OF b ON public.main_table1 FOR EACH ROW EXECUTE FUNCTION trigger_func('after_upd_b_row')
+ CREATE TRIGGER after_upd_b_stmt_trig AFTER UPDATE OF b ON public.main_table FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_upd_b_stmt')
+ CREATE TRIGGER after_upd_b_stmt_trig AFTER UPDATE OF b ON public.main_table1 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_upd_b_stmt')
+ CREATE TRIGGER after_upd_stmt_trig AFTER UPDATE ON public.main_table FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_upd_stmt')
+ CREATE TRIGGER after_upd_stmt_trig AFTER UPDATE ON public.main_table1 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('after_upd_stmt')
+ CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON public.main_table FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('before_ins_stmt')
+ CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON public.main_table1 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('before_ins_stmt')
+ CREATE TRIGGER before_upd_a_row_trig BEFORE UPDATE OF a ON public.main_table FOR EACH ROW EXECUTE FUNCTION trigger_func('before_upd_a_row')
+ CREATE TRIGGER before_upd_a_row_trig BEFORE UPDATE OF a ON public.main_table1 FOR EACH ROW EXECUTE FUNCTION trigger_func('before_upd_a_row')
+ CREATE TRIGGER before_upd_a_stmt_trig BEFORE UPDATE OF a ON public.main_table FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('before_upd_a_stmt')
+ CREATE TRIGGER before_upd_a_stmt_trig BEFORE UPDATE OF a ON public.main_table1 FOR EACH STATEMENT EXECUTE FUNCTION trigger_func('before_upd_a_stmt')
+(16 rows)
+
+SELECT  pc.relname, pd.tgname, obj_description(pd.oid, 'pg_trigger')
+FROM    pg_trigger pd JOIN pg_class pc
+ON      pc.oid = pd.tgrelid AND pd.tgname = 'before_ins_stmt_trig'
+ORDER BY 1;
+   relname   |        tgname        |       obj_description        
+-------------+----------------------+------------------------------
+ main_table  | before_ins_stmt_trig | trigger before_ins_stmt_trig
+ main_table1 | before_ins_stmt_trig | trigger before_ins_stmt_trig
+(2 rows)
+
+COMMENT ON TRIGGER before_ins_stmt_trig ON main_table IS NULL;
+DROP TABLE main_table1, main_table2;
 --
 -- Test case for bug with BEFORE trigger followed by AFTER trigger with WHEN
 --
@@ -422,7 +476,22 @@ NOTICE:  dummy_update_func(afterb) called: action = UPDATE, old = (t), new = (f)
 UPDATE some_t SET some_col = TRUE;
 NOTICE:  dummy_update_func(before) called: action = UPDATE, old = (f), new = (t)
 NOTICE:  dummy_update_func(aftera) called: action = UPDATE, old = (f), new = (t)
+CREATE TABLE some_t1 (c INT, LIKE some_t INCLUDING TRIGGERS INCLUDING COMMENTS);
+\d+ some_t1
+                                   Table "public.some_t1"
+  Column  |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
+----------+---------+-----------+----------+---------+---------+--------------+-------------
+ c        | integer |           |          |         | plain   |              | 
+ some_col | boolean |           | not null |         | plain   |              | 
+Not-null constraints:
+    "some_t_some_col_not_null" NOT NULL "some_col"
+Triggers:
+    some_trig_aftera AFTER UPDATE ON some_t1 FOR EACH ROW WHEN (NOT old.some_col AND new.some_col) EXECUTE FUNCTION dummy_update_func('aftera')
+    some_trig_afterb AFTER UPDATE ON some_t1 FOR EACH ROW WHEN (NOT new.some_col) EXECUTE FUNCTION dummy_update_func('afterb')
+    some_trig_before BEFORE UPDATE ON some_t1 FOR EACH ROW EXECUTE FUNCTION dummy_update_func('before')
+
 DROP TABLE some_t;
+DROP TABLE some_t1;
 -- bogus cases
 CREATE TRIGGER error_upd_and_col BEFORE UPDATE OR UPDATE OF a ON main_table
 FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_upd_and_col');
@@ -861,6 +930,15 @@ CREATE TRIGGER instead_of_update_trig INSTEAD OF UPDATE ON main_view
 FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_upd');
 CREATE TRIGGER instead_of_delete_trig INSTEAD OF DELETE ON main_view
 FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_del');
+CREATE TABLE main_view_table(LIKE main_view INCLUDING TRIGGERS); -- View triggers are not copied
+\d main_view_table
+          Table "public.main_view_table"
+ Column |  Type   | Collation | Nullable | Default 
+--------+---------+-----------+----------+---------
+ a      | integer |           |          | 
+ b      | integer |           |          | 
+
+DROP TABLE main_view_table;
 -- Valid BEFORE statement VIEW triggers
 CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_view
 FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('before_view_ins_stmt');
@@ -2326,6 +2404,20 @@ create constraint trigger parted_trig_two after insert on parted_constr
   deferrable initially deferred enforced
   for each row when (bark(new.b) AND new.a % 2 = 1)
   execute procedure trigger_notice_ab();
+create table parted_constr_copy (like parted_constr including all);
+select  pg_get_triggerdef(oid)
+from    pg_trigger
+where   not tgisinternal and tgrelid in ('parted_constr_copy'::regclass, 'parted_constr'::regclass)
+order by tgname;
+                                                                                               pg_get_triggerdef                                                                                                
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE CONSTRAINT TRIGGER parted_trig AFTER INSERT ON public.parted_constr DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION trigger_notice_ab()
+ CREATE CONSTRAINT TRIGGER parted_trig AFTER INSERT ON public.parted_constr_copy DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION trigger_notice_ab()
+ CREATE CONSTRAINT TRIGGER parted_trig_two AFTER INSERT ON public.parted_constr DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((bark(new.b) AND ((new.a % 2) = 1))) EXECUTE FUNCTION trigger_notice_ab()
+ CREATE CONSTRAINT TRIGGER parted_trig_two AFTER INSERT ON public.parted_constr_copy DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((bark(new.b) AND ((new.a % 2) = 1))) EXECUTE FUNCTION trigger_notice_ab()
+(4 rows)
+
+drop table parted_constr_copy;
 -- The immediate constraint is fired immediately; the WHEN clause of the
 -- deferred constraint is also called immediately.  The deferred constraint
 -- is fired at commit time.
@@ -3106,6 +3198,18 @@ create trigger iocdu_tt_parted_insert_trig
 create trigger iocdu_tt_parted_update_trig
   after update on iocdu_tt_parted referencing old table as old_table new table as new_table
   for each statement execute procedure dump_update();
+CREATE TABLE iocdu_tt_parted_copy(LIKE iocdu_tt_parted INCLUDING TRIGGERS);
+\d iocdu_tt_parted_copy
+        Table "public.iocdu_tt_parted_copy"
+ Column |  Type   | Collation | Nullable | Default 
+--------+---------+-----------+----------+---------
+ a      | integer |           | not null | 
+ b      | text    |           |          | 
+Triggers:
+    iocdu_tt_parted_insert_trig AFTER INSERT ON iocdu_tt_parted_copy REFERENCING NEW TABLE AS new_table FOR EACH STATEMENT EXECUTE FUNCTION dump_insert()
+    iocdu_tt_parted_update_trig AFTER UPDATE ON iocdu_tt_parted_copy REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table FOR EACH STATEMENT EXECUTE FUNCTION dump_update()
+
+DROP TABLE iocdu_tt_parted_copy;
 -- inserts only
 insert into iocdu_tt_parted values (1, 'AAA'), (2, 'BBB')
   on conflict (a) do
@@ -3589,6 +3693,26 @@ begin
 end;
 $$;
 alter function whoami() owner to regress_fn_owner;
+-- CREATE TABLE LIKE INCLUDING TRIGGERS for constraint trigger
+create schema test_trig;
+create table test_trig.trig_t1 (id integer);
+create table test_trig.trig_t2 (id integer);
+alter function whoami() set schema test_trig;
+create constraint trigger con_trig_test after insert on test_trig.trig_t1
+from test_trig.trig_t2
+deferrable initially deferred
+for each row
+execute function test_trig.whoami();
+create table trig_t1_copy(like test_trig.trig_t1 including triggers);
+select pg_get_triggerdef(oid) from pg_trigger where tgrelid = 'trig_t1_copy'::regclass;
+                                                                                 pg_get_triggerdef                                                                                 
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE CONSTRAINT TRIGGER con_trig_test AFTER INSERT ON public.trig_t1_copy FROM test_trig.trig_t2 DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION test_trig.whoami()
+(1 row)
+
+alter function test_trig.whoami() set schema public;
+drop table test_trig.trig_t1, test_trig.trig_t2, trig_t1_copy;
+drop schema test_trig;
 create table defer_trig (id integer);
 grant insert on defer_trig to public;
 create constraint trigger whoami after insert on defer_trig
diff --git a/src/test/regress/sql/create_table_like.sql b/src/test/regress/sql/create_table_like.sql
index d52a93ef131..c2d8acf6b6f 100644
--- a/src/test/regress/sql/create_table_like.sql
+++ b/src/test/regress/sql/create_table_like.sql
@@ -259,6 +259,30 @@ ALTER TABLE ctl_table ALTER COLUMN b SET STORAGE MAIN;
 
 \d+ ctl_table
 
+CREATE OR REPLACE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS '
+BEGIN
+	RAISE NOTICE ''trigger_func(%) called: action = %, when = %, level = %'', TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL;
+	RETURN NULL;
+END;';
+CREATE TRIGGER trigtest_before_stmt BEFORE DELETE OR UPDATE ON ctl_table
+FOR EACH ROW WHEN (OLD.a > 0)
+EXECUTE PROCEDURE trigger_func('trigtest_before_stmt');
+
+CREATE TRIGGER trigtest_after_stmt AFTER UPDATE OF a, b ON ctl_table
+FOR EACH STATEMENT
+EXECUTE PROCEDURE trigger_func('trigtest_before_stmt');
+
+-- CREATE FOREIGN TABLE LIKE should not copy triggers that have transition tables
+CREATE TRIGGER trigtest_after_stmt1 AFTER INSERT ON ctl_table
+REFERENCING NEW TABLE AS new_table
+FOR EACH STATEMENT
+EXECUTE PROCEDURE trigger_func('trigtest_after_stmt1');
+
+-- CREATE FOREIGN TABLE LIKE should not copy source table cosntraint trigger
+CREATE CONSTRAINT TRIGGER constr_trig
+    AFTER INSERT ON ctl_table DEFERRABLE INITIALLY DEFERRED enforced FOR EACH ROW
+    EXECUTE PROCEDURE trigger_func ();
+
 -- Test EXCLUDING ALL
 CREATE FOREIGN TABLE ctl_foreign_table1(LIKE ctl_table EXCLUDING ALL) SERVER ctl_s0;
 \d+ ctl_foreign_table1
diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql
index 2285e90110e..1afaeb863f7 100644
--- a/src/test/regress/sql/triggers.sql
+++ b/src/test/regress/sql/triggers.sql
@@ -120,6 +120,18 @@ FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_ins_stmt');
 CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_table
 FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_ins_stmt');
 
+CREATE TRIGGER wholetrig BEFORE UPDATE ON main_table FOR EACH ROW
+WHEN (OLD IS NOT NULL)
+EXECUTE PROCEDURE trigger_func('modified_a');
+CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS); -- error, wholerow reference not allowed
+DROP TRIGGER wholetrig ON main_table;
+
+CREATE TRIGGER wholetrig BEFORE UPDATE ON main_table FOR EACH ROW
+WHEN (NEW IS NOT NULL)
+EXECUTE PROCEDURE trigger_func('modified_a');
+CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS); -- error, wholerow reference not allowed
+DROP TRIGGER wholetrig ON main_table;
+
 --
 -- if neither 'FOR EACH ROW' nor 'FOR EACH STATEMENT' was specified,
 -- CREATE TRIGGER should default to 'FOR EACH STATEMENT'
@@ -234,6 +246,24 @@ SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = 'main_table'::regc
 UPDATE main_table SET a = 50;
 UPDATE main_table SET b = 10;
 
+-- CREATE TABLE LIKE INCLUDING TRIGGERS tests
+COMMENT ON TRIGGER before_ins_stmt_trig ON main_table IS 'trigger before_ins_stmt_trig';
+CREATE TABLE main_table1(c int, LIKE main_table INCLUDING TRIGGERS INCLUDING COMMENTS);
+CREATE TABLE main_table2(c int, LIKE main_table EXCLUDING TRIGGERS INCLUDING COMMENTS);
+
+SELECT  pg_get_triggerdef(oid)
+FROM    pg_trigger
+WHERE NOT tgisinternal AND tgrelid IN ('main_table'::regclass, 'main_table1'::regclass, 'main_table2'::regclass)
+ORDER BY tgname, tgrelid::regclass::text COLLATE "C";
+
+SELECT  pc.relname, pd.tgname, obj_description(pd.oid, 'pg_trigger')
+FROM    pg_trigger pd JOIN pg_class pc
+ON      pc.oid = pd.tgrelid AND pd.tgname = 'before_ins_stmt_trig'
+ORDER BY 1;
+COMMENT ON TRIGGER before_ins_stmt_trig ON main_table IS NULL;
+
+DROP TABLE main_table1, main_table2;
+
 --
 -- Test case for bug with BEFORE trigger followed by AFTER trigger with WHEN
 --
@@ -258,7 +288,10 @@ INSERT INTO some_t VALUES (TRUE);
 UPDATE some_t SET some_col = TRUE;
 UPDATE some_t SET some_col = FALSE;
 UPDATE some_t SET some_col = TRUE;
+CREATE TABLE some_t1 (c INT, LIKE some_t INCLUDING TRIGGERS INCLUDING COMMENTS);
+\d+ some_t1
 DROP TABLE some_t;
+DROP TABLE some_t1;
 
 -- bogus cases
 CREATE TRIGGER error_upd_and_col BEFORE UPDATE OR UPDATE OF a ON main_table
@@ -621,6 +654,10 @@ FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_upd');
 CREATE TRIGGER instead_of_delete_trig INSTEAD OF DELETE ON main_view
 FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_del');
 
+CREATE TABLE main_view_table(LIKE main_view INCLUDING TRIGGERS); -- View triggers are not copied
+\d main_view_table
+DROP TABLE main_view_table;
+
 -- Valid BEFORE statement VIEW triggers
 CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_view
 FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('before_view_ins_stmt');
@@ -1609,6 +1646,13 @@ create constraint trigger parted_trig_two after insert on parted_constr
   for each row when (bark(new.b) AND new.a % 2 = 1)
   execute procedure trigger_notice_ab();
 
+create table parted_constr_copy (like parted_constr including all);
+select  pg_get_triggerdef(oid)
+from    pg_trigger
+where   not tgisinternal and tgrelid in ('parted_constr_copy'::regclass, 'parted_constr'::regclass)
+order by tgname;
+drop table parted_constr_copy;
+
 -- The immediate constraint is fired immediately; the WHEN clause of the
 -- deferred constraint is also called immediately.  The deferred constraint
 -- is fired at commit time.
@@ -2283,6 +2327,10 @@ create trigger iocdu_tt_parted_update_trig
   after update on iocdu_tt_parted referencing old table as old_table new table as new_table
   for each statement execute procedure dump_update();
 
+CREATE TABLE iocdu_tt_parted_copy(LIKE iocdu_tt_parted INCLUDING TRIGGERS);
+\d iocdu_tt_parted_copy
+DROP TABLE iocdu_tt_parted_copy;
+
 -- inserts only
 insert into iocdu_tt_parted values (1, 'AAA'), (2, 'BBB')
   on conflict (a) do
@@ -2740,6 +2788,25 @@ end;
 $$;
 alter function whoami() owner to regress_fn_owner;
 
+-- CREATE TABLE LIKE INCLUDING TRIGGERS for constraint trigger
+create schema test_trig;
+create table test_trig.trig_t1 (id integer);
+create table test_trig.trig_t2 (id integer);
+alter function whoami() set schema test_trig;
+
+create constraint trigger con_trig_test after insert on test_trig.trig_t1
+from test_trig.trig_t2
+deferrable initially deferred
+for each row
+execute function test_trig.whoami();
+
+create table trig_t1_copy(like test_trig.trig_t1 including triggers);
+select pg_get_triggerdef(oid) from pg_trigger where tgrelid = 'trig_t1_copy'::regclass;
+
+alter function test_trig.whoami() set schema public;
+drop table test_trig.trig_t1, test_trig.trig_t2, trig_t1_copy;
+drop schema test_trig;
+
 create table defer_trig (id integer);
 grant insert on defer_trig to public;
 create constraint trigger whoami after insert on defer_trig
-- 
2.34.1

