CREATE TABLE LIKE INCLUDING TRIGGERS

Поиск
Список
Период
Сортировка
Искать

CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

poc demo:
CREATE TABLE main_table (a int, b int);
CREATE 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 modified_a BEFORE UPDATE OF a ON main_table
FOR EACH ROW WHEN (OLD.a <> NEW.a) EXECUTE PROCEDURE trigger_func('modified_a');

CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS INCLUDING COMMENTS);
\d main_table1
            Table "public.main_table1"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 a      | integer |           |          |
 b      | integer |           |          |
Triggers:
    modified_a BEFORE UPDATE OF a ON main_table1 FOR EACH ROW WHEN
(old.a <> new.a) EXECUTE FUNCTION trigger_func('modified_a')

foreign key associated internal triggers won't be copied to the new table.
source table trigger associated comment will be copied to the new table,
if INCLUDING COMMENTS is specified.

---------------
v1-0001:  "refactor CreateTrigger and CreateTriggerFiringOn".

Similar to CreateStatistics, some of the expressions stored in the
catalog pg_trigger are
already transformed, when we retrieve it as a base model for constructing a new
CreateTrigStmt, we can not do parse analysis of it again.
see transformStatsStmt for similar handling.
The CreateTrigger function, (Node *whenClause) is always NULL,
so I think it's safe to remove the argument whenClause.

v1-0002: CREATE TABLE LIKE INCLUDING TRIGGERS.

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Sep 29, 2025 at 5:35 PM jian he  wrote:
>
> hi.
>
> poc demo:
> CREATE TABLE main_table (a int, b int);
> CREATE 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 modified_a BEFORE UPDATE OF a ON main_table
> FOR EACH ROW WHEN (OLD.a <> NEW.a) EXECUTE PROCEDURE trigger_func('modified_a');
>
> CREATE TABLE main_table1(LIKE main_table INCLUDING TRIGGERS INCLUDING COMMENTS);
> \d main_table1
>             Table "public.main_table1"
>  Column |  Type   | Collation | Nullable | Default
> --------+---------+-----------+----------+---------
>  a      | integer |           |          |
>  b      | integer |           |          |
> Triggers:
>     modified_a BEFORE UPDATE OF a ON main_table1 FOR EACH ROW WHEN
> (old.a <> new.a) EXECUTE FUNCTION trigger_func('modified_a')
>
> foreign key associated internal triggers won't be copied to the new table.
> source table trigger associated comment will be copied to the new table,
> if INCLUDING COMMENTS is specified.
>

per
https://api.cirrus-ci.com/v1/artifact/task/5194724417470464/testrun/build/testrun/regress/regress/regression.diffs

there are many table name as t1 in regress test, add tests like
""CREATE TABLE t1 (a int, b text, c int);"
may result in error
+ERROR:  relation "t1" already exists
in some OS.
So I changed the table name to avoid parallel regess test failure.

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

in CreateTrigger, we have comments:

 * relOid, if nonzero, is the relation on which the trigger should be
 * created.  If zero, the name provided in the statement will be looked up.
 *
 * refRelOid, if nonzero, is the relation to which the constraint trigger
 * refers.  If zero, the constraint relation name provided in the statement
 * will be looked up as needed.

We can put these two parameters into the CreateTrigStmt.
change it from
CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
              Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid,
              Oid funcoid, Oid parentTriggerOid, Node *whenClause,
              bool isInternal, bool in_partition)
to:

CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
              Oid constraintOid, Oid indexOid,
              Oid funcoid, Oid parentTriggerOid, Node *whenClause,
              bool isInternal, bool in_partition)

This is needed, ProcessUtilitySlow->CreateTrigger don't have the new
target table relation OID information, using CreateTrigStmt.relation
would cause repeated name lookup issue.

v3-0001 and v3-0002 refactor the CreateTrigger function.
The parameters relOid and refRelOid are removed and instead added to the
CreateTrigStmt structure.

These two patch (v3-0001, v3-0002) will also be used in [1]
[1]: https://postgr.es/m/CACJufxGkqYrmwMdvUOUPet0443oUTgF_dKCpw3TfJiutfuywAQ@mail.gmail.com

v3-0003 is for CREATE TABLE LIKE INCLUDING TRIGGERS.


--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Dec 29, 2025 at 9:26 AM jian he  wrote:
>
> v3-0001 and v3-0002 refactor the CreateTrigger function.
> The parameters relOid and refRelOid are removed and instead added to the
> CreateTrigStmt structure.
>
> These two patch (v3-0001, v3-0002) will also be used in [1]
> [1]: https://postgr.es/m/CACJufxGkqYrmwMdvUOUPet0443oUTgF_dKCpw3TfJiutfuywAQ@mail.gmail.com
>
> v3-0003 is for CREATE TABLE LIKE INCLUDING TRIGGERS.
>
hi.

https://cirrus-ci.com/build/6583555523870720
https://api.cirrus-ci.com/v1/artifact/task/5664491007901696/testrun/build/testrun/pg_upgrade/002_pg_upgrade/data/regression.diffs

only FreeBSD fails. I suspect this is because pstrdup was not used in
generateClonedTriggerStmt.

now using pstrdup in generateClonedTriggerStmt; otherwise v4-0003 is identical
to v3-0003.


--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Hi Jian!

The feature makes sense from my POV.

> On 31 Dec 2025, at 10:08, jian he  wrote:
> 
> 

I'm not an expert in the area, but still decided to review the patch a bit.

First two steps seems to add Oids along with RangeVars. It seems suspicious to me.
Parse Nodes seem to use "textual" identifiers without resolving them to Oids. Oids are specific to session catalog snapshot, but parse nodes
By adding Oid fields we will have to check both RangeVars and Oids all over the code.
Other INCLUDING options (indexes, constraints) don't modify their statement nodes this way - they create fresh nodes with resolved references.

I'm not opposed, but I suggest you to get an opinion of an expert in parse nodes about it, maybe in Discord if this thread does not attract attention. It seems a fundamental stuff for two of your patchsets.

+ char *trigcomment; /* comment to apply to trigger, or NULL */
No other Create*Stmt has a comment field. Comments seem to be handled through separate CommentStmt creation.

Some nitpicking about tests:
1. INSTEAD OF triggers on views - The error is tested, but should also test that statement-level VIEW triggers work
2. Triggers on partitioned tables - What happens when you LIKE a partitioned table? Are partition triggers cloned?
3. Cross-schema trigger functions - The function name reconstruction handles schemas, but is it tested?

+ funcname = list_make2(makeString(schemaname),makeString(NameStr(procform->proname)));
Other NameStr() are pstrdup()'d, maybe let's pstrdup() this too?

+ /* Reconstruct trigger old transition table */
Second instance of this comment is wrong.

+ PG_KEYWORD("triggers", TRIGGERS, UNRESERVED_KEYWORD, BARE_LABEL)
Won't this break some user SQLs?

Thanks!


Best regards, Andrey Borodin.

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Jan 2, 2026 at 4:25 AM Andrey Borodin  wrote:
> First two steps seems to add Oids along with RangeVars. It seems suspicious to me.
> Parse Nodes seem to use "textual" identifiers without resolving them to Oids. Oids are specific to session catalog snapshot, but parse nodes
> By adding Oid fields we will have to check both RangeVars and Oids all over the code.
> Other INCLUDING options (indexes, constraints) don't modify their statement nodes this way - they create fresh nodes with resolved references.

It seems like what generateClonedIndexStmt() does for the relation name is just:

        index->relation = heapRel;

This is not a "resolved reference", which I would understand to mean
an OID in this context. In fact, if heapRel->schemaname were ever NULL
here, this would be at least a bug and possibly a security issue.
However, I don't think that ever happens. ProcessUtilitySlow() calls
transformCreateStmt(), which forces the RangeVar to be
fully-qualified, and then ProcessUtilitySlow() fishes out the
transformed RangeVar so that it gets passed through to
expandTableLikeClause(), which in turn passes it through to
generateClonedIndexStmt() and generateClonedExtStatsStmt(). Similarly
constraints are handled by using that same transformed (i.e. forcibly
schema-qualified) RangeVar in the AlterTableStmt we construct.

To be honest, I find this all incredibly ugly. I think that
translating from names to OIDs and back to names so that we can later
translate back to OIDs is a horrendous, bug-prone mess. Nor is the
problem confined to table names. For example,
generateClonedIndexStmt() needs to translate the AM name and
tablespace name and any column names back to textual format so that
when we actually create the index we can redo the translation in the
forward direction and hopefully get the right answer.

But having said that it's incredibly ugly and I don't like anything
about it, it also does seem to be the established pattern. As you say,
it seems as though the patch makes CREATE LIKE ... (INCLUDING
TRIGGERS) work differently from other cases, and I'm guessing that's
not what we want to do. It's better to use the same ugly hack
consistently than to use different ugly hacks in different places.
Then if somebody ever decides to try to clean this up, they can clean
up all the cases in the same way.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Fri, Jan 2, 2026 at 5:25 PM Andrey Borodin  wrote:
>
> + char *trigcomment; /* comment to apply to trigger, or NULL */
> No other Create*Stmt has a comment field. Comments seem to be handled through separate CommentStmt creation.
>

See CreateStatsStmt.stxcomment, IndexStmt.idxcomment.
We need CreateTrigStmt.trigcomment, because if INCLUDING COMMENTS is specified,
CreateTrigStmt.trigcomment can be used to hold the source object's comments.

> Some nitpicking about tests:
> 1. INSTEAD OF triggers on views - The error is tested, but should also test that statement-level VIEW triggers work
ok. test added.

> 2. Triggers on partitioned tables - What happens when you LIKE a partitioned table? Are partition triggers cloned?
no. only the trigger on the partitioned table itself will be cloned.
see tests ``create table parted_constr_copy (like parted_constr
including all);``

> 3. Cross-schema trigger functions - The function name reconstruction handles schemas, but is it tested?
>
ok. test added.

> + funcname = list_make2(makeString(schemaname),makeString(NameStr(procform->proname)));
> Other NameStr() are pstrdup()'d, maybe let's pstrdup() this too?
>
ok.

> + /* Reconstruct trigger old transition table */
> Second instance of this comment is wrong.
>
ok.

> + PG_KEYWORD("triggers", TRIGGERS, UNRESERVED_KEYWORD, BARE_LABEL)
> Won't this break some user SQLs?
it's marked as an un-reserved word, so it won't break any SQL, i think.

v4-0001, v4-0002 was removed, as Robert said in [1],  now I am using
the same ugly
hack consistently, now code is more aligned with INCLUDING INDEXES, INCLUDING
STATISTICS.

pstrdup have been used in more places in generateClonedTriggerStmt.



--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:


> On 16 Jan 2026, at 12:34, jian he  wrote:


IMO the patch is ready for committer.


Best regards, Andrey Borodin.


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello!

I tested the patch, it works as described, but I did notice one possible issue:

Shouldn't this preserve the enabled state of the triggers, or if it
doesn't, should the documentation include this limitations?

Currently the new table will always use the default
TRIGGER_FIRES_ON_ORIGIN, regardless how it is configured for the
original table.

diff --git a/src/test/regress/sql/triggers.sql
b/src/test/regress/sql/triggers.sql
index a1e9dbba8bd..24f7bfb5837 100644
--- a/src/test/regress/sql/triggers.sql
+++ b/src/test/regress/sql/triggers.sql
@@ -260,6 +260,18 @@ 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;

+-- Test that trigger firing state is not preserved by LIKE INCLUDING TRIGGERS
+ALTER TABLE main_table DISABLE TRIGGER before_ins_stmt_trig;
+CREATE TABLE main_table2 (LIKE main_table INCLUDING TRIGGERS);
+SELECT c.relname, t.tgname, t.tgenabled
+FROM pg_trigger t
+JOIN pg_class c ON t.tgrelid = c.oid
+WHERE t.tgname = 'before_ins_stmt_trig'
+  AND c.relname IN ('main_table', 'main_table2')
+ORDER BY c.relname;
+DROP TABLE main_table2;
+ALTER TABLE main_table ENABLE TRIGGER before_ins_stmt_trig;
+
 --
 -- Test case for bug with BEFORE trigger followed by AFTER trigger with WHEN
 --

On Wed, Jan 21, 2026 at 12:00 PM jian he  wrote:
>
> On Fri, Jan 2, 2026 at 5:25 PM Andrey Borodin  wrote:
> >
> > + char *trigcomment; /* comment to apply to trigger, or NULL */
> > No other Create*Stmt has a comment field. Comments seem to be handled through separate CommentStmt creation.
> >
>
> See CreateStatsStmt.stxcomment, IndexStmt.idxcomment.
> We need CreateTrigStmt.trigcomment, because if INCLUDING COMMENTS is specified,
> CreateTrigStmt.trigcomment can be used to hold the source object's comments.
>
> > Some nitpicking about tests:
> > 1. INSTEAD OF triggers on views - The error is tested, but should also test that statement-level VIEW triggers work
> ok. test added.
>
> > 2. Triggers on partitioned tables - What happens when you LIKE a partitioned table? Are partition triggers cloned?
> no. only the trigger on the partitioned table itself will be cloned.
> see tests ``create table parted_constr_copy (like parted_constr
> including all);``
>
> > 3. Cross-schema trigger functions - The function name reconstruction handles schemas, but is it tested?
> >
> ok. test added.
>
> > + funcname = list_make2(makeString(schemaname),makeString(NameStr(procform->proname)));
> > Other NameStr() are pstrdup()'d, maybe let's pstrdup() this too?
> >
> ok.
>
> > + /* Reconstruct trigger old transition table */
> > Second instance of this comment is wrong.
> >
> ok.
>
> > + PG_KEYWORD("triggers", TRIGGERS, UNRESERVED_KEYWORD, BARE_LABEL)
> > Won't this break some user SQLs?
> it's marked as an un-reserved word, so it won't break any SQL, i think.
>
> v4-0001, v4-0002 was removed, as Robert said in [1],  now I am using
> the same ugly
> hack consistently, now code is more aligned with INCLUDING INDEXES, INCLUDING
> STATISTICS.
>
> pstrdup have been used in more places in generateClonedTriggerStmt.
>
>
>
> --
> jian
> https://url.avanan.click/v2/r01/___https://www.enterprisedb.com/___.YXAzOnBlcmNvbmE6YTpnOjE5NWMwMWNmNDE3Y2Y3Yzg3MGZkNWQyM2FkM2UxYjc4Ojc6NWM5NTo0YjU3NGI1Y2MzZjIyMjk5MzRiYWU0Njk1Yjk4NTJkNzg0YjMwYzMwZWFiMjIzYTQ4YjU1ZWUwZDIxZWI4ZWFhOnA6VDpO


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
On Wed, Jan 21, 2026 at 8:13 PM Zsolt Parragi  wrote:
>
> Hello!
>
> I tested the patch, it works as described, but I did notice one possible issue:
>
> Shouldn't this preserve the enabled state of the triggers, or if it
> doesn't, should the documentation include this limitations?
>

I intended to document it as
         
          All non-internal triggers on the original table will be
created on the new table.
          By default, these triggers fire in "origin" and "local" modes. Refer
          to ALTER
TABLE
          to modify the firing condition.
         

what do you think?


--
jian
https://www.enterprisedb.com/


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
> > Shouldn't this preserve the enabled state of the triggers, or if it
> > doesn't, should the documentation include this limitations?
> >
>
> I intended to document it as ...


After looking into this a bit more, I am more on the side of copying
this setting properly.

The already existing INCLUDING CONSTRAINTS copies the constraints,
including their enabled/disabled status, correctly marking them
disabled if a CHECK constraint is defined but not enforced. Wouldn't
it be strange for INCLUDING TRIGGERS to work differently?

From the test suite:

CREATE TABLE ctlt1_inh (LIKE ctlt1 INCLUDING CONSTRAINTS INCLUDING
COMMENTS) INHERITS (ctlt1);
\d+ ctlt1_inh
                                Table "public.ctlt1_inh"
 Column | Type | Collation | Nullable | Default | Storage  | Stats
target | Description
--------+------+-----------+----------+---------+----------+--------------+-------------
 a      | text |           | not null |         | main     |              | A
 b      | text |           |          |         | extended |              | B
Check constraints:
    "cc" CHECK (length(b) > 100)
    "ctlt1_a_check" CHECK (length(a) > 2)
    "ctlt1_b_check" CHECK (length(b) > 100) NOT ENFORCED
Not-null constraints:
    "ctlt1_a_not_null" NOT NULL "a" (local, inherited)
Inherits: ctlt1


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jan 22, 2026 at 10:20 PM Zsolt Parragi
 wrote:
>
> After looking into this a bit more, I am more on the side of copying
> this setting properly.
>
> The already existing INCLUDING CONSTRAINTS copies the constraints,
> including their enabled/disabled status, correctly marking them
> disabled if a CHECK constraint is defined but not enforced. Wouldn't
> it be strange for INCLUDING TRIGGERS to work differently?
>

hi.
please check the attached.

v6-0001 is the same as v5-0001.
v6-0002 ensures that CREATE TABLE ... LIKE ... INCLUDING TRIGGERS
correctly copies the tgenabled status from the source table's triggers
to the new table



--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
This looks good to me, I only have two minor comments:

1. The test should drop main_table1 and some_t1

2. there's a missing word in a comment (do -> to do)

+ char    *trigcomment; /* comment to apply to trigger, or NULL */
+ bool transformed; /* true means no need do parse analysis for *
+ * whenClause */


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Fri, Feb 6, 2026 at 10:49 PM Zsolt Parragi  wrote:
>
> This looks good to me, I only have two minor comments:
>
> 1. The test should drop main_table1 and some_t1
>
> 2. there's a missing word in a comment (do -> to do)
>
> + char    *trigcomment; /* comment to apply to trigger, or NULL */
> + bool transformed; /* true means no need do parse analysis for *
> + * whenClause */

hi.
The attached have addressed these two points.

I still keep two separate patches, in case there are differing opinions about
whether to copy the old table’s trigger tgenabled to the new table.
Squashing them into a single patch is quite straightforward.



--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

Minor rebase due to changes in
https://git.postgresql.org/cgit/postgresql.git/commit/?id=b2ff2a0b52962dcbcbc9c5a8d74fd4e8c28d1f2a



--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.
rebase due to changes in
https://git.postgresql.org/cgit/postgresql.git/commit/?id=7724cb9935a96eabba80f5e62ee4b32068967dd2
https://git.postgresql.org/cgit/postgresql.git/commit/?id=fba4233c832870c8363438419743c48fdcb2151c


--
jian
https://www.enterprisedb.com/

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Jian,

Thank you for the patch.  I applied v9 to a clean checkout, built it,
and ran the regression suite — all tests pass.  Nice work.

I have attached a quality assessment report below.

A line-by-line code review will follow in due course.

Detailed gcov coverage in HTML format is included in coverage.tgz.


CREATE TABLE LIKE INCLUDING TRIGGERS — Coverage Review
======================================================

Patch:       CREATE TABLE LIKE INCLUDING TRIGGERS
Commitfest:  https://commitfest.postgresql.org/patch/6087

Review Methodology:
  Quality assessment: build verification, regression testing, and code
  coverage analysis (gcov, modified lines only).  This is not a full
  code review.

Limitations:
  - Not a security audit or formal verification


TABLE OF CONTENTS
-----------------

1. Executive Summary
2. Issues Found
   2.1 Critical / Major
   2.2 Minor (Review Needed)
3. Test Coverage
   3.1 Covered Areas
   3.2 Untested Items
4. Code Coverage Analysis
   4.1 Overall Coverage
   4.2 Uncovered Code Risk Assessment
5. Commit Analysis
6. Recommendations
7. Conclusion


1. EXECUTIVE SUMMARY
--------------------

Overall assessment: GOOD

The patch adds INCLUDING TRIGGERS to CREATE TABLE LIKE (and CREATE
FOREIGN TABLE LIKE).  Build succeeds and all regression tests pass.

The following behaviors are verified by the test suite:
  - Internal triggers (FK-associated) are not copied
  - INSTEAD OF triggers on views produce an error
  - Whole-row references in WHEN clauses produce an error
  - Trigger comments are copied only when INCLUDING COMMENTS is given
  - The trigger's enabled state is preserved on the new table

Rating by Area:
  Test Coverage:    Good (broad scenario coverage)
  Documentation:    Thin (functional but sparse)
  Build/Regress:    Pass


2. ISSUES FOUND
---------------

2.1 Critical / Major

None.


2.2 Minor (Review Needed)

#1 [Documentation] INCLUDING TRIGGERS entry is too brief

   create_table.sgml currently says only:
     "All non-internal triggers on the original table will be
      created on the new table."

   The following behaviors are not mentioned:
     (a) The trigger's enabled state is preserved on the new table.
     (b) A WHEN clause with a whole-row reference causes an error.
     (c) INSTEAD OF triggers cannot be copied to a plain table.

   Suggested addition after the existing sentence:
     <para>
      The enabled state of each trigger (as set by ALTER TABLE ...
      ENABLE/DISABLE TRIGGER) is preserved on the new table.
      An error is raised if any trigger's WHEN clause contains a
      whole-row table reference.  INSTEAD OF triggers on views cannot
      be copied to a plain table.
     </para>

   The same applies to the entry in create_foreign_table.sgml.


3. TEST COVERAGE
----------------

3.1 Covered Areas

triggers.sql additions exercise:

  - Whole-row WHEN clause (OLD IS NOT NULL) → error
  - Whole-row WHEN clause (NEW IS NOT NULL) → error
  - Basic LIKE INCLUDING TRIGGERS + INCLUDING COMMENTS
  - Trigger enabled state: ENABLE REPLICA, DISABLE, ENABLE ALWAYS
  - INSTEAD OF triggers on a view → error
  - Statement-level view triggers with transition tables
  - Partitioned table: table-level trigger only, not partition triggers
  - Transition table triggers on partitioned table copy
  - Cross-schema trigger function
  - Constraint trigger with FROM clause

create_table_like.sql additions exercise:

  - Triggers with WHEN clause and column-specific UPDATE (via
    LIKE ctl_table INCLUDING ALL on a foreign table)

3.2 Untested Items

The following lines were uncovered per gcov analysis (see section 4).

Line                    Code path
-------------------------------------------------------------------------------
trigger.c:6959          elog: trigger OID not found in pg_trigger
trigger.c:6966          elog: trigger function OID not in syscache
trigger.c:7002          elog: tgargs is null when tgnargs > 0
parse_utilcmd.c:1640    continue: skip internal trigger

Lines 6959, 6966, 7002 are catalog-inconsistency guards.
All three require catalog corruption to reach; untestable under normal
operation.  No functional risk.

Line 1640 (the internal-trigger skip) is reachable but requires a
source table that has FK constraints (which create internal triggers).
The patch description explicitly states that FK-associated internal
triggers are excluded, but no test verifies this behavior.

Suggested test (add near the tgenabled block in triggers.sql):

  -- Internal triggers (e.g. FK) must not be copied
  CREATE TABLE fk_parent (id int PRIMARY KEY);
  CREATE TABLE fk_child (id int REFERENCES fk_parent(id));
  CREATE TABLE fk_child_copy (LIKE fk_child INCLUDING TRIGGERS);
  SELECT count(*) FROM pg_trigger
  WHERE tgrelid = 'fk_child_copy'::regclass;  -- expect 0
  DROP TABLE fk_child_copy, fk_child, fk_parent;


4. CODE COVERAGE ANALYSIS
-------------------------

4.1 Overall Coverage (modified lines only)

  trigger.c          96.8%  (91 / 94 lines)
  parse_utilcmd.c    92.3%  (12 / 13 lines)
  -----------------------------------------------
  Combined           96.8%  (120 / 124 lines)

4.2 Uncovered Code Risk Assessment

trigger.c:6959, 6966, 7002 — catalog-inconsistency guards.
All three require catalog corruption to reach; untestable under normal
operation.  No functional risk.

parse_utilcmd.c:1640 — internal trigger skip.  Reachable with a table
that has FK constraints.  A test is straightforward; see section 3.2
for sample SQL.


5. COMMIT ANALYSIS
------------------

2 commits:

Commit       Area            Files   +/-        Key Content
-----------------------------------------------------------------------
e73f551      Core feature    14      +531/-19   generateClonedTriggerStmt,
                                                expandTableLikeClause,
                                                grammar, docs, tests
39ae762      tgenabled copy   8       +27/-6    trigger enabled state
                                                preserved on new table

The two-commit structure is sensible given that the enabled state copy
was a post-review addition.  Squashing is straightforward if preferred.


6. RECOMMENDATIONS
------------------

1. Add a test verifying that FK internal triggers are not copied
   (sample SQL in section 3.2).

2. Expand the INCLUDING TRIGGERS documentation entry (section 2.2 #1).


7. CONCLUSION
-------------

From a quality standpoint, the patch is in good shape: regression tests
pass, coverage is at 96.8% on modified lines, and the key scenarios
(enabled state, whole-row errors, partitioned tables, cross-schema
functions) are all exercised by the test suite.

The missing test for internal trigger exclusion (#1) and the
documentation gaps (#2) are worth addressing before commit.  The
remaining items are minor.

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

This is the line-by-line code review I promised earlier.  The overall
conclusion is that the patch is in good shape.  I have some minor
items below, none of which are blockers.

WHAT LOOKS GOOD
---------------

The keyword placement is correct.  TRIGGERS is classified as
UNRESERVED_KEYWORD and also listed in bare_label_keyword, so existing
SQL that uses "triggers" as an identifier continues to work without
quoting.  No compatibility concern here.

generateClonedTriggerStmt() is well-structured.  The WHEN-clause
remapping via map_variable_attnos() and the transformed flag to prevent
re-transformation in CreateTriggerFiringOn() are correct.

pg_dump needs no changes.  LIKE-copied triggers are stored as
independent pg_trigger rows, so the existing dump logic picks them up
automatically.

MINOR ISSUES
------------

1. Test: cross-file dependency on trigger_func (create_table_like.sql)

   create_table_like.sql references trigger_func without creating it,
   relying on triggers.sql having run first.  The dependency is noted
   in a comment, and parallel_schedule guarantees the correct order for
   a full "make check" run.  However, "make check TESTS=create_table_like"
   will fail because trigger_func does not exist.

   PostgreSQL convention is that each test file creates and drops the
   objects it needs.  Please add a local definition of trigger_func in
   create_table_like.sql (and drop it at the end of the new block).

2. Test: EXCLUDING TRIGGERS not exercised

   The grammar now accepts EXCLUDING TRIGGERS, but no test uses it.
   The default (no option) is equivalent, but a one-line smoke test
   would confirm the keyword is accepted and has the expected effect:

     CREATE TABLE t_excl (LIKE source_table EXCLUDING TRIGGERS);

3. Documentation: create_table.sgml wording inconsistent with
   create_foreign_table.sgml

   create_foreign_table.sgml already reads:

     "All non-internal triggers are copied to the new table."

   create_table.sgml reads:

     "All non-internal triggers on the original table will be created
      on the new table."

   Two problems with the latter:
   a) "on the original table" is redundant; no other INCLUDING option
      includes this phrase (compare INCLUDING STATISTICS: "Extended
      statistics are copied to the new table.").
   b) "will be created" misrepresents the action; the correct verb
      is "are copied", matching the pattern used elsewhere.

   Recommended wording for create_table.sgml:

     "All non-internal triggers are copied to the new table."

4. Code comment: capitalisation in generateClonedTriggerStmt()
   (trigger.c)

     /* Reconstruct trigger function String list */

   "String" should be lowercase "string".

5. Code comment: overly verbose in expandTableLikeClause()
   (parse_utilcmd.c)

     /* We make use of CreateTrigStmt's trigcomment option */

   The code is self-explanatory.  I would recommend removing it or
   replacing it with something like:

     /* pass comment through to CreateTrigger */

6. Commit message grammar (commit e73f551)

   Several sentences contain grammatical errors:

   a) "This will copy all source table's trigger to the new table."
      -> "...triggers..."

   b) "Internal trigger (such as foreign key associated trigger) won't
       being copied to new table."
      -> "Internal triggers (such as foreign-key-associated triggers)
         won't be copied to the new table."

   c) "However this command will fail if the source table's trigger
       contain whole-row reference."
      -> "However, this command will fail if the source table's triggers
         contain a whole-row reference."

7. Whole-row reference restriction: implementation gap or deliberate?

   Triggers whose WHEN clause contains a whole-row reference (OLD.*,
   NEW.*) are rejected.  Is this a deliberate decision, or a known gap
   left for a follow-up?  If the latter, a XXX comment at the rejection
   site would help future contributors:

     /*
      * XXX: whole-row Vars could in principle be handled by passing the
      * target table's composite type OID as to_rowtype, but
      * generateClonedTriggerStmt() currently has no access to it.
      */

SUMMARY OF ITEMS TO ADDRESS
----------------------------

  [1] create_table_like.sql: define and drop trigger_func locally so
      the file can be run in isolation.

  [2] Add a test for EXCLUDING TRIGGERS.

  [3] create_table.sgml: align the INCLUDING TRIGGERS description with
      create_foreign_table.sgml, which already reads correctly:
      "All non-internal triggers are copied to the new table."

  [4] trigger.c generateClonedTriggerStmt(): lowercase "string" in
      comment "/* Reconstruct trigger function String list */".

  [5] parse_utilcmd.c expandTableLikeClause(): simplify or remove the
      comment "/* We make use of CreateTrigStmt's trigcomment option */".

  [6] Commit message: fix grammar in items (a), (b), (c) listed above.

Items [3]-[6] are purely cosmetic.  [1] and [2] are worth considering
before commit, but none of these are blockers.

Thanks for the patch.

Best regards,
Henson Choi

Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, May 7, 2026 at 9:38 AM Henson Choi  wrote:
>
> MINOR ISSUES
> ------------
>
> 1. Test: cross-file dependency on trigger_func (create_table_like.sql)
>
>    create_table_like.sql references trigger_func without creating it,
>    relying on triggers.sql having run first.  The dependency is noted
>    in a comment, and parallel_schedule guarantees the correct order for
>    a full "make check" run.  However, "make check TESTS=create_table_like"
>    will fail because trigger_func does not exist.
>
>    PostgreSQL convention is that each test file creates and drops the
>    objects it needs.  Please add a local definition of trigger_func in
>    create_table_like.sql (and drop it at the end of the new block).
>
OK.

> 2. Test: EXCLUDING TRIGGERS not exercised
>
>    The grammar now accepts EXCLUDING TRIGGERS, but no test uses it.
>    The default (no option) is equivalent, but a one-line smoke test
>    would confirm the keyword is accepted and has the expected effect:
>
>      CREATE TABLE t_excl (LIKE source_table EXCLUDING TRIGGERS);
>
OK.

> 3. Documentation: create_table.sgml wording inconsistent with
>    create_foreign_table.sgml
>
>    create_foreign_table.sgml already reads:
>
>      "All non-internal triggers are copied to the new table."
>
>    create_table.sgml reads:
>
>      "All non-internal triggers on the original table will be created
>       on the new table."
>
>    Recommended wording for create_table.sgml:
>
>      "All non-internal triggers are copied to the new table."
>
OK.

> 4. Code comment: capitalisation in generateClonedTriggerStmt()
>    (trigger.c)
>
>      /* Reconstruct trigger function String list */
>
>    "String" should be lowercase "string".
>
Other places also have "String list", it refers to the T_String node type.

> 5. Code comment: overly verbose in expandTableLikeClause()
>    (parse_utilcmd.c)
>
>      /* We make use of CreateTrigStmt's trigcomment option */
>
>    The code is self-explanatory.  I would recommend removing it or
>    replacing it with something like:
>
>      /* pass comment through to CreateTrigger */
>

Other places in parse_utilcmd.c have:
/*
 * We make use of IndexStmt's idxcomment option, so as not to
 * need to know now what name the index will have.
 */

/*
 * We make use of CreateStatsStmt's stxcomment option, so as
 * not to need to know now what name the statistics will have.
 */

We can change it to:
/*
 * We make use of CreateTrigStmt's trigcomment option,  so as
 * not to need to know now what name the triggers will have.
 */

>
> 7. Whole-row reference restriction: implementation gap or deliberate?
>
>    Triggers whose WHEN clause contains a whole-row reference (OLD.*,
>    NEW.*) are rejected.  Is this a deliberate decision, or a known gap
>    left for a follow-up?  If the latter, a XXX comment at the rejection
>    site would help future contributors:
>
>      /*
>       * XXX: whole-row Vars could in principle be handled by passing the
>       * target table's composite type OID as to_rowtype, but
>       * generateClonedTriggerStmt() currently has no access to it.
>       */
>

Other places already reject it (search found_whole_row in parse_utilcmd.c).
It cannot be supported because the source table's whole-row type
differs from the target table's whole-row type.

The v10 in https://www.postgresql.org/message-id/CACJufxEcKTa5DaDJS%3DZ25xezCEyuLbSzORDSmT4%3DjyZymsAK8A%40mail.gmail.com
has addressed most of the issues mentioned above.

Only issue remaining is changing one of the comments to
/*
 * We make use of CreateTrigStmt's trigcomment option,  so as
 * not to need to know now what name the triggers will have.
 */


Re: CREATE TABLE LIKE INCLUDING TRIGGERS

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

I didn't read all of v10 line by line, but a few things stood out on a pass;
I've grouped them by how you might want to act on each.

1. Docs / typos (all cosmetic)

   - "not be copied" grammar in the source-view sentence of both
     create_table.sgml and create_foreign_table.sgml:
         now:  triggers from a source view are not be copied.
         ->    triggers from a source view are not copied.

   - Typo "cosntraint" in a create_table_like test comment:
         now:  ... should not copy source table cosntraint trigger
         ->    ... should not copy source table constraint trigger

   - In the create_table_like test, trigger trigtest_after_stmt passes
     'trigtest_before_stmt' as its argument, which doesn't match the trigger
     name (looks like a copy-paste):
         now:  CREATE TRIGGER trigtest_after_stmt ... ('trigtest_before_stmt')
         ->    CREATE TRIGGER trigtest_after_stmt ... ('trigtest_after_stmt')

   - 0002: create_table.sgml's INCLUDING TRIGGERS entry doesn't mention that a
     trigger's enabled/disabled (tgenabled) state is preserved.  Suggested,
     after the source-view sentence ("... are not copied."):
         "The enabled state of each trigger (as set by ALTER TABLE ...
          ENABLE/DISABLE TRIGGER) is preserved on the new table."

2. Code -- two fixes to consider

   (a) Concurrent trigger add can fail CREATE TABLE via a duplicate (reproduced)

   expandTableLikeClause() walks the source trigger array (trigdesc) by index,
   calling generateClonedTriggerStmt(), whose catalog access can process an
   invalidation and rebuild the source trigdesc.  The array is sorted by tgname,
   so if another session adds a lower-sorting trigger mid-walk, the indexes shift
   and an already-processed trigger gets cloned again.

   I reproduced it by putting a sleep in the loop: with t100/t101/t102 on the
   source, adding t000 from another session right after t100 was processed
   (CREATE TRIGGER is compatible with AccessShareLock, so it isn't blocked) made
   the next iteration see the rebuilt array [t000, t100, t101, t102], with nt=1
   pointing at t100 again -- so it tried to create t100 twice on the new table
   and the whole CREATE TABLE failed with "trigger ... already exists".

   The removal side (DROP/ALTER/RENAME TRIGGER) is blocked by AccessExclusiveLock
   against the source's AccessShareLock, so the array can't shrink and nothing is
   missed; the only thing that can run concurrently is CREATE TRIGGER (a
   compatible lock), leaving just this duplicate.  It's probably a rare path, but
   it seems worth addressing.

   (b) tgenabled channel unification (CreateTriggerFiringOn)

   0002 adds a tgenabled field to CreateTrigStmt and sets it in several places,
   but the deferred-unique trigger in index.c and the FK triggers in
   tablecmds.c still call CreateTrigger().  CreateTrigger() hardcodes tgenabled
   to TRIGGER_FIRES_ON_ORIGIN internally, so the trigger->tgenabled just
   assigned is a dead store.  It's harmless today since the value is always
   ORIGIN, but it's a field set and then ignored.  Unifying those sites on
   CreateTriggerFiringOn(..., trigger->tgenabled) (or dropping the assignment)
   would consolidate the two channels.

Best regards,
Henson
FAQ